three.js 836 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '53dev' };
  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. isZero: function ( v ) {
  434. return this.lengthSq() < ( v !== undefined ? v : 0.0001 );
  435. },
  436. clone: function () {
  437. return new THREE.Vector2( this.x, this.y );
  438. }
  439. };
  440. /**
  441. * @author mrdoob / http://mrdoob.com/
  442. * @author kile / http://kile.stravaganza.org/
  443. * @author philogb / http://blog.thejit.org/
  444. * @author mikael emtinger / http://gomo.se/
  445. * @author egraether / http://egraether.com/
  446. * @author WestLangley / http://github.com/WestLangley
  447. */
  448. THREE.Vector3 = function ( x, y, z ) {
  449. this.x = x || 0;
  450. this.y = y || 0;
  451. this.z = z || 0;
  452. };
  453. THREE.Vector3.prototype = {
  454. constructor: THREE.Vector3,
  455. set: function ( x, y, z ) {
  456. this.x = x;
  457. this.y = y;
  458. this.z = z;
  459. return this;
  460. },
  461. setX: function ( x ) {
  462. this.x = x;
  463. return this;
  464. },
  465. setY: function ( y ) {
  466. this.y = y;
  467. return this;
  468. },
  469. setZ: function ( z ) {
  470. this.z = z;
  471. return this;
  472. },
  473. copy: function ( v ) {
  474. this.x = v.x;
  475. this.y = v.y;
  476. this.z = v.z;
  477. return this;
  478. },
  479. add: function ( a, b ) {
  480. this.x = a.x + b.x;
  481. this.y = a.y + b.y;
  482. this.z = a.z + b.z;
  483. return this;
  484. },
  485. addSelf: function ( v ) {
  486. this.x += v.x;
  487. this.y += v.y;
  488. this.z += v.z;
  489. return this;
  490. },
  491. addScalar: function ( s ) {
  492. this.x += s;
  493. this.y += s;
  494. this.z += s;
  495. return this;
  496. },
  497. sub: function ( a, b ) {
  498. this.x = a.x - b.x;
  499. this.y = a.y - b.y;
  500. this.z = a.z - b.z;
  501. return this;
  502. },
  503. subSelf: function ( v ) {
  504. this.x -= v.x;
  505. this.y -= v.y;
  506. this.z -= v.z;
  507. return this;
  508. },
  509. multiply: function ( a, b ) {
  510. this.x = a.x * b.x;
  511. this.y = a.y * b.y;
  512. this.z = a.z * b.z;
  513. return this;
  514. },
  515. multiplySelf: function ( v ) {
  516. this.x *= v.x;
  517. this.y *= v.y;
  518. this.z *= v.z;
  519. return this;
  520. },
  521. multiplyScalar: function ( s ) {
  522. this.x *= s;
  523. this.y *= s;
  524. this.z *= s;
  525. return this;
  526. },
  527. divideSelf: function ( v ) {
  528. this.x /= v.x;
  529. this.y /= v.y;
  530. this.z /= v.z;
  531. return this;
  532. },
  533. divideScalar: function ( s ) {
  534. if ( s ) {
  535. this.x /= s;
  536. this.y /= s;
  537. this.z /= s;
  538. } else {
  539. this.x = 0;
  540. this.y = 0;
  541. this.z = 0;
  542. }
  543. return this;
  544. },
  545. negate: function() {
  546. return this.multiplyScalar( - 1 );
  547. },
  548. dot: function ( v ) {
  549. return this.x * v.x + this.y * v.y + this.z * v.z;
  550. },
  551. lengthSq: function () {
  552. return this.x * this.x + this.y * this.y + this.z * this.z;
  553. },
  554. length: function () {
  555. return Math.sqrt( this.lengthSq() );
  556. },
  557. lengthManhattan: function () {
  558. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  559. },
  560. normalize: function () {
  561. return this.divideScalar( this.length() );
  562. },
  563. setLength: function ( l ) {
  564. return this.normalize().multiplyScalar( l );
  565. },
  566. lerpSelf: function ( v, alpha ) {
  567. this.x += ( v.x - this.x ) * alpha;
  568. this.y += ( v.y - this.y ) * alpha;
  569. this.z += ( v.z - this.z ) * alpha;
  570. return this;
  571. },
  572. cross: function ( a, b ) {
  573. this.x = a.y * b.z - a.z * b.y;
  574. this.y = a.z * b.x - a.x * b.z;
  575. this.z = a.x * b.y - a.y * b.x;
  576. return this;
  577. },
  578. crossSelf: function ( v ) {
  579. var x = this.x, y = this.y, z = this.z;
  580. this.x = y * v.z - z * v.y;
  581. this.y = z * v.x - x * v.z;
  582. this.z = x * v.y - y * v.x;
  583. return this;
  584. },
  585. angleTo: function ( v ) {
  586. return Math.acos( this.dot( v ) / this.length() / v.length() );
  587. },
  588. distanceTo: function ( v ) {
  589. return Math.sqrt( this.distanceToSquared( v ) );
  590. },
  591. distanceToSquared: function ( v ) {
  592. return new THREE.Vector3().sub( this, v ).lengthSq();
  593. },
  594. getPositionFromMatrix: function ( m ) {
  595. this.x = m.elements[12];
  596. this.y = m.elements[13];
  597. this.z = m.elements[14];
  598. return this;
  599. },
  600. setEulerFromRotationMatrix: function ( m, order ) {
  601. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  602. // clamp, to handle numerical problems
  603. function clamp( x ) {
  604. return Math.min( Math.max( x, -1 ), 1 );
  605. }
  606. var te = m.elements;
  607. var m11 = te[0], m12 = te[4], m13 = te[8];
  608. var m21 = te[1], m22 = te[5], m23 = te[9];
  609. var m31 = te[2], m32 = te[6], m33 = te[10];
  610. if ( order === undefined || order === 'XYZ' ) {
  611. this.y = Math.asin( clamp( m13 ) );
  612. if ( Math.abs( m13 ) < 0.99999 ) {
  613. this.x = Math.atan2( - m23, m33 );
  614. this.z = Math.atan2( - m12, m11 );
  615. } else {
  616. this.x = Math.atan2( m32, m22 );
  617. this.z = 0;
  618. }
  619. } else if ( order === 'YXZ' ) {
  620. this.x = Math.asin( - clamp( m23 ) );
  621. if ( Math.abs( m23 ) < 0.99999 ) {
  622. this.y = Math.atan2( m13, m33 );
  623. this.z = Math.atan2( m21, m22 );
  624. } else {
  625. this.y = Math.atan2( - m31, m11 );
  626. this.z = 0;
  627. }
  628. } else if ( order === 'ZXY' ) {
  629. this.x = Math.asin( clamp( m32 ) );
  630. if ( Math.abs( m32 ) < 0.99999 ) {
  631. this.y = Math.atan2( - m31, m33 );
  632. this.z = Math.atan2( - m12, m22 );
  633. } else {
  634. this.y = 0;
  635. this.z = Math.atan2( m21, m11 );
  636. }
  637. } else if ( order === 'ZYX' ) {
  638. this.y = Math.asin( - clamp( m31 ) );
  639. if ( Math.abs( m31 ) < 0.99999 ) {
  640. this.x = Math.atan2( m32, m33 );
  641. this.z = Math.atan2( m21, m11 );
  642. } else {
  643. this.x = 0;
  644. this.z = Math.atan2( - m12, m22 );
  645. }
  646. } else if ( order === 'YZX' ) {
  647. this.z = Math.asin( clamp( m21 ) );
  648. if ( Math.abs( m21 ) < 0.99999 ) {
  649. this.x = Math.atan2( - m23, m22 );
  650. this.y = Math.atan2( - m31, m11 );
  651. } else {
  652. this.x = 0;
  653. this.y = Math.atan2( m13, m33 );
  654. }
  655. } else if ( order === 'XZY' ) {
  656. this.z = Math.asin( - clamp( m12 ) );
  657. if ( Math.abs( m12 ) < 0.99999 ) {
  658. this.x = Math.atan2( m32, m22 );
  659. this.y = Math.atan2( m13, m11 );
  660. } else {
  661. this.x = Math.atan2( - m23, m33 );
  662. this.y = 0;
  663. }
  664. }
  665. return this;
  666. },
  667. setEulerFromQuaternion: function ( q, order ) {
  668. // q is assumed to be normalized
  669. // clamp, to handle numerical problems
  670. function clamp( x ) {
  671. return Math.min( Math.max( x, -1 ), 1 );
  672. }
  673. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  674. var sqx = q.x * q.x;
  675. var sqy = q.y * q.y;
  676. var sqz = q.z * q.z;
  677. var sqw = q.w * q.w;
  678. if ( order === undefined || order === 'XYZ' ) {
  679. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  680. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  681. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  682. } else if ( order === 'YXZ' ) {
  683. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  684. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  685. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  686. } else if ( order === 'ZXY' ) {
  687. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  688. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  689. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  690. } else if ( order === 'ZYX' ) {
  691. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  692. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  693. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  694. } else if ( order === 'YZX' ) {
  695. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  696. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  697. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  698. } else if ( order === 'XZY' ) {
  699. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  700. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  701. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  702. }
  703. return this;
  704. },
  705. getScaleFromMatrix: function ( m ) {
  706. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  707. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  708. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  709. this.x = sx;
  710. this.y = sy;
  711. this.z = sz;
  712. return this;
  713. },
  714. equals: function ( v ) {
  715. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  716. },
  717. isZero: function ( v ) {
  718. return this.lengthSq() < ( v !== undefined ? v : 0.0001 );
  719. },
  720. clone: function () {
  721. return new THREE.Vector3( this.x, this.y, this.z );
  722. }
  723. };
  724. /**
  725. * @author supereggbert / http://www.paulbrunt.co.uk/
  726. * @author philogb / http://blog.thejit.org/
  727. * @author mikael emtinger / http://gomo.se/
  728. * @author egraether / http://egraether.com/
  729. * @author WestLangley / http://github.com/WestLangley
  730. */
  731. THREE.Vector4 = function ( x, y, z, w ) {
  732. this.x = x || 0;
  733. this.y = y || 0;
  734. this.z = z || 0;
  735. this.w = ( w !== undefined ) ? w : 1;
  736. };
  737. THREE.Vector4.prototype = {
  738. constructor: THREE.Vector4,
  739. set: function ( x, y, z, w ) {
  740. this.x = x;
  741. this.y = y;
  742. this.z = z;
  743. this.w = w;
  744. return this;
  745. },
  746. copy: function ( v ) {
  747. this.x = v.x;
  748. this.y = v.y;
  749. this.z = v.z;
  750. this.w = ( v.w !== undefined ) ? v.w : 1;
  751. return this;
  752. },
  753. add: function ( a, b ) {
  754. this.x = a.x + b.x;
  755. this.y = a.y + b.y;
  756. this.z = a.z + b.z;
  757. this.w = a.w + b.w;
  758. return this;
  759. },
  760. addSelf: function ( v ) {
  761. this.x += v.x;
  762. this.y += v.y;
  763. this.z += v.z;
  764. this.w += v.w;
  765. return this;
  766. },
  767. sub: function ( a, b ) {
  768. this.x = a.x - b.x;
  769. this.y = a.y - b.y;
  770. this.z = a.z - b.z;
  771. this.w = a.w - b.w;
  772. return this;
  773. },
  774. subSelf: function ( v ) {
  775. this.x -= v.x;
  776. this.y -= v.y;
  777. this.z -= v.z;
  778. this.w -= v.w;
  779. return this;
  780. },
  781. multiplyScalar: function ( s ) {
  782. this.x *= s;
  783. this.y *= s;
  784. this.z *= s;
  785. this.w *= s;
  786. return this;
  787. },
  788. divideScalar: function ( s ) {
  789. if ( s ) {
  790. this.x /= s;
  791. this.y /= s;
  792. this.z /= s;
  793. this.w /= s;
  794. } else {
  795. this.x = 0;
  796. this.y = 0;
  797. this.z = 0;
  798. this.w = 1;
  799. }
  800. return this;
  801. },
  802. negate: function() {
  803. return this.multiplyScalar( -1 );
  804. },
  805. dot: function ( v ) {
  806. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  807. },
  808. lengthSq: function () {
  809. return this.dot( this );
  810. },
  811. length: function () {
  812. return Math.sqrt( this.lengthSq() );
  813. },
  814. lengthManhattan: function () {
  815. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  816. },
  817. normalize: function () {
  818. return this.divideScalar( this.length() );
  819. },
  820. setLength: function ( l ) {
  821. return this.normalize().multiplyScalar( l );
  822. },
  823. lerpSelf: function ( v, alpha ) {
  824. this.x += ( v.x - this.x ) * alpha;
  825. this.y += ( v.y - this.y ) * alpha;
  826. this.z += ( v.z - this.z ) * alpha;
  827. this.w += ( v.w - this.w ) * alpha;
  828. return this;
  829. },
  830. clone: function () {
  831. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  832. },
  833. setAxisAngleFromQuaternion: function ( q ) {
  834. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  835. // q is assumed to be normalized
  836. this.w = 2 * Math.acos( q.w );
  837. var s = Math.sqrt( 1 - q.w * q.w );
  838. if ( s < 0.0001 ) {
  839. this.x = 1;
  840. this.y = 0;
  841. this.z = 0;
  842. } else {
  843. this.x = q.x / s;
  844. this.y = q.y / s;
  845. this.z = q.z / s;
  846. }
  847. return this;
  848. },
  849. setAxisAngleFromRotationMatrix: function ( m ) {
  850. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  851. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  852. var angle, x, y, z, // variables for result
  853. epsilon = 0.01, // margin to allow for rounding errors
  854. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  855. te = m.elements,
  856. m11 = te[0], m12 = te[4], m13 = te[8],
  857. m21 = te[1], m22 = te[5], m23 = te[9],
  858. m31 = te[2], m32 = te[6], m33 = te[10];
  859. if ( ( Math.abs( m12 - m21 ) < epsilon )
  860. && ( Math.abs( m13 - m31 ) < epsilon )
  861. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  862. // singularity found
  863. // first check for identity matrix which must have +1 for all terms
  864. // in leading diagonal and zero in other terms
  865. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  866. && ( Math.abs( m13 + m31 ) < epsilon2 )
  867. && ( Math.abs( m23 + m32 ) < epsilon2 )
  868. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  869. // this singularity is identity matrix so angle = 0
  870. this.set( 1, 0, 0, 0 );
  871. return this; // zero angle, arbitrary axis
  872. }
  873. // otherwise this singularity is angle = 180
  874. angle = Math.PI;
  875. var xx = ( m11 + 1 ) / 2;
  876. var yy = ( m22 + 1 ) / 2;
  877. var zz = ( m33 + 1 ) / 2;
  878. var xy = ( m12 + m21 ) / 4;
  879. var xz = ( m13 + m31 ) / 4;
  880. var yz = ( m23 + m32 ) / 4;
  881. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  882. if ( xx < epsilon ) {
  883. x = 0;
  884. y = 0.707106781;
  885. z = 0.707106781;
  886. } else {
  887. x = Math.sqrt( xx );
  888. y = xy / x;
  889. z = xz / x;
  890. }
  891. } else if ( yy > zz ) { // m22 is the largest diagonal term
  892. if ( yy < epsilon ) {
  893. x = 0.707106781;
  894. y = 0;
  895. z = 0.707106781;
  896. } else {
  897. y = Math.sqrt( yy );
  898. x = xy / y;
  899. z = yz / y;
  900. }
  901. } else { // m33 is the largest diagonal term so base result on this
  902. if ( zz < epsilon ) {
  903. x = 0.707106781;
  904. y = 0.707106781;
  905. z = 0;
  906. } else {
  907. z = Math.sqrt( zz );
  908. x = xz / z;
  909. y = yz / z;
  910. }
  911. }
  912. this.set( x, y, z, angle );
  913. return this; // return 180 deg rotation
  914. }
  915. // as we have reached here there are no singularities so we can handle normally
  916. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  917. + ( m13 - m31 ) * ( m13 - m31 )
  918. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  919. if ( Math.abs( s ) < 0.001 ) s = 1;
  920. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  921. // caught by singularity test above, but I've left it in just in case
  922. this.x = ( m32 - m23 ) / s;
  923. this.y = ( m13 - m31 ) / s;
  924. this.z = ( m21 - m12 ) / s;
  925. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  926. return this;
  927. }
  928. };
  929. /**
  930. * @author alteredq / http://alteredqualia.com/
  931. * @author WestLangley / http://github.com/WestLangley
  932. */
  933. THREE.Matrix3 = function () {
  934. this.elements = new Float32Array(9);
  935. };
  936. THREE.Matrix3.prototype = {
  937. constructor: THREE.Matrix3,
  938. multiplyVector3: function ( v ) {
  939. var te = this.elements;
  940. var vx = v.x, vy = v.y, vz = v.z;
  941. v.x = te[0] * vx + te[3] * vy + te[6] * vz;
  942. v.y = te[1] * vx + te[4] * vy + te[7] * vz;
  943. v.z = te[2] * vx + te[5] * vy + te[8] * vz;
  944. return v;
  945. },
  946. multiplyVector3Array: function ( a ) {
  947. var tmp = THREE.Matrix3.__v1;
  948. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  949. tmp.x = a[ i ];
  950. tmp.y = a[ i + 1 ];
  951. tmp.z = a[ i + 2 ];
  952. this.multiplyVector3( tmp );
  953. a[ i ] = tmp.x;
  954. a[ i + 1 ] = tmp.y;
  955. a[ i + 2 ] = tmp.z;
  956. }
  957. return a;
  958. },
  959. getInverse: function ( matrix ) {
  960. // input: THREE.Matrix4
  961. // ( based on http://code.google.com/p/webgl-mjs/ )
  962. var me = matrix.elements;
  963. var a11 = me[10] * me[5] - me[6] * me[9];
  964. var a21 = - me[10] * me[1] + me[2] * me[9];
  965. var a31 = me[6] * me[1] - me[2] * me[5];
  966. var a12 = - me[10] * me[4] + me[6] * me[8];
  967. var a22 = me[10] * me[0] - me[2] * me[8];
  968. var a32 = - me[6] * me[0] + me[2] * me[4];
  969. var a13 = me[9] * me[4] - me[5] * me[8];
  970. var a23 = - me[9] * me[0] + me[1] * me[8];
  971. var a33 = me[5] * me[0] - me[1] * me[4];
  972. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  973. // no inverse
  974. if ( det === 0 ) {
  975. console.warn( "Matrix3.getInverse(): determinant == 0" );
  976. }
  977. var idet = 1.0 / det;
  978. var m = this.elements;
  979. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  980. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  981. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  982. return this;
  983. },
  984. transpose: function () {
  985. var tmp, m = this.elements;
  986. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  987. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  988. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  989. return this;
  990. },
  991. transposeIntoArray: function ( r ) {
  992. var m = this.m;
  993. r[ 0 ] = m[ 0 ];
  994. r[ 1 ] = m[ 3 ];
  995. r[ 2 ] = m[ 6 ];
  996. r[ 3 ] = m[ 1 ];
  997. r[ 4 ] = m[ 4 ];
  998. r[ 5 ] = m[ 7 ];
  999. r[ 6 ] = m[ 2 ];
  1000. r[ 7 ] = m[ 5 ];
  1001. r[ 8 ] = m[ 8 ];
  1002. return this;
  1003. }
  1004. };
  1005. THREE.Matrix3.__v1 = new THREE.Vector3();/**
  1006. * @author mrdoob / http://mrdoob.com/
  1007. * @author supereggbert / http://www.paulbrunt.co.uk/
  1008. * @author philogb / http://blog.thejit.org/
  1009. * @author jordi_ros / http://plattsoft.com
  1010. * @author D1plo1d / http://github.com/D1plo1d
  1011. * @author alteredq / http://alteredqualia.com/
  1012. * @author mikael emtinger / http://gomo.se/
  1013. * @author timknip / http://www.floorplanner.com/
  1014. */
  1015. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1016. this.elements = new Float32Array( 16 );
  1017. this.set(
  1018. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1019. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1020. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1021. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1022. );
  1023. };
  1024. THREE.Matrix4.prototype = {
  1025. constructor: THREE.Matrix4,
  1026. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1027. var te = this.elements;
  1028. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1029. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1030. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1031. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1032. return this;
  1033. },
  1034. identity: function () {
  1035. this.set(
  1036. 1, 0, 0, 0,
  1037. 0, 1, 0, 0,
  1038. 0, 0, 1, 0,
  1039. 0, 0, 0, 1
  1040. );
  1041. return this;
  1042. },
  1043. copy: function ( m ) {
  1044. var me = m.elements;
  1045. this.set(
  1046. me[0], me[4], me[8], me[12],
  1047. me[1], me[5], me[9], me[13],
  1048. me[2], me[6], me[10], me[14],
  1049. me[3], me[7], me[11], me[15]
  1050. );
  1051. return this;
  1052. },
  1053. lookAt: function ( eye, target, up ) {
  1054. var te = this.elements;
  1055. var x = THREE.Matrix4.__v1;
  1056. var y = THREE.Matrix4.__v2;
  1057. var z = THREE.Matrix4.__v3;
  1058. z.sub( eye, target ).normalize();
  1059. if ( z.length() === 0 ) {
  1060. z.z = 1;
  1061. }
  1062. x.cross( up, z ).normalize();
  1063. if ( x.length() === 0 ) {
  1064. z.x += 0.0001;
  1065. x.cross( up, z ).normalize();
  1066. }
  1067. y.cross( z, x );
  1068. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1069. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1070. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1071. return this;
  1072. },
  1073. multiply: function ( a, b ) {
  1074. var ae = a.elements;
  1075. var be = b.elements;
  1076. var te = this.elements;
  1077. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1078. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1079. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1080. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1081. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1082. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1083. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1084. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1085. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1086. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1087. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1088. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1089. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1090. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1091. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1092. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1093. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1094. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1095. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1096. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1097. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1098. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1099. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1100. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1101. return this;
  1102. },
  1103. multiplySelf: function ( m ) {
  1104. return this.multiply( this, m );
  1105. },
  1106. multiplyToArray: function ( a, b, r ) {
  1107. var te = this.elements;
  1108. this.multiply( a, b );
  1109. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1110. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1111. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1112. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1113. return this;
  1114. },
  1115. multiplyScalar: function ( s ) {
  1116. var te = this.elements;
  1117. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1118. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1119. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1120. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1121. return this;
  1122. },
  1123. multiplyVector3: function ( v ) {
  1124. var te = this.elements;
  1125. var vx = v.x, vy = v.y, vz = v.z;
  1126. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1127. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1128. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1129. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1130. return v;
  1131. },
  1132. multiplyVector4: function ( v ) {
  1133. var te = this.elements;
  1134. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1135. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1136. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1137. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1138. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1139. return v;
  1140. },
  1141. multiplyVector3Array: function ( a ) {
  1142. var tmp = THREE.Matrix4.__v1;
  1143. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1144. tmp.x = a[ i ];
  1145. tmp.y = a[ i + 1 ];
  1146. tmp.z = a[ i + 2 ];
  1147. this.multiplyVector3( tmp );
  1148. a[ i ] = tmp.x;
  1149. a[ i + 1 ] = tmp.y;
  1150. a[ i + 2 ] = tmp.z;
  1151. }
  1152. return a;
  1153. },
  1154. rotateAxis: function ( v ) {
  1155. var te = this.elements;
  1156. var vx = v.x, vy = v.y, vz = v.z;
  1157. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1158. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1159. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1160. v.normalize();
  1161. return v;
  1162. },
  1163. crossVector: function ( a ) {
  1164. var te = this.elements;
  1165. var v = new THREE.Vector4();
  1166. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1167. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1168. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1169. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1170. return v;
  1171. },
  1172. determinant: function () {
  1173. var te = this.elements;
  1174. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1175. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1176. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1177. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1178. //TODO: make this more efficient
  1179. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1180. return (
  1181. n14 * n23 * n32 * n41-
  1182. n13 * n24 * n32 * n41-
  1183. n14 * n22 * n33 * n41+
  1184. n12 * n24 * n33 * n41+
  1185. n13 * n22 * n34 * n41-
  1186. n12 * n23 * n34 * n41-
  1187. n14 * n23 * n31 * n42+
  1188. n13 * n24 * n31 * n42+
  1189. n14 * n21 * n33 * n42-
  1190. n11 * n24 * n33 * n42-
  1191. n13 * n21 * n34 * n42+
  1192. n11 * n23 * n34 * n42+
  1193. n14 * n22 * n31 * n43-
  1194. n12 * n24 * n31 * n43-
  1195. n14 * n21 * n32 * n43+
  1196. n11 * n24 * n32 * n43+
  1197. n12 * n21 * n34 * n43-
  1198. n11 * n22 * n34 * n43-
  1199. n13 * n22 * n31 * n44+
  1200. n12 * n23 * n31 * n44+
  1201. n13 * n21 * n32 * n44-
  1202. n11 * n23 * n32 * n44-
  1203. n12 * n21 * n33 * n44+
  1204. n11 * n22 * n33 * n44
  1205. );
  1206. },
  1207. transpose: function () {
  1208. var te = this.elements;
  1209. var tmp;
  1210. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1211. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1212. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1213. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1214. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1215. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1216. return this;
  1217. },
  1218. flattenToArray: function ( flat ) {
  1219. var te = this.elements;
  1220. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1221. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1222. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1223. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1224. return flat;
  1225. },
  1226. flattenToArrayOffset: function( flat, offset ) {
  1227. var te = this.elements;
  1228. flat[ offset ] = te[0];
  1229. flat[ offset + 1 ] = te[1];
  1230. flat[ offset + 2 ] = te[2];
  1231. flat[ offset + 3 ] = te[3];
  1232. flat[ offset + 4 ] = te[4];
  1233. flat[ offset + 5 ] = te[5];
  1234. flat[ offset + 6 ] = te[6];
  1235. flat[ offset + 7 ] = te[7];
  1236. flat[ offset + 8 ] = te[8];
  1237. flat[ offset + 9 ] = te[9];
  1238. flat[ offset + 10 ] = te[10];
  1239. flat[ offset + 11 ] = te[11];
  1240. flat[ offset + 12 ] = te[12];
  1241. flat[ offset + 13 ] = te[13];
  1242. flat[ offset + 14 ] = te[14];
  1243. flat[ offset + 15 ] = te[15];
  1244. return flat;
  1245. },
  1246. getPosition: function () {
  1247. var te = this.elements;
  1248. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1249. },
  1250. setPosition: function ( v ) {
  1251. var te = this.elements;
  1252. te[12] = v.x;
  1253. te[13] = v.y;
  1254. te[14] = v.z;
  1255. return this;
  1256. },
  1257. getColumnX: function () {
  1258. var te = this.elements;
  1259. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1260. },
  1261. getColumnY: function () {
  1262. var te = this.elements;
  1263. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1264. },
  1265. getColumnZ: function() {
  1266. var te = this.elements;
  1267. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1268. },
  1269. getInverse: function ( m ) {
  1270. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1271. var te = this.elements;
  1272. var me = m.elements;
  1273. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1274. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1275. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1276. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1277. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1278. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1279. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1280. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1281. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1282. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1283. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1284. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1285. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1286. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1287. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1288. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1289. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1290. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1291. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1292. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1293. this.multiplyScalar( 1 / m.determinant() );
  1294. return this;
  1295. },
  1296. setRotationFromEuler: function ( v, order ) {
  1297. var te = this.elements;
  1298. var x = v.x, y = v.y, z = v.z;
  1299. var a = Math.cos( x ), b = Math.sin( x );
  1300. var c = Math.cos( y ), d = Math.sin( y );
  1301. var e = Math.cos( z ), f = Math.sin( z );
  1302. if ( order === undefined || order === 'XYZ' ) {
  1303. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1304. te[0] = c * e;
  1305. te[4] = - c * f;
  1306. te[8] = d;
  1307. te[1] = af + be * d;
  1308. te[5] = ae - bf * d;
  1309. te[9] = - b * c;
  1310. te[2] = bf - ae * d;
  1311. te[6] = be + af * d;
  1312. te[10] = a * c;
  1313. } else if ( order === 'YXZ' ) {
  1314. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1315. te[0] = ce + df * b;
  1316. te[4] = de * b - cf;
  1317. te[8] = a * d;
  1318. te[1] = a * f;
  1319. te[5] = a * e;
  1320. te[9] = - b;
  1321. te[2] = cf * b - de;
  1322. te[6] = df + ce * b;
  1323. te[10] = a * c;
  1324. } else if ( order === 'ZXY' ) {
  1325. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1326. te[0] = ce - df * b;
  1327. te[4] = - a * f;
  1328. te[8] = de + cf * b;
  1329. te[1] = cf + de * b;
  1330. te[5] = a * e;
  1331. te[9] = df - ce * b;
  1332. te[2] = - a * d;
  1333. te[6] = b;
  1334. te[10] = a * c;
  1335. } else if ( order === 'ZYX' ) {
  1336. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1337. te[0] = c * e;
  1338. te[4] = be * d - af;
  1339. te[8] = ae * d + bf;
  1340. te[1] = c * f;
  1341. te[5] = bf * d + ae;
  1342. te[9] = af * d - be;
  1343. te[2] = - d;
  1344. te[6] = b * c;
  1345. te[10] = a * c;
  1346. } else if ( order === 'YZX' ) {
  1347. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1348. te[0] = c * e;
  1349. te[4] = bd - ac * f;
  1350. te[8] = bc * f + ad;
  1351. te[1] = f;
  1352. te[5] = a * e;
  1353. te[9] = - b * e;
  1354. te[2] = - d * e;
  1355. te[6] = ad * f + bc;
  1356. te[10] = ac - bd * f;
  1357. } else if ( order === 'XZY' ) {
  1358. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1359. te[0] = c * e;
  1360. te[4] = - f;
  1361. te[8] = d * e;
  1362. te[1] = ac * f + bd;
  1363. te[5] = a * e;
  1364. te[9] = ad * f - bc;
  1365. te[2] = bc * f - ad;
  1366. te[6] = b * e;
  1367. te[10] = bd * f + ac;
  1368. }
  1369. return this;
  1370. },
  1371. setRotationFromQuaternion: function ( q ) {
  1372. var te = this.elements;
  1373. var x = q.x, y = q.y, z = q.z, w = q.w;
  1374. var x2 = x + x, y2 = y + y, z2 = z + z;
  1375. var xx = x * x2, xy = x * y2, xz = x * z2;
  1376. var yy = y * y2, yz = y * z2, zz = z * z2;
  1377. var wx = w * x2, wy = w * y2, wz = w * z2;
  1378. te[0] = 1 - ( yy + zz );
  1379. te[4] = xy - wz;
  1380. te[8] = xz + wy;
  1381. te[1] = xy + wz;
  1382. te[5] = 1 - ( xx + zz );
  1383. te[9] = yz - wx;
  1384. te[2] = xz - wy;
  1385. te[6] = yz + wx;
  1386. te[10] = 1 - ( xx + yy );
  1387. return this;
  1388. },
  1389. compose: function ( translation, rotation, scale ) {
  1390. var te = this.elements;
  1391. var mRotation = THREE.Matrix4.__m1;
  1392. var mScale = THREE.Matrix4.__m2;
  1393. mRotation.identity();
  1394. mRotation.setRotationFromQuaternion( rotation );
  1395. mScale.makeScale( scale.x, scale.y, scale.z );
  1396. this.multiply( mRotation, mScale );
  1397. te[12] = translation.x;
  1398. te[13] = translation.y;
  1399. te[14] = translation.z;
  1400. return this;
  1401. },
  1402. decompose: function ( translation, rotation, scale ) {
  1403. var te = this.elements;
  1404. // grab the axis vectors
  1405. var x = THREE.Matrix4.__v1;
  1406. var y = THREE.Matrix4.__v2;
  1407. var z = THREE.Matrix4.__v3;
  1408. x.set( te[0], te[1], te[2] );
  1409. y.set( te[4], te[5], te[6] );
  1410. z.set( te[8], te[9], te[10] );
  1411. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1412. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1413. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1414. scale.x = x.length();
  1415. scale.y = y.length();
  1416. scale.z = z.length();
  1417. translation.x = te[12];
  1418. translation.y = te[13];
  1419. translation.z = te[14];
  1420. // scale the rotation part
  1421. var matrix = THREE.Matrix4.__m1;
  1422. matrix.copy( this );
  1423. matrix.elements[0] /= scale.x;
  1424. matrix.elements[1] /= scale.x;
  1425. matrix.elements[2] /= scale.x;
  1426. matrix.elements[4] /= scale.y;
  1427. matrix.elements[5] /= scale.y;
  1428. matrix.elements[6] /= scale.y;
  1429. matrix.elements[8] /= scale.z;
  1430. matrix.elements[9] /= scale.z;
  1431. matrix.elements[10] /= scale.z;
  1432. rotation.setFromRotationMatrix( matrix );
  1433. return [ translation, rotation, scale ];
  1434. },
  1435. extractPosition: function ( m ) {
  1436. var te = this.elements;
  1437. var me = m.elements;
  1438. te[12] = me[12];
  1439. te[13] = me[13];
  1440. te[14] = me[14];
  1441. return this;
  1442. },
  1443. extractRotation: function ( m ) {
  1444. var te = this.elements;
  1445. var me = m.elements;
  1446. var vector = THREE.Matrix4.__v1;
  1447. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1448. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1449. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1450. te[0] = me[0] * scaleX;
  1451. te[1] = me[1] * scaleX;
  1452. te[2] = me[2] * scaleX;
  1453. te[4] = me[4] * scaleY;
  1454. te[5] = me[5] * scaleY;
  1455. te[6] = me[6] * scaleY;
  1456. te[8] = me[8] * scaleZ;
  1457. te[9] = me[9] * scaleZ;
  1458. te[10] = me[10] * scaleZ;
  1459. return this;
  1460. },
  1461. //
  1462. translate: function ( v ) {
  1463. var te = this.elements;
  1464. var x = v.x, y = v.y, z = v.z;
  1465. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1466. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1467. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1468. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1469. return this;
  1470. },
  1471. rotateX: function ( angle ) {
  1472. var te = this.elements;
  1473. var m12 = te[4];
  1474. var m22 = te[5];
  1475. var m32 = te[6];
  1476. var m42 = te[7];
  1477. var m13 = te[8];
  1478. var m23 = te[9];
  1479. var m33 = te[10];
  1480. var m43 = te[11];
  1481. var c = Math.cos( angle );
  1482. var s = Math.sin( angle );
  1483. te[4] = c * m12 + s * m13;
  1484. te[5] = c * m22 + s * m23;
  1485. te[6] = c * m32 + s * m33;
  1486. te[7] = c * m42 + s * m43;
  1487. te[8] = c * m13 - s * m12;
  1488. te[9] = c * m23 - s * m22;
  1489. te[10] = c * m33 - s * m32;
  1490. te[11] = c * m43 - s * m42;
  1491. return this;
  1492. },
  1493. rotateY: function ( angle ) {
  1494. var te = this.elements;
  1495. var m11 = te[0];
  1496. var m21 = te[1];
  1497. var m31 = te[2];
  1498. var m41 = te[3];
  1499. var m13 = te[8];
  1500. var m23 = te[9];
  1501. var m33 = te[10];
  1502. var m43 = te[11];
  1503. var c = Math.cos( angle );
  1504. var s = Math.sin( angle );
  1505. te[0] = c * m11 - s * m13;
  1506. te[1] = c * m21 - s * m23;
  1507. te[2] = c * m31 - s * m33;
  1508. te[3] = c * m41 - s * m43;
  1509. te[8] = c * m13 + s * m11;
  1510. te[9] = c * m23 + s * m21;
  1511. te[10] = c * m33 + s * m31;
  1512. te[11] = c * m43 + s * m41;
  1513. return this;
  1514. },
  1515. rotateZ: function ( angle ) {
  1516. var te = this.elements;
  1517. var m11 = te[0];
  1518. var m21 = te[1];
  1519. var m31 = te[2];
  1520. var m41 = te[3];
  1521. var m12 = te[4];
  1522. var m22 = te[5];
  1523. var m32 = te[6];
  1524. var m42 = te[7];
  1525. var c = Math.cos( angle );
  1526. var s = Math.sin( angle );
  1527. te[0] = c * m11 + s * m12;
  1528. te[1] = c * m21 + s * m22;
  1529. te[2] = c * m31 + s * m32;
  1530. te[3] = c * m41 + s * m42;
  1531. te[4] = c * m12 - s * m11;
  1532. te[5] = c * m22 - s * m21;
  1533. te[6] = c * m32 - s * m31;
  1534. te[7] = c * m42 - s * m41;
  1535. return this;
  1536. },
  1537. rotateByAxis: function ( axis, angle ) {
  1538. var te = this.elements;
  1539. // optimize by checking axis
  1540. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1541. return this.rotateX( angle );
  1542. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1543. return this.rotateY( angle );
  1544. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1545. return this.rotateZ( angle );
  1546. }
  1547. var x = axis.x, y = axis.y, z = axis.z;
  1548. var n = Math.sqrt(x * x + y * y + z * z);
  1549. x /= n;
  1550. y /= n;
  1551. z /= n;
  1552. var xx = x * x, yy = y * y, zz = z * z;
  1553. var c = Math.cos( angle );
  1554. var s = Math.sin( angle );
  1555. var oneMinusCosine = 1 - c;
  1556. var xy = x * y * oneMinusCosine;
  1557. var xz = x * z * oneMinusCosine;
  1558. var yz = y * z * oneMinusCosine;
  1559. var xs = x * s;
  1560. var ys = y * s;
  1561. var zs = z * s;
  1562. var r11 = xx + (1 - xx) * c;
  1563. var r21 = xy + zs;
  1564. var r31 = xz - ys;
  1565. var r12 = xy - zs;
  1566. var r22 = yy + (1 - yy) * c;
  1567. var r32 = yz + xs;
  1568. var r13 = xz + ys;
  1569. var r23 = yz - xs;
  1570. var r33 = zz + (1 - zz) * c;
  1571. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1572. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1573. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1574. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1575. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1576. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1577. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1578. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1579. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1580. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1581. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1582. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1583. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1584. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1585. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1586. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1587. return this;
  1588. },
  1589. scale: function ( v ) {
  1590. var te = this.elements;
  1591. var x = v.x, y = v.y, z = v.z;
  1592. te[0] *= x; te[4] *= y; te[8] *= z;
  1593. te[1] *= x; te[5] *= y; te[9] *= z;
  1594. te[2] *= x; te[6] *= y; te[10] *= z;
  1595. te[3] *= x; te[7] *= y; te[11] *= z;
  1596. return this;
  1597. },
  1598. getMaxScaleOnAxis: function () {
  1599. var te = this.elements;
  1600. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  1601. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  1602. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  1603. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  1604. },
  1605. //
  1606. makeTranslation: function ( x, y, z ) {
  1607. this.set(
  1608. 1, 0, 0, x,
  1609. 0, 1, 0, y,
  1610. 0, 0, 1, z,
  1611. 0, 0, 0, 1
  1612. );
  1613. return this;
  1614. },
  1615. makeRotationX: function ( theta ) {
  1616. var c = Math.cos( theta ), s = Math.sin( theta );
  1617. this.set(
  1618. 1, 0, 0, 0,
  1619. 0, c, -s, 0,
  1620. 0, s, c, 0,
  1621. 0, 0, 0, 1
  1622. );
  1623. return this;
  1624. },
  1625. makeRotationY: function ( theta ) {
  1626. var c = Math.cos( theta ), s = Math.sin( theta );
  1627. this.set(
  1628. c, 0, s, 0,
  1629. 0, 1, 0, 0,
  1630. -s, 0, c, 0,
  1631. 0, 0, 0, 1
  1632. );
  1633. return this;
  1634. },
  1635. makeRotationZ: function ( theta ) {
  1636. var c = Math.cos( theta ), s = Math.sin( theta );
  1637. this.set(
  1638. c, -s, 0, 0,
  1639. s, c, 0, 0,
  1640. 0, 0, 1, 0,
  1641. 0, 0, 0, 1
  1642. );
  1643. return this;
  1644. },
  1645. makeRotationAxis: function ( axis, angle ) {
  1646. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1647. var c = Math.cos( angle );
  1648. var s = Math.sin( angle );
  1649. var t = 1 - c;
  1650. var x = axis.x, y = axis.y, z = axis.z;
  1651. var tx = t * x, ty = t * y;
  1652. this.set(
  1653. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1654. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1655. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1656. 0, 0, 0, 1
  1657. );
  1658. return this;
  1659. },
  1660. makeScale: function ( x, y, z ) {
  1661. this.set(
  1662. x, 0, 0, 0,
  1663. 0, y, 0, 0,
  1664. 0, 0, z, 0,
  1665. 0, 0, 0, 1
  1666. );
  1667. return this;
  1668. },
  1669. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1670. var te = this.elements;
  1671. var x = 2 * near / ( right - left );
  1672. var y = 2 * near / ( top - bottom );
  1673. var a = ( right + left ) / ( right - left );
  1674. var b = ( top + bottom ) / ( top - bottom );
  1675. var c = - ( far + near ) / ( far - near );
  1676. var d = - 2 * far * near / ( far - near );
  1677. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1678. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1679. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1680. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1681. return this;
  1682. },
  1683. makePerspective: function ( fov, aspect, near, far ) {
  1684. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1685. var ymin = - ymax;
  1686. var xmin = ymin * aspect;
  1687. var xmax = ymax * aspect;
  1688. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1689. },
  1690. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1691. var te = this.elements;
  1692. var w = right - left;
  1693. var h = top - bottom;
  1694. var p = far - near;
  1695. var x = ( right + left ) / w;
  1696. var y = ( top + bottom ) / h;
  1697. var z = ( far + near ) / p;
  1698. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1699. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1700. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1701. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1702. return this;
  1703. },
  1704. clone: function () {
  1705. var te = this.elements;
  1706. return new THREE.Matrix4(
  1707. te[0], te[4], te[8], te[12],
  1708. te[1], te[5], te[9], te[13],
  1709. te[2], te[6], te[10], te[14],
  1710. te[3], te[7], te[11], te[15]
  1711. );
  1712. }
  1713. };
  1714. THREE.Matrix4.__v1 = new THREE.Vector3();
  1715. THREE.Matrix4.__v2 = new THREE.Vector3();
  1716. THREE.Matrix4.__v3 = new THREE.Vector3();
  1717. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1718. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1719. /**
  1720. * https://github.com/mrdoob/eventtarget.js/
  1721. */
  1722. THREE.EventTarget = function () {
  1723. var listeners = {};
  1724. this.addEventListener = function ( type, listener ) {
  1725. if ( listeners[ type ] === undefined ) {
  1726. listeners[ type ] = [];
  1727. }
  1728. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1729. listeners[ type ].push( listener );
  1730. }
  1731. };
  1732. this.dispatchEvent = function ( event ) {
  1733. for ( var listener in listeners[ event.type ] ) {
  1734. listeners[ event.type ][ listener ]( event );
  1735. }
  1736. };
  1737. this.removeEventListener = function ( type, listener ) {
  1738. var index = listeners[ type ].indexOf( listener );
  1739. if ( index !== - 1 ) {
  1740. listeners[ type ].splice( index, 1 );
  1741. }
  1742. };
  1743. };
  1744. /**
  1745. * @author mrdoob / http://mrdoob.com/
  1746. * @author alteredq / http://alteredqualia.com/
  1747. */
  1748. THREE.Frustum = function ( ) {
  1749. this.planes = [
  1750. new THREE.Vector4(),
  1751. new THREE.Vector4(),
  1752. new THREE.Vector4(),
  1753. new THREE.Vector4(),
  1754. new THREE.Vector4(),
  1755. new THREE.Vector4()
  1756. ];
  1757. };
  1758. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  1759. var plane;
  1760. var planes = this.planes;
  1761. var me = m.elements;
  1762. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  1763. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  1764. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  1765. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  1766. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  1767. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  1768. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  1769. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  1770. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  1771. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  1772. for ( var i = 0; i < 6; i ++ ) {
  1773. plane = planes[ i ];
  1774. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  1775. }
  1776. };
  1777. THREE.Frustum.prototype.contains = function ( object ) {
  1778. var distance = 0.0;
  1779. var planes = this.planes;
  1780. var matrix = object.matrixWorld;
  1781. var me = matrix.elements;
  1782. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  1783. for ( var i = 0; i < 6; i ++ ) {
  1784. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  1785. if ( distance <= radius ) return false;
  1786. }
  1787. return true;
  1788. };
  1789. THREE.Frustum.__v1 = new THREE.Vector3();
  1790. /**
  1791. * @author mrdoob / http://mrdoob.com/
  1792. */
  1793. ( function ( THREE ) {
  1794. THREE.Ray = function ( origin, direction, near, far ) {
  1795. this.origin = origin || new THREE.Vector3();
  1796. this.direction = direction || new THREE.Vector3();
  1797. this.near = near || 0;
  1798. this.far = far || Infinity;
  1799. };
  1800. var originCopy = new THREE.Vector3();
  1801. var localOriginCopy = new THREE.Vector3();
  1802. var localDirectionCopy = new THREE.Vector3();
  1803. var vector = new THREE.Vector3();
  1804. var normal = new THREE.Vector3();
  1805. var intersectPoint = new THREE.Vector3();
  1806. var inverseMatrix = new THREE.Matrix4();
  1807. var descSort = function ( a, b ) {
  1808. return a.distance - b.distance;
  1809. };
  1810. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  1811. var distanceFromIntersection = function ( origin, direction, position ) {
  1812. v0.sub( position, origin );
  1813. var dot = v0.dot( direction );
  1814. var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  1815. var distance = position.distanceTo( intersect );
  1816. return distance;
  1817. };
  1818. // http://www.blackpawn.com/texts/pointinpoly/default.html
  1819. var pointInFace3 = function ( p, a, b, c ) {
  1820. v0.sub( c, a );
  1821. v1.sub( b, a );
  1822. v2.sub( p, a );
  1823. var dot00 = v0.dot( v0 );
  1824. var dot01 = v0.dot( v1 );
  1825. var dot02 = v0.dot( v2 );
  1826. var dot11 = v1.dot( v1 );
  1827. var dot12 = v1.dot( v2 );
  1828. var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  1829. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  1830. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  1831. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  1832. };
  1833. var intersectObject = function ( object, ray, intersects ) {
  1834. if ( object instanceof THREE.Particle ) {
  1835. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1836. if ( distance > object.scale.x ) {
  1837. return intersects;
  1838. }
  1839. intersects.push( {
  1840. distance: distance,
  1841. point: object.position,
  1842. face: null,
  1843. object: object
  1844. } );
  1845. } else if ( object instanceof THREE.Mesh ) {
  1846. // Checking boundingSphere
  1847. var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
  1848. // Checking distance to ray
  1849. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1850. if ( distance > scaledRadius) {
  1851. return intersects;
  1852. }
  1853. // Checking faces
  1854. var geometry = object.geometry;
  1855. var vertices = geometry.vertices;
  1856. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  1857. var geometryMaterials = ( isFaceMaterial && object.material.materials.length > 0 ) ? object.material.materials : object.geometry.materials;
  1858. var side = object.material.side;
  1859. var a, b, c, d;
  1860. var precision = ray.precision;
  1861. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  1862. originCopy.copy( ray.origin );
  1863. inverseMatrix.getInverse( object.matrixWorld );
  1864. localOriginCopy.copy( originCopy );
  1865. inverseMatrix.multiplyVector3( localOriginCopy );
  1866. localDirectionCopy.copy( ray.direction );
  1867. inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
  1868. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  1869. var face = geometry.faces[ f ];
  1870. var material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  1871. if ( material === undefined ) continue;
  1872. side = material.side;
  1873. vector.sub( face.centroid, localOriginCopy );
  1874. var normal = face.normal;
  1875. var dot = localDirectionCopy.dot( normal );
  1876. // bail if ray and plane are parallel
  1877. if ( Math.abs( dot ) < precision ) continue;
  1878. // calc distance to plane
  1879. var scalar = normal.dot( vector ) / dot;
  1880. // if negative distance, then plane is behind ray
  1881. if ( scalar < 0 ) continue;
  1882. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  1883. intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
  1884. if ( face instanceof THREE.Face3 ) {
  1885. a = vertices[ face.a ];
  1886. b = vertices[ face.b ];
  1887. c = vertices[ face.c ];
  1888. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  1889. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1890. distance = originCopy.distanceTo( point );
  1891. if ( distance < ray.near || distance > ray.far ) continue;
  1892. intersects.push( {
  1893. distance: distance,
  1894. point: point,
  1895. face: face,
  1896. faceIndex: f,
  1897. object: object
  1898. } );
  1899. }
  1900. } else if ( face instanceof THREE.Face4 ) {
  1901. a = vertices[ face.a ];
  1902. b = vertices[ face.b ];
  1903. c = vertices[ face.c ];
  1904. d = vertices[ face.d ];
  1905. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  1906. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1907. distance = originCopy.distanceTo( point );
  1908. if ( distance < ray.near || distance > ray.far ) continue;
  1909. intersects.push( {
  1910. distance: distance,
  1911. point: point,
  1912. face: face,
  1913. faceIndex: f,
  1914. object: object
  1915. } );
  1916. }
  1917. }
  1918. }
  1919. }
  1920. }
  1921. };
  1922. var intersectDescendants = function ( object, ray, intersects ) {
  1923. var descendants = object.getDescendants();
  1924. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  1925. intersectObject( descendants[ i ], ray, intersects );
  1926. }
  1927. };
  1928. //
  1929. THREE.Ray.prototype.precision = 0.0001;
  1930. THREE.Ray.prototype.set = function ( origin, direction ) {
  1931. this.origin = origin;
  1932. this.direction = direction;
  1933. };
  1934. THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
  1935. var intersects = [];
  1936. if ( recursive === true ) {
  1937. intersectDescendants( object, this, intersects );
  1938. }
  1939. intersectObject( object, this, intersects );
  1940. intersects.sort( descSort );
  1941. return intersects;
  1942. };
  1943. THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
  1944. var intersects = [];
  1945. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  1946. intersectObject( objects[ i ], this, intersects );
  1947. if ( recursive === true ) {
  1948. intersectDescendants( objects[ i ], this, intersects );
  1949. }
  1950. }
  1951. intersects.sort( descSort );
  1952. return intersects;
  1953. };
  1954. }( THREE ) );
  1955. /**
  1956. * @author mrdoob / http://mrdoob.com/
  1957. */
  1958. THREE.Rectangle = function () {
  1959. var _left = 0;
  1960. var _top = 0;
  1961. var _right = 0;
  1962. var _bottom = 0;
  1963. var _width = 0;
  1964. var _height = 0;
  1965. var _isEmpty = true;
  1966. function resize() {
  1967. _width = _right - _left;
  1968. _height = _bottom - _top;
  1969. }
  1970. this.getX = function () {
  1971. return _left;
  1972. };
  1973. this.getY = function () {
  1974. return _top;
  1975. };
  1976. this.getWidth = function () {
  1977. return _width;
  1978. };
  1979. this.getHeight = function () {
  1980. return _height;
  1981. };
  1982. this.getLeft = function() {
  1983. return _left;
  1984. };
  1985. this.getTop = function() {
  1986. return _top;
  1987. };
  1988. this.getRight = function() {
  1989. return _right;
  1990. };
  1991. this.getBottom = function() {
  1992. return _bottom;
  1993. };
  1994. this.set = function ( left, top, right, bottom ) {
  1995. _isEmpty = false;
  1996. _left = left; _top = top;
  1997. _right = right; _bottom = bottom;
  1998. resize();
  1999. };
  2000. this.addPoint = function ( x, y ) {
  2001. if ( _isEmpty === true ) {
  2002. _isEmpty = false;
  2003. _left = x; _top = y;
  2004. _right = x; _bottom = y;
  2005. resize();
  2006. } else {
  2007. _left = _left < x ? _left : x; // Math.min( _left, x );
  2008. _top = _top < y ? _top : y; // Math.min( _top, y );
  2009. _right = _right > x ? _right : x; // Math.max( _right, x );
  2010. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  2011. resize();
  2012. }
  2013. };
  2014. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  2015. if ( _isEmpty === true ) {
  2016. _isEmpty = false;
  2017. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  2018. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  2019. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  2020. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  2021. resize();
  2022. } else {
  2023. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  2024. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  2025. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  2026. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  2027. resize();
  2028. };
  2029. };
  2030. this.addRectangle = function ( r ) {
  2031. if ( _isEmpty === true ) {
  2032. _isEmpty = false;
  2033. _left = r.getLeft(); _top = r.getTop();
  2034. _right = r.getRight(); _bottom = r.getBottom();
  2035. resize();
  2036. } else {
  2037. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  2038. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  2039. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  2040. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  2041. resize();
  2042. }
  2043. };
  2044. this.inflate = function ( v ) {
  2045. _left -= v; _top -= v;
  2046. _right += v; _bottom += v;
  2047. resize();
  2048. };
  2049. this.minSelf = function ( r ) {
  2050. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  2051. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  2052. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  2053. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  2054. resize();
  2055. };
  2056. this.intersects = function ( r ) {
  2057. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  2058. if ( _right < r.getLeft() ) return false;
  2059. if ( _left > r.getRight() ) return false;
  2060. if ( _bottom < r.getTop() ) return false;
  2061. if ( _top > r.getBottom() ) return false;
  2062. return true;
  2063. };
  2064. this.empty = function () {
  2065. _isEmpty = true;
  2066. _left = 0; _top = 0;
  2067. _right = 0; _bottom = 0;
  2068. resize();
  2069. };
  2070. this.isEmpty = function () {
  2071. return _isEmpty;
  2072. };
  2073. };
  2074. /**
  2075. * @author alteredq / http://alteredqualia.com/
  2076. */
  2077. THREE.Math = {
  2078. // Clamp value to range <a, b>
  2079. clamp: function ( x, a, b ) {
  2080. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2081. },
  2082. // Clamp value to range <a, inf)
  2083. clampBottom: function ( x, a ) {
  2084. return x < a ? a : x;
  2085. },
  2086. // Linear mapping from range <a1, a2> to range <b1, b2>
  2087. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2088. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2089. },
  2090. // Random float from <0, 1> with 16 bits of randomness
  2091. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2092. random16: function () {
  2093. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2094. },
  2095. // Random integer from <low, high> interval
  2096. randInt: function ( low, high ) {
  2097. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2098. },
  2099. // Random float from <low, high> interval
  2100. randFloat: function ( low, high ) {
  2101. return low + Math.random() * ( high - low );
  2102. },
  2103. // Random float from <-range/2, range/2> interval
  2104. randFloatSpread: function ( range ) {
  2105. return range * ( 0.5 - Math.random() );
  2106. },
  2107. sign: function ( x ) {
  2108. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2109. }
  2110. };
  2111. /**
  2112. * @author mrdoob / http://mrdoob.com/
  2113. * @author mikael emtinger / http://gomo.se/
  2114. * @author alteredq / http://alteredqualia.com/
  2115. */
  2116. THREE.Object3D = function () {
  2117. THREE.Object3DLibrary.push( this );
  2118. this.id = THREE.Object3DIdCount ++;
  2119. this.name = '';
  2120. this.properties = {};
  2121. this.parent = undefined;
  2122. this.children = [];
  2123. this.up = new THREE.Vector3( 0, 1, 0 );
  2124. this.position = new THREE.Vector3();
  2125. this.rotation = new THREE.Vector3();
  2126. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  2127. this.scale = new THREE.Vector3( 1, 1, 1 );
  2128. this.renderDepth = null;
  2129. this.rotationAutoUpdate = true;
  2130. this.matrix = new THREE.Matrix4();
  2131. this.matrixWorld = new THREE.Matrix4();
  2132. this.matrixRotationWorld = new THREE.Matrix4();
  2133. this.matrixAutoUpdate = true;
  2134. this.matrixWorldNeedsUpdate = true;
  2135. this.quaternion = new THREE.Quaternion();
  2136. this.useQuaternion = false;
  2137. this.boundRadius = 0.0;
  2138. this.boundRadiusScale = 1.0;
  2139. this.visible = true;
  2140. this.castShadow = false;
  2141. this.receiveShadow = false;
  2142. this.frustumCulled = true;
  2143. this._vector = new THREE.Vector3();
  2144. };
  2145. THREE.Object3D.prototype = {
  2146. constructor: THREE.Object3D,
  2147. applyMatrix: function ( matrix ) {
  2148. this.matrix.multiply( matrix, this.matrix );
  2149. this.scale.getScaleFromMatrix( this.matrix );
  2150. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2151. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2152. this.position.getPositionFromMatrix( this.matrix );
  2153. },
  2154. translate: function ( distance, axis ) {
  2155. this.matrix.rotateAxis( axis );
  2156. this.position.addSelf( axis.multiplyScalar( distance ) );
  2157. },
  2158. translateX: function ( distance ) {
  2159. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2160. },
  2161. translateY: function ( distance ) {
  2162. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2163. },
  2164. translateZ: function ( distance ) {
  2165. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2166. },
  2167. localToWorld: function ( vector ) {
  2168. return this.matrixWorld.multiplyVector3( vector );
  2169. },
  2170. worldToLocal: function ( vector ) {
  2171. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2172. },
  2173. lookAt: function ( vector ) {
  2174. // TODO: Add hierarchy support.
  2175. this.matrix.lookAt( vector, this.position, this.up );
  2176. if ( this.rotationAutoUpdate ) {
  2177. if ( this.useQuaternion === false ) {
  2178. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2179. } else {
  2180. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  2181. }
  2182. }
  2183. },
  2184. add: function ( object ) {
  2185. if ( object === this ) {
  2186. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2187. return;
  2188. }
  2189. if ( object instanceof THREE.Object3D ) {
  2190. if ( object.parent !== undefined ) {
  2191. object.parent.remove( object );
  2192. }
  2193. object.parent = this;
  2194. this.children.push( object );
  2195. // add to scene
  2196. var scene = this;
  2197. while ( scene.parent !== undefined ) {
  2198. scene = scene.parent;
  2199. }
  2200. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2201. scene.__addObject( object );
  2202. }
  2203. }
  2204. },
  2205. remove: function ( object ) {
  2206. var index = this.children.indexOf( object );
  2207. if ( index !== - 1 ) {
  2208. object.parent = undefined;
  2209. this.children.splice( index, 1 );
  2210. // remove from scene
  2211. var scene = this;
  2212. while ( scene.parent !== undefined ) {
  2213. scene = scene.parent;
  2214. }
  2215. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2216. scene.__removeObject( object );
  2217. }
  2218. }
  2219. },
  2220. traverse: function ( callback ) {
  2221. callback( this );
  2222. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2223. this.children[ i ].traverse( callback );
  2224. }
  2225. },
  2226. getChildByName: function ( name, recursive ) {
  2227. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2228. var child = this.children[ i ];
  2229. if ( child.name === name ) {
  2230. return child;
  2231. }
  2232. if ( recursive === true ) {
  2233. child = child.getChildByName( name, recursive );
  2234. if ( child !== undefined ) {
  2235. return child;
  2236. }
  2237. }
  2238. }
  2239. return undefined;
  2240. },
  2241. getDescendants: function ( array ) {
  2242. if ( array === undefined ) array = [];
  2243. Array.prototype.push.apply( array, this.children );
  2244. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2245. this.children[ i ].getDescendants( array );
  2246. }
  2247. return array;
  2248. },
  2249. updateMatrix: function () {
  2250. this.matrix.setPosition( this.position );
  2251. if ( this.useQuaternion === false ) {
  2252. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2253. } else {
  2254. this.matrix.setRotationFromQuaternion( this.quaternion );
  2255. }
  2256. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2257. this.matrix.scale( this.scale );
  2258. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2259. }
  2260. this.matrixWorldNeedsUpdate = true;
  2261. },
  2262. updateMatrixWorld: function ( force ) {
  2263. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2264. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2265. if ( this.parent === undefined ) {
  2266. this.matrixWorld.copy( this.matrix );
  2267. } else {
  2268. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2269. }
  2270. this.matrixWorldNeedsUpdate = false;
  2271. force = true;
  2272. }
  2273. // update children
  2274. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2275. this.children[ i ].updateMatrixWorld( force );
  2276. }
  2277. },
  2278. clone: function ( object ) {
  2279. if ( object === undefined ) object = new THREE.Object3D();
  2280. object.name = this.name;
  2281. object.up.copy( this.up );
  2282. object.position.copy( this.position );
  2283. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  2284. object.eulerOrder = this.eulerOrder;
  2285. object.scale.copy( this.scale );
  2286. object.renderDepth = this.renderDepth;
  2287. object.rotationAutoUpdate = this.rotationAutoUpdate;
  2288. object.matrix.copy( this.matrix );
  2289. object.matrixWorld.copy( this.matrixWorld );
  2290. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  2291. object.matrixAutoUpdate = this.matrixAutoUpdate;
  2292. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  2293. object.quaternion.copy( this.quaternion );
  2294. object.useQuaternion = this.useQuaternion;
  2295. object.boundRadius = this.boundRadius;
  2296. object.boundRadiusScale = this.boundRadiusScale;
  2297. object.visible = this.visible;
  2298. object.castShadow = this.castShadow;
  2299. object.receiveShadow = this.receiveShadow;
  2300. object.frustumCulled = this.frustumCulled;
  2301. for ( var i = 0; i < this.children.length; i ++ ) {
  2302. var child = this.children[ i ];
  2303. object.add( child.clone() );
  2304. }
  2305. return object;
  2306. },
  2307. deallocate: function () {
  2308. var index = THREE.Object3DLibrary.indexOf( this );
  2309. if ( index !== -1 ) THREE.Object3DLibrary.splice( index, 1 );
  2310. }
  2311. };
  2312. THREE.Object3D.__m1 = new THREE.Matrix4();
  2313. THREE.Object3D.defaultEulerOrder = 'XYZ',
  2314. THREE.Object3DIdCount = 0;
  2315. THREE.Object3DLibrary = [];
  2316. /**
  2317. * @author mrdoob / http://mrdoob.com/
  2318. * @author supereggbert / http://www.paulbrunt.co.uk/
  2319. * @author julianwa / https://github.com/julianwa
  2320. */
  2321. THREE.Projector = function() {
  2322. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  2323. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  2324. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  2325. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  2326. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  2327. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  2328. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  2329. _vector3 = new THREE.Vector3(),
  2330. _vector4 = new THREE.Vector4(),
  2331. _viewProjectionMatrix = new THREE.Matrix4(),
  2332. _modelViewProjectionMatrix = new THREE.Matrix4(),
  2333. _normalMatrix = new THREE.Matrix3(),
  2334. _frustum = new THREE.Frustum(),
  2335. _clippedVertex1PositionScreen = new THREE.Vector4(),
  2336. _clippedVertex2PositionScreen = new THREE.Vector4(),
  2337. _face3VertexNormals;
  2338. this.projectVector = function ( vector, camera ) {
  2339. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2340. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2341. _viewProjectionMatrix.multiplyVector3( vector );
  2342. return vector;
  2343. };
  2344. this.unprojectVector = function ( vector, camera ) {
  2345. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  2346. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  2347. _viewProjectionMatrix.multiplyVector3( vector );
  2348. return vector;
  2349. };
  2350. this.pickingRay = function ( vector, camera ) {
  2351. var end, ray, t;
  2352. // set two vectors with opposing z values
  2353. vector.z = -1.0;
  2354. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  2355. this.unprojectVector( vector, camera );
  2356. this.unprojectVector( end, camera );
  2357. // find direction from vector to end
  2358. end.subSelf( vector ).normalize();
  2359. return new THREE.Ray( vector, end );
  2360. };
  2361. var projectGraph = function ( root, sortObjects ) {
  2362. _objectCount = 0;
  2363. _renderData.objects.length = 0;
  2364. _renderData.sprites.length = 0;
  2365. _renderData.lights.length = 0;
  2366. var projectObject = function ( parent ) {
  2367. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  2368. var object = parent.children[ c ];
  2369. if ( object.visible === false ) continue;
  2370. if ( object instanceof THREE.Light ) {
  2371. _renderData.lights.push( object );
  2372. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  2373. if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
  2374. _object = getNextObjectInPool();
  2375. _object.object = object;
  2376. if ( object.renderDepth !== null ) {
  2377. _object.z = object.renderDepth;
  2378. } else {
  2379. _vector3.copy( object.matrixWorld.getPosition() );
  2380. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2381. _object.z = _vector3.z;
  2382. }
  2383. _renderData.objects.push( _object );
  2384. }
  2385. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  2386. _object = getNextObjectInPool();
  2387. _object.object = object;
  2388. // TODO: Find an elegant and performant solution and remove this dupe code.
  2389. if ( object.renderDepth !== null ) {
  2390. _object.z = object.renderDepth;
  2391. } else {
  2392. _vector3.copy( object.matrixWorld.getPosition() );
  2393. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2394. _object.z = _vector3.z;
  2395. }
  2396. _renderData.sprites.push( _object );
  2397. } else {
  2398. _object = getNextObjectInPool();
  2399. _object.object = object;
  2400. if ( object.renderDepth !== null ) {
  2401. _object.z = object.renderDepth;
  2402. } else {
  2403. _vector3.copy( object.matrixWorld.getPosition() );
  2404. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2405. _object.z = _vector3.z;
  2406. }
  2407. _renderData.objects.push( _object );
  2408. }
  2409. projectObject( object );
  2410. }
  2411. };
  2412. projectObject( root );
  2413. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  2414. return _renderData;
  2415. };
  2416. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  2417. var near = camera.near, far = camera.far, visible = false,
  2418. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  2419. modelMatrix,
  2420. geometry, geometryMaterials, vertices, vertex, vertexPositionScreen,
  2421. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  2422. v1, v2, v3, v4, isFaceMaterial, material, side;
  2423. _face3Count = 0;
  2424. _face4Count = 0;
  2425. _lineCount = 0;
  2426. _particleCount = 0;
  2427. _renderData.elements.length = 0;
  2428. scene.updateMatrixWorld();
  2429. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2430. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2431. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2432. _frustum.setFromMatrix( _viewProjectionMatrix );
  2433. _renderData = projectGraph( scene, sortObjects );
  2434. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  2435. object = _renderData.objects[ o ].object;
  2436. modelMatrix = object.matrixWorld;
  2437. _vertexCount = 0;
  2438. if ( object instanceof THREE.Mesh ) {
  2439. geometry = object.geometry;
  2440. vertices = geometry.vertices;
  2441. faces = geometry.faces;
  2442. faceVertexUvs = geometry.faceVertexUvs;
  2443. _normalMatrix.getInverse( modelMatrix );
  2444. _normalMatrix.transpose();
  2445. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2446. geometryMaterials = ( isFaceMaterial && object.material.materials.length > 0 ) ? object.material.materials : object.geometry.materials;
  2447. side = object.material.side;
  2448. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  2449. _vertex = getNextVertexInPool();
  2450. _vertex.positionWorld.copy( vertices[ v ] );
  2451. modelMatrix.multiplyVector3( _vertex.positionWorld );
  2452. _vertex.positionScreen.copy( _vertex.positionWorld );
  2453. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  2454. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  2455. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  2456. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  2457. }
  2458. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  2459. face = faces[ f ];
  2460. material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  2461. if ( material === undefined ) continue;
  2462. side = material.side;
  2463. if ( face instanceof THREE.Face3 ) {
  2464. v1 = _vertexPool[ face.a ];
  2465. v2 = _vertexPool[ face.b ];
  2466. v3 = _vertexPool[ face.c ];
  2467. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  2468. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2469. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  2470. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2471. _face = getNextFace3InPool();
  2472. _face.v1.copy( v1 );
  2473. _face.v2.copy( v2 );
  2474. _face.v3.copy( v3 );
  2475. } else {
  2476. continue;
  2477. }
  2478. } else {
  2479. continue;
  2480. }
  2481. } else if ( face instanceof THREE.Face4 ) {
  2482. v1 = _vertexPool[ face.a ];
  2483. v2 = _vertexPool[ face.b ];
  2484. v3 = _vertexPool[ face.c ];
  2485. v4 = _vertexPool[ face.d ];
  2486. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  2487. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2488. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  2489. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  2490. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  2491. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2492. _face = getNextFace4InPool();
  2493. _face.v1.copy( v1 );
  2494. _face.v2.copy( v2 );
  2495. _face.v3.copy( v3 );
  2496. _face.v4.copy( v4 );
  2497. } else {
  2498. continue;
  2499. }
  2500. } else {
  2501. continue;
  2502. }
  2503. }
  2504. _face.normalWorld.copy( face.normal );
  2505. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  2506. _normalMatrix.multiplyVector3( _face.normalWorld ).normalize();
  2507. _face.centroidWorld.copy( face.centroid );
  2508. modelMatrix.multiplyVector3( _face.centroidWorld );
  2509. _face.centroidScreen.copy( _face.centroidWorld );
  2510. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  2511. faceVertexNormals = face.vertexNormals;
  2512. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  2513. normal = _face.vertexNormalsWorld[ n ];
  2514. normal.copy( faceVertexNormals[ n ] );
  2515. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  2516. _normalMatrix.multiplyVector3( normal ).normalize();
  2517. }
  2518. _face.vertexNormalsLength = faceVertexNormals.length;
  2519. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  2520. uvs = faceVertexUvs[ c ][ f ];
  2521. if ( uvs === undefined ) continue;
  2522. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2523. _face.uvs[ c ][ u ] = uvs[ u ];
  2524. }
  2525. }
  2526. _face.color = face.color;
  2527. _face.material = material;
  2528. _face.z = _face.centroidScreen.z;
  2529. _renderData.elements.push( _face );
  2530. }
  2531. } else if ( object instanceof THREE.Line ) {
  2532. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  2533. vertices = object.geometry.vertices;
  2534. v1 = getNextVertexInPool();
  2535. v1.positionScreen.copy( vertices[ 0 ] );
  2536. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2537. // Handle LineStrip and LinePieces
  2538. var step = object.type === THREE.LinePieces ? 2 : 1;
  2539. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2540. v1 = getNextVertexInPool();
  2541. v1.positionScreen.copy( vertices[ v ] );
  2542. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2543. if ( ( v + 1 ) % step > 0 ) continue;
  2544. v2 = _vertexPool[ _vertexCount - 2 ];
  2545. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2546. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2547. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  2548. // Perform the perspective divide
  2549. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2550. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2551. _line = getNextLineInPool();
  2552. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2553. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2554. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2555. _line.material = object.material;
  2556. _renderData.elements.push( _line );
  2557. }
  2558. }
  2559. }
  2560. }
  2561. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2562. object = _renderData.sprites[ o ].object;
  2563. modelMatrix = object.matrixWorld;
  2564. if ( object instanceof THREE.Particle ) {
  2565. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  2566. _viewProjectionMatrix.multiplyVector4( _vector4 );
  2567. _vector4.z /= _vector4.w;
  2568. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2569. _particle = getNextParticleInPool();
  2570. _particle.object = object;
  2571. _particle.x = _vector4.x / _vector4.w;
  2572. _particle.y = _vector4.y / _vector4.w;
  2573. _particle.z = _vector4.z;
  2574. _particle.rotation = object.rotation.z;
  2575. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2576. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2577. _particle.material = object.material;
  2578. _renderData.elements.push( _particle );
  2579. }
  2580. }
  2581. }
  2582. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  2583. return _renderData;
  2584. };
  2585. // Pools
  2586. function getNextObjectInPool() {
  2587. if ( _objectCount === _objectPoolLength ) {
  2588. var object = new THREE.RenderableObject();
  2589. _objectPool.push( object );
  2590. _objectPoolLength ++;
  2591. _objectCount ++;
  2592. return object;
  2593. }
  2594. return _objectPool[ _objectCount ++ ];
  2595. }
  2596. function getNextVertexInPool() {
  2597. if ( _vertexCount === _vertexPoolLength ) {
  2598. var vertex = new THREE.RenderableVertex();
  2599. _vertexPool.push( vertex );
  2600. _vertexPoolLength ++;
  2601. _vertexCount ++;
  2602. return vertex;
  2603. }
  2604. return _vertexPool[ _vertexCount ++ ];
  2605. }
  2606. function getNextFace3InPool() {
  2607. if ( _face3Count === _face3PoolLength ) {
  2608. var face = new THREE.RenderableFace3();
  2609. _face3Pool.push( face );
  2610. _face3PoolLength ++;
  2611. _face3Count ++;
  2612. return face;
  2613. }
  2614. return _face3Pool[ _face3Count ++ ];
  2615. }
  2616. function getNextFace4InPool() {
  2617. if ( _face4Count === _face4PoolLength ) {
  2618. var face = new THREE.RenderableFace4();
  2619. _face4Pool.push( face );
  2620. _face4PoolLength ++;
  2621. _face4Count ++;
  2622. return face;
  2623. }
  2624. return _face4Pool[ _face4Count ++ ];
  2625. }
  2626. function getNextLineInPool() {
  2627. if ( _lineCount === _linePoolLength ) {
  2628. var line = new THREE.RenderableLine();
  2629. _linePool.push( line );
  2630. _linePoolLength ++;
  2631. _lineCount ++
  2632. return line;
  2633. }
  2634. return _linePool[ _lineCount ++ ];
  2635. }
  2636. function getNextParticleInPool() {
  2637. if ( _particleCount === _particlePoolLength ) {
  2638. var particle = new THREE.RenderableParticle();
  2639. _particlePool.push( particle );
  2640. _particlePoolLength ++;
  2641. _particleCount ++
  2642. return particle;
  2643. }
  2644. return _particlePool[ _particleCount ++ ];
  2645. }
  2646. //
  2647. function painterSort( a, b ) {
  2648. return b.z - a.z;
  2649. }
  2650. function clipLine( s1, s2 ) {
  2651. var alpha1 = 0, alpha2 = 1,
  2652. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2653. // Z = -1 and Z = +1, respectively.
  2654. bc1near = s1.z + s1.w,
  2655. bc2near = s2.z + s2.w,
  2656. bc1far = - s1.z + s1.w,
  2657. bc2far = - s2.z + s2.w;
  2658. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2659. // Both vertices lie entirely within all clip planes.
  2660. return true;
  2661. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2662. // Both vertices lie entirely outside one of the clip planes.
  2663. return false;
  2664. } else {
  2665. // The line segment spans at least one clip plane.
  2666. if ( bc1near < 0 ) {
  2667. // v1 lies outside the near plane, v2 inside
  2668. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2669. } else if ( bc2near < 0 ) {
  2670. // v2 lies outside the near plane, v1 inside
  2671. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2672. }
  2673. if ( bc1far < 0 ) {
  2674. // v1 lies outside the far plane, v2 inside
  2675. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2676. } else if ( bc2far < 0 ) {
  2677. // v2 lies outside the far plane, v2 inside
  2678. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2679. }
  2680. if ( alpha2 < alpha1 ) {
  2681. // The line segment spans two boundaries, but is outside both of them.
  2682. // (This can't happen when we're only clipping against just near/far but good
  2683. // to leave the check here for future usage if other clip planes are added.)
  2684. return false;
  2685. } else {
  2686. // Update the s1 and s2 vertices to match the clipped line segment.
  2687. s1.lerpSelf( s2, alpha1 );
  2688. s2.lerpSelf( s1, 1 - alpha2 );
  2689. return true;
  2690. }
  2691. }
  2692. }
  2693. };
  2694. /**
  2695. * @author mikael emtinger / http://gomo.se/
  2696. * @author alteredq / http://alteredqualia.com/
  2697. * @author WestLangley / http://github.com/WestLangley
  2698. */
  2699. THREE.Quaternion = function( x, y, z, w ) {
  2700. this.x = x || 0;
  2701. this.y = y || 0;
  2702. this.z = z || 0;
  2703. this.w = ( w !== undefined ) ? w : 1;
  2704. };
  2705. THREE.Quaternion.prototype = {
  2706. constructor: THREE.Quaternion,
  2707. set: function ( x, y, z, w ) {
  2708. this.x = x;
  2709. this.y = y;
  2710. this.z = z;
  2711. this.w = w;
  2712. return this;
  2713. },
  2714. copy: function ( q ) {
  2715. this.x = q.x;
  2716. this.y = q.y;
  2717. this.z = q.z;
  2718. this.w = q.w;
  2719. return this;
  2720. },
  2721. setFromEuler: function ( v, order ) {
  2722. // http://www.mathworks.com/matlabcentral/fileexchange/
  2723. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2724. // content/SpinCalc.m
  2725. var c1 = Math.cos( v.x / 2 );
  2726. var c2 = Math.cos( v.y / 2 );
  2727. var c3 = Math.cos( v.z / 2 );
  2728. var s1 = Math.sin( v.x / 2 );
  2729. var s2 = Math.sin( v.y / 2 );
  2730. var s3 = Math.sin( v.z / 2 );
  2731. if ( order === undefined || order === 'XYZ' ) {
  2732. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2733. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2734. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2735. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2736. } else if ( order === 'YXZ' ) {
  2737. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2738. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2739. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2740. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2741. } else if ( order === 'ZXY' ) {
  2742. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2743. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2744. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2745. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2746. } else if ( order === 'ZYX' ) {
  2747. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2748. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2749. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2750. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2751. } else if ( order === 'YZX' ) {
  2752. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2753. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2754. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2755. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2756. } else if ( order === 'XZY' ) {
  2757. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2758. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2759. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2760. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2761. }
  2762. return this;
  2763. },
  2764. setFromAxisAngle: function ( axis, angle ) {
  2765. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2766. // axis have to be normalized
  2767. var halfAngle = angle / 2,
  2768. s = Math.sin( halfAngle );
  2769. this.x = axis.x * s;
  2770. this.y = axis.y * s;
  2771. this.z = axis.z * s;
  2772. this.w = Math.cos( halfAngle );
  2773. return this;
  2774. },
  2775. setFromRotationMatrix: function ( m ) {
  2776. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2777. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2778. var te = m.elements,
  2779. m11 = te[0], m12 = te[4], m13 = te[8],
  2780. m21 = te[1], m22 = te[5], m23 = te[9],
  2781. m31 = te[2], m32 = te[6], m33 = te[10],
  2782. trace = m11 + m22 + m33,
  2783. s;
  2784. if( trace > 0 ) {
  2785. s = 0.5 / Math.sqrt( trace + 1.0 );
  2786. this.w = 0.25 / s;
  2787. this.x = ( m32 - m23 ) * s;
  2788. this.y = ( m13 - m31 ) * s;
  2789. this.z = ( m21 - m12 ) * s;
  2790. } else if ( m11 > m22 && m11 > m33 ) {
  2791. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2792. this.w = (m32 - m23 ) / s;
  2793. this.x = 0.25 * s;
  2794. this.y = (m12 + m21 ) / s;
  2795. this.z = (m13 + m31 ) / s;
  2796. } else if (m22 > m33) {
  2797. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2798. this.w = (m13 - m31 ) / s;
  2799. this.x = (m12 + m21 ) / s;
  2800. this.y = 0.25 * s;
  2801. this.z = (m23 + m32 ) / s;
  2802. } else {
  2803. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2804. this.w = ( m21 - m12 ) / s;
  2805. this.x = ( m13 + m31 ) / s;
  2806. this.y = ( m23 + m32 ) / s;
  2807. this.z = 0.25 * s;
  2808. }
  2809. return this;
  2810. },
  2811. inverse: function () {
  2812. this.conjugate().normalize();
  2813. return this;
  2814. },
  2815. conjugate: function () {
  2816. this.x *= -1;
  2817. this.y *= -1;
  2818. this.z *= -1;
  2819. return this;
  2820. },
  2821. length: function () {
  2822. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2823. },
  2824. normalize: function () {
  2825. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2826. if ( l === 0 ) {
  2827. this.x = 0;
  2828. this.y = 0;
  2829. this.z = 0;
  2830. this.w = 1;
  2831. } else {
  2832. l = 1 / l;
  2833. this.x = this.x * l;
  2834. this.y = this.y * l;
  2835. this.z = this.z * l;
  2836. this.w = this.w * l;
  2837. }
  2838. return this;
  2839. },
  2840. multiply: function ( a, b ) {
  2841. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2842. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2843. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2844. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2845. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2846. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2847. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2848. return this;
  2849. },
  2850. multiplySelf: function ( b ) {
  2851. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2852. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2853. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2854. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2855. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2856. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2857. return this;
  2858. },
  2859. multiplyVector3: function ( vector, dest ) {
  2860. if ( !dest ) { dest = vector; }
  2861. var x = vector.x, y = vector.y, z = vector.z,
  2862. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2863. // calculate quat * vector
  2864. var ix = qw * x + qy * z - qz * y,
  2865. iy = qw * y + qz * x - qx * z,
  2866. iz = qw * z + qx * y - qy * x,
  2867. iw = -qx * x - qy * y - qz * z;
  2868. // calculate result * inverse quat
  2869. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2870. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2871. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2872. return dest;
  2873. },
  2874. slerpSelf: function ( qb, t ) {
  2875. var x = this.x, y = this.y, z = this.z, w = this.w;
  2876. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2877. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2878. if ( cosHalfTheta < 0 ) {
  2879. this.w = -qb.w;
  2880. this.x = -qb.x;
  2881. this.y = -qb.y;
  2882. this.z = -qb.z;
  2883. cosHalfTheta = -cosHalfTheta;
  2884. } else {
  2885. this.copy( qb );
  2886. }
  2887. if ( cosHalfTheta >= 1.0 ) {
  2888. this.w = w;
  2889. this.x = x;
  2890. this.y = y;
  2891. this.z = z;
  2892. return this;
  2893. }
  2894. var halfTheta = Math.acos( cosHalfTheta );
  2895. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2896. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2897. this.w = 0.5 * ( w + this.w );
  2898. this.x = 0.5 * ( x + this.x );
  2899. this.y = 0.5 * ( y + this.y );
  2900. this.z = 0.5 * ( z + this.z );
  2901. return this;
  2902. }
  2903. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2904. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2905. this.w = ( w * ratioA + this.w * ratioB );
  2906. this.x = ( x * ratioA + this.x * ratioB );
  2907. this.y = ( y * ratioA + this.y * ratioB );
  2908. this.z = ( z * ratioA + this.z * ratioB );
  2909. return this;
  2910. },
  2911. clone: function () {
  2912. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2913. }
  2914. }
  2915. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2916. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2917. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2918. if ( cosHalfTheta < 0 ) {
  2919. qm.w = -qb.w;
  2920. qm.x = -qb.x;
  2921. qm.y = -qb.y;
  2922. qm.z = -qb.z;
  2923. cosHalfTheta = -cosHalfTheta;
  2924. } else {
  2925. qm.copy( qb );
  2926. }
  2927. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2928. qm.w = qa.w;
  2929. qm.x = qa.x;
  2930. qm.y = qa.y;
  2931. qm.z = qa.z;
  2932. return qm;
  2933. }
  2934. var halfTheta = Math.acos( cosHalfTheta );
  2935. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2936. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2937. qm.w = 0.5 * ( qa.w + qm.w );
  2938. qm.x = 0.5 * ( qa.x + qm.x );
  2939. qm.y = 0.5 * ( qa.y + qm.y );
  2940. qm.z = 0.5 * ( qa.z + qm.z );
  2941. return qm;
  2942. }
  2943. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2944. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2945. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2946. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2947. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2948. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2949. return qm;
  2950. }
  2951. /**
  2952. * @author mrdoob / http://mrdoob.com/
  2953. */
  2954. THREE.Vertex = function ( v ) {
  2955. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  2956. return v;
  2957. };
  2958. /**
  2959. * @author mrdoob / http://mrdoob.com/
  2960. * @author alteredq / http://alteredqualia.com/
  2961. */
  2962. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2963. this.a = a;
  2964. this.b = b;
  2965. this.c = c;
  2966. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2967. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2968. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2969. this.vertexColors = color instanceof Array ? color : [];
  2970. this.vertexTangents = [];
  2971. this.materialIndex = materialIndex;
  2972. this.centroid = new THREE.Vector3();
  2973. };
  2974. THREE.Face3.prototype = {
  2975. constructor: THREE.Face3,
  2976. clone: function () {
  2977. var face = new THREE.Face3( this.a, this.b, this.c );
  2978. face.normal.copy( this.normal );
  2979. face.color.copy( this.color );
  2980. face.centroid.copy( this.centroid );
  2981. face.materialIndex = this.materialIndex;
  2982. var i, il;
  2983. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2984. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2985. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2986. return face;
  2987. }
  2988. };
  2989. /**
  2990. * @author mrdoob / http://mrdoob.com/
  2991. * @author alteredq / http://alteredqualia.com/
  2992. */
  2993. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2994. this.a = a;
  2995. this.b = b;
  2996. this.c = c;
  2997. this.d = d;
  2998. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2999. this.vertexNormals = normal instanceof Array ? normal : [ ];
  3000. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  3001. this.vertexColors = color instanceof Array ? color : [];
  3002. this.vertexTangents = [];
  3003. this.materialIndex = materialIndex;
  3004. this.centroid = new THREE.Vector3();
  3005. };
  3006. THREE.Face4.prototype = {
  3007. constructor: THREE.Face4,
  3008. clone: function () {
  3009. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  3010. face.normal.copy( this.normal );
  3011. face.color.copy( this.color );
  3012. face.centroid.copy( this.centroid );
  3013. face.materialIndex = this.materialIndex;
  3014. var i, il;
  3015. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3016. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3017. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3018. return face;
  3019. }
  3020. };
  3021. /**
  3022. * @author mrdoob / http://mrdoob.com/
  3023. */
  3024. THREE.UV = function ( u, v ) {
  3025. this.u = u || 0;
  3026. this.v = v || 0;
  3027. };
  3028. THREE.UV.prototype = {
  3029. constructor: THREE.UV,
  3030. set: function ( u, v ) {
  3031. this.u = u;
  3032. this.v = v;
  3033. return this;
  3034. },
  3035. copy: function ( uv ) {
  3036. this.u = uv.u;
  3037. this.v = uv.v;
  3038. return this;
  3039. },
  3040. lerpSelf: function ( uv, alpha ) {
  3041. this.u += ( uv.u - this.u ) * alpha;
  3042. this.v += ( uv.v - this.v ) * alpha;
  3043. return this;
  3044. },
  3045. clone: function () {
  3046. return new THREE.UV( this.u, this.v );
  3047. }
  3048. };
  3049. /**
  3050. * @author mrdoob / http://mrdoob.com/
  3051. * @author kile / http://kile.stravaganza.org/
  3052. * @author alteredq / http://alteredqualia.com/
  3053. * @author mikael emtinger / http://gomo.se/
  3054. * @author zz85 / http://www.lab4games.net/zz85/blog
  3055. */
  3056. THREE.Geometry = function () {
  3057. THREE.GeometryLibrary.push( this );
  3058. this.id = THREE.GeometryIdCount ++;
  3059. this.name = '';
  3060. this.vertices = [];
  3061. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  3062. this.normals = []; // one-to-one vertex normals, used in Ribbon
  3063. this.materials = [];
  3064. this.faces = [];
  3065. this.faceUvs = [[]];
  3066. this.faceVertexUvs = [[]];
  3067. this.morphTargets = [];
  3068. this.morphColors = [];
  3069. this.morphNormals = [];
  3070. this.skinWeights = [];
  3071. this.skinIndices = [];
  3072. this.lineDistances = [];
  3073. this.boundingBox = null;
  3074. this.boundingSphere = null;
  3075. this.hasTangents = false;
  3076. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  3077. // update flags
  3078. this.verticesNeedUpdate = false;
  3079. this.elementsNeedUpdate = false;
  3080. this.uvsNeedUpdate = false;
  3081. this.normalsNeedUpdate = false;
  3082. this.tangentsNeedUpdate = false;
  3083. this.colorsNeedUpdate = false;
  3084. this.lineDistancesNeedUpdate = false;
  3085. this.buffersNeedUpdate = false;
  3086. };
  3087. THREE.Geometry.prototype = {
  3088. constructor : THREE.Geometry,
  3089. applyMatrix: function ( matrix ) {
  3090. var normalMatrix = new THREE.Matrix3();
  3091. normalMatrix.getInverse( matrix ).transpose();
  3092. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  3093. var vertex = this.vertices[ i ];
  3094. matrix.multiplyVector3( vertex );
  3095. }
  3096. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  3097. var face = this.faces[ i ];
  3098. normalMatrix.multiplyVector3( face.normal ).normalize();
  3099. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  3100. normalMatrix.multiplyVector3( face.vertexNormals[ j ] ).normalize();
  3101. }
  3102. matrix.multiplyVector3( face.centroid );
  3103. }
  3104. },
  3105. computeCentroids: function () {
  3106. var f, fl, face;
  3107. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3108. face = this.faces[ f ];
  3109. face.centroid.set( 0, 0, 0 );
  3110. if ( face instanceof THREE.Face3 ) {
  3111. face.centroid.addSelf( this.vertices[ face.a ] );
  3112. face.centroid.addSelf( this.vertices[ face.b ] );
  3113. face.centroid.addSelf( this.vertices[ face.c ] );
  3114. face.centroid.divideScalar( 3 );
  3115. } else if ( face instanceof THREE.Face4 ) {
  3116. face.centroid.addSelf( this.vertices[ face.a ] );
  3117. face.centroid.addSelf( this.vertices[ face.b ] );
  3118. face.centroid.addSelf( this.vertices[ face.c ] );
  3119. face.centroid.addSelf( this.vertices[ face.d ] );
  3120. face.centroid.divideScalar( 4 );
  3121. }
  3122. }
  3123. },
  3124. computeFaceNormals: function () {
  3125. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  3126. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  3127. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3128. face = this.faces[ f ];
  3129. vA = this.vertices[ face.a ];
  3130. vB = this.vertices[ face.b ];
  3131. vC = this.vertices[ face.c ];
  3132. cb.sub( vC, vB );
  3133. ab.sub( vA, vB );
  3134. cb.crossSelf( ab );
  3135. if ( !cb.isZero() ) {
  3136. cb.normalize();
  3137. }
  3138. face.normal.copy( cb );
  3139. }
  3140. },
  3141. computeVertexNormals: function ( areaWeighted ) {
  3142. var v, vl, f, fl, face, vertices;
  3143. // create internal buffers for reuse when calling this method repeatedly
  3144. // (otherwise memory allocation / deallocation every frame is big resource hog)
  3145. if ( this.__tmpVertices === undefined ) {
  3146. this.__tmpVertices = new Array( this.vertices.length );
  3147. vertices = this.__tmpVertices;
  3148. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3149. vertices[ v ] = new THREE.Vector3();
  3150. }
  3151. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3152. face = this.faces[ f ];
  3153. if ( face instanceof THREE.Face3 ) {
  3154. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3155. } else if ( face instanceof THREE.Face4 ) {
  3156. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3157. }
  3158. }
  3159. } else {
  3160. vertices = this.__tmpVertices;
  3161. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3162. vertices[ v ].set( 0, 0, 0 );
  3163. }
  3164. }
  3165. if ( areaWeighted ) {
  3166. // vertex normals weighted by triangle areas
  3167. // http://www.iquilezles.org/www/articles/normals/normals.htm
  3168. var vA, vB, vC, vD;
  3169. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  3170. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  3171. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3172. face = this.faces[ f ];
  3173. if ( face instanceof THREE.Face3 ) {
  3174. vA = this.vertices[ face.a ];
  3175. vB = this.vertices[ face.b ];
  3176. vC = this.vertices[ face.c ];
  3177. cb.sub( vC, vB );
  3178. ab.sub( vA, vB );
  3179. cb.crossSelf( ab );
  3180. vertices[ face.a ].addSelf( cb );
  3181. vertices[ face.b ].addSelf( cb );
  3182. vertices[ face.c ].addSelf( cb );
  3183. } else if ( face instanceof THREE.Face4 ) {
  3184. vA = this.vertices[ face.a ];
  3185. vB = this.vertices[ face.b ];
  3186. vC = this.vertices[ face.c ];
  3187. vD = this.vertices[ face.d ];
  3188. // abd
  3189. db.sub( vD, vB );
  3190. ab.sub( vA, vB );
  3191. db.crossSelf( ab );
  3192. vertices[ face.a ].addSelf( db );
  3193. vertices[ face.b ].addSelf( db );
  3194. vertices[ face.d ].addSelf( db );
  3195. // bcd
  3196. dc.sub( vD, vC );
  3197. bc.sub( vB, vC );
  3198. dc.crossSelf( bc );
  3199. vertices[ face.b ].addSelf( dc );
  3200. vertices[ face.c ].addSelf( dc );
  3201. vertices[ face.d ].addSelf( dc );
  3202. }
  3203. }
  3204. } else {
  3205. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3206. face = this.faces[ f ];
  3207. if ( face instanceof THREE.Face3 ) {
  3208. vertices[ face.a ].addSelf( face.normal );
  3209. vertices[ face.b ].addSelf( face.normal );
  3210. vertices[ face.c ].addSelf( face.normal );
  3211. } else if ( face instanceof THREE.Face4 ) {
  3212. vertices[ face.a ].addSelf( face.normal );
  3213. vertices[ face.b ].addSelf( face.normal );
  3214. vertices[ face.c ].addSelf( face.normal );
  3215. vertices[ face.d ].addSelf( face.normal );
  3216. }
  3217. }
  3218. }
  3219. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3220. vertices[ v ].normalize();
  3221. }
  3222. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3223. face = this.faces[ f ];
  3224. if ( face instanceof THREE.Face3 ) {
  3225. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3226. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3227. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3228. } else if ( face instanceof THREE.Face4 ) {
  3229. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3230. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3231. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3232. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3233. }
  3234. }
  3235. },
  3236. computeMorphNormals: function () {
  3237. var i, il, f, fl, face;
  3238. // save original normals
  3239. // - create temp variables on first access
  3240. // otherwise just copy (for faster repeated calls)
  3241. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3242. face = this.faces[ f ];
  3243. if ( ! face.__originalFaceNormal ) {
  3244. face.__originalFaceNormal = face.normal.clone();
  3245. } else {
  3246. face.__originalFaceNormal.copy( face.normal );
  3247. }
  3248. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3249. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3250. if ( ! face.__originalVertexNormals[ i ] ) {
  3251. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3252. } else {
  3253. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3254. }
  3255. }
  3256. }
  3257. // use temp geometry to compute face and vertex normals for each morph
  3258. var tmpGeo = new THREE.Geometry();
  3259. tmpGeo.faces = this.faces;
  3260. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3261. // create on first access
  3262. if ( ! this.morphNormals[ i ] ) {
  3263. this.morphNormals[ i ] = {};
  3264. this.morphNormals[ i ].faceNormals = [];
  3265. this.morphNormals[ i ].vertexNormals = [];
  3266. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3267. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3268. var faceNormal, vertexNormals;
  3269. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3270. face = this.faces[ f ];
  3271. faceNormal = new THREE.Vector3();
  3272. if ( face instanceof THREE.Face3 ) {
  3273. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3274. } else {
  3275. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3276. }
  3277. dstNormalsFace.push( faceNormal );
  3278. dstNormalsVertex.push( vertexNormals );
  3279. }
  3280. }
  3281. var morphNormals = this.morphNormals[ i ];
  3282. // set vertices to morph target
  3283. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3284. // compute morph normals
  3285. tmpGeo.computeFaceNormals();
  3286. tmpGeo.computeVertexNormals();
  3287. // store morph normals
  3288. var faceNormal, vertexNormals;
  3289. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3290. face = this.faces[ f ];
  3291. faceNormal = morphNormals.faceNormals[ f ];
  3292. vertexNormals = morphNormals.vertexNormals[ f ];
  3293. faceNormal.copy( face.normal );
  3294. if ( face instanceof THREE.Face3 ) {
  3295. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3296. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3297. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3298. } else {
  3299. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3300. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3301. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3302. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3303. }
  3304. }
  3305. }
  3306. // restore original normals
  3307. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3308. face = this.faces[ f ];
  3309. face.normal = face.__originalFaceNormal;
  3310. face.vertexNormals = face.__originalVertexNormals;
  3311. }
  3312. },
  3313. computeTangents: function () {
  3314. // based on http://www.terathon.com/code/tangent.html
  3315. // tangents go to vertices
  3316. var f, fl, v, vl, i, il, vertexIndex,
  3317. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3318. x1, x2, y1, y2, z1, z2,
  3319. s1, s2, t1, t2, r, t, test,
  3320. tan1 = [], tan2 = [],
  3321. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3322. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3323. n = new THREE.Vector3(), w;
  3324. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3325. tan1[ v ] = new THREE.Vector3();
  3326. tan2[ v ] = new THREE.Vector3();
  3327. }
  3328. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  3329. vA = context.vertices[ a ];
  3330. vB = context.vertices[ b ];
  3331. vC = context.vertices[ c ];
  3332. uvA = uv[ ua ];
  3333. uvB = uv[ ub ];
  3334. uvC = uv[ uc ];
  3335. x1 = vB.x - vA.x;
  3336. x2 = vC.x - vA.x;
  3337. y1 = vB.y - vA.y;
  3338. y2 = vC.y - vA.y;
  3339. z1 = vB.z - vA.z;
  3340. z2 = vC.z - vA.z;
  3341. s1 = uvB.u - uvA.u;
  3342. s2 = uvC.u - uvA.u;
  3343. t1 = uvB.v - uvA.v;
  3344. t2 = uvC.v - uvA.v;
  3345. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3346. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  3347. ( t2 * y1 - t1 * y2 ) * r,
  3348. ( t2 * z1 - t1 * z2 ) * r );
  3349. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  3350. ( s1 * y2 - s2 * y1 ) * r,
  3351. ( s1 * z2 - s2 * z1 ) * r );
  3352. tan1[ a ].addSelf( sdir );
  3353. tan1[ b ].addSelf( sdir );
  3354. tan1[ c ].addSelf( sdir );
  3355. tan2[ a ].addSelf( tdir );
  3356. tan2[ b ].addSelf( tdir );
  3357. tan2[ c ].addSelf( tdir );
  3358. }
  3359. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3360. face = this.faces[ f ];
  3361. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  3362. if ( face instanceof THREE.Face3 ) {
  3363. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  3364. } else if ( face instanceof THREE.Face4 ) {
  3365. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  3366. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  3367. }
  3368. }
  3369. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  3370. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3371. face = this.faces[ f ];
  3372. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  3373. n.copy( face.vertexNormals[ i ] );
  3374. vertexIndex = face[ faceIndex[ i ] ];
  3375. t = tan1[ vertexIndex ];
  3376. // Gram-Schmidt orthogonalize
  3377. tmp.copy( t );
  3378. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3379. // Calculate handedness
  3380. tmp2.cross( face.vertexNormals[ i ], t );
  3381. test = tmp2.dot( tan2[ vertexIndex ] );
  3382. w = (test < 0.0) ? -1.0 : 1.0;
  3383. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  3384. }
  3385. }
  3386. this.hasTangents = true;
  3387. },
  3388. computeLineDistances: function ( ) {
  3389. var d = 0;
  3390. var vertices = this.vertices;
  3391. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  3392. if ( i > 0 ) {
  3393. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  3394. }
  3395. this.lineDistances[ i ] = d;
  3396. }
  3397. },
  3398. computeBoundingBox: function () {
  3399. if ( ! this.boundingBox ) {
  3400. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  3401. }
  3402. if ( this.vertices.length > 0 ) {
  3403. var position, firstPosition = this.vertices[ 0 ];
  3404. this.boundingBox.min.copy( firstPosition );
  3405. this.boundingBox.max.copy( firstPosition );
  3406. var min = this.boundingBox.min,
  3407. max = this.boundingBox.max;
  3408. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  3409. position = this.vertices[ v ];
  3410. if ( position.x < min.x ) {
  3411. min.x = position.x;
  3412. } else if ( position.x > max.x ) {
  3413. max.x = position.x;
  3414. }
  3415. if ( position.y < min.y ) {
  3416. min.y = position.y;
  3417. } else if ( position.y > max.y ) {
  3418. max.y = position.y;
  3419. }
  3420. if ( position.z < min.z ) {
  3421. min.z = position.z;
  3422. } else if ( position.z > max.z ) {
  3423. max.z = position.z;
  3424. }
  3425. }
  3426. } else {
  3427. this.boundingBox.min.set( 0, 0, 0 );
  3428. this.boundingBox.max.set( 0, 0, 0 );
  3429. }
  3430. },
  3431. computeBoundingSphere: function () {
  3432. var maxRadiusSq = 0;
  3433. if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
  3434. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  3435. var radiusSq = this.vertices[ i ].lengthSq();
  3436. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3437. }
  3438. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3439. },
  3440. /*
  3441. * Checks for duplicate vertices with hashmap.
  3442. * Duplicated vertices are removed
  3443. * and faces' vertices are updated.
  3444. */
  3445. mergeVertices: function () {
  3446. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  3447. var unique = [], changes = [];
  3448. var v, key;
  3449. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  3450. var precision = Math.pow( 10, precisionPoints );
  3451. var i,il, face;
  3452. var abcd = 'abcd', o, k, j, jl, u;
  3453. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  3454. v = this.vertices[ i ];
  3455. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  3456. if ( verticesMap[ key ] === undefined ) {
  3457. verticesMap[ key ] = i;
  3458. unique.push( this.vertices[ i ] );
  3459. changes[ i ] = unique.length - 1;
  3460. } else {
  3461. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3462. changes[ i ] = changes[ verticesMap[ key ] ];
  3463. }
  3464. };
  3465. // Start to patch face indices
  3466. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  3467. face = this.faces[ i ];
  3468. if ( face instanceof THREE.Face3 ) {
  3469. face.a = changes[ face.a ];
  3470. face.b = changes[ face.b ];
  3471. face.c = changes[ face.c ];
  3472. } else if ( face instanceof THREE.Face4 ) {
  3473. face.a = changes[ face.a ];
  3474. face.b = changes[ face.b ];
  3475. face.c = changes[ face.c ];
  3476. face.d = changes[ face.d ];
  3477. // check dups in (a, b, c, d) and convert to -> face3
  3478. o = [ face.a, face.b, face.c, face.d ];
  3479. for ( k = 3; k > 0; k -- ) {
  3480. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  3481. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  3482. o.splice( k, 1 );
  3483. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  3484. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  3485. u = this.faceVertexUvs[ j ][ i ];
  3486. if ( u ) u.splice( k, 1 );
  3487. }
  3488. this.faces[ i ].vertexColors = face.vertexColors;
  3489. break;
  3490. }
  3491. }
  3492. }
  3493. }
  3494. // Use unique set of vertices
  3495. var diff = this.vertices.length - unique.length;
  3496. this.vertices = unique;
  3497. return diff;
  3498. },
  3499. clone: function () {
  3500. // TODO
  3501. },
  3502. deallocate: function () {
  3503. var index = THREE.GeometryLibrary.indexOf( this );
  3504. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3505. }
  3506. };
  3507. THREE.GeometryIdCount = 0;
  3508. THREE.GeometryLibrary = [];
  3509. /**
  3510. * @author alteredq / http://alteredqualia.com/
  3511. */
  3512. THREE.BufferGeometry = function () {
  3513. THREE.GeometryLibrary.push( this );
  3514. this.id = THREE.GeometryIdCount ++;
  3515. // attributes
  3516. this.attributes = {};
  3517. // attributes typed arrays are kept only if dynamic flag is set
  3518. this.dynamic = false;
  3519. // boundings
  3520. this.boundingBox = null;
  3521. this.boundingSphere = null;
  3522. this.hasTangents = false;
  3523. // for compatibility
  3524. this.morphTargets = [];
  3525. };
  3526. THREE.BufferGeometry.prototype = {
  3527. constructor : THREE.BufferGeometry,
  3528. applyMatrix: function ( matrix ) {
  3529. var positionArray;
  3530. var normalArray;
  3531. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  3532. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  3533. if ( positionArray !== undefined ) {
  3534. matrix.multiplyVector3Array( positionArray );
  3535. this.verticesNeedUpdate = true;
  3536. }
  3537. if ( normalArray !== undefined ) {
  3538. var normalMatrix = new THREE.Matrix3();
  3539. normalMatrix.getInverse( matrix ).transpose();
  3540. normalMatrix.multiplyVector3Array( normalArray );
  3541. this.normalizeNormals();
  3542. this.normalsNeedUpdate = true;
  3543. }
  3544. },
  3545. computeBoundingBox: function () {
  3546. if ( ! this.boundingBox ) {
  3547. this.boundingBox = {
  3548. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  3549. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  3550. };
  3551. }
  3552. var positions = this.attributes[ "position" ].array;
  3553. if ( positions ) {
  3554. var bb = this.boundingBox;
  3555. var x, y, z;
  3556. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3557. x = positions[ i ];
  3558. y = positions[ i + 1 ];
  3559. z = positions[ i + 2 ];
  3560. // bounding box
  3561. if ( x < bb.min.x ) {
  3562. bb.min.x = x;
  3563. } else if ( x > bb.max.x ) {
  3564. bb.max.x = x;
  3565. }
  3566. if ( y < bb.min.y ) {
  3567. bb.min.y = y;
  3568. } else if ( y > bb.max.y ) {
  3569. bb.max.y = y;
  3570. }
  3571. if ( z < bb.min.z ) {
  3572. bb.min.z = z;
  3573. } else if ( z > bb.max.z ) {
  3574. bb.max.z = z;
  3575. }
  3576. }
  3577. }
  3578. if ( positions === undefined || positions.length === 0 ) {
  3579. this.boundingBox.min.set( 0, 0, 0 );
  3580. this.boundingBox.max.set( 0, 0, 0 );
  3581. }
  3582. },
  3583. computeBoundingSphere: function () {
  3584. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  3585. var positions = this.attributes[ "position" ].array;
  3586. if ( positions ) {
  3587. var radiusSq, maxRadiusSq = 0;
  3588. var x, y, z;
  3589. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3590. x = positions[ i ];
  3591. y = positions[ i + 1 ];
  3592. z = positions[ i + 2 ];
  3593. radiusSq = x * x + y * y + z * z;
  3594. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3595. }
  3596. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3597. }
  3598. },
  3599. computeVertexNormals: function () {
  3600. if ( this.attributes[ "position" ] && this.attributes[ "index" ] ) {
  3601. var i, il;
  3602. var j, jl;
  3603. var nVertexElements = this.attributes[ "position" ].array.length;
  3604. if ( this.attributes[ "normal" ] === undefined ) {
  3605. this.attributes[ "normal" ] = {
  3606. itemSize: 3,
  3607. array: new Float32Array( nVertexElements ),
  3608. numItems: nVertexElements
  3609. };
  3610. } else {
  3611. // reset existing normals to zero
  3612. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  3613. this.attributes[ "normal" ].array[ i ] = 0;
  3614. }
  3615. }
  3616. var offsets = this.offsets;
  3617. var indices = this.attributes[ "index" ].array;
  3618. var positions = this.attributes[ "position" ].array;
  3619. var normals = this.attributes[ "normal" ].array;
  3620. var vA, vB, vC, x, y, z,
  3621. pA = new THREE.Vector3(),
  3622. pB = new THREE.Vector3(),
  3623. pC = new THREE.Vector3(),
  3624. cb = new THREE.Vector3(),
  3625. ab = new THREE.Vector3();
  3626. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3627. var start = offsets[ j ].start;
  3628. var count = offsets[ j ].count;
  3629. var index = offsets[ j ].index;
  3630. for ( i = start, il = start + count; i < il; i += 3 ) {
  3631. vA = index + indices[ i ];
  3632. vB = index + indices[ i + 1 ];
  3633. vC = index + indices[ i + 2 ];
  3634. x = positions[ vA * 3 ];
  3635. y = positions[ vA * 3 + 1 ];
  3636. z = positions[ vA * 3 + 2 ];
  3637. pA.set( x, y, z );
  3638. x = positions[ vB * 3 ];
  3639. y = positions[ vB * 3 + 1 ];
  3640. z = positions[ vB * 3 + 2 ];
  3641. pB.set( x, y, z );
  3642. x = positions[ vC * 3 ];
  3643. y = positions[ vC * 3 + 1 ];
  3644. z = positions[ vC * 3 + 2 ];
  3645. pC.set( x, y, z );
  3646. cb.sub( pC, pB );
  3647. ab.sub( pA, pB );
  3648. cb.crossSelf( ab );
  3649. normals[ vA * 3 ] += cb.x;
  3650. normals[ vA * 3 + 1 ] += cb.y;
  3651. normals[ vA * 3 + 2 ] += cb.z;
  3652. normals[ vB * 3 ] += cb.x;
  3653. normals[ vB * 3 + 1 ] += cb.y;
  3654. normals[ vB * 3 + 2 ] += cb.z;
  3655. normals[ vC * 3 ] += cb.x;
  3656. normals[ vC * 3 + 1 ] += cb.y;
  3657. normals[ vC * 3 + 2 ] += cb.z;
  3658. }
  3659. }
  3660. this.normalizeNormals();
  3661. this.normalsNeedUpdate = true;
  3662. }
  3663. },
  3664. normalizeNormals: function () {
  3665. var normals = this.attributes[ "normal" ].array;
  3666. var x, y, z, n;
  3667. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  3668. x = normals[ i ];
  3669. y = normals[ i + 1 ];
  3670. z = normals[ i + 2 ];
  3671. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  3672. normals[ i ] *= n;
  3673. normals[ i + 1 ] *= n;
  3674. normals[ i + 2 ] *= n;
  3675. }
  3676. },
  3677. computeTangents: function () {
  3678. // based on http://www.terathon.com/code/tangent.html
  3679. // (per vertex tangents)
  3680. if ( this.attributes[ "index" ] === undefined ||
  3681. this.attributes[ "position" ] === undefined ||
  3682. this.attributes[ "normal" ] === undefined ||
  3683. this.attributes[ "uv" ] === undefined ) {
  3684. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  3685. return;
  3686. }
  3687. var indices = this.attributes[ "index" ].array;
  3688. var positions = this.attributes[ "position" ].array;
  3689. var normals = this.attributes[ "normal" ].array;
  3690. var uvs = this.attributes[ "uv" ].array;
  3691. var nVertices = positions.length / 3;
  3692. if ( this.attributes[ "tangent" ] === undefined ) {
  3693. var nTangentElements = 4 * nVertices;
  3694. this.attributes[ "tangent" ] = {
  3695. itemSize: 4,
  3696. array: new Float32Array( nTangentElements ),
  3697. numItems: nTangentElements
  3698. };
  3699. }
  3700. var tangents = this.attributes[ "tangent" ].array;
  3701. var tan1 = [], tan2 = [];
  3702. for ( var k = 0; k < nVertices; k ++ ) {
  3703. tan1[ k ] = new THREE.Vector3();
  3704. tan2[ k ] = new THREE.Vector3();
  3705. }
  3706. var xA, yA, zA,
  3707. xB, yB, zB,
  3708. xC, yC, zC,
  3709. uA, vA,
  3710. uB, vB,
  3711. uC, vC,
  3712. x1, x2, y1, y2, z1, z2,
  3713. s1, s2, t1, t2, r;
  3714. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  3715. function handleTriangle( a, b, c ) {
  3716. xA = positions[ a * 3 ];
  3717. yA = positions[ a * 3 + 1 ];
  3718. zA = positions[ a * 3 + 2 ];
  3719. xB = positions[ b * 3 ];
  3720. yB = positions[ b * 3 + 1 ];
  3721. zB = positions[ b * 3 + 2 ];
  3722. xC = positions[ c * 3 ];
  3723. yC = positions[ c * 3 + 1 ];
  3724. zC = positions[ c * 3 + 2 ];
  3725. uA = uvs[ a * 2 ];
  3726. vA = uvs[ a * 2 + 1 ];
  3727. uB = uvs[ b * 2 ];
  3728. vB = uvs[ b * 2 + 1 ];
  3729. uC = uvs[ c * 2 ];
  3730. vC = uvs[ c * 2 + 1 ];
  3731. x1 = xB - xA;
  3732. x2 = xC - xA;
  3733. y1 = yB - yA;
  3734. y2 = yC - yA;
  3735. z1 = zB - zA;
  3736. z2 = zC - zA;
  3737. s1 = uB - uA;
  3738. s2 = uC - uA;
  3739. t1 = vB - vA;
  3740. t2 = vC - vA;
  3741. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3742. sdir.set(
  3743. ( t2 * x1 - t1 * x2 ) * r,
  3744. ( t2 * y1 - t1 * y2 ) * r,
  3745. ( t2 * z1 - t1 * z2 ) * r
  3746. );
  3747. tdir.set(
  3748. ( s1 * x2 - s2 * x1 ) * r,
  3749. ( s1 * y2 - s2 * y1 ) * r,
  3750. ( s1 * z2 - s2 * z1 ) * r
  3751. );
  3752. tan1[ a ].addSelf( sdir );
  3753. tan1[ b ].addSelf( sdir );
  3754. tan1[ c ].addSelf( sdir );
  3755. tan2[ a ].addSelf( tdir );
  3756. tan2[ b ].addSelf( tdir );
  3757. tan2[ c ].addSelf( tdir );
  3758. }
  3759. var i, il;
  3760. var j, jl;
  3761. var iA, iB, iC;
  3762. var offsets = this.offsets;
  3763. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3764. var start = offsets[ j ].start;
  3765. var count = offsets[ j ].count;
  3766. var index = offsets[ j ].index;
  3767. for ( i = start, il = start + count; i < il; i += 3 ) {
  3768. iA = index + indices[ i ];
  3769. iB = index + indices[ i + 1 ];
  3770. iC = index + indices[ i + 2 ];
  3771. handleTriangle( iA, iB, iC );
  3772. }
  3773. }
  3774. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  3775. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  3776. var w, t, test;
  3777. var nx, ny, nz;
  3778. function handleVertex( v ) {
  3779. n.x = normals[ v * 3 ];
  3780. n.y = normals[ v * 3 + 1 ];
  3781. n.z = normals[ v * 3 + 2 ];
  3782. n2.copy( n );
  3783. t = tan1[ v ];
  3784. // Gram-Schmidt orthogonalize
  3785. tmp.copy( t );
  3786. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3787. // Calculate handedness
  3788. tmp2.cross( n2, t );
  3789. test = tmp2.dot( tan2[ v ] );
  3790. w = ( test < 0.0 ) ? -1.0 : 1.0;
  3791. tangents[ v * 4 ] = tmp.x;
  3792. tangents[ v * 4 + 1 ] = tmp.y;
  3793. tangents[ v * 4 + 2 ] = tmp.z;
  3794. tangents[ v * 4 + 3 ] = w;
  3795. }
  3796. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3797. var start = offsets[ j ].start;
  3798. var count = offsets[ j ].count;
  3799. var index = offsets[ j ].index;
  3800. for ( i = start, il = start + count; i < il; i += 3 ) {
  3801. iA = index + indices[ i ];
  3802. iB = index + indices[ i + 1 ];
  3803. iC = index + indices[ i + 2 ];
  3804. handleVertex( iA );
  3805. handleVertex( iB );
  3806. handleVertex( iC );
  3807. }
  3808. }
  3809. this.hasTangents = true;
  3810. this.tangentsNeedUpdate = true;
  3811. },
  3812. deallocate: function () {
  3813. var index = THREE.GeometryLibrary.indexOf( this );
  3814. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3815. }
  3816. };
  3817. /**
  3818. * Spline from Tween.js, slightly optimized (and trashed)
  3819. * http://sole.github.com/tween.js/examples/05_spline.html
  3820. *
  3821. * @author mrdoob / http://mrdoob.com/
  3822. * @author alteredq / http://alteredqualia.com/
  3823. */
  3824. THREE.Spline = function ( points ) {
  3825. this.points = points;
  3826. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3827. point, intPoint, weight, w2, w3,
  3828. pa, pb, pc, pd;
  3829. this.initFromArray = function( a ) {
  3830. this.points = [];
  3831. for ( var i = 0; i < a.length; i++ ) {
  3832. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3833. }
  3834. };
  3835. this.getPoint = function ( k ) {
  3836. point = ( this.points.length - 1 ) * k;
  3837. intPoint = Math.floor( point );
  3838. weight = point - intPoint;
  3839. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3840. c[ 1 ] = intPoint;
  3841. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3842. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3843. pa = this.points[ c[ 0 ] ];
  3844. pb = this.points[ c[ 1 ] ];
  3845. pc = this.points[ c[ 2 ] ];
  3846. pd = this.points[ c[ 3 ] ];
  3847. w2 = weight * weight;
  3848. w3 = weight * w2;
  3849. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3850. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3851. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3852. return v3;
  3853. };
  3854. this.getControlPointsArray = function () {
  3855. var i, p, l = this.points.length,
  3856. coords = [];
  3857. for ( i = 0; i < l; i ++ ) {
  3858. p = this.points[ i ];
  3859. coords[ i ] = [ p.x, p.y, p.z ];
  3860. }
  3861. return coords;
  3862. };
  3863. // approximate length by summing linear segments
  3864. this.getLength = function ( nSubDivisions ) {
  3865. var i, index, nSamples, position,
  3866. point = 0, intPoint = 0, oldIntPoint = 0,
  3867. oldPosition = new THREE.Vector3(),
  3868. tmpVec = new THREE.Vector3(),
  3869. chunkLengths = [],
  3870. totalLength = 0;
  3871. // first point has 0 length
  3872. chunkLengths[ 0 ] = 0;
  3873. if ( !nSubDivisions ) nSubDivisions = 100;
  3874. nSamples = this.points.length * nSubDivisions;
  3875. oldPosition.copy( this.points[ 0 ] );
  3876. for ( i = 1; i < nSamples; i ++ ) {
  3877. index = i / nSamples;
  3878. position = this.getPoint( index );
  3879. tmpVec.copy( position );
  3880. totalLength += tmpVec.distanceTo( oldPosition );
  3881. oldPosition.copy( position );
  3882. point = ( this.points.length - 1 ) * index;
  3883. intPoint = Math.floor( point );
  3884. if ( intPoint != oldIntPoint ) {
  3885. chunkLengths[ intPoint ] = totalLength;
  3886. oldIntPoint = intPoint;
  3887. }
  3888. }
  3889. // last point ends with total length
  3890. chunkLengths[ chunkLengths.length ] = totalLength;
  3891. return { chunks: chunkLengths, total: totalLength };
  3892. };
  3893. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3894. var i, j,
  3895. index, indexCurrent, indexNext,
  3896. linearDistance, realDistance,
  3897. sampling, position,
  3898. newpoints = [],
  3899. tmpVec = new THREE.Vector3(),
  3900. sl = this.getLength();
  3901. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3902. for ( i = 1; i < this.points.length; i++ ) {
  3903. //tmpVec.copy( this.points[ i - 1 ] );
  3904. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3905. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3906. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3907. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3908. indexNext = i / ( this.points.length - 1 );
  3909. for ( j = 1; j < sampling - 1; j++ ) {
  3910. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3911. position = this.getPoint( index );
  3912. newpoints.push( tmpVec.copy( position ).clone() );
  3913. }
  3914. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3915. }
  3916. this.points = newpoints;
  3917. };
  3918. // Catmull-Rom
  3919. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3920. var v0 = ( p2 - p0 ) * 0.5,
  3921. v1 = ( p3 - p1 ) * 0.5;
  3922. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3923. };
  3924. };
  3925. /**
  3926. * @author mrdoob / http://mrdoob.com/
  3927. * @author mikael emtinger / http://gomo.se/
  3928. */
  3929. THREE.Camera = function () {
  3930. THREE.Object3D.call( this );
  3931. this.matrixWorldInverse = new THREE.Matrix4();
  3932. this.projectionMatrix = new THREE.Matrix4();
  3933. this.projectionMatrixInverse = new THREE.Matrix4();
  3934. };
  3935. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  3936. THREE.Camera.prototype.lookAt = function ( vector ) {
  3937. // TODO: Add hierarchy support.
  3938. this.matrix.lookAt( this.position, vector, this.up );
  3939. if ( this.rotationAutoUpdate === true ) {
  3940. if ( this.useQuaternion === false ) {
  3941. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3942. } else {
  3943. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3944. }
  3945. }
  3946. };
  3947. /**
  3948. * @author alteredq / http://alteredqualia.com/
  3949. */
  3950. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  3951. THREE.Camera.call( this );
  3952. this.left = left;
  3953. this.right = right;
  3954. this.top = top;
  3955. this.bottom = bottom;
  3956. this.near = ( near !== undefined ) ? near : 0.1;
  3957. this.far = ( far !== undefined ) ? far : 2000;
  3958. this.updateProjectionMatrix();
  3959. };
  3960. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  3961. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  3962. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  3963. };
  3964. /**
  3965. * @author mrdoob / http://mrdoob.com/
  3966. * @author greggman / http://games.greggman.com/
  3967. * @author zz85 / http://www.lab4games.net/zz85/blog
  3968. */
  3969. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  3970. THREE.Camera.call( this );
  3971. this.fov = fov !== undefined ? fov : 50;
  3972. this.aspect = aspect !== undefined ? aspect : 1;
  3973. this.near = near !== undefined ? near : 0.1;
  3974. this.far = far !== undefined ? far : 2000;
  3975. this.updateProjectionMatrix();
  3976. };
  3977. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  3978. /**
  3979. * Uses Focal Length (in mm) to estimate and set FOV
  3980. * 35mm (fullframe) camera is used if frame size is not specified;
  3981. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  3982. */
  3983. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  3984. if ( frameHeight === undefined ) frameHeight = 24;
  3985. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  3986. this.updateProjectionMatrix();
  3987. }
  3988. /**
  3989. * Sets an offset in a larger frustum. This is useful for multi-window or
  3990. * multi-monitor/multi-machine setups.
  3991. *
  3992. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  3993. * the monitors are in grid like this
  3994. *
  3995. * +---+---+---+
  3996. * | A | B | C |
  3997. * +---+---+---+
  3998. * | D | E | F |
  3999. * +---+---+---+
  4000. *
  4001. * then for each monitor you would call it like this
  4002. *
  4003. * var w = 1920;
  4004. * var h = 1080;
  4005. * var fullWidth = w * 3;
  4006. * var fullHeight = h * 2;
  4007. *
  4008. * --A--
  4009. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  4010. * --B--
  4011. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  4012. * --C--
  4013. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  4014. * --D--
  4015. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  4016. * --E--
  4017. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  4018. * --F--
  4019. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  4020. *
  4021. * Note there is no reason monitors have to be the same size or in a grid.
  4022. */
  4023. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  4024. this.fullWidth = fullWidth;
  4025. this.fullHeight = fullHeight;
  4026. this.x = x;
  4027. this.y = y;
  4028. this.width = width;
  4029. this.height = height;
  4030. this.updateProjectionMatrix();
  4031. };
  4032. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  4033. if ( this.fullWidth ) {
  4034. var aspect = this.fullWidth / this.fullHeight;
  4035. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  4036. var bottom = -top;
  4037. var left = aspect * bottom;
  4038. var right = aspect * top;
  4039. var width = Math.abs( right - left );
  4040. var height = Math.abs( top - bottom );
  4041. this.projectionMatrix.makeFrustum(
  4042. left + this.x * width / this.fullWidth,
  4043. left + ( this.x + this.width ) * width / this.fullWidth,
  4044. top - ( this.y + this.height ) * height / this.fullHeight,
  4045. top - this.y * height / this.fullHeight,
  4046. this.near,
  4047. this.far
  4048. );
  4049. } else {
  4050. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  4051. }
  4052. };
  4053. /**
  4054. * @author mrdoob / http://mrdoob.com/
  4055. * @author alteredq / http://alteredqualia.com/
  4056. */
  4057. THREE.Light = function ( hex ) {
  4058. THREE.Object3D.call( this );
  4059. this.color = new THREE.Color( hex );
  4060. };
  4061. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  4062. /**
  4063. * @author mrdoob / http://mrdoob.com/
  4064. */
  4065. THREE.AmbientLight = function ( hex ) {
  4066. THREE.Light.call( this, hex );
  4067. };
  4068. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  4069. /**
  4070. * @author mrdoob / http://mrdoob.com/
  4071. * @author alteredq / http://alteredqualia.com/
  4072. */
  4073. THREE.DirectionalLight = function ( hex, intensity ) {
  4074. THREE.Light.call( this, hex );
  4075. this.position = new THREE.Vector3( 0, 1, 0 );
  4076. this.target = new THREE.Object3D();
  4077. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4078. this.castShadow = false;
  4079. this.onlyShadow = false;
  4080. //
  4081. this.shadowCameraNear = 50;
  4082. this.shadowCameraFar = 5000;
  4083. this.shadowCameraLeft = -500;
  4084. this.shadowCameraRight = 500;
  4085. this.shadowCameraTop = 500;
  4086. this.shadowCameraBottom = -500;
  4087. this.shadowCameraVisible = false;
  4088. this.shadowBias = 0;
  4089. this.shadowDarkness = 0.5;
  4090. this.shadowMapWidth = 512;
  4091. this.shadowMapHeight = 512;
  4092. //
  4093. this.shadowCascade = false;
  4094. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  4095. this.shadowCascadeCount = 2;
  4096. this.shadowCascadeBias = [ 0, 0, 0 ];
  4097. this.shadowCascadeWidth = [ 512, 512, 512 ];
  4098. this.shadowCascadeHeight = [ 512, 512, 512 ];
  4099. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  4100. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  4101. this.shadowCascadeArray = [];
  4102. //
  4103. this.shadowMap = null;
  4104. this.shadowMapSize = null;
  4105. this.shadowCamera = null;
  4106. this.shadowMatrix = null;
  4107. };
  4108. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  4109. /**
  4110. * @author alteredq / http://alteredqualia.com/
  4111. */
  4112. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  4113. THREE.Light.call( this, skyColorHex );
  4114. this.groundColor = new THREE.Color( groundColorHex );
  4115. this.position = new THREE.Vector3( 0, 100, 0 );
  4116. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4117. };
  4118. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  4119. /**
  4120. * @author mrdoob / http://mrdoob.com/
  4121. */
  4122. THREE.PointLight = function ( hex, intensity, distance ) {
  4123. THREE.Light.call( this, hex );
  4124. this.position = new THREE.Vector3( 0, 0, 0 );
  4125. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4126. this.distance = ( distance !== undefined ) ? distance : 0;
  4127. };
  4128. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  4129. /**
  4130. * @author alteredq / http://alteredqualia.com/
  4131. */
  4132. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  4133. THREE.Light.call( this, hex );
  4134. this.position = new THREE.Vector3( 0, 1, 0 );
  4135. this.target = new THREE.Object3D();
  4136. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4137. this.distance = ( distance !== undefined ) ? distance : 0;
  4138. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  4139. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  4140. this.castShadow = false;
  4141. this.onlyShadow = false;
  4142. //
  4143. this.shadowCameraNear = 50;
  4144. this.shadowCameraFar = 5000;
  4145. this.shadowCameraFov = 50;
  4146. this.shadowCameraVisible = false;
  4147. this.shadowBias = 0;
  4148. this.shadowDarkness = 0.5;
  4149. this.shadowMapWidth = 512;
  4150. this.shadowMapHeight = 512;
  4151. //
  4152. this.shadowMap = null;
  4153. this.shadowMapSize = null;
  4154. this.shadowCamera = null;
  4155. this.shadowMatrix = null;
  4156. };
  4157. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  4158. /**
  4159. * @author alteredq / http://alteredqualia.com/
  4160. */
  4161. THREE.Loader = function ( showStatus ) {
  4162. this.showStatus = showStatus;
  4163. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  4164. this.onLoadStart = function () {};
  4165. this.onLoadProgress = function () {};
  4166. this.onLoadComplete = function () {};
  4167. };
  4168. THREE.Loader.prototype = {
  4169. constructor: THREE.Loader,
  4170. crossOrigin: 'anonymous',
  4171. addStatusElement: function () {
  4172. var e = document.createElement( "div" );
  4173. e.style.position = "absolute";
  4174. e.style.right = "0px";
  4175. e.style.top = "0px";
  4176. e.style.fontSize = "0.8em";
  4177. e.style.textAlign = "left";
  4178. e.style.background = "rgba(0,0,0,0.25)";
  4179. e.style.color = "#fff";
  4180. e.style.width = "120px";
  4181. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  4182. e.style.zIndex = 1000;
  4183. e.innerHTML = "Loading ...";
  4184. return e;
  4185. },
  4186. updateProgress: function ( progress ) {
  4187. var message = "Loaded ";
  4188. if ( progress.total ) {
  4189. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  4190. } else {
  4191. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  4192. }
  4193. this.statusDomElement.innerHTML = message;
  4194. },
  4195. extractUrlBase: function ( url ) {
  4196. var parts = url.split( '/' );
  4197. parts.pop();
  4198. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  4199. },
  4200. initMaterials: function ( scope, materials, texturePath ) {
  4201. scope.materials = [];
  4202. for ( var i = 0; i < materials.length; ++ i ) {
  4203. scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  4204. }
  4205. },
  4206. hasNormals: function ( scope ) {
  4207. var m, i, il = scope.materials.length;
  4208. for( i = 0; i < il; i ++ ) {
  4209. m = scope.materials[ i ];
  4210. if ( m instanceof THREE.ShaderMaterial ) return true;
  4211. }
  4212. return false;
  4213. },
  4214. createMaterial: function ( m, texturePath ) {
  4215. var _this = this;
  4216. function is_pow2( n ) {
  4217. var l = Math.log( n ) / Math.LN2;
  4218. return Math.floor( l ) == l;
  4219. }
  4220. function nearest_pow2( n ) {
  4221. var l = Math.log( n ) / Math.LN2;
  4222. return Math.pow( 2, Math.round( l ) );
  4223. }
  4224. function load_image( where, url ) {
  4225. var image = new Image();
  4226. image.onload = function () {
  4227. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  4228. var width = nearest_pow2( this.width );
  4229. var height = nearest_pow2( this.height );
  4230. where.image.width = width;
  4231. where.image.height = height;
  4232. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  4233. } else {
  4234. where.image = this;
  4235. }
  4236. where.needsUpdate = true;
  4237. };
  4238. image.crossOrigin = _this.crossOrigin;
  4239. image.src = url;
  4240. }
  4241. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  4242. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  4243. var fullPath = texturePath + "/" + sourceFile;
  4244. if ( isCompressed ) {
  4245. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  4246. where[ name ] = texture;
  4247. } else {
  4248. var texture = document.createElement( 'canvas' );
  4249. where[ name ] = new THREE.Texture( texture );
  4250. }
  4251. where[ name ].sourceFile = sourceFile;
  4252. if( repeat ) {
  4253. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4254. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4255. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4256. }
  4257. if ( offset ) {
  4258. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4259. }
  4260. if ( wrap ) {
  4261. var wrapMap = {
  4262. "repeat": THREE.RepeatWrapping,
  4263. "mirror": THREE.MirroredRepeatWrapping
  4264. }
  4265. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4266. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4267. }
  4268. if ( anisotropy ) {
  4269. where[ name ].anisotropy = anisotropy;
  4270. }
  4271. if ( ! isCompressed ) {
  4272. load_image( where[ name ], fullPath );
  4273. }
  4274. }
  4275. function rgb2hex( rgb ) {
  4276. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4277. }
  4278. // defaults
  4279. var mtype = "MeshLambertMaterial";
  4280. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4281. // parameters from model file
  4282. if ( m.shading ) {
  4283. var shading = m.shading.toLowerCase();
  4284. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4285. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4286. }
  4287. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4288. mpars.blending = THREE[ m.blending ];
  4289. }
  4290. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4291. mpars.transparent = m.transparent;
  4292. }
  4293. if ( m.depthTest !== undefined ) {
  4294. mpars.depthTest = m.depthTest;
  4295. }
  4296. if ( m.depthWrite !== undefined ) {
  4297. mpars.depthWrite = m.depthWrite;
  4298. }
  4299. if ( m.visible !== undefined ) {
  4300. mpars.visible = m.visible;
  4301. }
  4302. if ( m.flipSided !== undefined ) {
  4303. mpars.side = THREE.BackSide;
  4304. }
  4305. if ( m.doubleSided !== undefined ) {
  4306. mpars.side = THREE.DoubleSide;
  4307. }
  4308. if ( m.wireframe !== undefined ) {
  4309. mpars.wireframe = m.wireframe;
  4310. }
  4311. if ( m.vertexColors !== undefined ) {
  4312. if ( m.vertexColors === "face" ) {
  4313. mpars.vertexColors = THREE.FaceColors;
  4314. } else if ( m.vertexColors ) {
  4315. mpars.vertexColors = THREE.VertexColors;
  4316. }
  4317. }
  4318. // colors
  4319. if ( m.colorDiffuse ) {
  4320. mpars.color = rgb2hex( m.colorDiffuse );
  4321. } else if ( m.DbgColor ) {
  4322. mpars.color = m.DbgColor;
  4323. }
  4324. if ( m.colorSpecular ) {
  4325. mpars.specular = rgb2hex( m.colorSpecular );
  4326. }
  4327. if ( m.colorAmbient ) {
  4328. mpars.ambient = rgb2hex( m.colorAmbient );
  4329. }
  4330. // modifiers
  4331. if ( m.transparency ) {
  4332. mpars.opacity = m.transparency;
  4333. }
  4334. if ( m.specularCoef ) {
  4335. mpars.shininess = m.specularCoef;
  4336. }
  4337. // textures
  4338. if ( m.mapDiffuse && texturePath ) {
  4339. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  4340. }
  4341. if ( m.mapLight && texturePath ) {
  4342. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  4343. }
  4344. if ( m.mapBump && texturePath ) {
  4345. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  4346. }
  4347. if ( m.mapNormal && texturePath ) {
  4348. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  4349. }
  4350. if ( m.mapSpecular && texturePath ) {
  4351. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  4352. }
  4353. //
  4354. if ( m.mapBumpScale ) {
  4355. mpars.bumpScale = m.mapBumpScale;
  4356. }
  4357. // special case for normal mapped material
  4358. if ( m.mapNormal ) {
  4359. var shader = THREE.ShaderUtils.lib[ "normal" ];
  4360. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  4361. uniforms[ "tNormal" ].value = mpars.normalMap;
  4362. if ( m.mapNormalFactor ) {
  4363. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  4364. }
  4365. if ( mpars.map ) {
  4366. uniforms[ "tDiffuse" ].value = mpars.map;
  4367. uniforms[ "enableDiffuse" ].value = true;
  4368. }
  4369. if ( mpars.specularMap ) {
  4370. uniforms[ "tSpecular" ].value = mpars.specularMap;
  4371. uniforms[ "enableSpecular" ].value = true;
  4372. }
  4373. if ( mpars.lightMap ) {
  4374. uniforms[ "tAO" ].value = mpars.lightMap;
  4375. uniforms[ "enableAO" ].value = true;
  4376. }
  4377. // for the moment don't handle displacement texture
  4378. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  4379. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  4380. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  4381. uniforms[ "uShininess" ].value = mpars.shininess;
  4382. if ( mpars.opacity !== undefined ) {
  4383. uniforms[ "uOpacity" ].value = mpars.opacity;
  4384. }
  4385. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  4386. var material = new THREE.ShaderMaterial( parameters );
  4387. } else {
  4388. var material = new THREE[ mtype ]( mpars );
  4389. }
  4390. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  4391. return material;
  4392. }
  4393. };
  4394. /**
  4395. * @author alteredq / http://alteredqualia.com/
  4396. */
  4397. THREE.BinaryLoader = function ( showStatus ) {
  4398. THREE.Loader.call( this, showStatus );
  4399. };
  4400. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  4401. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  4402. // - binary models consist of two files: JS and BIN
  4403. // - parameters
  4404. // - url (required)
  4405. // - callback (required)
  4406. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  4407. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  4408. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  4409. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4410. binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
  4411. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  4412. this.onLoadStart();
  4413. // #1 load JS part via web worker
  4414. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  4415. };
  4416. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  4417. var xhr = new XMLHttpRequest();
  4418. xhr.onreadystatechange = function () {
  4419. if ( xhr.readyState == 4 ) {
  4420. if ( xhr.status == 200 || xhr.status == 0 ) {
  4421. var json = JSON.parse( xhr.responseText );
  4422. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  4423. } else {
  4424. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4425. }
  4426. }
  4427. };
  4428. xhr.open( "GET", url, true );
  4429. xhr.send( null );
  4430. };
  4431. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  4432. var xhr = new XMLHttpRequest(),
  4433. url = binaryPath + "/" + json.buffers;
  4434. var length = 0;
  4435. xhr.onreadystatechange = function () {
  4436. if ( xhr.readyState == 4 ) {
  4437. if ( xhr.status == 200 || xhr.status == 0 ) {
  4438. var buffer = xhr.response;
  4439. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  4440. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  4441. } else {
  4442. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4443. }
  4444. } else if ( xhr.readyState == 3 ) {
  4445. if ( callbackProgress ) {
  4446. if ( length == 0 ) {
  4447. length = xhr.getResponseHeader( "Content-Length" );
  4448. }
  4449. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4450. }
  4451. } else if ( xhr.readyState == 2 ) {
  4452. length = xhr.getResponseHeader( "Content-Length" );
  4453. }
  4454. };
  4455. xhr.open( "GET", url, true );
  4456. xhr.responseType = "arraybuffer";
  4457. xhr.send( null );
  4458. };
  4459. // Binary AJAX parser
  4460. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
  4461. var Model = function ( texturePath ) {
  4462. var scope = this,
  4463. currentOffset = 0,
  4464. md,
  4465. normals = [],
  4466. uvs = [],
  4467. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  4468. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  4469. tri_size, quad_size,
  4470. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  4471. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  4472. THREE.Geometry.call( this );
  4473. THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
  4474. md = parseMetaData( data, currentOffset );
  4475. currentOffset += md.header_bytes;
  4476. /*
  4477. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4478. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  4479. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4480. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4481. */
  4482. // buffers sizes
  4483. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  4484. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  4485. len_tri_flat = md.ntri_flat * ( tri_size );
  4486. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  4487. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  4488. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  4489. len_quad_flat = md.nquad_flat * ( quad_size );
  4490. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  4491. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  4492. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  4493. // read buffers
  4494. currentOffset += init_vertices( currentOffset );
  4495. currentOffset += init_normals( currentOffset );
  4496. currentOffset += handlePadding( md.nnormals * 3 );
  4497. currentOffset += init_uvs( currentOffset );
  4498. start_tri_flat = currentOffset;
  4499. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  4500. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  4501. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  4502. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  4503. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  4504. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  4505. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  4506. // have to first process faces with uvs
  4507. // so that face and uv indices match
  4508. init_triangles_flat_uv( start_tri_flat_uv );
  4509. init_triangles_smooth_uv( start_tri_smooth_uv );
  4510. init_quads_flat_uv( start_quad_flat_uv );
  4511. init_quads_smooth_uv( start_quad_smooth_uv );
  4512. // now we can process untextured faces
  4513. init_triangles_flat( start_tri_flat );
  4514. init_triangles_smooth( start_tri_smooth );
  4515. init_quads_flat( start_quad_flat );
  4516. init_quads_smooth( start_quad_smooth );
  4517. this.computeCentroids();
  4518. this.computeFaceNormals();
  4519. if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
  4520. function handlePadding( n ) {
  4521. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  4522. };
  4523. function parseMetaData( data, offset ) {
  4524. var metaData = {
  4525. 'signature' :parseString( data, offset, 12 ),
  4526. 'header_bytes' :parseUChar8( data, offset + 12 ),
  4527. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  4528. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  4529. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  4530. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  4531. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  4532. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  4533. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  4534. 'nvertices' :parseUInt32( data, offset + 20 ),
  4535. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  4536. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  4537. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  4538. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  4539. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  4540. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  4541. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  4542. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  4543. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  4544. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  4545. };
  4546. /*
  4547. console.log( "signature: " + metaData.signature );
  4548. console.log( "header_bytes: " + metaData.header_bytes );
  4549. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  4550. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  4551. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  4552. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  4553. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  4554. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  4555. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  4556. console.log( "nvertices: " + metaData.nvertices );
  4557. console.log( "nnormals: " + metaData.nnormals );
  4558. console.log( "nuvs: " + metaData.nuvs );
  4559. console.log( "ntri_flat: " + metaData.ntri_flat );
  4560. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  4561. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  4562. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  4563. console.log( "nquad_flat: " + metaData.nquad_flat );
  4564. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  4565. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  4566. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  4567. var total = metaData.header_bytes
  4568. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  4569. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  4570. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  4571. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  4572. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  4573. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  4574. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  4575. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  4576. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  4577. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  4578. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  4579. console.log( "total bytes: " + total );
  4580. */
  4581. return metaData;
  4582. };
  4583. function parseString( data, offset, length ) {
  4584. var charArray = new Uint8Array( data, offset, length );
  4585. var text = "";
  4586. for ( var i = 0; i < length; i ++ ) {
  4587. text += String.fromCharCode( charArray[ offset + i ] );
  4588. }
  4589. return text;
  4590. };
  4591. function parseUChar8( data, offset ) {
  4592. var charArray = new Uint8Array( data, offset, 1 );
  4593. return charArray[ 0 ];
  4594. };
  4595. function parseUInt32( data, offset ) {
  4596. var intArray = new Uint32Array( data, offset, 1 );
  4597. return intArray[ 0 ];
  4598. };
  4599. function init_vertices( start ) {
  4600. var nElements = md.nvertices;
  4601. var coordArray = new Float32Array( data, start, nElements * 3 );
  4602. var i, x, y, z;
  4603. for( i = 0; i < nElements; i ++ ) {
  4604. x = coordArray[ i * 3 ];
  4605. y = coordArray[ i * 3 + 1 ];
  4606. z = coordArray[ i * 3 + 2 ];
  4607. vertex( scope, x, y, z );
  4608. }
  4609. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  4610. };
  4611. function init_normals( start ) {
  4612. var nElements = md.nnormals;
  4613. if ( nElements ) {
  4614. var normalArray = new Int8Array( data, start, nElements * 3 );
  4615. var i, x, y, z;
  4616. for( i = 0; i < nElements; i ++ ) {
  4617. x = normalArray[ i * 3 ];
  4618. y = normalArray[ i * 3 + 1 ];
  4619. z = normalArray[ i * 3 + 2 ];
  4620. normals.push( x/127, y/127, z/127 );
  4621. }
  4622. }
  4623. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  4624. };
  4625. function init_uvs( start ) {
  4626. var nElements = md.nuvs;
  4627. if ( nElements ) {
  4628. var uvArray = new Float32Array( data, start, nElements * 2 );
  4629. var i, u, v;
  4630. for( i = 0; i < nElements; i ++ ) {
  4631. u = uvArray[ i * 2 ];
  4632. v = uvArray[ i * 2 + 1 ];
  4633. uvs.push( u, v );
  4634. }
  4635. }
  4636. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  4637. };
  4638. function init_uvs3( nElements, offset ) {
  4639. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  4640. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  4641. for( i = 0; i < nElements; i ++ ) {
  4642. uva = uvIndexBuffer[ i * 3 ];
  4643. uvb = uvIndexBuffer[ i * 3 + 1 ];
  4644. uvc = uvIndexBuffer[ i * 3 + 2 ];
  4645. u1 = uvs[ uva*2 ];
  4646. v1 = uvs[ uva*2 + 1 ];
  4647. u2 = uvs[ uvb*2 ];
  4648. v2 = uvs[ uvb*2 + 1 ];
  4649. u3 = uvs[ uvc*2 ];
  4650. v3 = uvs[ uvc*2 + 1 ];
  4651. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  4652. }
  4653. };
  4654. function init_uvs4( nElements, offset ) {
  4655. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  4656. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  4657. for( i = 0; i < nElements; i ++ ) {
  4658. uva = uvIndexBuffer[ i * 4 ];
  4659. uvb = uvIndexBuffer[ i * 4 + 1 ];
  4660. uvc = uvIndexBuffer[ i * 4 + 2 ];
  4661. uvd = uvIndexBuffer[ i * 4 + 3 ];
  4662. u1 = uvs[ uva*2 ];
  4663. v1 = uvs[ uva*2 + 1 ];
  4664. u2 = uvs[ uvb*2 ];
  4665. v2 = uvs[ uvb*2 + 1 ];
  4666. u3 = uvs[ uvc*2 ];
  4667. v3 = uvs[ uvc*2 + 1 ];
  4668. u4 = uvs[ uvd*2 ];
  4669. v4 = uvs[ uvd*2 + 1 ];
  4670. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  4671. }
  4672. };
  4673. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  4674. var i, a, b, c, m;
  4675. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4676. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4677. for( i = 0; i < nElements; i ++ ) {
  4678. a = vertexIndexBuffer[ i * 3 ];
  4679. b = vertexIndexBuffer[ i * 3 + 1 ];
  4680. c = vertexIndexBuffer[ i * 3 + 2 ];
  4681. m = materialIndexBuffer[ i ];
  4682. f3( scope, a, b, c, m );
  4683. }
  4684. };
  4685. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  4686. var i, a, b, c, d, m;
  4687. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4688. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4689. for( i = 0; i < nElements; i ++ ) {
  4690. a = vertexIndexBuffer[ i * 4 ];
  4691. b = vertexIndexBuffer[ i * 4 + 1 ];
  4692. c = vertexIndexBuffer[ i * 4 + 2 ];
  4693. d = vertexIndexBuffer[ i * 4 + 3 ];
  4694. m = materialIndexBuffer[ i ];
  4695. f4( scope, a, b, c, d, m );
  4696. }
  4697. };
  4698. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4699. var i, a, b, c, m;
  4700. var na, nb, nc;
  4701. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4702. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  4703. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4704. for( i = 0; i < nElements; i ++ ) {
  4705. a = vertexIndexBuffer[ i * 3 ];
  4706. b = vertexIndexBuffer[ i * 3 + 1 ];
  4707. c = vertexIndexBuffer[ i * 3 + 2 ];
  4708. na = normalIndexBuffer[ i * 3 ];
  4709. nb = normalIndexBuffer[ i * 3 + 1 ];
  4710. nc = normalIndexBuffer[ i * 3 + 2 ];
  4711. m = materialIndexBuffer[ i ];
  4712. f3n( scope, normals, a, b, c, m, na, nb, nc );
  4713. }
  4714. };
  4715. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4716. var i, a, b, c, d, m;
  4717. var na, nb, nc, nd;
  4718. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4719. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  4720. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4721. for( i = 0; i < nElements; i ++ ) {
  4722. a = vertexIndexBuffer[ i * 4 ];
  4723. b = vertexIndexBuffer[ i * 4 + 1 ];
  4724. c = vertexIndexBuffer[ i * 4 + 2 ];
  4725. d = vertexIndexBuffer[ i * 4 + 3 ];
  4726. na = normalIndexBuffer[ i * 4 ];
  4727. nb = normalIndexBuffer[ i * 4 + 1 ];
  4728. nc = normalIndexBuffer[ i * 4 + 2 ];
  4729. nd = normalIndexBuffer[ i * 4 + 3 ];
  4730. m = materialIndexBuffer[ i ];
  4731. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  4732. }
  4733. };
  4734. function init_triangles_flat( start ) {
  4735. var nElements = md.ntri_flat;
  4736. if ( nElements ) {
  4737. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4738. init_faces3_flat( nElements, start, offsetMaterials );
  4739. }
  4740. };
  4741. function init_triangles_flat_uv( start ) {
  4742. var nElements = md.ntri_flat_uv;
  4743. if ( nElements ) {
  4744. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4745. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4746. init_faces3_flat( nElements, start, offsetMaterials );
  4747. init_uvs3( nElements, offsetUvs );
  4748. }
  4749. };
  4750. function init_triangles_smooth( start ) {
  4751. var nElements = md.ntri_smooth;
  4752. if ( nElements ) {
  4753. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4754. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4755. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4756. }
  4757. };
  4758. function init_triangles_smooth_uv( start ) {
  4759. var nElements = md.ntri_smooth_uv;
  4760. if ( nElements ) {
  4761. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4762. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4763. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4764. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4765. init_uvs3( nElements, offsetUvs );
  4766. }
  4767. };
  4768. function init_quads_flat( start ) {
  4769. var nElements = md.nquad_flat;
  4770. if ( nElements ) {
  4771. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4772. init_faces4_flat( nElements, start, offsetMaterials );
  4773. }
  4774. };
  4775. function init_quads_flat_uv( start ) {
  4776. var nElements = md.nquad_flat_uv;
  4777. if ( nElements ) {
  4778. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4779. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4780. init_faces4_flat( nElements, start, offsetMaterials );
  4781. init_uvs4( nElements, offsetUvs );
  4782. }
  4783. };
  4784. function init_quads_smooth( start ) {
  4785. var nElements = md.nquad_smooth;
  4786. if ( nElements ) {
  4787. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4788. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4789. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4790. }
  4791. };
  4792. function init_quads_smooth_uv( start ) {
  4793. var nElements = md.nquad_smooth_uv;
  4794. if ( nElements ) {
  4795. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4796. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4797. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4798. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4799. init_uvs4( nElements, offsetUvs );
  4800. }
  4801. };
  4802. };
  4803. function vertex ( scope, x, y, z ) {
  4804. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  4805. };
  4806. function f3 ( scope, a, b, c, mi ) {
  4807. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  4808. };
  4809. function f4 ( scope, a, b, c, d, mi ) {
  4810. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  4811. };
  4812. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  4813. var nax = normals[ na*3 ],
  4814. nay = normals[ na*3 + 1 ],
  4815. naz = normals[ na*3 + 2 ],
  4816. nbx = normals[ nb*3 ],
  4817. nby = normals[ nb*3 + 1 ],
  4818. nbz = normals[ nb*3 + 2 ],
  4819. ncx = normals[ nc*3 ],
  4820. ncy = normals[ nc*3 + 1 ],
  4821. ncz = normals[ nc*3 + 2 ];
  4822. scope.faces.push( new THREE.Face3( a, b, c,
  4823. [new THREE.Vector3( nax, nay, naz ),
  4824. new THREE.Vector3( nbx, nby, nbz ),
  4825. new THREE.Vector3( ncx, ncy, ncz )],
  4826. null,
  4827. mi ) );
  4828. };
  4829. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  4830. var nax = normals[ na*3 ],
  4831. nay = normals[ na*3 + 1 ],
  4832. naz = normals[ na*3 + 2 ],
  4833. nbx = normals[ nb*3 ],
  4834. nby = normals[ nb*3 + 1 ],
  4835. nbz = normals[ nb*3 + 2 ],
  4836. ncx = normals[ nc*3 ],
  4837. ncy = normals[ nc*3 + 1 ],
  4838. ncz = normals[ nc*3 + 2 ],
  4839. ndx = normals[ nd*3 ],
  4840. ndy = normals[ nd*3 + 1 ],
  4841. ndz = normals[ nd*3 + 2 ];
  4842. scope.faces.push( new THREE.Face4( a, b, c, d,
  4843. [new THREE.Vector3( nax, nay, naz ),
  4844. new THREE.Vector3( nbx, nby, nbz ),
  4845. new THREE.Vector3( ncx, ncy, ncz ),
  4846. new THREE.Vector3( ndx, ndy, ndz )],
  4847. null,
  4848. mi ) );
  4849. };
  4850. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  4851. var uv = [];
  4852. uv.push( new THREE.UV( u1, v1 ) );
  4853. uv.push( new THREE.UV( u2, v2 ) );
  4854. uv.push( new THREE.UV( u3, v3 ) );
  4855. where.push( uv );
  4856. };
  4857. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  4858. var uv = [];
  4859. uv.push( new THREE.UV( u1, v1 ) );
  4860. uv.push( new THREE.UV( u2, v2 ) );
  4861. uv.push( new THREE.UV( u3, v3 ) );
  4862. uv.push( new THREE.UV( u4, v4 ) );
  4863. where.push( uv );
  4864. };
  4865. Model.prototype = Object.create( THREE.Geometry.prototype );
  4866. callback( new Model( texturePath ) );
  4867. };
  4868. /**
  4869. * @author mrdoob / http://mrdoob.com/
  4870. */
  4871. THREE.ImageLoader = function () {
  4872. THREE.EventTarget.call( this );
  4873. this.crossOrigin = null;
  4874. };
  4875. THREE.ImageLoader.prototype = {
  4876. constructor: THREE.ImageLoader,
  4877. load: function ( url, image ) {
  4878. var scope = this;
  4879. if ( image === undefined ) image = new Image();
  4880. image.addEventListener( 'load', function () {
  4881. scope.dispatchEvent( { type: 'load', content: image } );
  4882. }, false );
  4883. image.addEventListener( 'error', function () {
  4884. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4885. }, false );
  4886. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  4887. image.src = url;
  4888. }
  4889. }
  4890. /**
  4891. * @author mrdoob / http://mrdoob.com/
  4892. * @author alteredq / http://alteredqualia.com/
  4893. */
  4894. THREE.JSONLoader = function ( showStatus ) {
  4895. THREE.Loader.call( this, showStatus );
  4896. this.withCredentials = false;
  4897. };
  4898. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  4899. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  4900. var scope = this;
  4901. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4902. this.onLoadStart();
  4903. this.loadAjaxJSON( this, url, callback, texturePath );
  4904. };
  4905. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  4906. var xhr = new XMLHttpRequest();
  4907. var length = 0;
  4908. xhr.withCredentials = this.withCredentials;
  4909. xhr.onreadystatechange = function () {
  4910. if ( xhr.readyState === xhr.DONE ) {
  4911. if ( xhr.status === 200 || xhr.status === 0 ) {
  4912. if ( xhr.responseText ) {
  4913. var json = JSON.parse( xhr.responseText );
  4914. context.createModel( json, callback, texturePath );
  4915. } else {
  4916. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  4917. }
  4918. // in context of more complex asset initialization
  4919. // do not block on single failed file
  4920. // maybe should go even one more level up
  4921. context.onLoadComplete();
  4922. } else {
  4923. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4924. }
  4925. } else if ( xhr.readyState === xhr.LOADING ) {
  4926. if ( callbackProgress ) {
  4927. if ( length === 0 ) {
  4928. length = xhr.getResponseHeader( "Content-Length" );
  4929. }
  4930. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4931. }
  4932. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  4933. length = xhr.getResponseHeader( "Content-Length" );
  4934. }
  4935. };
  4936. xhr.open( "GET", url, true );
  4937. xhr.send( null );
  4938. };
  4939. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  4940. var scope = this,
  4941. geometry = new THREE.Geometry(),
  4942. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  4943. this.initMaterials( geometry, json.materials, texturePath );
  4944. parseModel( scale );
  4945. parseSkin();
  4946. parseMorphing( scale );
  4947. geometry.computeCentroids();
  4948. geometry.computeFaceNormals();
  4949. if ( this.hasNormals( geometry ) ) geometry.computeTangents();
  4950. function parseModel( scale ) {
  4951. function isBitSet( value, position ) {
  4952. return value & ( 1 << position );
  4953. }
  4954. var i, j, fi,
  4955. offset, zLength, nVertices,
  4956. colorIndex, normalIndex, uvIndex, materialIndex,
  4957. type,
  4958. isQuad,
  4959. hasMaterial,
  4960. hasFaceUv, hasFaceVertexUv,
  4961. hasFaceNormal, hasFaceVertexNormal,
  4962. hasFaceColor, hasFaceVertexColor,
  4963. vertex, face, color, normal,
  4964. uvLayer, uvs, u, v,
  4965. faces = json.faces,
  4966. vertices = json.vertices,
  4967. normals = json.normals,
  4968. colors = json.colors,
  4969. nUvLayers = 0;
  4970. // disregard empty arrays
  4971. for ( i = 0; i < json.uvs.length; i++ ) {
  4972. if ( json.uvs[ i ].length ) nUvLayers ++;
  4973. }
  4974. for ( i = 0; i < nUvLayers; i++ ) {
  4975. geometry.faceUvs[ i ] = [];
  4976. geometry.faceVertexUvs[ i ] = [];
  4977. }
  4978. offset = 0;
  4979. zLength = vertices.length;
  4980. while ( offset < zLength ) {
  4981. vertex = new THREE.Vector3();
  4982. vertex.x = vertices[ offset ++ ] * scale;
  4983. vertex.y = vertices[ offset ++ ] * scale;
  4984. vertex.z = vertices[ offset ++ ] * scale;
  4985. geometry.vertices.push( vertex );
  4986. }
  4987. offset = 0;
  4988. zLength = faces.length;
  4989. while ( offset < zLength ) {
  4990. type = faces[ offset ++ ];
  4991. isQuad = isBitSet( type, 0 );
  4992. hasMaterial = isBitSet( type, 1 );
  4993. hasFaceUv = isBitSet( type, 2 );
  4994. hasFaceVertexUv = isBitSet( type, 3 );
  4995. hasFaceNormal = isBitSet( type, 4 );
  4996. hasFaceVertexNormal = isBitSet( type, 5 );
  4997. hasFaceColor = isBitSet( type, 6 );
  4998. hasFaceVertexColor = isBitSet( type, 7 );
  4999. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5000. if ( isQuad ) {
  5001. face = new THREE.Face4();
  5002. face.a = faces[ offset ++ ];
  5003. face.b = faces[ offset ++ ];
  5004. face.c = faces[ offset ++ ];
  5005. face.d = faces[ offset ++ ];
  5006. nVertices = 4;
  5007. } else {
  5008. face = new THREE.Face3();
  5009. face.a = faces[ offset ++ ];
  5010. face.b = faces[ offset ++ ];
  5011. face.c = faces[ offset ++ ];
  5012. nVertices = 3;
  5013. }
  5014. if ( hasMaterial ) {
  5015. materialIndex = faces[ offset ++ ];
  5016. face.materialIndex = materialIndex;
  5017. }
  5018. // to get face <=> uv index correspondence
  5019. fi = geometry.faces.length;
  5020. if ( hasFaceUv ) {
  5021. for ( i = 0; i < nUvLayers; i++ ) {
  5022. uvLayer = json.uvs[ i ];
  5023. uvIndex = faces[ offset ++ ];
  5024. u = uvLayer[ uvIndex * 2 ];
  5025. v = uvLayer[ uvIndex * 2 + 1 ];
  5026. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5027. }
  5028. }
  5029. if ( hasFaceVertexUv ) {
  5030. for ( i = 0; i < nUvLayers; i++ ) {
  5031. uvLayer = json.uvs[ i ];
  5032. uvs = [];
  5033. for ( j = 0; j < nVertices; j ++ ) {
  5034. uvIndex = faces[ offset ++ ];
  5035. u = uvLayer[ uvIndex * 2 ];
  5036. v = uvLayer[ uvIndex * 2 + 1 ];
  5037. uvs[ j ] = new THREE.UV( u, v );
  5038. }
  5039. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5040. }
  5041. }
  5042. if ( hasFaceNormal ) {
  5043. normalIndex = faces[ offset ++ ] * 3;
  5044. normal = new THREE.Vector3();
  5045. normal.x = normals[ normalIndex ++ ];
  5046. normal.y = normals[ normalIndex ++ ];
  5047. normal.z = normals[ normalIndex ];
  5048. face.normal = normal;
  5049. }
  5050. if ( hasFaceVertexNormal ) {
  5051. for ( i = 0; i < nVertices; i++ ) {
  5052. normalIndex = faces[ offset ++ ] * 3;
  5053. normal = new THREE.Vector3();
  5054. normal.x = normals[ normalIndex ++ ];
  5055. normal.y = normals[ normalIndex ++ ];
  5056. normal.z = normals[ normalIndex ];
  5057. face.vertexNormals.push( normal );
  5058. }
  5059. }
  5060. if ( hasFaceColor ) {
  5061. colorIndex = faces[ offset ++ ];
  5062. color = new THREE.Color( colors[ colorIndex ] );
  5063. face.color = color;
  5064. }
  5065. if ( hasFaceVertexColor ) {
  5066. for ( i = 0; i < nVertices; i++ ) {
  5067. colorIndex = faces[ offset ++ ];
  5068. color = new THREE.Color( colors[ colorIndex ] );
  5069. face.vertexColors.push( color );
  5070. }
  5071. }
  5072. geometry.faces.push( face );
  5073. }
  5074. };
  5075. function parseSkin() {
  5076. var i, l, x, y, z, w, a, b, c, d;
  5077. if ( json.skinWeights ) {
  5078. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5079. x = json.skinWeights[ i ];
  5080. y = json.skinWeights[ i + 1 ];
  5081. z = 0;
  5082. w = 0;
  5083. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5084. }
  5085. }
  5086. if ( json.skinIndices ) {
  5087. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5088. a = json.skinIndices[ i ];
  5089. b = json.skinIndices[ i + 1 ];
  5090. c = 0;
  5091. d = 0;
  5092. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5093. }
  5094. }
  5095. geometry.bones = json.bones;
  5096. geometry.animation = json.animation;
  5097. };
  5098. function parseMorphing( scale ) {
  5099. if ( json.morphTargets !== undefined ) {
  5100. var i, l, v, vl, dstVertices, srcVertices;
  5101. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5102. geometry.morphTargets[ i ] = {};
  5103. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5104. geometry.morphTargets[ i ].vertices = [];
  5105. dstVertices = geometry.morphTargets[ i ].vertices;
  5106. srcVertices = json.morphTargets [ i ].vertices;
  5107. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5108. var vertex = new THREE.Vector3();
  5109. vertex.x = srcVertices[ v ] * scale;
  5110. vertex.y = srcVertices[ v + 1 ] * scale;
  5111. vertex.z = srcVertices[ v + 2 ] * scale;
  5112. dstVertices.push( vertex );
  5113. }
  5114. }
  5115. }
  5116. if ( json.morphColors !== undefined ) {
  5117. var i, l, c, cl, dstColors, srcColors, color;
  5118. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5119. geometry.morphColors[ i ] = {};
  5120. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5121. geometry.morphColors[ i ].colors = [];
  5122. dstColors = geometry.morphColors[ i ].colors;
  5123. srcColors = json.morphColors [ i ].colors;
  5124. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5125. color = new THREE.Color( 0xffaa00 );
  5126. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5127. dstColors.push( color );
  5128. }
  5129. }
  5130. }
  5131. };
  5132. callback( geometry );
  5133. };
  5134. /**
  5135. * @author mrdoob / http://mrdoob.com/
  5136. */
  5137. THREE.LoadingMonitor = function () {
  5138. THREE.EventTarget.call( this );
  5139. var scope = this;
  5140. var loaded = 0;
  5141. var total = 0;
  5142. var onLoad = function ( event ) {
  5143. loaded ++;
  5144. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5145. if ( loaded === total ) {
  5146. scope.dispatchEvent( { type: 'load' } );
  5147. }
  5148. };
  5149. this.add = function ( loader ) {
  5150. total ++;
  5151. loader.addEventListener( 'load', onLoad, false );
  5152. };
  5153. };
  5154. /**
  5155. * @author mrdoob / http://mrdoob.com/
  5156. * @author alteredq / http://alteredqualia.com/
  5157. */
  5158. THREE.GeometryLoader = function () {
  5159. THREE.EventTarget.call( this );
  5160. this.crossOrigin = null;
  5161. this.path = null;
  5162. };
  5163. THREE.GeometryLoader.prototype = {
  5164. constructor: THREE.GeometryLoader,
  5165. load: function ( url ) {
  5166. var scope = this;
  5167. var geometry = null;
  5168. if ( scope.path === null ) {
  5169. var parts = url.split( '/' ); parts.pop();
  5170. scope.path = ( parts.length < 1 ? '.' : parts.join( '/' ) );
  5171. }
  5172. //
  5173. var xhr = new XMLHttpRequest();
  5174. xhr.addEventListener( 'load', function ( event ) {
  5175. if ( event.target.responseText ) {
  5176. geometry = scope.parse( JSON.parse( event.target.responseText ), monitor );
  5177. } else {
  5178. scope.dispatchEvent( { type: 'error', message: 'Invalid file [' + url + ']' } );
  5179. }
  5180. }, false );
  5181. xhr.addEventListener( 'error', function () {
  5182. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5183. }, false );
  5184. xhr.open( 'GET', url, true );
  5185. xhr.send( null );
  5186. //
  5187. var monitor = new THREE.LoadingMonitor();
  5188. monitor.addEventListener( 'load', function ( event ) {
  5189. scope.dispatchEvent( { type: 'load', content: geometry } );
  5190. } );
  5191. monitor.add( xhr );
  5192. },
  5193. parse: function ( data, monitor ) {
  5194. var scope = this;
  5195. var geometry = new THREE.Geometry();
  5196. var scale = ( data.scale !== undefined ) ? 1 / data.scale : 1;
  5197. // materials
  5198. if ( data.materials ) {
  5199. geometry.materials = [];
  5200. for ( var i = 0; i < data.materials.length; ++ i ) {
  5201. var m = data.materials[ i ];
  5202. function isPow2( n ) {
  5203. var l = Math.log( n ) / Math.LN2;
  5204. return Math.floor( l ) == l;
  5205. }
  5206. function nearestPow2( n ) {
  5207. var l = Math.log( n ) / Math.LN2;
  5208. return Math.pow( 2, Math.round( l ) );
  5209. }
  5210. function createTexture( where, name, sourceFile, repeat, offset, wrap ) {
  5211. where[ name ] = new THREE.Texture();
  5212. where[ name ].sourceFile = sourceFile;
  5213. if ( repeat ) {
  5214. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5215. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5216. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5217. }
  5218. if ( offset ) {
  5219. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5220. }
  5221. if ( wrap ) {
  5222. var wrapMap = {
  5223. "repeat": THREE.RepeatWrapping,
  5224. "mirror": THREE.MirroredRepeatWrapping
  5225. }
  5226. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5227. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5228. }
  5229. // load image
  5230. var texture = where[ name ];
  5231. var loader = new THREE.ImageLoader();
  5232. loader.addEventListener( 'load', function ( event ) {
  5233. var image = event.content;
  5234. if ( !isPow2( image.width ) || !isPow2( image.height ) ) {
  5235. var width = nearestPow2( image.width );
  5236. var height = nearestPow2( image.height );
  5237. texture.image = document.createElement( 'canvas' );
  5238. texture.image.width = width;
  5239. texture.image.height = height;
  5240. texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
  5241. } else {
  5242. texture.image = image;
  5243. }
  5244. texture.needsUpdate = true;
  5245. } );
  5246. loader.crossOrigin = scope.crossOrigin;
  5247. loader.load( scope.path + '/' + sourceFile );
  5248. if ( monitor ) monitor.add( loader );
  5249. }
  5250. function rgb2hex( rgb ) {
  5251. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5252. }
  5253. // defaults
  5254. var mtype = "MeshLambertMaterial";
  5255. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5256. // parameters from model file
  5257. if ( m.shading ) {
  5258. var shading = m.shading.toLowerCase();
  5259. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5260. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5261. }
  5262. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5263. mpars.blending = THREE[ m.blending ];
  5264. }
  5265. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5266. mpars.transparent = m.transparent;
  5267. }
  5268. if ( m.depthTest !== undefined ) {
  5269. mpars.depthTest = m.depthTest;
  5270. }
  5271. if ( m.depthWrite !== undefined ) {
  5272. mpars.depthWrite = m.depthWrite;
  5273. }
  5274. if ( m.vertexColors !== undefined ) {
  5275. if ( m.vertexColors == "face" ) {
  5276. mpars.vertexColors = THREE.FaceColors;
  5277. } else if ( m.vertexColors ) {
  5278. mpars.vertexColors = THREE.VertexColors;
  5279. }
  5280. }
  5281. // colors
  5282. if ( m.colorDiffuse ) {
  5283. mpars.color = rgb2hex( m.colorDiffuse );
  5284. } else if ( m.DbgColor ) {
  5285. mpars.color = m.DbgColor;
  5286. }
  5287. if ( m.colorSpecular ) {
  5288. mpars.specular = rgb2hex( m.colorSpecular );
  5289. }
  5290. if ( m.colorAmbient ) {
  5291. mpars.ambient = rgb2hex( m.colorAmbient );
  5292. }
  5293. // modifiers
  5294. if ( m.transparency ) {
  5295. mpars.opacity = m.transparency;
  5296. }
  5297. if ( m.specularCoef ) {
  5298. mpars.shininess = m.specularCoef;
  5299. }
  5300. if ( m.visible !== undefined ) {
  5301. mpars.visible = m.visible;
  5302. }
  5303. if ( m.flipSided !== undefined ) {
  5304. mpars.side = THREE.BackSide;
  5305. }
  5306. if ( m.doubleSided !== undefined ) {
  5307. mpars.side = THREE.DoubleSide;
  5308. }
  5309. if ( m.wireframe !== undefined ) {
  5310. mpars.wireframe = m.wireframe;
  5311. }
  5312. // textures
  5313. if ( m.mapDiffuse ) {
  5314. createTexture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  5315. }
  5316. if ( m.mapLight ) {
  5317. createTexture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  5318. }
  5319. if ( m.mapBump ) {
  5320. createTexture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap );
  5321. }
  5322. if ( m.mapNormal ) {
  5323. createTexture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  5324. }
  5325. if ( m.mapSpecular ) {
  5326. createTexture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  5327. }
  5328. // special case for normal mapped material
  5329. if ( m.mapNormal ) {
  5330. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5331. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5332. uniforms[ "tNormal" ].value = mpars.normalMap;
  5333. if ( m.mapNormalFactor ) {
  5334. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5335. }
  5336. if ( mpars.map ) {
  5337. uniforms[ "tDiffuse" ].value = mpars.map;
  5338. uniforms[ "enableDiffuse" ].value = true;
  5339. }
  5340. if ( mpars.specularMap ) {
  5341. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5342. uniforms[ "enableSpecular" ].value = true;
  5343. }
  5344. if ( mpars.lightMap ) {
  5345. uniforms[ "tAO" ].value = mpars.lightMap;
  5346. uniforms[ "enableAO" ].value = true;
  5347. }
  5348. // for the moment don't handle displacement texture
  5349. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5350. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5351. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5352. uniforms[ "uShininess" ].value = mpars.shininess;
  5353. if ( mpars.opacity !== undefined ) {
  5354. uniforms[ "uOpacity" ].value = mpars.opacity;
  5355. }
  5356. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5357. var material = new THREE.ShaderMaterial( parameters );
  5358. } else {
  5359. var material = new THREE[ mtype ]( mpars );
  5360. }
  5361. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5362. geometry.materials[ i ] = material;
  5363. }
  5364. }
  5365. // geometry
  5366. function isBitSet( value, position ) {
  5367. return value & ( 1 << position );
  5368. }
  5369. var faces = data.faces;
  5370. var vertices = data.vertices;
  5371. var normals = data.normals;
  5372. var colors = data.colors;
  5373. var nUvLayers = 0;
  5374. // disregard empty arrays
  5375. if ( data.uvs ) {
  5376. for ( var i = 0; i < data.uvs.length; i ++ ) {
  5377. if ( data.uvs[ i ].length ) nUvLayers ++;
  5378. }
  5379. }
  5380. for ( var i = 0; i < nUvLayers; i ++ ) {
  5381. geometry.faceUvs[ i ] = [];
  5382. geometry.faceVertexUvs[ i ] = [];
  5383. }
  5384. var offset = 0;
  5385. var zLength = vertices.length;
  5386. while ( offset < zLength ) {
  5387. var vertex = new THREE.Vector3();
  5388. vertex.x = vertices[ offset ++ ] * scale;
  5389. vertex.y = vertices[ offset ++ ] * scale;
  5390. vertex.z = vertices[ offset ++ ] * scale;
  5391. geometry.vertices.push( vertex );
  5392. }
  5393. offset = 0;
  5394. zLength = faces.length;
  5395. while ( offset < zLength ) {
  5396. var type = faces[ offset ++ ];
  5397. var isQuad = isBitSet( type, 0 );
  5398. var hasMaterial = isBitSet( type, 1 );
  5399. var hasFaceUv = isBitSet( type, 2 );
  5400. var hasFaceVertexUv = isBitSet( type, 3 );
  5401. var hasFaceNormal = isBitSet( type, 4 );
  5402. var hasFaceVertexNormal = isBitSet( type, 5 );
  5403. var hasFaceColor = isBitSet( type, 6 );
  5404. var hasFaceVertexColor = isBitSet( type, 7 );
  5405. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5406. if ( isQuad ) {
  5407. var face = new THREE.Face4();
  5408. face.a = faces[ offset ++ ];
  5409. face.b = faces[ offset ++ ];
  5410. face.c = faces[ offset ++ ];
  5411. face.d = faces[ offset ++ ];
  5412. var nVertices = 4;
  5413. } else {
  5414. var face = new THREE.Face3();
  5415. face.a = faces[ offset ++ ];
  5416. face.b = faces[ offset ++ ];
  5417. face.c = faces[ offset ++ ];
  5418. var nVertices = 3;
  5419. }
  5420. if ( hasMaterial ) {
  5421. var materialIndex = faces[ offset ++ ];
  5422. face.materialIndex = materialIndex;
  5423. }
  5424. // to get face <=> uv index correspondence
  5425. var fi = geometry.faces.length;
  5426. if ( hasFaceUv ) {
  5427. for ( var i = 0; i < nUvLayers; i ++ ) {
  5428. var uvLayer = data.uvs[ i ];
  5429. var uvIndex = faces[ offset ++ ];
  5430. var u = uvLayer[ uvIndex * 2 ];
  5431. var v = uvLayer[ uvIndex * 2 + 1 ];
  5432. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5433. }
  5434. }
  5435. if ( hasFaceVertexUv ) {
  5436. for ( var i = 0; i < nUvLayers; i ++ ) {
  5437. var uvLayer = data.uvs[ i ];
  5438. var uvs = [];
  5439. for ( var j = 0; j < nVertices; j ++ ) {
  5440. var uvIndex = faces[ offset ++ ];
  5441. var u = uvLayer[ uvIndex * 2 ];
  5442. var v = uvLayer[ uvIndex * 2 + 1 ];
  5443. uvs[ j ] = new THREE.UV( u, v );
  5444. }
  5445. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5446. }
  5447. }
  5448. if ( hasFaceNormal ) {
  5449. var normalIndex = faces[ offset ++ ] * 3;
  5450. var normal = new THREE.Vector3();
  5451. normal.x = normals[ normalIndex ++ ];
  5452. normal.y = normals[ normalIndex ++ ];
  5453. normal.z = normals[ normalIndex ];
  5454. face.normal = normal;
  5455. }
  5456. if ( hasFaceVertexNormal ) {
  5457. for ( i = 0; i < nVertices; i ++ ) {
  5458. var normalIndex = faces[ offset ++ ] * 3;
  5459. var normal = new THREE.Vector3();
  5460. normal.x = normals[ normalIndex ++ ];
  5461. normal.y = normals[ normalIndex ++ ];
  5462. normal.z = normals[ normalIndex ];
  5463. face.vertexNormals.push( normal );
  5464. }
  5465. }
  5466. if ( hasFaceColor ) {
  5467. var colorIndex = faces[ offset ++ ];
  5468. face.color = new THREE.Color( colors[ colorIndex ] );
  5469. }
  5470. if ( hasFaceVertexColor ) {
  5471. for ( var i = 0; i < nVertices; i ++ ) {
  5472. var colorIndex = faces[ offset ++ ];
  5473. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  5474. }
  5475. }
  5476. geometry.faces.push( face );
  5477. }
  5478. // skin
  5479. if ( data.skinWeights ) {
  5480. for ( var i = 0, l = data.skinWeights.length; i < l; i += 2 ) {
  5481. var x = data.skinWeights[ i ];
  5482. var y = data.skinWeights[ i + 1 ];
  5483. var z = 0;
  5484. var w = 0;
  5485. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5486. }
  5487. }
  5488. if ( data.skinIndices ) {
  5489. for ( var i = 0, l = data.skinIndices.length; i < l; i += 2 ) {
  5490. var a = data.skinIndices[ i ];
  5491. var b = data.skinIndices[ i + 1 ];
  5492. var c = 0;
  5493. var d = 0;
  5494. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5495. }
  5496. }
  5497. geometry.bones = data.bones;
  5498. geometry.animation = data.animation;
  5499. // morphing
  5500. if ( data.morphTargets ) {
  5501. for ( var i = 0, l = data.morphTargets.length; i < l; i ++ ) {
  5502. geometry.morphTargets[ i ] = {};
  5503. geometry.morphTargets[ i ].name = data.morphTargets[ i ].name;
  5504. geometry.morphTargets[ i ].vertices = [];
  5505. var dstVertices = geometry.morphTargets[ i ].vertices;
  5506. var srcVertices = data.morphTargets [ i ].vertices;
  5507. for( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5508. var vertex = new THREE.Vector3();
  5509. vertex.x = srcVertices[ v ] * scale;
  5510. vertex.y = srcVertices[ v + 1 ] * scale;
  5511. vertex.z = srcVertices[ v + 2 ] * scale;
  5512. dstVertices.push( vertex );
  5513. }
  5514. }
  5515. }
  5516. if ( data.morphColors ) {
  5517. for ( var i = 0, l = data.morphColors.length; i < l; i++ ) {
  5518. geometry.morphColors[ i ] = {};
  5519. geometry.morphColors[ i ].name = data.morphColors[ i ].name;
  5520. geometry.morphColors[ i ].colors = [];
  5521. var dstColors = geometry.morphColors[ i ].colors;
  5522. var srcColors = data.morphColors [ i ].colors;
  5523. for ( var c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5524. var color = new THREE.Color( 0xffaa00 );
  5525. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5526. dstColors.push( color );
  5527. }
  5528. }
  5529. }
  5530. geometry.computeCentroids();
  5531. geometry.computeFaceNormals();
  5532. return geometry;
  5533. }
  5534. };
  5535. /**
  5536. * @author alteredq / http://alteredqualia.com/
  5537. */
  5538. THREE.SceneLoader = function () {
  5539. this.onLoadStart = function () {};
  5540. this.onLoadProgress = function() {};
  5541. this.onLoadComplete = function () {};
  5542. this.callbackSync = function () {};
  5543. this.callbackProgress = function () {};
  5544. this.geometryHandlerMap = {};
  5545. this.hierarchyHandlerMap = {};
  5546. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5547. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  5548. };
  5549. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5550. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5551. var scope = this;
  5552. var xhr = new XMLHttpRequest();
  5553. xhr.onreadystatechange = function () {
  5554. if ( xhr.readyState === 4 ) {
  5555. if ( xhr.status === 200 || xhr.status === 0 ) {
  5556. var json = JSON.parse( xhr.responseText );
  5557. scope.parse( json, callbackFinished, url );
  5558. } else {
  5559. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5560. }
  5561. }
  5562. };
  5563. xhr.open( "GET", url, true );
  5564. xhr.send( null );
  5565. };
  5566. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5567. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5568. };
  5569. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5570. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5571. };
  5572. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5573. var scope = this;
  5574. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5575. var dg, dm, dc, df, dt,
  5576. g, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  5577. geometry, material, camera, fog,
  5578. texture, images,
  5579. light, hex, intensity,
  5580. counter_models, counter_textures,
  5581. total_models, total_textures,
  5582. result;
  5583. var target_array = [];
  5584. var data = json;
  5585. // async geometry loaders
  5586. for ( var typeID in this.geometryHandlerMap ) {
  5587. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5588. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5589. }
  5590. // async hierachy loaders
  5591. for ( var typeID in this.hierarchyHandlerMap ) {
  5592. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5593. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5594. }
  5595. counter_models = 0;
  5596. counter_textures = 0;
  5597. result = {
  5598. scene: new THREE.Scene(),
  5599. geometries: {},
  5600. materials: {},
  5601. textures: {},
  5602. objects: {},
  5603. cameras: {},
  5604. lights: {},
  5605. fogs: {},
  5606. empties: {}
  5607. };
  5608. if ( data.transform ) {
  5609. var position = data.transform.position,
  5610. rotation = data.transform.rotation,
  5611. scale = data.transform.scale;
  5612. if ( position )
  5613. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5614. if ( rotation )
  5615. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5616. if ( scale )
  5617. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5618. if ( position || rotation || scale ) {
  5619. result.scene.updateMatrix();
  5620. result.scene.updateMatrixWorld();
  5621. }
  5622. }
  5623. function get_url( source_url, url_type ) {
  5624. if ( url_type == "relativeToHTML" ) {
  5625. return source_url;
  5626. } else {
  5627. return urlBase + "/" + source_url;
  5628. }
  5629. };
  5630. // toplevel loader function, delegates to handle_children
  5631. function handle_objects() {
  5632. handle_children( result.scene, data.objects );
  5633. }
  5634. // handle all the children from the loaded json and attach them to given parent
  5635. function handle_children( parent, children ) {
  5636. for ( var dd in children ) {
  5637. // check by id if child has already been handled,
  5638. // if not, create new object
  5639. if ( result.objects[ dd ] === undefined ) {
  5640. var o = children[ dd ];
  5641. var object = null;
  5642. // meshes
  5643. if ( o.type && ( o.type in scope.hierarchyHandlerMap ) && o.loading === undefined ) {
  5644. var loaderParameters = {};
  5645. for ( var parType in g ) {
  5646. if ( parType !== "type" && parType !== "url" ) {
  5647. loaderParameters[ parType ] = g[ parType ];
  5648. }
  5649. }
  5650. material = result.materials[ o.materials[ 0 ] ];
  5651. o.loading = true;
  5652. var loader = scope.hierarchyHandlerMap[ o.type ][ "loaderObject" ];
  5653. // OBJLoader
  5654. if ( loader.addEventListener ) {
  5655. loader.addEventListener( 'load', create_callback_hierachy( dd, parent, material, o ) );
  5656. loader.load( get_url( o.url, data.urlBaseType ) );
  5657. } else {
  5658. // ColladaLoader
  5659. if ( loader.options ) {
  5660. loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ) );
  5661. // UTF8Loader
  5662. } else {
  5663. loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ), loaderParameters );
  5664. }
  5665. }
  5666. } else if ( o.geometry !== undefined ) {
  5667. geometry = result.geometries[ o.geometry ];
  5668. // geometry already loaded
  5669. if ( geometry ) {
  5670. var hasNormals = false;
  5671. // not anymore support for multiple materials
  5672. // shouldn't really be array
  5673. material = result.materials[ o.materials[ 0 ] ];
  5674. hasNormals = material instanceof THREE.ShaderMaterial;
  5675. if ( hasNormals ) {
  5676. geometry.computeTangents();
  5677. }
  5678. p = o.position;
  5679. r = o.rotation;
  5680. q = o.quaternion;
  5681. s = o.scale;
  5682. m = o.matrix;
  5683. // turn off quaternions, for the moment
  5684. q = 0;
  5685. if ( o.materials.length === 0 ) {
  5686. material = new THREE.MeshFaceMaterial();
  5687. }
  5688. // dirty hack to handle meshes with multiple materials
  5689. // just use face materials defined in model
  5690. if ( o.materials.length > 1 ) {
  5691. material = new THREE.MeshFaceMaterial();
  5692. }
  5693. if ( o.skin ) {
  5694. object = new THREE.SkinnedMesh( geometry, material );
  5695. } else if ( o.morph ) {
  5696. object = new THREE.MorphAnimMesh( geometry, material );
  5697. if ( o.duration !== undefined ) {
  5698. object.duration = o.duration;
  5699. }
  5700. if ( o.time !== undefined ) {
  5701. object.time = o.time;
  5702. }
  5703. if ( o.mirroredLoop !== undefined ) {
  5704. object.mirroredLoop = o.mirroredLoop;
  5705. }
  5706. if ( material.morphNormals ) {
  5707. geometry.computeMorphNormals();
  5708. }
  5709. } else {
  5710. object = new THREE.Mesh( geometry, material );
  5711. }
  5712. object.name = dd;
  5713. if ( m ) {
  5714. object.matrixAutoUpdate = false;
  5715. object.matrix.set(
  5716. m[0], m[1], m[2], m[3],
  5717. m[4], m[5], m[6], m[7],
  5718. m[8], m[9], m[10], m[11],
  5719. m[12], m[13], m[14], m[15]
  5720. );
  5721. } else {
  5722. object.position.set( p[0], p[1], p[2] );
  5723. if ( q ) {
  5724. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5725. object.useQuaternion = true;
  5726. } else {
  5727. object.rotation.set( r[0], r[1], r[2] );
  5728. }
  5729. object.scale.set( s[0], s[1], s[2] );
  5730. }
  5731. object.visible = o.visible;
  5732. object.castShadow = o.castShadow;
  5733. object.receiveShadow = o.receiveShadow;
  5734. parent.add( object );
  5735. result.objects[ dd ] = object;
  5736. }
  5737. // lights
  5738. } else if ( o.type === "DirectionalLight" || o.type === "PointLight" || o.type === "AmbientLight" ) {
  5739. hex = ( o.color !== undefined ) ? o.color : 0xffffff;
  5740. intensity = ( o.intensity !== undefined ) ? o.intensity : 1;
  5741. if ( o.type === "DirectionalLight" ) {
  5742. p = o.direction;
  5743. light = new THREE.DirectionalLight( hex, intensity );
  5744. light.position.set( p[0], p[1], p[2] );
  5745. if ( o.target ) {
  5746. target_array.push( { "object": light, "targetName" : o.target } );
  5747. // kill existing default target
  5748. // otherwise it gets added to scene when parent gets added
  5749. light.target = null;
  5750. }
  5751. } else if ( o.type === "PointLight" ) {
  5752. p = o.position;
  5753. d = o.distance;
  5754. light = new THREE.PointLight( hex, intensity, d );
  5755. light.position.set( p[0], p[1], p[2] );
  5756. } else if ( o.type === "AmbientLight" ) {
  5757. light = new THREE.AmbientLight( hex );
  5758. }
  5759. parent.add( light );
  5760. light.name = dd;
  5761. result.lights[ dd ] = light;
  5762. result.objects[ dd ] = light;
  5763. // cameras
  5764. } else if ( o.type === "PerspectiveCamera" || o.type === "OrthographicCamera" ) {
  5765. if ( o.type === "PerspectiveCamera" ) {
  5766. camera = new THREE.PerspectiveCamera( o.fov, o.aspect, o.near, o.far );
  5767. } else if ( o.type === "OrthographicCamera" ) {
  5768. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  5769. }
  5770. p = o.position;
  5771. camera.position.set( p[0], p[1], p[2] );
  5772. parent.add( camera );
  5773. camera.name = dd;
  5774. result.cameras[ dd ] = camera;
  5775. result.objects[ dd ] = camera;
  5776. // pure Object3D
  5777. } else {
  5778. p = o.position;
  5779. r = o.rotation;
  5780. q = o.quaternion;
  5781. s = o.scale;
  5782. // turn off quaternions, for the moment
  5783. q = 0;
  5784. object = new THREE.Object3D();
  5785. object.name = dd;
  5786. object.position.set( p[0], p[1], p[2] );
  5787. if ( q ) {
  5788. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5789. object.useQuaternion = true;
  5790. } else {
  5791. object.rotation.set( r[0], r[1], r[2] );
  5792. }
  5793. object.scale.set( s[0], s[1], s[2] );
  5794. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  5795. parent.add( object );
  5796. result.objects[ dd ] = object;
  5797. result.empties[ dd ] = object;
  5798. }
  5799. if ( object ) {
  5800. if ( o.properties !== undefined ) {
  5801. for ( var key in o.properties ) {
  5802. var value = o.properties[ key ];
  5803. object.properties[ key ] = value;
  5804. }
  5805. }
  5806. if ( o.children !== undefined ) {
  5807. handle_children( object, o.children );
  5808. }
  5809. }
  5810. }
  5811. }
  5812. };
  5813. function handle_mesh( geo, id ) {
  5814. result.geometries[ id ] = geo;
  5815. handle_objects();
  5816. };
  5817. function handle_hierarchy( node, id, parent, material, o ) {
  5818. var p = o.position;
  5819. var r = o.rotation;
  5820. var q = o.quaternion;
  5821. var s = o.scale;
  5822. node.position.set( p[0], p[1], p[2] );
  5823. if ( q ) {
  5824. node.quaternion.set( q[0], q[1], q[2], q[3] );
  5825. node.useQuaternion = true;
  5826. } else {
  5827. node.rotation.set( r[0], r[1], r[2] );
  5828. }
  5829. node.scale.set( s[0], s[1], s[2] );
  5830. if ( material ) {
  5831. node.traverse( function ( child ) {
  5832. child.material = material;
  5833. } );
  5834. }
  5835. parent.add( node );
  5836. result.objects[ id ] = node;
  5837. handle_objects();
  5838. };
  5839. function create_callback_geometry( id ) {
  5840. return function( geo ) {
  5841. handle_mesh( geo, id );
  5842. counter_models -= 1;
  5843. scope.onLoadComplete();
  5844. async_callback_gate();
  5845. }
  5846. };
  5847. function create_callback_hierachy( id, parent, material, obj ) {
  5848. return function( event ) {
  5849. var result;
  5850. // loaders which use EventTarget
  5851. if ( event.content ) {
  5852. result = event.content;
  5853. // ColladaLoader
  5854. } else if ( event.dae ) {
  5855. result = event.scene;
  5856. // UTF8Loader
  5857. } else {
  5858. result = event;
  5859. }
  5860. handle_hierarchy( result, id, parent, material, obj );
  5861. counter_models -= 1;
  5862. scope.onLoadComplete();
  5863. async_callback_gate();
  5864. }
  5865. };
  5866. function create_callback_embed( id ) {
  5867. return function( geo ) {
  5868. result.geometries[ id ] = geo;
  5869. }
  5870. };
  5871. function async_callback_gate() {
  5872. var progress = {
  5873. totalModels : total_models,
  5874. totalTextures : total_textures,
  5875. loadedModels : total_models - counter_models,
  5876. loadedTextures : total_textures - counter_textures
  5877. };
  5878. scope.callbackProgress( progress, result );
  5879. scope.onLoadProgress();
  5880. if ( counter_models === 0 && counter_textures === 0 ) {
  5881. finalize();
  5882. callbackFinished( result );
  5883. }
  5884. };
  5885. function finalize() {
  5886. // take care of targets which could be asynchronously loaded objects
  5887. for ( var i = 0; i < target_array.length; i ++ ) {
  5888. var ta = target_array[ i ];
  5889. var target = result.objects[ ta.targetName ];
  5890. if ( target ) {
  5891. ta.object.target = target;
  5892. } else {
  5893. // if there was error and target of specified name doesn't exist in the scene file
  5894. // create instead dummy target
  5895. // (target must be added to scene explicitly as parent is already added)
  5896. ta.object.target = new THREE.Object3D();
  5897. result.scene.add( ta.object.target );
  5898. }
  5899. ta.object.target.properties.targetInverse = ta.object;
  5900. }
  5901. };
  5902. var callbackTexture = function ( count ) {
  5903. counter_textures -= count;
  5904. async_callback_gate();
  5905. scope.onLoadComplete();
  5906. };
  5907. // must use this instead of just directly calling callbackTexture
  5908. // because of closure in the calling context loop
  5909. var generateTextureCallback = function ( count ) {
  5910. return function() {
  5911. callbackTexture( count );
  5912. };
  5913. };
  5914. // first go synchronous elements
  5915. // fogs
  5916. for ( df in data.fogs ) {
  5917. f = data.fogs[ df ];
  5918. if ( f.type === "linear" ) {
  5919. fog = new THREE.Fog( 0x000000, f.near, f.far );
  5920. } else if ( f.type === "exp2" ) {
  5921. fog = new THREE.FogExp2( 0x000000, f.density );
  5922. }
  5923. c = f.color;
  5924. fog.color.setRGB( c[0], c[1], c[2] );
  5925. result.fogs[ df ] = fog;
  5926. }
  5927. // now come potentially asynchronous elements
  5928. // geometries
  5929. // count how many geometries will be loaded asynchronously
  5930. for ( dg in data.geometries ) {
  5931. g = data.geometries[ dg ];
  5932. if ( g.type in this.geometryHandlerMap ) {
  5933. counter_models += 1;
  5934. scope.onLoadStart();
  5935. }
  5936. }
  5937. // count how many hierarchies will be loaded asynchronously
  5938. for ( var dd in data.objects ) {
  5939. var o = data.objects[ dd ];
  5940. if ( o.type && ( o.type in this.hierarchyHandlerMap ) ) {
  5941. counter_models += 1;
  5942. scope.onLoadStart();
  5943. }
  5944. }
  5945. total_models = counter_models;
  5946. for ( dg in data.geometries ) {
  5947. g = data.geometries[ dg ];
  5948. if ( g.type === "cube" ) {
  5949. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.widthSegments, g.heightSegments, g.depthSegments, null, g.flipped, g.sides );
  5950. result.geometries[ dg ] = geometry;
  5951. } else if ( g.type === "plane" ) {
  5952. geometry = new THREE.PlaneGeometry( g.width, g.height, g.widthSegments, g.heightSegments );
  5953. result.geometries[ dg ] = geometry;
  5954. } else if ( g.type === "sphere" ) {
  5955. geometry = new THREE.SphereGeometry( g.radius, g.widthSegments, g.heightSegments );
  5956. result.geometries[ dg ] = geometry;
  5957. } else if ( g.type === "cylinder" ) {
  5958. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  5959. result.geometries[ dg ] = geometry;
  5960. } else if ( g.type === "torus" ) {
  5961. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  5962. result.geometries[ dg ] = geometry;
  5963. } else if ( g.type === "icosahedron" ) {
  5964. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  5965. result.geometries[ dg ] = geometry;
  5966. } else if ( g.type in this.geometryHandlerMap ) {
  5967. var loaderParameters = {};
  5968. for ( var parType in g ) {
  5969. if ( parType !== "type" && parType !== "url" ) {
  5970. loaderParameters[ parType ] = g[ parType ];
  5971. }
  5972. }
  5973. var loader = this.geometryHandlerMap[ g.type ][ "loaderObject" ];
  5974. loader.load( get_url( g.url, data.urlBaseType ), create_callback_geometry( dg ), loaderParameters );
  5975. } else if ( g.type === "embedded" ) {
  5976. var modelJson = data.embeds[ g.id ],
  5977. texture_path = "";
  5978. // pass metadata along to jsonLoader so it knows the format version
  5979. modelJson.metadata = data.metadata;
  5980. if ( modelJson ) {
  5981. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  5982. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  5983. }
  5984. }
  5985. }
  5986. // textures
  5987. // count how many textures will be loaded asynchronously
  5988. for ( dt in data.textures ) {
  5989. tt = data.textures[ dt ];
  5990. if ( tt.url instanceof Array ) {
  5991. counter_textures += tt.url.length;
  5992. for( var n = 0; n < tt.url.length; n ++ ) {
  5993. scope.onLoadStart();
  5994. }
  5995. } else {
  5996. counter_textures += 1;
  5997. scope.onLoadStart();
  5998. }
  5999. }
  6000. total_textures = counter_textures;
  6001. for ( dt in data.textures ) {
  6002. tt = data.textures[ dt ];
  6003. if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined ) {
  6004. tt.mapping = new THREE[ tt.mapping ]();
  6005. }
  6006. if ( tt.url instanceof Array ) {
  6007. var count = tt.url.length;
  6008. var url_array = [];
  6009. for( var i = 0; i < count; i ++ ) {
  6010. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  6011. }
  6012. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  6013. if ( isCompressed ) {
  6014. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  6015. } else {
  6016. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  6017. }
  6018. } else {
  6019. var isCompressed = tt.url.toLowerCase().endsWith( ".dds" );
  6020. var fullUrl = get_url( tt.url, data.urlBaseType );
  6021. var textureCallback = generateTextureCallback( 1 );
  6022. if ( isCompressed ) {
  6023. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, tt.mapping, textureCallback );
  6024. } else {
  6025. texture = THREE.ImageUtils.loadTexture( fullUrl, tt.mapping, textureCallback );
  6026. }
  6027. if ( THREE[ tt.minFilter ] !== undefined )
  6028. texture.minFilter = THREE[ tt.minFilter ];
  6029. if ( THREE[ tt.magFilter ] !== undefined )
  6030. texture.magFilter = THREE[ tt.magFilter ];
  6031. if ( tt.anisotropy ) texture.anisotropy = tt.anisotropy;
  6032. if ( tt.repeat ) {
  6033. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  6034. if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6035. if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6036. }
  6037. if ( tt.offset ) {
  6038. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  6039. }
  6040. // handle wrap after repeat so that default repeat can be overriden
  6041. if ( tt.wrap ) {
  6042. var wrapMap = {
  6043. "repeat" : THREE.RepeatWrapping,
  6044. "mirror" : THREE.MirroredRepeatWrapping
  6045. }
  6046. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  6047. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  6048. }
  6049. }
  6050. result.textures[ dt ] = texture;
  6051. }
  6052. // materials
  6053. for ( dm in data.materials ) {
  6054. m = data.materials[ dm ];
  6055. for ( pp in m.parameters ) {
  6056. if ( pp === "envMap" || pp === "map" || pp === "lightMap" || pp === "bumpMap" ) {
  6057. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  6058. } else if ( pp === "shading" ) {
  6059. m.parameters[ pp ] = ( m.parameters[ pp ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6060. } else if ( pp === "side" ) {
  6061. if ( m.parameters[ pp ] == "double" ) {
  6062. m.parameters[ pp ] = THREE.DoubleSide;
  6063. } else if ( m.parameters[ pp ] == "back" ) {
  6064. m.parameters[ pp ] = THREE.BackSide;
  6065. } else {
  6066. m.parameters[ pp ] = THREE.FrontSide;
  6067. }
  6068. } else if ( pp === "blending" ) {
  6069. m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  6070. } else if ( pp === "combine" ) {
  6071. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  6072. } else if ( pp === "vertexColors" ) {
  6073. if ( m.parameters[ pp ] == "face" ) {
  6074. m.parameters[ pp ] = THREE.FaceColors;
  6075. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6076. } else if ( m.parameters[ pp ] ) {
  6077. m.parameters[ pp ] = THREE.VertexColors;
  6078. }
  6079. } else if ( pp === "wrapRGB" ) {
  6080. var v3 = m.parameters[ pp ];
  6081. m.parameters[ pp ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6082. }
  6083. }
  6084. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  6085. m.parameters.transparent = true;
  6086. }
  6087. if ( m.parameters.normalMap ) {
  6088. var shader = THREE.ShaderUtils.lib[ "normal" ];
  6089. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6090. var diffuse = m.parameters.color;
  6091. var specular = m.parameters.specular;
  6092. var ambient = m.parameters.ambient;
  6093. var shininess = m.parameters.shininess;
  6094. uniforms[ "tNormal" ].value = result.textures[ m.parameters.normalMap ];
  6095. if ( m.parameters.normalScale ) {
  6096. uniforms[ "uNormalScale" ].value.set( m.parameters.normalScale[ 0 ], m.parameters.normalScale[ 1 ] );
  6097. }
  6098. if ( m.parameters.map ) {
  6099. uniforms[ "tDiffuse" ].value = m.parameters.map;
  6100. uniforms[ "enableDiffuse" ].value = true;
  6101. }
  6102. if ( m.parameters.envMap ) {
  6103. uniforms[ "tCube" ].value = m.parameters.envMap;
  6104. uniforms[ "enableReflection" ].value = true;
  6105. uniforms[ "uReflectivity" ].value = m.parameters.reflectivity;
  6106. }
  6107. if ( m.parameters.lightMap ) {
  6108. uniforms[ "tAO" ].value = m.parameters.lightMap;
  6109. uniforms[ "enableAO" ].value = true;
  6110. }
  6111. if ( m.parameters.specularMap ) {
  6112. uniforms[ "tSpecular" ].value = result.textures[ m.parameters.specularMap ];
  6113. uniforms[ "enableSpecular" ].value = true;
  6114. }
  6115. if ( m.parameters.displacementMap ) {
  6116. uniforms[ "tDisplacement" ].value = result.textures[ m.parameters.displacementMap ];
  6117. uniforms[ "enableDisplacement" ].value = true;
  6118. uniforms[ "uDisplacementBias" ].value = m.parameters.displacementBias;
  6119. uniforms[ "uDisplacementScale" ].value = m.parameters.displacementScale;
  6120. }
  6121. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6122. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6123. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6124. uniforms[ "uShininess" ].value = shininess;
  6125. if ( m.parameters.opacity ) {
  6126. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  6127. }
  6128. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6129. material = new THREE.ShaderMaterial( parameters );
  6130. } else {
  6131. material = new THREE[ m.type ]( m.parameters );
  6132. }
  6133. result.materials[ dm ] = material;
  6134. }
  6135. // objects ( synchronous init of procedural primitives )
  6136. handle_objects();
  6137. // defaults
  6138. if ( result.cameras && data.defaults.camera ) {
  6139. result.currentCamera = result.cameras[ data.defaults.camera ];
  6140. }
  6141. if ( result.fogs && data.defaults.fog ) {
  6142. result.scene.fog = result.fogs[ data.defaults.fog ];
  6143. }
  6144. c = data.defaults.bgcolor;
  6145. result.bgColor = new THREE.Color();
  6146. result.bgColor.setRGB( c[0], c[1], c[2] );
  6147. result.bgColorAlpha = data.defaults.bgalpha;
  6148. // synchronous callback
  6149. scope.callbackSync( result );
  6150. // just in case there are no async elements
  6151. async_callback_gate();
  6152. };
  6153. /**
  6154. * @author mrdoob / http://mrdoob.com/
  6155. */
  6156. THREE.TextureLoader = function () {
  6157. THREE.EventTarget.call( this );
  6158. this.crossOrigin = null;
  6159. };
  6160. THREE.TextureLoader.prototype = {
  6161. constructor: THREE.TextureLoader,
  6162. load: function ( url ) {
  6163. var scope = this;
  6164. var image = new Image();
  6165. image.addEventListener( 'load', function () {
  6166. var texture = new THREE.Texture( image );
  6167. texture.needsUpdate = true;
  6168. scope.dispatchEvent( { type: 'load', content: texture } );
  6169. }, false );
  6170. image.addEventListener( 'error', function () {
  6171. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6172. }, false );
  6173. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6174. image.src = url;
  6175. }
  6176. }
  6177. /**
  6178. * @author mrdoob / http://mrdoob.com/
  6179. * @author alteredq / http://alteredqualia.com/
  6180. */
  6181. THREE.Material = function () {
  6182. THREE.MaterialLibrary.push( this );
  6183. this.id = THREE.MaterialIdCount ++;
  6184. this.name = '';
  6185. this.side = THREE.FrontSide;
  6186. this.opacity = 1;
  6187. this.transparent = false;
  6188. this.blending = THREE.NormalBlending;
  6189. this.blendSrc = THREE.SrcAlphaFactor;
  6190. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6191. this.blendEquation = THREE.AddEquation;
  6192. this.depthTest = true;
  6193. this.depthWrite = true;
  6194. this.polygonOffset = false;
  6195. this.polygonOffsetFactor = 0;
  6196. this.polygonOffsetUnits = 0;
  6197. this.alphaTest = 0;
  6198. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6199. this.visible = true;
  6200. this.needsUpdate = true;
  6201. };
  6202. THREE.Material.prototype.setValues = function ( values ) {
  6203. if ( values === undefined ) return;
  6204. for ( var key in values ) {
  6205. var newValue = values[ key ];
  6206. if ( newValue === undefined ) {
  6207. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6208. continue;
  6209. }
  6210. if ( key in this ) {
  6211. var currentValue = this[ key ];
  6212. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6213. currentValue.copy( newValue );
  6214. } else if ( currentValue instanceof THREE.Color && typeof( newValue ) === "number" ) {
  6215. currentValue.setHex( newValue );
  6216. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6217. currentValue.copy( newValue );
  6218. } else {
  6219. this[ key ] = newValue;
  6220. }
  6221. }
  6222. }
  6223. };
  6224. THREE.Material.prototype.clone = function ( material ) {
  6225. if ( material === undefined ) material = new THREE.Material();
  6226. material.name = this.name;
  6227. material.side = this.side;
  6228. material.opacity = this.opacity;
  6229. material.transparent = this.transparent;
  6230. material.blending = this.blending;
  6231. material.blendSrc = this.blendSrc;
  6232. material.blendDst = this.blendDst;
  6233. material.blendEquation = this.blendEquation;
  6234. material.depthTest = this.depthTest;
  6235. material.depthWrite = this.depthWrite;
  6236. material.polygonOffset = this.polygonOffset;
  6237. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6238. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6239. material.alphaTest = this.alphaTest;
  6240. material.overdraw = this.overdraw;
  6241. material.visible = this.visible;
  6242. return material;
  6243. };
  6244. THREE.Material.prototype.deallocate = function () {
  6245. var index = THREE.MaterialLibrary.indexOf( this );
  6246. if ( index !== -1 ) THREE.MaterialLibrary.splice( index, 1 );
  6247. };
  6248. THREE.MaterialIdCount = 0;
  6249. THREE.MaterialLibrary = [];
  6250. /**
  6251. * @author mrdoob / http://mrdoob.com/
  6252. * @author alteredq / http://alteredqualia.com/
  6253. *
  6254. * parameters = {
  6255. * color: <hex>,
  6256. * opacity: <float>,
  6257. *
  6258. * blending: THREE.NormalBlending,
  6259. * depthTest: <bool>,
  6260. *
  6261. * linewidth: <float>,
  6262. * linecap: "round",
  6263. * linejoin: "round",
  6264. *
  6265. * vertexColors: <bool>
  6266. *
  6267. * fog: <bool>
  6268. * }
  6269. */
  6270. THREE.LineBasicMaterial = function ( parameters ) {
  6271. THREE.Material.call( this );
  6272. this.color = new THREE.Color( 0xffffff );
  6273. this.linewidth = 1;
  6274. this.linecap = 'round';
  6275. this.linejoin = 'round';
  6276. this.vertexColors = false;
  6277. this.fog = true;
  6278. this.setValues( parameters );
  6279. };
  6280. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6281. THREE.LineBasicMaterial.prototype.clone = function () {
  6282. var material = new THREE.LineBasicMaterial();
  6283. THREE.Material.prototype.clone.call( this, material );
  6284. material.color.copy( this.color );
  6285. material.linewidth = this.linewidth;
  6286. material.linecap = this.linecap;
  6287. material.linejoin = this.linejoin;
  6288. material.vertexColors = this.vertexColors;
  6289. material.fog = this.fog;
  6290. return material;
  6291. };
  6292. /**
  6293. * @author alteredq / http://alteredqualia.com/
  6294. *
  6295. * parameters = {
  6296. * color: <hex>,
  6297. * opacity: <float>,
  6298. *
  6299. * blending: THREE.NormalBlending,
  6300. * depthTest: <bool>,
  6301. *
  6302. * linewidth: <float>,
  6303. *
  6304. * scale: <float>,
  6305. * dashSize: <float>,
  6306. * gapSize: <float>,
  6307. *
  6308. * vertexColors: <bool>
  6309. *
  6310. * fog: <bool>
  6311. * }
  6312. */
  6313. THREE.LineDashedMaterial = function ( parameters ) {
  6314. THREE.Material.call( this );
  6315. this.color = new THREE.Color( 0xffffff );
  6316. this.linewidth = 1;
  6317. this.scale = 1;
  6318. this.dashSize = 3;
  6319. this.gapSize = 1;
  6320. this.vertexColors = false;
  6321. this.fog = true;
  6322. this.setValues( parameters );
  6323. };
  6324. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6325. THREE.LineDashedMaterial.prototype.clone = function () {
  6326. var material = new THREE.LineDashedMaterial();
  6327. THREE.Material.prototype.clone.call( this, material );
  6328. material.color.copy( this.color );
  6329. material.linewidth = this.linewidth;
  6330. material.scale = this.scale;
  6331. material.dashSize = this.dashSize;
  6332. material.gapSize = this.gapSize;
  6333. material.vertexColors = this.vertexColors;
  6334. material.fog = this.fog;
  6335. return material;
  6336. };
  6337. /**
  6338. * @author mrdoob / http://mrdoob.com/
  6339. * @author alteredq / http://alteredqualia.com/
  6340. *
  6341. * parameters = {
  6342. * color: <hex>,
  6343. * opacity: <float>,
  6344. * map: new THREE.Texture( <Image> ),
  6345. *
  6346. * lightMap: new THREE.Texture( <Image> ),
  6347. *
  6348. * specularMap: new THREE.Texture( <Image> ),
  6349. *
  6350. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6351. * combine: THREE.Multiply,
  6352. * reflectivity: <float>,
  6353. * refractionRatio: <float>,
  6354. *
  6355. * shading: THREE.SmoothShading,
  6356. * blending: THREE.NormalBlending,
  6357. * depthTest: <bool>,
  6358. *
  6359. * wireframe: <boolean>,
  6360. * wireframeLinewidth: <float>,
  6361. *
  6362. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6363. *
  6364. * skinning: <bool>,
  6365. * morphTargets: <bool>,
  6366. *
  6367. * fog: <bool>
  6368. * }
  6369. */
  6370. THREE.MeshBasicMaterial = function ( parameters ) {
  6371. THREE.Material.call( this );
  6372. this.color = new THREE.Color( 0xffffff ); // emissive
  6373. this.map = null;
  6374. this.lightMap = null;
  6375. this.specularMap = null;
  6376. this.envMap = null;
  6377. this.combine = THREE.MultiplyOperation;
  6378. this.reflectivity = 1;
  6379. this.refractionRatio = 0.98;
  6380. this.fog = true;
  6381. this.shading = THREE.SmoothShading;
  6382. this.wireframe = false;
  6383. this.wireframeLinewidth = 1;
  6384. this.wireframeLinecap = 'round';
  6385. this.wireframeLinejoin = 'round';
  6386. this.vertexColors = THREE.NoColors;
  6387. this.skinning = false;
  6388. this.morphTargets = false;
  6389. this.setValues( parameters );
  6390. };
  6391. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6392. THREE.MeshBasicMaterial.prototype.clone = function () {
  6393. var material = new THREE.MeshBasicMaterial();
  6394. THREE.Material.prototype.clone.call( this, material );
  6395. material.color.copy( this.color );
  6396. material.map = this.map;
  6397. material.lightMap = this.lightMap;
  6398. material.specularMap = this.specularMap;
  6399. material.envMap = this.envMap;
  6400. material.combine = this.combine;
  6401. material.reflectivity = this.reflectivity;
  6402. material.refractionRatio = this.refractionRatio;
  6403. material.fog = this.fog;
  6404. material.shading = this.shading;
  6405. material.wireframe = this.wireframe;
  6406. material.wireframeLinewidth = this.wireframeLinewidth;
  6407. material.wireframeLinecap = this.wireframeLinecap;
  6408. material.wireframeLinejoin = this.wireframeLinejoin;
  6409. material.vertexColors = this.vertexColors;
  6410. material.skinning = this.skinning;
  6411. material.morphTargets = this.morphTargets;
  6412. return material;
  6413. };
  6414. /**
  6415. * @author mrdoob / http://mrdoob.com/
  6416. * @author alteredq / http://alteredqualia.com/
  6417. *
  6418. * parameters = {
  6419. * color: <hex>,
  6420. * ambient: <hex>,
  6421. * emissive: <hex>,
  6422. * opacity: <float>,
  6423. *
  6424. * map: new THREE.Texture( <Image> ),
  6425. *
  6426. * lightMap: new THREE.Texture( <Image> ),
  6427. *
  6428. * specularMap: new THREE.Texture( <Image> ),
  6429. *
  6430. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6431. * combine: THREE.Multiply,
  6432. * reflectivity: <float>,
  6433. * refractionRatio: <float>,
  6434. *
  6435. * shading: THREE.SmoothShading,
  6436. * blending: THREE.NormalBlending,
  6437. * depthTest: <bool>,
  6438. *
  6439. * wireframe: <boolean>,
  6440. * wireframeLinewidth: <float>,
  6441. *
  6442. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6443. *
  6444. * skinning: <bool>,
  6445. * morphTargets: <bool>,
  6446. * morphNormals: <bool>,
  6447. *
  6448. * fog: <bool>
  6449. * }
  6450. */
  6451. THREE.MeshLambertMaterial = function ( parameters ) {
  6452. THREE.Material.call( this );
  6453. this.color = new THREE.Color( 0xffffff ); // diffuse
  6454. this.ambient = new THREE.Color( 0xffffff );
  6455. this.emissive = new THREE.Color( 0x000000 );
  6456. this.wrapAround = false;
  6457. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6458. this.map = null;
  6459. this.lightMap = null;
  6460. this.specularMap = null;
  6461. this.envMap = null;
  6462. this.combine = THREE.MultiplyOperation;
  6463. this.reflectivity = 1;
  6464. this.refractionRatio = 0.98;
  6465. this.fog = true;
  6466. this.shading = THREE.SmoothShading;
  6467. this.wireframe = false;
  6468. this.wireframeLinewidth = 1;
  6469. this.wireframeLinecap = 'round';
  6470. this.wireframeLinejoin = 'round';
  6471. this.vertexColors = THREE.NoColors;
  6472. this.skinning = false;
  6473. this.morphTargets = false;
  6474. this.morphNormals = false;
  6475. this.setValues( parameters );
  6476. };
  6477. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6478. THREE.MeshLambertMaterial.prototype.clone = function () {
  6479. var material = new THREE.MeshLambertMaterial();
  6480. THREE.Material.prototype.clone.call( this, material );
  6481. material.color.copy( this.color );
  6482. material.ambient.copy( this.ambient );
  6483. material.emissive.copy( this.emissive );
  6484. material.wrapAround = this.wrapAround;
  6485. material.wrapRGB.copy( this.wrapRGB );
  6486. material.map = this.map;
  6487. material.lightMap = this.lightMap;
  6488. material.specularMap = this.specularMap;
  6489. material.envMap = this.envMap;
  6490. material.combine = this.combine;
  6491. material.reflectivity = this.reflectivity;
  6492. material.refractionRatio = this.refractionRatio;
  6493. material.fog = this.fog;
  6494. material.shading = this.shading;
  6495. material.wireframe = this.wireframe;
  6496. material.wireframeLinewidth = this.wireframeLinewidth;
  6497. material.wireframeLinecap = this.wireframeLinecap;
  6498. material.wireframeLinejoin = this.wireframeLinejoin;
  6499. material.vertexColors = this.vertexColors;
  6500. material.skinning = this.skinning;
  6501. material.morphTargets = this.morphTargets;
  6502. material.morphNormals = this.morphNormals;
  6503. return material;
  6504. };
  6505. /**
  6506. * @author mrdoob / http://mrdoob.com/
  6507. * @author alteredq / http://alteredqualia.com/
  6508. *
  6509. * parameters = {
  6510. * color: <hex>,
  6511. * ambient: <hex>,
  6512. * emissive: <hex>,
  6513. * specular: <hex>,
  6514. * shininess: <float>,
  6515. * opacity: <float>,
  6516. *
  6517. * map: new THREE.Texture( <Image> ),
  6518. *
  6519. * lightMap: new THREE.Texture( <Image> ),
  6520. *
  6521. * bumpMap: new THREE.Texture( <Image> ),
  6522. * bumpScale: <float>,
  6523. *
  6524. * normalMap: new THREE.Texture( <Image> ),
  6525. * normalScale: <Vector2>,
  6526. *
  6527. * specularMap: new THREE.Texture( <Image> ),
  6528. *
  6529. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6530. * combine: THREE.Multiply,
  6531. * reflectivity: <float>,
  6532. * refractionRatio: <float>,
  6533. *
  6534. * shading: THREE.SmoothShading,
  6535. * blending: THREE.NormalBlending,
  6536. * depthTest: <bool>,
  6537. *
  6538. * wireframe: <boolean>,
  6539. * wireframeLinewidth: <float>,
  6540. *
  6541. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6542. *
  6543. * skinning: <bool>,
  6544. * morphTargets: <bool>,
  6545. * morphNormals: <bool>,
  6546. *
  6547. * fog: <bool>
  6548. * }
  6549. */
  6550. THREE.MeshPhongMaterial = function ( parameters ) {
  6551. THREE.Material.call( this );
  6552. this.color = new THREE.Color( 0xffffff ); // diffuse
  6553. this.ambient = new THREE.Color( 0xffffff );
  6554. this.emissive = new THREE.Color( 0x000000 );
  6555. this.specular = new THREE.Color( 0x111111 );
  6556. this.shininess = 30;
  6557. this.metal = false;
  6558. this.perPixel = true;
  6559. this.wrapAround = false;
  6560. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6561. this.map = null;
  6562. this.lightMap = null;
  6563. this.bumpMap = null;
  6564. this.bumpScale = 1;
  6565. this.normalMap = null;
  6566. this.normalScale = new THREE.Vector2( 1, 1 );
  6567. this.specularMap = null;
  6568. this.envMap = null;
  6569. this.combine = THREE.MultiplyOperation;
  6570. this.reflectivity = 1;
  6571. this.refractionRatio = 0.98;
  6572. this.fog = true;
  6573. this.shading = THREE.SmoothShading;
  6574. this.wireframe = false;
  6575. this.wireframeLinewidth = 1;
  6576. this.wireframeLinecap = 'round';
  6577. this.wireframeLinejoin = 'round';
  6578. this.vertexColors = THREE.NoColors;
  6579. this.skinning = false;
  6580. this.morphTargets = false;
  6581. this.morphNormals = false;
  6582. this.setValues( parameters );
  6583. };
  6584. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6585. THREE.MeshPhongMaterial.prototype.clone = function () {
  6586. var material = new THREE.MeshPhongMaterial();
  6587. THREE.Material.prototype.clone.call( this, material );
  6588. material.color.copy( this.color );
  6589. material.ambient.copy( this.ambient );
  6590. material.emissive.copy( this.emissive );
  6591. material.specular.copy( this.specular );
  6592. material.shininess = this.shininess;
  6593. material.metal = this.metal;
  6594. material.perPixel = this.perPixel;
  6595. material.wrapAround = this.wrapAround;
  6596. material.wrapRGB.copy( this.wrapRGB );
  6597. material.map = this.map;
  6598. material.lightMap = this.lightMap;
  6599. material.bumpMap = this.bumpMap;
  6600. material.bumpScale = this.bumpScale;
  6601. material.normalMap = this.normalMap;
  6602. material.normalScale.copy( this.normalScale );
  6603. material.specularMap = this.specularMap;
  6604. material.envMap = this.envMap;
  6605. material.combine = this.combine;
  6606. material.reflectivity = this.reflectivity;
  6607. material.refractionRatio = this.refractionRatio;
  6608. material.fog = this.fog;
  6609. material.shading = this.shading;
  6610. material.wireframe = this.wireframe;
  6611. material.wireframeLinewidth = this.wireframeLinewidth;
  6612. material.wireframeLinecap = this.wireframeLinecap;
  6613. material.wireframeLinejoin = this.wireframeLinejoin;
  6614. material.vertexColors = this.vertexColors;
  6615. material.skinning = this.skinning;
  6616. material.morphTargets = this.morphTargets;
  6617. material.morphNormals = this.morphNormals;
  6618. return material;
  6619. };
  6620. /**
  6621. * @author mrdoob / http://mrdoob.com/
  6622. * @author alteredq / http://alteredqualia.com/
  6623. *
  6624. * parameters = {
  6625. * opacity: <float>,
  6626. * blending: THREE.NormalBlending,
  6627. * depthTest: <bool>,
  6628. * wireframe: <boolean>,
  6629. * wireframeLinewidth: <float>
  6630. * }
  6631. */
  6632. THREE.MeshDepthMaterial = function ( parameters ) {
  6633. THREE.Material.call( this );
  6634. this.wireframe = false;
  6635. this.wireframeLinewidth = 1;
  6636. this.setValues( parameters );
  6637. };
  6638. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6639. THREE.MeshDepthMaterial.prototype.clone = function () {
  6640. var material = new THREE.LineBasicMaterial();
  6641. THREE.Material.prototype.clone.call( this, material );
  6642. material.wireframe = this.wireframe;
  6643. material.wireframeLinewidth = this.wireframeLinewidth;
  6644. return material;
  6645. };
  6646. /**
  6647. * @author mrdoob / http://mrdoob.com/
  6648. *
  6649. * parameters = {
  6650. * opacity: <float>,
  6651. * shading: THREE.FlatShading,
  6652. * blending: THREE.NormalBlending,
  6653. * depthTest: <bool>,
  6654. * wireframe: <boolean>,
  6655. * wireframeLinewidth: <float>
  6656. * }
  6657. */
  6658. THREE.MeshNormalMaterial = function ( parameters ) {
  6659. THREE.Material.call( this, parameters );
  6660. this.shading = THREE.FlatShading;
  6661. this.wireframe = false;
  6662. this.wireframeLinewidth = 1;
  6663. this.setValues( parameters );
  6664. };
  6665. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6666. THREE.MeshNormalMaterial.prototype.clone = function () {
  6667. var material = new THREE.MeshNormalMaterial();
  6668. THREE.Material.prototype.clone.call( this, material );
  6669. material.shading = this.shading;
  6670. material.wireframe = this.wireframe;
  6671. material.wireframeLinewidth = this.wireframeLinewidth;
  6672. return material;
  6673. };
  6674. /**
  6675. * @author mrdoob / http://mrdoob.com/
  6676. */
  6677. THREE.MeshFaceMaterial = function ( materials ) {
  6678. this.materials = materials instanceof Array ? materials : [];
  6679. };
  6680. THREE.MeshFaceMaterial.prototype.clone = function () {
  6681. return new THREE.MeshFaceMaterial();
  6682. };
  6683. /**
  6684. * @author mrdoob / http://mrdoob.com/
  6685. * @author alteredq / http://alteredqualia.com/
  6686. *
  6687. * parameters = {
  6688. * color: <hex>,
  6689. * opacity: <float>,
  6690. * map: new THREE.Texture( <Image> ),
  6691. *
  6692. * size: <float>,
  6693. *
  6694. * blending: THREE.NormalBlending,
  6695. * depthTest: <bool>,
  6696. *
  6697. * vertexColors: <bool>,
  6698. *
  6699. * fog: <bool>
  6700. * }
  6701. */
  6702. THREE.ParticleBasicMaterial = function ( parameters ) {
  6703. THREE.Material.call( this );
  6704. this.color = new THREE.Color( 0xffffff );
  6705. this.map = null;
  6706. this.size = 1;
  6707. this.sizeAttenuation = true;
  6708. this.vertexColors = false;
  6709. this.fog = true;
  6710. this.setValues( parameters );
  6711. };
  6712. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6713. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6714. var material = new THREE.ParticleBasicMaterial();
  6715. THREE.Material.prototype.clone.call( this, material );
  6716. material.color.copy( this.color );
  6717. material.map = this.map;
  6718. material.size = this.size;
  6719. material.sizeAttenuation = this.sizeAttenuation;
  6720. material.vertexColors = this.vertexColors;
  6721. material.fog = this.fog;
  6722. return material;
  6723. };
  6724. /**
  6725. * @author mrdoob / http://mrdoob.com/
  6726. *
  6727. * parameters = {
  6728. * color: <hex>,
  6729. * program: <function>,
  6730. * opacity: <float>,
  6731. * blending: THREE.NormalBlending
  6732. * }
  6733. */
  6734. THREE.ParticleCanvasMaterial = function ( parameters ) {
  6735. THREE.Material.call( this );
  6736. this.color = new THREE.Color( 0xffffff );
  6737. this.program = function ( context, color ) {};
  6738. this.setValues( parameters );
  6739. };
  6740. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  6741. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  6742. var material = new THREE.ParticleCanvasMaterial();
  6743. THREE.Material.prototype.clone.call( this, material );
  6744. material.color.copy( this.color );
  6745. material.program = this.program;
  6746. return material;
  6747. };
  6748. /**
  6749. * @author mrdoob / http://mrdoob.com/
  6750. */
  6751. THREE.ParticleDOMMaterial = function ( element ) {
  6752. this.element = element;
  6753. };
  6754. THREE.ParticleDOMMaterial.prototype.clone = function(){
  6755. return new THREE.ParticleDOMMaterial( this.element );
  6756. };
  6757. /**
  6758. * @author alteredq / http://alteredqualia.com/
  6759. *
  6760. * parameters = {
  6761. * fragmentShader: <string>,
  6762. * vertexShader: <string>,
  6763. *
  6764. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  6765. *
  6766. * defines: { "label" : "value" },
  6767. *
  6768. * shading: THREE.SmoothShading,
  6769. * blending: THREE.NormalBlending,
  6770. * depthTest: <bool>,
  6771. *
  6772. * wireframe: <boolean>,
  6773. * wireframeLinewidth: <float>,
  6774. *
  6775. * lights: <bool>,
  6776. *
  6777. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6778. *
  6779. * skinning: <bool>,
  6780. * morphTargets: <bool>,
  6781. * morphNormals: <bool>,
  6782. *
  6783. * fog: <bool>
  6784. * }
  6785. */
  6786. THREE.ShaderMaterial = function ( parameters ) {
  6787. THREE.Material.call( this );
  6788. this.fragmentShader = "void main() {}";
  6789. this.vertexShader = "void main() {}";
  6790. this.uniforms = {};
  6791. this.defines = {};
  6792. this.attributes = null;
  6793. this.shading = THREE.SmoothShading;
  6794. this.wireframe = false;
  6795. this.wireframeLinewidth = 1;
  6796. this.fog = false; // set to use scene fog
  6797. this.lights = false; // set to use scene lights
  6798. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  6799. this.skinning = false; // set to use skinning attribute streams
  6800. this.morphTargets = false; // set to use morph targets
  6801. this.morphNormals = false; // set to use morph normals
  6802. this.setValues( parameters );
  6803. };
  6804. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  6805. THREE.ShaderMaterial.prototype.clone = function () {
  6806. var material = new THREE.ShaderMaterial();
  6807. THREE.Material.prototype.clone.call( this, material );
  6808. material.fragmentShader = this.fragmentShader;
  6809. material.vertexShader = this.vertexShader;
  6810. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  6811. material.attributes = this.attributes;
  6812. material.defines = this.defines;
  6813. material.shading = this.shading;
  6814. material.wireframe = this.wireframe;
  6815. material.wireframeLinewidth = this.wireframeLinewidth;
  6816. material.fog = this.fog;
  6817. material.lights = this.lights;
  6818. material.vertexColors = this.vertexColors;
  6819. material.skinning = this.skinning;
  6820. material.morphTargets = this.morphTargets;
  6821. material.morphNormals = this.morphNormals;
  6822. return material;
  6823. };
  6824. /**
  6825. * @author mrdoob / http://mrdoob.com/
  6826. * @author alteredq / http://alteredqualia.com/
  6827. * @author szimek / https://github.com/szimek/
  6828. */
  6829. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  6830. THREE.TextureLibrary.push( this );
  6831. this.id = THREE.TextureIdCount ++;
  6832. this.name = '';
  6833. this.image = image;
  6834. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  6835. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  6836. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  6837. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  6838. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  6839. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6840. this.format = format !== undefined ? format : THREE.RGBAFormat;
  6841. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  6842. this.offset = new THREE.Vector2( 0, 0 );
  6843. this.repeat = new THREE.Vector2( 1, 1 );
  6844. this.generateMipmaps = true;
  6845. this.premultiplyAlpha = false;
  6846. this.flipY = true;
  6847. this.needsUpdate = false;
  6848. this.onUpdate = null;
  6849. };
  6850. THREE.Texture.prototype = {
  6851. constructor: THREE.Texture,
  6852. clone: function () {
  6853. var texture = new THREE.Texture();
  6854. texture.image = this.image;
  6855. texture.mapping = this.mapping;
  6856. texture.wrapS = this.wrapS;
  6857. texture.wrapT = this.wrapT;
  6858. texture.magFilter = this.magFilter;
  6859. texture.minFilter = this.minFilter;
  6860. texture.anisotropy = this.anisotropy;
  6861. texture.format = this.format;
  6862. texture.type = this.type;
  6863. texture.offset.copy( this.offset );
  6864. texture.repeat.copy( this.repeat );
  6865. texture.generateMipmaps = this.generateMipmaps;
  6866. texture.premultiplyAlpha = this.premultiplyAlpha;
  6867. texture.flipY = this.flipY;
  6868. return texture;
  6869. },
  6870. deallocate: function () {
  6871. var index = THREE.TextureLibrary.indexOf( this );
  6872. if ( index !== -1 ) THREE.TextureLibrary.splice( index, 1 );
  6873. }
  6874. };
  6875. THREE.TextureIdCount = 0;
  6876. THREE.TextureLibrary = [];
  6877. /**
  6878. * @author alteredq / http://alteredqualia.com/
  6879. */
  6880. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6881. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6882. this.image = { width: width, height: height };
  6883. this.mipmaps = mipmaps;
  6884. };
  6885. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  6886. THREE.CompressedTexture.prototype.clone = function () {
  6887. var texture = new THREE.CompressedTexture();
  6888. texture.image = this.image;
  6889. texture.mipmaps = this.mipmaps;
  6890. texture.format = this.format;
  6891. texture.type = this.type;
  6892. texture.mapping = this.mapping;
  6893. texture.wrapS = this.wrapS;
  6894. texture.wrapT = this.wrapT;
  6895. texture.magFilter = this.magFilter;
  6896. texture.minFilter = this.minFilter;
  6897. texture.anisotropy = this.anisotropy;
  6898. texture.offset.copy( this.offset );
  6899. texture.repeat.copy( this.repeat );
  6900. return texture;
  6901. };
  6902. /**
  6903. * @author alteredq / http://alteredqualia.com/
  6904. */
  6905. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6906. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6907. this.image = { data: data, width: width, height: height };
  6908. };
  6909. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  6910. THREE.DataTexture.prototype.clone = function () {
  6911. 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 );
  6912. clonedTexture.offset.copy( this.offset );
  6913. clonedTexture.repeat.copy( this.repeat );
  6914. return clonedTexture;
  6915. };
  6916. /**
  6917. * @author mrdoob / http://mrdoob.com/
  6918. */
  6919. THREE.Particle = function ( material ) {
  6920. THREE.Object3D.call( this );
  6921. this.material = material;
  6922. };
  6923. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  6924. THREE.Particle.prototype.clone = function ( object ) {
  6925. if ( object === undefined ) object = new THREE.Particle( this.material );
  6926. THREE.Object3D.prototype.clone.call( this, object );
  6927. return object;
  6928. };
  6929. /**
  6930. * @author alteredq / http://alteredqualia.com/
  6931. */
  6932. THREE.ParticleSystem = function ( geometry, material ) {
  6933. THREE.Object3D.call( this );
  6934. this.geometry = geometry;
  6935. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  6936. this.sortParticles = false;
  6937. if ( this.geometry ) {
  6938. // calc bound radius
  6939. if( this.geometry.boundingSphere === null ) {
  6940. this.geometry.computeBoundingSphere();
  6941. }
  6942. this.boundRadius = geometry.boundingSphere.radius;
  6943. }
  6944. this.frustumCulled = false;
  6945. };
  6946. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  6947. THREE.ParticleSystem.prototype.clone = function ( object ) {
  6948. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  6949. object.sortParticles = this.sortParticles;
  6950. THREE.Object3D.prototype.clone.call( this, object );
  6951. return object;
  6952. };
  6953. /**
  6954. * @author mrdoob / http://mrdoob.com/
  6955. */
  6956. THREE.Line = function ( geometry, material, type ) {
  6957. THREE.Object3D.call( this );
  6958. this.geometry = geometry;
  6959. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6960. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  6961. if ( this.geometry ) {
  6962. if ( ! this.geometry.boundingSphere ) {
  6963. this.geometry.computeBoundingSphere();
  6964. }
  6965. }
  6966. };
  6967. THREE.LineStrip = 0;
  6968. THREE.LinePieces = 1;
  6969. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  6970. THREE.Line.prototype.clone = function ( object ) {
  6971. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  6972. THREE.Object3D.prototype.clone.call( this, object );
  6973. return object;
  6974. };
  6975. /**
  6976. * @author mrdoob / http://mrdoob.com/
  6977. * @author alteredq / http://alteredqualia.com/
  6978. * @author mikael emtinger / http://gomo.se/
  6979. */
  6980. THREE.Mesh = function ( geometry, material ) {
  6981. THREE.Object3D.call( this );
  6982. this.geometry = geometry;
  6983. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  6984. if ( this.geometry ) {
  6985. // calc bound radius
  6986. if ( this.geometry.boundingSphere === null ) {
  6987. this.geometry.computeBoundingSphere();
  6988. }
  6989. this.boundRadius = geometry.boundingSphere.radius;
  6990. // setup morph targets
  6991. if ( this.geometry.morphTargets.length ) {
  6992. this.morphTargetBase = -1;
  6993. this.morphTargetForcedOrder = [];
  6994. this.morphTargetInfluences = [];
  6995. this.morphTargetDictionary = {};
  6996. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  6997. this.morphTargetInfluences.push( 0 );
  6998. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  6999. }
  7000. }
  7001. }
  7002. }
  7003. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7004. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7005. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7006. return this.morphTargetDictionary[ name ];
  7007. }
  7008. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7009. return 0;
  7010. };
  7011. THREE.Mesh.prototype.clone = function ( object ) {
  7012. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7013. THREE.Object3D.prototype.clone.call( this, object );
  7014. return object;
  7015. };
  7016. /**
  7017. * @author mikael emtinger / http://gomo.se/
  7018. * @author alteredq / http://alteredqualia.com/
  7019. */
  7020. THREE.Bone = function( belongsToSkin ) {
  7021. THREE.Object3D.call( this );
  7022. this.skin = belongsToSkin;
  7023. this.skinMatrix = new THREE.Matrix4();
  7024. };
  7025. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7026. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  7027. // update local
  7028. if ( this.matrixAutoUpdate ) {
  7029. forceUpdate |= this.updateMatrix();
  7030. }
  7031. // update skin matrix
  7032. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7033. if( parentSkinMatrix ) {
  7034. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  7035. } else {
  7036. this.skinMatrix.copy( this.matrix );
  7037. }
  7038. this.matrixWorldNeedsUpdate = false;
  7039. forceUpdate = true;
  7040. }
  7041. // update children
  7042. var child, i, l = this.children.length;
  7043. for ( i = 0; i < l; i ++ ) {
  7044. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7045. }
  7046. };
  7047. /**
  7048. * @author mikael emtinger / http://gomo.se/
  7049. * @author alteredq / http://alteredqualia.com/
  7050. */
  7051. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7052. THREE.Mesh.call( this, geometry, material );
  7053. //
  7054. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7055. // init bones
  7056. this.identityMatrix = new THREE.Matrix4();
  7057. this.bones = [];
  7058. this.boneMatrices = [];
  7059. var b, bone, gbone, p, q, s;
  7060. if ( this.geometry && this.geometry.bones !== undefined ) {
  7061. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7062. gbone = this.geometry.bones[ b ];
  7063. p = gbone.pos;
  7064. q = gbone.rotq;
  7065. s = gbone.scl;
  7066. bone = this.addBone();
  7067. bone.name = gbone.name;
  7068. bone.position.set( p[0], p[1], p[2] );
  7069. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7070. bone.useQuaternion = true;
  7071. if ( s !== undefined ) {
  7072. bone.scale.set( s[0], s[1], s[2] );
  7073. } else {
  7074. bone.scale.set( 1, 1, 1 );
  7075. }
  7076. }
  7077. for ( b = 0; b < this.bones.length; b ++ ) {
  7078. gbone = this.geometry.bones[ b ];
  7079. bone = this.bones[ b ];
  7080. if ( gbone.parent === -1 ) {
  7081. this.add( bone );
  7082. } else {
  7083. this.bones[ gbone.parent ].add( bone );
  7084. }
  7085. }
  7086. //
  7087. var nBones = this.bones.length;
  7088. if ( this.useVertexTexture ) {
  7089. // layout (1 matrix = 4 pixels)
  7090. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7091. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7092. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7093. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7094. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7095. var size;
  7096. if ( nBones > 256 )
  7097. size = 64;
  7098. else if ( nBones > 64 )
  7099. size = 32;
  7100. else if ( nBones > 16 )
  7101. size = 16;
  7102. else
  7103. size = 8;
  7104. this.boneTextureWidth = size;
  7105. this.boneTextureHeight = size;
  7106. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7107. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7108. this.boneTexture.minFilter = THREE.NearestFilter;
  7109. this.boneTexture.magFilter = THREE.NearestFilter;
  7110. this.boneTexture.generateMipmaps = false;
  7111. this.boneTexture.flipY = false;
  7112. } else {
  7113. this.boneMatrices = new Float32Array( 16 * nBones );
  7114. }
  7115. this.pose();
  7116. }
  7117. };
  7118. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7119. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7120. if ( bone === undefined ) {
  7121. bone = new THREE.Bone( this );
  7122. }
  7123. this.bones.push( bone );
  7124. return bone;
  7125. };
  7126. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7127. this.matrixAutoUpdate && this.updateMatrix();
  7128. // update matrixWorld
  7129. if ( this.matrixWorldNeedsUpdate || force ) {
  7130. if ( this.parent ) {
  7131. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  7132. } else {
  7133. this.matrixWorld.copy( this.matrix );
  7134. }
  7135. this.matrixWorldNeedsUpdate = false;
  7136. force = true;
  7137. }
  7138. // update children
  7139. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7140. var child = this.children[ i ];
  7141. if ( child instanceof THREE.Bone ) {
  7142. child.update( this.identityMatrix, false );
  7143. } else {
  7144. child.updateMatrixWorld( true );
  7145. }
  7146. }
  7147. // make a snapshot of the bones' rest position
  7148. if ( this.boneInverses == undefined ) {
  7149. this.boneInverses = [];
  7150. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7151. var inverse = new THREE.Matrix4();
  7152. inverse.getInverse( this.bones[ b ].skinMatrix );
  7153. this.boneInverses.push( inverse );
  7154. }
  7155. }
  7156. // flatten bone matrices to array
  7157. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7158. // compute the offset between the current and the original transform;
  7159. //TODO: we could get rid of this multiplication step if the skinMatrix
  7160. // was already representing the offset; however, this requires some
  7161. // major changes to the animation system
  7162. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7163. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7164. }
  7165. if ( this.useVertexTexture ) {
  7166. this.boneTexture.needsUpdate = true;
  7167. }
  7168. };
  7169. THREE.SkinnedMesh.prototype.pose = function() {
  7170. this.updateMatrixWorld( true );
  7171. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7172. // normalize weights
  7173. var sw = this.geometry.skinWeights[ i ];
  7174. var scale = 1.0 / sw.lengthManhattan();
  7175. if ( scale !== Infinity ) {
  7176. sw.multiplyScalar( scale );
  7177. } else {
  7178. sw.set( 1 ); // this will be normalized by the shader anyway
  7179. }
  7180. }
  7181. };
  7182. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7183. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7184. THREE.Mesh.prototype.clone.call( this, object );
  7185. return object;
  7186. };
  7187. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7188. /**
  7189. * @author alteredq / http://alteredqualia.com/
  7190. */
  7191. THREE.MorphAnimMesh = function ( geometry, material ) {
  7192. THREE.Mesh.call( this, geometry, material );
  7193. // API
  7194. this.duration = 1000; // milliseconds
  7195. this.mirroredLoop = false;
  7196. this.time = 0;
  7197. // internals
  7198. this.lastKeyframe = 0;
  7199. this.currentKeyframe = 0;
  7200. this.direction = 1;
  7201. this.directionBackwards = false;
  7202. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7203. };
  7204. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7205. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7206. this.startKeyframe = start;
  7207. this.endKeyframe = end;
  7208. this.length = this.endKeyframe - this.startKeyframe + 1;
  7209. };
  7210. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7211. this.direction = 1;
  7212. this.directionBackwards = false;
  7213. };
  7214. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7215. this.direction = -1;
  7216. this.directionBackwards = true;
  7217. };
  7218. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7219. var geometry = this.geometry;
  7220. if ( ! geometry.animations ) geometry.animations = {};
  7221. var firstAnimation, animations = geometry.animations;
  7222. var pattern = /([a-z]+)(\d+)/;
  7223. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7224. var morph = geometry.morphTargets[ i ];
  7225. var parts = morph.name.match( pattern );
  7226. if ( parts && parts.length > 1 ) {
  7227. var label = parts[ 1 ];
  7228. var num = parts[ 2 ];
  7229. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7230. var animation = animations[ label ];
  7231. if ( i < animation.start ) animation.start = i;
  7232. if ( i > animation.end ) animation.end = i;
  7233. if ( ! firstAnimation ) firstAnimation = label;
  7234. }
  7235. }
  7236. geometry.firstAnimation = firstAnimation;
  7237. };
  7238. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7239. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7240. this.geometry.animations[ label ] = { start: start, end: end };
  7241. };
  7242. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7243. var animation = this.geometry.animations[ label ];
  7244. if ( animation ) {
  7245. this.setFrameRange( animation.start, animation.end );
  7246. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7247. this.time = 0;
  7248. } else {
  7249. console.warn( "animation[" + label + "] undefined" );
  7250. }
  7251. };
  7252. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7253. var frameTime = this.duration / this.length;
  7254. this.time += this.direction * delta;
  7255. if ( this.mirroredLoop ) {
  7256. if ( this.time > this.duration || this.time < 0 ) {
  7257. this.direction *= -1;
  7258. if ( this.time > this.duration ) {
  7259. this.time = this.duration;
  7260. this.directionBackwards = true;
  7261. }
  7262. if ( this.time < 0 ) {
  7263. this.time = 0;
  7264. this.directionBackwards = false;
  7265. }
  7266. }
  7267. } else {
  7268. this.time = this.time % this.duration;
  7269. if ( this.time < 0 ) this.time += this.duration;
  7270. }
  7271. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7272. if ( keyframe !== this.currentKeyframe ) {
  7273. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7274. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7275. this.morphTargetInfluences[ keyframe ] = 0;
  7276. this.lastKeyframe = this.currentKeyframe;
  7277. this.currentKeyframe = keyframe;
  7278. }
  7279. var mix = ( this.time % frameTime ) / frameTime;
  7280. if ( this.directionBackwards ) {
  7281. mix = 1 - mix;
  7282. }
  7283. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7284. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7285. };
  7286. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7287. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7288. object.duration = this.duration;
  7289. object.mirroredLoop = this.mirroredLoop;
  7290. object.time = this.time;
  7291. object.lastKeyframe = this.lastKeyframe;
  7292. object.currentKeyframe = this.currentKeyframe;
  7293. object.direction = this.direction;
  7294. object.directionBackwards = this.directionBackwards;
  7295. THREE.Mesh.prototype.clone.call( this, object );
  7296. return object;
  7297. };
  7298. /**
  7299. * @author alteredq / http://alteredqualia.com/
  7300. */
  7301. THREE.Ribbon = function ( geometry, material ) {
  7302. THREE.Object3D.call( this );
  7303. this.geometry = geometry;
  7304. this.material = material;
  7305. };
  7306. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7307. THREE.Ribbon.prototype.clone = function ( object ) {
  7308. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7309. THREE.Object3D.prototype.clone.call( this, object );
  7310. return object;
  7311. };
  7312. /**
  7313. * @author mikael emtinger / http://gomo.se/
  7314. * @author alteredq / http://alteredqualia.com/
  7315. * @author mrdoob / http://mrdoob.com/
  7316. */
  7317. THREE.LOD = function () {
  7318. THREE.Object3D.call( this );
  7319. this.LODs = [];
  7320. };
  7321. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7322. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7323. if ( visibleAtDistance === undefined ) {
  7324. visibleAtDistance = 0;
  7325. }
  7326. visibleAtDistance = Math.abs( visibleAtDistance );
  7327. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7328. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7329. break;
  7330. }
  7331. }
  7332. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7333. this.add( object3D );
  7334. };
  7335. THREE.LOD.prototype.update = function ( camera ) {
  7336. if ( this.LODs.length > 1 ) {
  7337. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7338. var inverse = camera.matrixWorldInverse;
  7339. 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] );
  7340. this.LODs[ 0 ].object3D.visible = true;
  7341. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7342. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7343. this.LODs[ l - 1 ].object3D.visible = false;
  7344. this.LODs[ l ].object3D.visible = true;
  7345. } else {
  7346. break;
  7347. }
  7348. }
  7349. for( ; l < this.LODs.length; l ++ ) {
  7350. this.LODs[ l ].object3D.visible = false;
  7351. }
  7352. }
  7353. };
  7354. THREE.LOD.prototype.clone = function () {
  7355. // TODO
  7356. };
  7357. /**
  7358. * @author mikael emtinger / http://gomo.se/
  7359. * @author alteredq / http://alteredqualia.com/
  7360. */
  7361. THREE.Sprite = function ( parameters ) {
  7362. THREE.Object3D.call( this );
  7363. parameters = parameters || {};
  7364. this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  7365. this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();
  7366. this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;
  7367. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  7368. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  7369. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  7370. this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
  7371. this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
  7372. this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
  7373. this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
  7374. this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center.clone();
  7375. this.fog = ( parameters.fog !== undefined ) ? parameters.fog : false;
  7376. this.rotation3d = this.rotation;
  7377. this.rotation = 0;
  7378. this.opacity = 1;
  7379. this.uvOffset = new THREE.Vector2( 0, 0 );
  7380. this.uvScale = new THREE.Vector2( 1, 1 );
  7381. };
  7382. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7383. /*
  7384. * Custom update matrix
  7385. */
  7386. THREE.Sprite.prototype.updateMatrix = function () {
  7387. this.matrix.setPosition( this.position );
  7388. this.rotation3d.set( 0, 0, this.rotation );
  7389. this.matrix.setRotationFromEuler( this.rotation3d );
  7390. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7391. this.matrix.scale( this.scale );
  7392. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  7393. }
  7394. this.matrixWorldNeedsUpdate = true;
  7395. };
  7396. THREE.Sprite.prototype.clone = function ( object ) {
  7397. if ( object === undefined ) object = new THREE.Sprite( {} );
  7398. object.color.copy( this.color );
  7399. object.map = this.map;
  7400. object.blending = this.blending;
  7401. object.useScreenCoordinates = this.useScreenCoordinates;
  7402. object.mergeWith3D = this.mergeWith3D;
  7403. object.affectedByDistance = this.affectedByDistance;
  7404. object.scaleByViewport = this.scaleByViewport;
  7405. object.alignment = this.alignment;
  7406. object.fog = this.fog;
  7407. object.rotation3d.copy( this.rotation3d );
  7408. object.rotation = this.rotation;
  7409. object.opacity = this.opacity;
  7410. object.uvOffset.copy( this.uvOffset );
  7411. object.uvScale.copy( this.uvScale);
  7412. THREE.Object3D.prototype.clone.call( this, object );
  7413. return object;
  7414. };
  7415. /*
  7416. * Alignment
  7417. */
  7418. THREE.SpriteAlignment = {};
  7419. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7420. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7421. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7422. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7423. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7424. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7425. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7426. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7427. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7428. /**
  7429. * @author mrdoob / http://mrdoob.com/
  7430. */
  7431. THREE.Scene = function () {
  7432. THREE.Object3D.call( this );
  7433. this.fog = null;
  7434. this.overrideMaterial = null;
  7435. this.matrixAutoUpdate = false;
  7436. this.__objects = [];
  7437. this.__lights = [];
  7438. this.__objectsAdded = [];
  7439. this.__objectsRemoved = [];
  7440. };
  7441. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7442. THREE.Scene.prototype.__addObject = function ( object ) {
  7443. if ( object instanceof THREE.Light ) {
  7444. if ( this.__lights.indexOf( object ) === - 1 ) {
  7445. this.__lights.push( object );
  7446. }
  7447. if ( object.target && object.target.parent === undefined ) {
  7448. this.add( object.target );
  7449. }
  7450. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7451. if ( this.__objects.indexOf( object ) === - 1 ) {
  7452. this.__objects.push( object );
  7453. this.__objectsAdded.push( object );
  7454. // check if previously removed
  7455. var i = this.__objectsRemoved.indexOf( object );
  7456. if ( i !== -1 ) {
  7457. this.__objectsRemoved.splice( i, 1 );
  7458. }
  7459. }
  7460. }
  7461. for ( var c = 0; c < object.children.length; c ++ ) {
  7462. this.__addObject( object.children[ c ] );
  7463. }
  7464. };
  7465. THREE.Scene.prototype.__removeObject = function ( object ) {
  7466. if ( object instanceof THREE.Light ) {
  7467. var i = this.__lights.indexOf( object );
  7468. if ( i !== -1 ) {
  7469. this.__lights.splice( i, 1 );
  7470. }
  7471. } else if ( !( object instanceof THREE.Camera ) ) {
  7472. var i = this.__objects.indexOf( object );
  7473. if( i !== -1 ) {
  7474. this.__objects.splice( i, 1 );
  7475. this.__objectsRemoved.push( object );
  7476. // check if previously added
  7477. var ai = this.__objectsAdded.indexOf( object );
  7478. if ( ai !== -1 ) {
  7479. this.__objectsAdded.splice( ai, 1 );
  7480. }
  7481. }
  7482. }
  7483. for ( var c = 0; c < object.children.length; c ++ ) {
  7484. this.__removeObject( object.children[ c ] );
  7485. }
  7486. };
  7487. /**
  7488. * @author mrdoob / http://mrdoob.com/
  7489. * @author alteredq / http://alteredqualia.com/
  7490. */
  7491. THREE.Fog = function ( hex, near, far ) {
  7492. this.name = '';
  7493. this.color = new THREE.Color( hex );
  7494. this.near = ( near !== undefined ) ? near : 1;
  7495. this.far = ( far !== undefined ) ? far : 1000;
  7496. };
  7497. THREE.Fog.prototype.clone = function () {
  7498. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7499. };
  7500. /**
  7501. * @author mrdoob / http://mrdoob.com/
  7502. * @author alteredq / http://alteredqualia.com/
  7503. */
  7504. THREE.FogExp2 = function ( hex, density ) {
  7505. this.name = '';
  7506. this.color = new THREE.Color( hex );
  7507. this.density = ( density !== undefined ) ? density : 0.00025;
  7508. };
  7509. THREE.FogExp2.prototype.clone = function () {
  7510. return new THREE.FogExp2( this.color.getHex(), this.density );
  7511. };
  7512. /**
  7513. * @author mrdoob / http://mrdoob.com/
  7514. */
  7515. THREE.CanvasRenderer = function ( parameters ) {
  7516. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7517. parameters = parameters || {};
  7518. var _this = this,
  7519. _renderData, _elements, _lights,
  7520. _projector = new THREE.Projector(),
  7521. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  7522. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7523. _context = _canvas.getContext( '2d' ),
  7524. _clearColor = new THREE.Color( 0x000000 ),
  7525. _clearOpacity = 0,
  7526. _contextGlobalAlpha = 1,
  7527. _contextGlobalCompositeOperation = 0,
  7528. _contextStrokeStyle = null,
  7529. _contextFillStyle = null,
  7530. _contextLineWidth = null,
  7531. _contextLineCap = null,
  7532. _contextLineJoin = null,
  7533. _v1, _v2, _v3, _v4,
  7534. _v5 = new THREE.RenderableVertex(),
  7535. _v6 = new THREE.RenderableVertex(),
  7536. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7537. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7538. _color = new THREE.Color(),
  7539. _color1 = new THREE.Color(),
  7540. _color2 = new THREE.Color(),
  7541. _color3 = new THREE.Color(),
  7542. _color4 = new THREE.Color(),
  7543. _diffuseColor = new THREE.Color(),
  7544. _emissiveColor = new THREE.Color(),
  7545. _patterns = {}, _imagedatas = {},
  7546. _near, _far,
  7547. _image, _uvs,
  7548. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7549. _clipRect = new THREE.Rectangle(),
  7550. _clearRect = new THREE.Rectangle(),
  7551. _bboxRect = new THREE.Rectangle(),
  7552. _enableLighting = false,
  7553. _ambientLight = new THREE.Color(),
  7554. _directionalLights = new THREE.Color(),
  7555. _pointLights = new THREE.Color(),
  7556. _pi2 = Math.PI * 2,
  7557. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7558. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7559. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7560. _pixelMap = document.createElement( 'canvas' );
  7561. _pixelMap.width = _pixelMap.height = 2;
  7562. _pixelMapContext = _pixelMap.getContext( '2d' );
  7563. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7564. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7565. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7566. _pixelMapData = _pixelMapImage.data;
  7567. _gradientMap = document.createElement( 'canvas' );
  7568. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7569. _gradientMapContext = _gradientMap.getContext( '2d' );
  7570. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7571. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7572. _gradientMapQuality --; // Fix UVs
  7573. this.domElement = _canvas;
  7574. this.autoClear = true;
  7575. this.sortObjects = true;
  7576. this.sortElements = true;
  7577. this.info = {
  7578. render: {
  7579. vertices: 0,
  7580. faces: 0
  7581. }
  7582. }
  7583. this.setSize = function ( width, height ) {
  7584. _canvasWidth = width;
  7585. _canvasHeight = height;
  7586. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7587. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7588. _canvas.width = _canvasWidth;
  7589. _canvas.height = _canvasHeight;
  7590. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7591. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7592. _contextGlobalAlpha = 1;
  7593. _contextGlobalCompositeOperation = 0;
  7594. _contextStrokeStyle = null;
  7595. _contextFillStyle = null;
  7596. _contextLineWidth = null;
  7597. _contextLineCap = null;
  7598. _contextLineJoin = null;
  7599. };
  7600. this.setClearColor = function ( color, opacity ) {
  7601. _clearColor.copy( color );
  7602. _clearOpacity = opacity !== undefined ? opacity : 1;
  7603. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7604. };
  7605. this.setClearColorHex = function ( hex, opacity ) {
  7606. _clearColor.setHex( hex );
  7607. _clearOpacity = opacity !== undefined ? opacity : 1;
  7608. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7609. };
  7610. this.getMaxAnisotropy = function () {
  7611. return 0;
  7612. };
  7613. this.clear = function () {
  7614. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7615. if ( _clearRect.isEmpty() === false ) {
  7616. _clearRect.minSelf( _clipRect );
  7617. _clearRect.inflate( 2 );
  7618. if ( _clearOpacity < 1 ) {
  7619. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7620. }
  7621. if ( _clearOpacity > 0 ) {
  7622. setBlending( THREE.NormalBlending );
  7623. setOpacity( 1 );
  7624. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7625. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7626. }
  7627. _clearRect.empty();
  7628. }
  7629. };
  7630. this.render = function ( scene, camera ) {
  7631. if ( camera instanceof THREE.Camera === false ) {
  7632. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7633. return;
  7634. }
  7635. var e, el, element, material;
  7636. this.autoClear === true
  7637. ? this.clear()
  7638. : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7639. _this.info.render.vertices = 0;
  7640. _this.info.render.faces = 0;
  7641. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  7642. _elements = _renderData.elements;
  7643. _lights = _renderData.lights;
  7644. /* DEBUG
  7645. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7646. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  7647. */
  7648. _enableLighting = _lights.length > 0;
  7649. if ( _enableLighting === true ) {
  7650. calculateLights();
  7651. }
  7652. for ( e = 0, el = _elements.length; e < el; e++ ) {
  7653. element = _elements[ e ];
  7654. material = element.material;
  7655. if ( material === undefined || material.visible === false ) continue;
  7656. _bboxRect.empty();
  7657. if ( element instanceof THREE.RenderableParticle ) {
  7658. _v1 = element;
  7659. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7660. renderParticle( _v1, element, material, scene );
  7661. } else if ( element instanceof THREE.RenderableLine ) {
  7662. _v1 = element.v1; _v2 = element.v2;
  7663. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7664. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7665. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7666. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7667. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7668. renderLine( _v1, _v2, element, material, scene );
  7669. }
  7670. } else if ( element instanceof THREE.RenderableFace3 ) {
  7671. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7672. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7673. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7674. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7675. if ( material.overdraw === true ) {
  7676. expand( _v1.positionScreen, _v2.positionScreen );
  7677. expand( _v2.positionScreen, _v3.positionScreen );
  7678. expand( _v3.positionScreen, _v1.positionScreen );
  7679. }
  7680. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  7681. _v2.positionScreen.x, _v2.positionScreen.y,
  7682. _v3.positionScreen.x, _v3.positionScreen.y );
  7683. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7684. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7685. }
  7686. } else if ( element instanceof THREE.RenderableFace4 ) {
  7687. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7688. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7689. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7690. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7691. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7692. _v5.positionScreen.copy( _v2.positionScreen );
  7693. _v6.positionScreen.copy( _v4.positionScreen );
  7694. if ( material.overdraw === true ) {
  7695. expand( _v1.positionScreen, _v2.positionScreen );
  7696. expand( _v2.positionScreen, _v4.positionScreen );
  7697. expand( _v4.positionScreen, _v1.positionScreen );
  7698. expand( _v3.positionScreen, _v5.positionScreen );
  7699. expand( _v3.positionScreen, _v6.positionScreen );
  7700. }
  7701. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7702. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7703. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  7704. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  7705. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7706. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  7707. }
  7708. }
  7709. /* DEBUG
  7710. _context.lineWidth = 1;
  7711. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  7712. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  7713. */
  7714. _clearRect.addRectangle( _bboxRect );
  7715. }
  7716. /* DEBUG
  7717. _context.lineWidth = 1;
  7718. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  7719. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  7720. */
  7721. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  7722. //
  7723. function calculateLights() {
  7724. _ambientLight.setRGB( 0, 0, 0 );
  7725. _directionalLights.setRGB( 0, 0, 0 );
  7726. _pointLights.setRGB( 0, 0, 0 );
  7727. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7728. var light = _lights[ l ];
  7729. var lightColor = light.color;
  7730. if ( light instanceof THREE.AmbientLight ) {
  7731. _ambientLight.r += lightColor.r;
  7732. _ambientLight.g += lightColor.g;
  7733. _ambientLight.b += lightColor.b;
  7734. } else if ( light instanceof THREE.DirectionalLight ) {
  7735. // for particles
  7736. _directionalLights.r += lightColor.r;
  7737. _directionalLights.g += lightColor.g;
  7738. _directionalLights.b += lightColor.b;
  7739. } else if ( light instanceof THREE.PointLight ) {
  7740. // for particles
  7741. _pointLights.r += lightColor.r;
  7742. _pointLights.g += lightColor.g;
  7743. _pointLights.b += lightColor.b;
  7744. }
  7745. }
  7746. }
  7747. function calculateLight( position, normal, color ) {
  7748. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7749. var light = _lights[ l ];
  7750. var lightColor = light.color;
  7751. if ( light instanceof THREE.DirectionalLight ) {
  7752. var lightPosition = light.matrixWorld.getPosition().normalize();
  7753. var amount = normal.dot( lightPosition );
  7754. if ( amount <= 0 ) continue;
  7755. amount *= light.intensity;
  7756. color.r += lightColor.r * amount;
  7757. color.g += lightColor.g * amount;
  7758. color.b += lightColor.b * amount;
  7759. } else if ( light instanceof THREE.PointLight ) {
  7760. var lightPosition = light.matrixWorld.getPosition();
  7761. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  7762. if ( amount <= 0 ) continue;
  7763. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  7764. if ( amount == 0 ) continue;
  7765. amount *= light.intensity;
  7766. color.r += lightColor.r * amount;
  7767. color.g += lightColor.g * amount;
  7768. color.b += lightColor.b * amount;
  7769. }
  7770. }
  7771. }
  7772. function renderParticle( v1, element, material, scene ) {
  7773. setOpacity( material.opacity );
  7774. setBlending( material.blending );
  7775. var width, height, scaleX, scaleY,
  7776. bitmap, bitmapWidth, bitmapHeight;
  7777. if ( material instanceof THREE.ParticleBasicMaterial ) {
  7778. if ( material.map === null ) {
  7779. scaleX = element.object.scale.x;
  7780. scaleY = element.object.scale.y;
  7781. // TODO: Be able to disable this
  7782. scaleX *= element.scale.x * _canvasWidthHalf;
  7783. scaleY *= element.scale.y * _canvasHeightHalf;
  7784. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  7785. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7786. return;
  7787. }
  7788. setFillStyle( material.color.getContextStyle() );
  7789. _context.save();
  7790. _context.translate( v1.x, v1.y );
  7791. _context.rotate( - element.rotation );
  7792. _context.scale( scaleX, scaleY );
  7793. _context.fillRect( -1, -1, 2, 2 );
  7794. _context.restore();
  7795. } else {
  7796. bitmap = material.map.image;
  7797. bitmapWidth = bitmap.width >> 1;
  7798. bitmapHeight = bitmap.height >> 1;
  7799. scaleX = element.scale.x * _canvasWidthHalf;
  7800. scaleY = element.scale.y * _canvasHeightHalf;
  7801. width = scaleX * bitmapWidth;
  7802. height = scaleY * bitmapHeight;
  7803. // TODO: Rotations break this...
  7804. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7805. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7806. return;
  7807. }
  7808. _context.save();
  7809. _context.translate( v1.x, v1.y );
  7810. _context.rotate( - element.rotation );
  7811. _context.scale( scaleX, - scaleY );
  7812. _context.translate( - bitmapWidth, - bitmapHeight );
  7813. _context.drawImage( bitmap, 0, 0 );
  7814. _context.restore();
  7815. }
  7816. /* DEBUG
  7817. setStrokeStyle( 'rgb(255,255,0)' );
  7818. _context.beginPath();
  7819. _context.moveTo( v1.x - 10, v1.y );
  7820. _context.lineTo( v1.x + 10, v1.y );
  7821. _context.moveTo( v1.x, v1.y - 10 );
  7822. _context.lineTo( v1.x, v1.y + 10 );
  7823. _context.stroke();
  7824. */
  7825. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  7826. width = element.scale.x * _canvasWidthHalf;
  7827. height = element.scale.y * _canvasHeightHalf;
  7828. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7829. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7830. return;
  7831. }
  7832. setStrokeStyle( material.color.getContextStyle() );
  7833. setFillStyle( material.color.getContextStyle() );
  7834. _context.save();
  7835. _context.translate( v1.x, v1.y );
  7836. _context.rotate( - element.rotation );
  7837. _context.scale( width, height );
  7838. material.program( _context );
  7839. _context.restore();
  7840. }
  7841. }
  7842. function renderLine( v1, v2, element, material, scene ) {
  7843. setOpacity( material.opacity );
  7844. setBlending( material.blending );
  7845. _context.beginPath();
  7846. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  7847. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  7848. if ( material instanceof THREE.LineBasicMaterial ) {
  7849. setLineWidth( material.linewidth );
  7850. setLineCap( material.linecap );
  7851. setLineJoin( material.linejoin );
  7852. setStrokeStyle( material.color.getContextStyle() );
  7853. _context.stroke();
  7854. _bboxRect.inflate( material.linewidth * 2 );
  7855. }
  7856. }
  7857. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  7858. _this.info.render.vertices += 3;
  7859. _this.info.render.faces ++;
  7860. setOpacity( material.opacity );
  7861. setBlending( material.blending );
  7862. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7863. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7864. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7865. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  7866. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  7867. _diffuseColor.copy( material.color );
  7868. _emissiveColor.copy( material.emissive );
  7869. if ( material.vertexColors === THREE.FaceColors ) {
  7870. _diffuseColor.r *= element.color.r;
  7871. _diffuseColor.g *= element.color.g;
  7872. _diffuseColor.b *= element.color.b;
  7873. }
  7874. if ( _enableLighting === true ) {
  7875. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  7876. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  7877. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  7878. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  7879. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7880. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7881. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  7882. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7883. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7884. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7885. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7886. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7887. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7888. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7889. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7890. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7891. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7892. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7893. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7894. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7895. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7896. } else {
  7897. _color.r = _ambientLight.r;
  7898. _color.g = _ambientLight.g;
  7899. _color.b = _ambientLight.b;
  7900. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7901. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7902. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7903. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7904. material.wireframe === true
  7905. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7906. : fillPath( _color );
  7907. }
  7908. } else {
  7909. material.wireframe === true
  7910. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7911. : fillPath( material.color );
  7912. }
  7913. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7914. if ( material.map !== null ) {
  7915. if ( material.map.mapping instanceof THREE.UVMapping ) {
  7916. _uvs = element.uvs[ 0 ];
  7917. 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 );
  7918. }
  7919. } else if ( material.envMap !== null ) {
  7920. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  7921. var cameraMatrix = camera.matrixWorldInverse;
  7922. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  7923. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7924. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7925. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  7926. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7927. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7928. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  7929. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7930. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7931. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  7932. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  7933. }*/
  7934. } else {
  7935. _color.copy( material.color );
  7936. if ( material.vertexColors === THREE.FaceColors ) {
  7937. _color.r *= element.color.r;
  7938. _color.g *= element.color.g;
  7939. _color.b *= element.color.b;
  7940. }
  7941. material.wireframe === true
  7942. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7943. : fillPath( _color );
  7944. }
  7945. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7946. _near = camera.near;
  7947. _far = camera.far;
  7948. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7949. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7950. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7951. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7952. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7953. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7954. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7955. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7956. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7957. _color.r = normalToComponent( element.normalWorld.x );
  7958. _color.g = normalToComponent( element.normalWorld.y );
  7959. _color.b = normalToComponent( element.normalWorld.z );
  7960. material.wireframe === true
  7961. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7962. : fillPath( _color );
  7963. }
  7964. }
  7965. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  7966. _this.info.render.vertices += 4;
  7967. _this.info.render.faces ++;
  7968. setOpacity( material.opacity );
  7969. setBlending( material.blending );
  7970. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  7971. // Let renderFace3() handle this
  7972. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  7973. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  7974. return;
  7975. }
  7976. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7977. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7978. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7979. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  7980. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  7981. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  7982. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7983. _diffuseColor.copy( material.color );
  7984. _emissiveColor.copy( material.emissive );
  7985. if ( material.vertexColors === THREE.FaceColors ) {
  7986. _diffuseColor.r *= element.color.r;
  7987. _diffuseColor.g *= element.color.g;
  7988. _diffuseColor.b *= element.color.b;
  7989. }
  7990. if ( _enableLighting === true ) {
  7991. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  7992. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  7993. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  7994. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  7995. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7996. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7997. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  7998. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  7999. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  8000. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  8001. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  8002. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  8003. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  8004. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  8005. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  8006. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  8007. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  8008. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  8009. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  8010. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  8011. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8012. // TODO: UVs are incorrect, v4->v3?
  8013. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8014. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8015. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8016. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8017. } else {
  8018. _color.r = _ambientLight.r;
  8019. _color.g = _ambientLight.g;
  8020. _color.b = _ambientLight.b;
  8021. calculateLight( element.centroidWorld, element.normalWorld, _color );
  8022. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  8023. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  8024. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  8025. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8026. material.wireframe === true
  8027. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8028. : fillPath( _color );
  8029. }
  8030. } else {
  8031. _color.r = _diffuseColor.r + _emissiveColor.r;
  8032. _color.g = _diffuseColor.g + _emissiveColor.g;
  8033. _color.b = _diffuseColor.b + _emissiveColor.b;
  8034. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8035. material.wireframe === true
  8036. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8037. : fillPath( _color );
  8038. }
  8039. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8040. _color.copy( material.color );
  8041. if ( material.vertexColors === THREE.FaceColors ) {
  8042. _color.r *= element.color.r;
  8043. _color.g *= element.color.g;
  8044. _color.b *= element.color.b;
  8045. }
  8046. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8047. material.wireframe === true
  8048. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8049. : fillPath( _color );
  8050. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8051. _color.r = normalToComponent( element.normalWorld.x );
  8052. _color.g = normalToComponent( element.normalWorld.y );
  8053. _color.b = normalToComponent( element.normalWorld.z );
  8054. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8055. material.wireframe === true
  8056. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8057. : fillPath( _color );
  8058. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8059. _near = camera.near;
  8060. _far = camera.far;
  8061. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8062. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8063. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  8064. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8065. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8066. // TODO: UVs are incorrect, v4->v3?
  8067. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8068. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8069. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8070. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8071. }
  8072. }
  8073. //
  8074. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8075. _context.beginPath();
  8076. _context.moveTo( x0, y0 );
  8077. _context.lineTo( x1, y1 );
  8078. _context.lineTo( x2, y2 );
  8079. _context.closePath();
  8080. }
  8081. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8082. _context.beginPath();
  8083. _context.moveTo( x0, y0 );
  8084. _context.lineTo( x1, y1 );
  8085. _context.lineTo( x2, y2 );
  8086. _context.lineTo( x3, y3 );
  8087. _context.closePath();
  8088. }
  8089. function strokePath( color, linewidth, linecap, linejoin ) {
  8090. setLineWidth( linewidth );
  8091. setLineCap( linecap );
  8092. setLineJoin( linejoin );
  8093. setStrokeStyle( color.getContextStyle() );
  8094. _context.stroke();
  8095. _bboxRect.inflate( linewidth * 2 );
  8096. }
  8097. function fillPath( color ) {
  8098. setFillStyle( color.getContextStyle() );
  8099. _context.fill();
  8100. }
  8101. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8102. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8103. if ( texture.needsUpdate === true ) {
  8104. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8105. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8106. _patterns[ texture.id ] = _context.createPattern(
  8107. texture.image, repeatX === true && repeatY === true
  8108. ? 'repeat'
  8109. : repeatX === true && repeatY === false
  8110. ? 'repeat-x'
  8111. : repeatX === false && repeatY === true
  8112. ? 'repeat-y'
  8113. : 'no-repeat'
  8114. );
  8115. texture.needsUpdate = false;
  8116. }
  8117. _patterns[ texture.id ] === undefined
  8118. ? setFillStyle( 'rgba(0,0,0,1)' )
  8119. : setFillStyle( _patterns[ texture.id ] );
  8120. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8121. var a, b, c, d, e, f, det, idet,
  8122. offsetX = texture.offset.x / texture.repeat.x,
  8123. offsetY = texture.offset.y / texture.repeat.y,
  8124. width = texture.image.width * texture.repeat.x,
  8125. height = texture.image.height * texture.repeat.y;
  8126. u0 = ( u0 + offsetX ) * width;
  8127. v0 = ( 1.0 - v0 + offsetY ) * height;
  8128. u1 = ( u1 + offsetX ) * width;
  8129. v1 = ( 1.0 - v1 + offsetY ) * height;
  8130. u2 = ( u2 + offsetX ) * width;
  8131. v2 = ( 1.0 - v2 + offsetY ) * height;
  8132. x1 -= x0; y1 -= y0;
  8133. x2 -= x0; y2 -= y0;
  8134. u1 -= u0; v1 -= v0;
  8135. u2 -= u0; v2 -= v0;
  8136. det = u1 * v2 - u2 * v1;
  8137. if ( det === 0 ) {
  8138. if ( _imagedatas[ texture.id ] === undefined ) {
  8139. var canvas = document.createElement( 'canvas' )
  8140. canvas.width = texture.image.width;
  8141. canvas.height = texture.image.height;
  8142. var context = canvas.getContext( '2d' );
  8143. context.drawImage( texture.image, 0, 0 );
  8144. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8145. }
  8146. var data = _imagedatas[ texture.id ];
  8147. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8148. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8149. fillPath( _color );
  8150. return;
  8151. }
  8152. idet = 1 / det;
  8153. a = ( v2 * x1 - v1 * x2 ) * idet;
  8154. b = ( v2 * y1 - v1 * y2 ) * idet;
  8155. c = ( u1 * x2 - u2 * x1 ) * idet;
  8156. d = ( u1 * y2 - u2 * y1 ) * idet;
  8157. e = x0 - a * u0 - c * v0;
  8158. f = y0 - b * u0 - d * v0;
  8159. _context.save();
  8160. _context.transform( a, b, c, d, e, f );
  8161. _context.fill();
  8162. _context.restore();
  8163. }
  8164. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8165. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8166. var a, b, c, d, e, f, det, idet,
  8167. width = image.width - 1,
  8168. height = image.height - 1;
  8169. u0 *= width; v0 *= height;
  8170. u1 *= width; v1 *= height;
  8171. u2 *= width; v2 *= height;
  8172. x1 -= x0; y1 -= y0;
  8173. x2 -= x0; y2 -= y0;
  8174. u1 -= u0; v1 -= v0;
  8175. u2 -= u0; v2 -= v0;
  8176. det = u1 * v2 - u2 * v1;
  8177. idet = 1 / det;
  8178. a = ( v2 * x1 - v1 * x2 ) * idet;
  8179. b = ( v2 * y1 - v1 * y2 ) * idet;
  8180. c = ( u1 * x2 - u2 * x1 ) * idet;
  8181. d = ( u1 * y2 - u2 * y1 ) * idet;
  8182. e = x0 - a * u0 - c * v0;
  8183. f = y0 - b * u0 - d * v0;
  8184. _context.save();
  8185. _context.transform( a, b, c, d, e, f );
  8186. _context.clip();
  8187. _context.drawImage( image, 0, 0 );
  8188. _context.restore();
  8189. }
  8190. function getGradientTexture( color1, color2, color3, color4 ) {
  8191. // http://mrdoob.com/blog/post/710
  8192. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8193. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8194. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8195. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8196. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8197. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8198. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8199. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8200. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8201. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8202. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8203. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8204. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8205. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8206. return _gradientMap;
  8207. }
  8208. function smoothstep( value, min, max ) {
  8209. var x = ( value - min ) / ( max - min );
  8210. return x * x * ( 3 - 2 * x );
  8211. }
  8212. function normalToComponent( normal ) {
  8213. var component = ( normal + 1 ) * 0.5;
  8214. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  8215. }
  8216. // Hide anti-alias gaps
  8217. function expand( v1, v2 ) {
  8218. var x = v2.x - v1.x, y = v2.y - v1.y,
  8219. det = x * x + y * y, idet;
  8220. if ( det === 0 ) return;
  8221. idet = 1 / Math.sqrt( det );
  8222. x *= idet; y *= idet;
  8223. v2.x += x; v2.y += y;
  8224. v1.x -= x; v1.y -= y;
  8225. }
  8226. };
  8227. // Context cached methods.
  8228. function setOpacity( value ) {
  8229. if ( _contextGlobalAlpha !== value ) {
  8230. _context.globalAlpha = value;
  8231. _contextGlobalAlpha = value;
  8232. }
  8233. }
  8234. function setBlending( value ) {
  8235. if ( _contextGlobalCompositeOperation !== value ) {
  8236. if ( value === THREE.NormalBlending ) {
  8237. _context.globalCompositeOperation = 'source-over';
  8238. } else if ( value === THREE.AdditiveBlending ) {
  8239. _context.globalCompositeOperation = 'lighter';
  8240. } else if ( value === THREE.SubtractiveBlending ) {
  8241. _context.globalCompositeOperation = 'darker';
  8242. }
  8243. _contextGlobalCompositeOperation = value;
  8244. }
  8245. }
  8246. function setLineWidth( value ) {
  8247. if ( _contextLineWidth !== value ) {
  8248. _context.lineWidth = value;
  8249. _contextLineWidth = value;
  8250. }
  8251. }
  8252. function setLineCap( value ) {
  8253. // "butt", "round", "square"
  8254. if ( _contextLineCap !== value ) {
  8255. _context.lineCap = value;
  8256. _contextLineCap = value;
  8257. }
  8258. }
  8259. function setLineJoin( value ) {
  8260. // "round", "bevel", "miter"
  8261. if ( _contextLineJoin !== value ) {
  8262. _context.lineJoin = value;
  8263. _contextLineJoin = value;
  8264. }
  8265. }
  8266. function setStrokeStyle( value ) {
  8267. if ( _contextStrokeStyle !== value ) {
  8268. _context.strokeStyle = value;
  8269. _contextStrokeStyle = value;
  8270. }
  8271. }
  8272. function setFillStyle( value ) {
  8273. if ( _contextFillStyle !== value ) {
  8274. _context.fillStyle = value;
  8275. _contextFillStyle = value;
  8276. }
  8277. }
  8278. };
  8279. /**
  8280. * @author alteredq / http://alteredqualia.com/
  8281. * @author mrdoob / http://mrdoob.com/
  8282. * @author mikael emtinger / http://gomo.se/
  8283. */
  8284. THREE.ShaderChunk = {
  8285. // FOG
  8286. fog_pars_fragment: [
  8287. "#ifdef USE_FOG",
  8288. "uniform vec3 fogColor;",
  8289. "#ifdef FOG_EXP2",
  8290. "uniform float fogDensity;",
  8291. "#else",
  8292. "uniform float fogNear;",
  8293. "uniform float fogFar;",
  8294. "#endif",
  8295. "#endif"
  8296. ].join("\n"),
  8297. fog_fragment: [
  8298. "#ifdef USE_FOG",
  8299. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8300. "#ifdef FOG_EXP2",
  8301. "const float LOG2 = 1.442695;",
  8302. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8303. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8304. "#else",
  8305. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8306. "#endif",
  8307. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8308. "#endif"
  8309. ].join("\n"),
  8310. // ENVIRONMENT MAP
  8311. envmap_pars_fragment: [
  8312. "#ifdef USE_ENVMAP",
  8313. "uniform float reflectivity;",
  8314. "uniform samplerCube envMap;",
  8315. "uniform float flipEnvMap;",
  8316. "uniform int combine;",
  8317. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8318. "uniform bool useRefract;",
  8319. "uniform float refractionRatio;",
  8320. "#else",
  8321. "varying vec3 vReflect;",
  8322. "#endif",
  8323. "#endif"
  8324. ].join("\n"),
  8325. envmap_fragment: [
  8326. "#ifdef USE_ENVMAP",
  8327. "vec3 reflectVec;",
  8328. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8329. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8330. "if ( useRefract ) {",
  8331. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8332. "} else { ",
  8333. "reflectVec = reflect( cameraToVertex, normal );",
  8334. "}",
  8335. "#else",
  8336. "reflectVec = vReflect;",
  8337. "#endif",
  8338. "#ifdef DOUBLE_SIDED",
  8339. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8340. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8341. "#else",
  8342. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8343. "#endif",
  8344. "#ifdef GAMMA_INPUT",
  8345. "cubeColor.xyz *= cubeColor.xyz;",
  8346. "#endif",
  8347. "if ( combine == 1 ) {",
  8348. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8349. "} else if ( combine == 2 ) {",
  8350. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8351. "} else {",
  8352. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8353. "}",
  8354. "#endif"
  8355. ].join("\n"),
  8356. envmap_pars_vertex: [
  8357. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8358. "varying vec3 vReflect;",
  8359. "uniform float refractionRatio;",
  8360. "uniform bool useRefract;",
  8361. "#endif"
  8362. ].join("\n"),
  8363. worldpos_vertex : [
  8364. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8365. "#ifdef USE_SKINNING",
  8366. "vec4 worldPosition = modelMatrix * skinned;",
  8367. "#endif",
  8368. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8369. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8370. "#endif",
  8371. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8372. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8373. "#endif",
  8374. "#endif"
  8375. ].join("\n"),
  8376. envmap_vertex : [
  8377. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8378. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8379. "worldNormal = normalize( worldNormal );",
  8380. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8381. "if ( useRefract ) {",
  8382. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8383. "} else {",
  8384. "vReflect = reflect( cameraToVertex, worldNormal );",
  8385. "}",
  8386. "#endif"
  8387. ].join("\n"),
  8388. // COLOR MAP (particles)
  8389. map_particle_pars_fragment: [
  8390. "#ifdef USE_MAP",
  8391. "uniform sampler2D map;",
  8392. "#endif"
  8393. ].join("\n"),
  8394. map_particle_fragment: [
  8395. "#ifdef USE_MAP",
  8396. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8397. "#endif"
  8398. ].join("\n"),
  8399. // COLOR MAP (triangles)
  8400. map_pars_vertex: [
  8401. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8402. "varying vec2 vUv;",
  8403. "uniform vec4 offsetRepeat;",
  8404. "#endif"
  8405. ].join("\n"),
  8406. map_pars_fragment: [
  8407. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8408. "varying vec2 vUv;",
  8409. "#endif",
  8410. "#ifdef USE_MAP",
  8411. "uniform sampler2D map;",
  8412. "#endif",
  8413. ].join("\n"),
  8414. map_vertex: [
  8415. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8416. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8417. "#endif"
  8418. ].join("\n"),
  8419. map_fragment: [
  8420. "#ifdef USE_MAP",
  8421. "#ifdef GAMMA_INPUT",
  8422. "vec4 texelColor = texture2D( map, vUv );",
  8423. "texelColor.xyz *= texelColor.xyz;",
  8424. "gl_FragColor = gl_FragColor * texelColor;",
  8425. "#else",
  8426. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  8427. "#endif",
  8428. "#endif"
  8429. ].join("\n"),
  8430. // LIGHT MAP
  8431. lightmap_pars_fragment: [
  8432. "#ifdef USE_LIGHTMAP",
  8433. "varying vec2 vUv2;",
  8434. "uniform sampler2D lightMap;",
  8435. "#endif"
  8436. ].join("\n"),
  8437. lightmap_pars_vertex: [
  8438. "#ifdef USE_LIGHTMAP",
  8439. "varying vec2 vUv2;",
  8440. "#endif"
  8441. ].join("\n"),
  8442. lightmap_fragment: [
  8443. "#ifdef USE_LIGHTMAP",
  8444. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8445. "#endif"
  8446. ].join("\n"),
  8447. lightmap_vertex: [
  8448. "#ifdef USE_LIGHTMAP",
  8449. "vUv2 = uv2;",
  8450. "#endif"
  8451. ].join("\n"),
  8452. // BUMP MAP
  8453. bumpmap_pars_fragment: [
  8454. "#ifdef USE_BUMPMAP",
  8455. "uniform sampler2D bumpMap;",
  8456. "uniform float bumpScale;",
  8457. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8458. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8459. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8460. "vec2 dHdxy_fwd() {",
  8461. "vec2 dSTdx = dFdx( vUv );",
  8462. "vec2 dSTdy = dFdy( vUv );",
  8463. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8464. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8465. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8466. "return vec2( dBx, dBy );",
  8467. "}",
  8468. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8469. "vec3 vSigmaX = dFdx( surf_pos );",
  8470. "vec3 vSigmaY = dFdy( surf_pos );",
  8471. "vec3 vN = surf_norm;", // normalized
  8472. "vec3 R1 = cross( vSigmaY, vN );",
  8473. "vec3 R2 = cross( vN, vSigmaX );",
  8474. "float fDet = dot( vSigmaX, R1 );",
  8475. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8476. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8477. "}",
  8478. "#endif"
  8479. ].join("\n"),
  8480. // NORMAL MAP
  8481. normalmap_pars_fragment: [
  8482. "#ifdef USE_NORMALMAP",
  8483. "uniform sampler2D normalMap;",
  8484. "uniform vec2 normalScale;",
  8485. // Per-Pixel Tangent Space Normal Mapping
  8486. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8487. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8488. "vec3 q0 = dFdx( eye_pos.xyz );",
  8489. "vec3 q1 = dFdy( eye_pos.xyz );",
  8490. "vec2 st0 = dFdx( vUv.st );",
  8491. "vec2 st1 = dFdy( vUv.st );",
  8492. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8493. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8494. "vec3 N = normalize( surf_norm );",
  8495. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8496. "mapN.xy = normalScale * mapN.xy;",
  8497. "mat3 tsn = mat3( S, T, N );",
  8498. "return normalize( tsn * mapN );",
  8499. "}",
  8500. "#endif"
  8501. ].join("\n"),
  8502. // SPECULAR MAP
  8503. specularmap_pars_fragment: [
  8504. "#ifdef USE_SPECULARMAP",
  8505. "uniform sampler2D specularMap;",
  8506. "#endif"
  8507. ].join("\n"),
  8508. specularmap_fragment: [
  8509. "float specularStrength;",
  8510. "#ifdef USE_SPECULARMAP",
  8511. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8512. "specularStrength = texelSpecular.r;",
  8513. "#else",
  8514. "specularStrength = 1.0;",
  8515. "#endif"
  8516. ].join("\n"),
  8517. // LIGHTS LAMBERT
  8518. lights_lambert_pars_vertex: [
  8519. "uniform vec3 ambient;",
  8520. "uniform vec3 diffuse;",
  8521. "uniform vec3 emissive;",
  8522. "uniform vec3 ambientLightColor;",
  8523. "#if MAX_DIR_LIGHTS > 0",
  8524. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8525. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8526. "#endif",
  8527. "#if MAX_HEMI_LIGHTS > 0",
  8528. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8529. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8530. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8531. "#endif",
  8532. "#if MAX_POINT_LIGHTS > 0",
  8533. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8534. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8535. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8536. "#endif",
  8537. "#if MAX_SPOT_LIGHTS > 0",
  8538. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8539. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8540. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8541. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8542. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8543. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8544. "#endif",
  8545. "#ifdef WRAP_AROUND",
  8546. "uniform vec3 wrapRGB;",
  8547. "#endif"
  8548. ].join("\n"),
  8549. lights_lambert_vertex: [
  8550. "vLightFront = vec3( 0.0 );",
  8551. "#ifdef DOUBLE_SIDED",
  8552. "vLightBack = vec3( 0.0 );",
  8553. "#endif",
  8554. "transformedNormal = normalize( transformedNormal );",
  8555. "#if MAX_DIR_LIGHTS > 0",
  8556. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8557. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8558. "vec3 dirVector = normalize( lDirection.xyz );",
  8559. "float dotProduct = dot( transformedNormal, dirVector );",
  8560. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8561. "#ifdef DOUBLE_SIDED",
  8562. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8563. "#ifdef WRAP_AROUND",
  8564. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8565. "#endif",
  8566. "#endif",
  8567. "#ifdef WRAP_AROUND",
  8568. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8569. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8570. "#ifdef DOUBLE_SIDED",
  8571. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8572. "#endif",
  8573. "#endif",
  8574. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8575. "#ifdef DOUBLE_SIDED",
  8576. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8577. "#endif",
  8578. "}",
  8579. "#endif",
  8580. "#if MAX_POINT_LIGHTS > 0",
  8581. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8582. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8583. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8584. "float lDistance = 1.0;",
  8585. "if ( pointLightDistance[ i ] > 0.0 )",
  8586. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8587. "lVector = normalize( lVector );",
  8588. "float dotProduct = dot( transformedNormal, lVector );",
  8589. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8590. "#ifdef DOUBLE_SIDED",
  8591. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8592. "#ifdef WRAP_AROUND",
  8593. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8594. "#endif",
  8595. "#endif",
  8596. "#ifdef WRAP_AROUND",
  8597. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8598. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8599. "#ifdef DOUBLE_SIDED",
  8600. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  8601. "#endif",
  8602. "#endif",
  8603. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  8604. "#ifdef DOUBLE_SIDED",
  8605. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  8606. "#endif",
  8607. "}",
  8608. "#endif",
  8609. "#if MAX_SPOT_LIGHTS > 0",
  8610. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8611. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8612. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8613. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  8614. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8615. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8616. "float lDistance = 1.0;",
  8617. "if ( spotLightDistance[ i ] > 0.0 )",
  8618. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8619. "lVector = normalize( lVector );",
  8620. "float dotProduct = dot( transformedNormal, lVector );",
  8621. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8622. "#ifdef DOUBLE_SIDED",
  8623. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8624. "#ifdef WRAP_AROUND",
  8625. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8626. "#endif",
  8627. "#endif",
  8628. "#ifdef WRAP_AROUND",
  8629. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8630. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  8631. "#ifdef DOUBLE_SIDED",
  8632. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  8633. "#endif",
  8634. "#endif",
  8635. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  8636. "#ifdef DOUBLE_SIDED",
  8637. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  8638. "#endif",
  8639. "}",
  8640. "}",
  8641. "#endif",
  8642. "#if MAX_HEMI_LIGHTS > 0",
  8643. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8644. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8645. "vec3 lVector = normalize( lDirection.xyz );",
  8646. "float dotProduct = dot( transformedNormal, lVector );",
  8647. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8648. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  8649. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8650. "#ifdef DOUBLE_SIDED",
  8651. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  8652. "#endif",
  8653. "}",
  8654. "#endif",
  8655. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  8656. "#ifdef DOUBLE_SIDED",
  8657. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  8658. "#endif"
  8659. ].join("\n"),
  8660. // LIGHTS PHONG
  8661. lights_phong_pars_vertex: [
  8662. "#ifndef PHONG_PER_PIXEL",
  8663. "#if MAX_POINT_LIGHTS > 0",
  8664. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8665. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8666. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8667. "#endif",
  8668. "#if MAX_SPOT_LIGHTS > 0",
  8669. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8670. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8671. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8672. "#endif",
  8673. "#endif",
  8674. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8675. "varying vec3 vWorldPosition;",
  8676. "#endif"
  8677. ].join("\n"),
  8678. lights_phong_vertex: [
  8679. "#ifndef PHONG_PER_PIXEL",
  8680. "#if MAX_POINT_LIGHTS > 0",
  8681. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8682. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8683. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8684. "float lDistance = 1.0;",
  8685. "if ( pointLightDistance[ i ] > 0.0 )",
  8686. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8687. "vPointLight[ i ] = vec4( lVector, lDistance );",
  8688. "}",
  8689. "#endif",
  8690. "#if MAX_SPOT_LIGHTS > 0",
  8691. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8692. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8693. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8694. "float lDistance = 1.0;",
  8695. "if ( spotLightDistance[ i ] > 0.0 )",
  8696. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8697. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  8698. "}",
  8699. "#endif",
  8700. "#endif",
  8701. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8702. "vWorldPosition = worldPosition.xyz;",
  8703. "#endif"
  8704. ].join("\n"),
  8705. lights_phong_pars_fragment: [
  8706. "uniform vec3 ambientLightColor;",
  8707. "#if MAX_DIR_LIGHTS > 0",
  8708. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8709. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8710. "#endif",
  8711. "#if MAX_HEMI_LIGHTS > 0",
  8712. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8713. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8714. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8715. "#endif",
  8716. "#if MAX_POINT_LIGHTS > 0",
  8717. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8718. "#ifdef PHONG_PER_PIXEL",
  8719. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8720. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8721. "#else",
  8722. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8723. "#endif",
  8724. "#endif",
  8725. "#if MAX_SPOT_LIGHTS > 0",
  8726. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8727. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8728. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8729. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8730. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8731. "#ifdef PHONG_PER_PIXEL",
  8732. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8733. "#else",
  8734. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8735. "#endif",
  8736. "#endif",
  8737. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8738. "varying vec3 vWorldPosition;",
  8739. "#endif",
  8740. "#ifdef WRAP_AROUND",
  8741. "uniform vec3 wrapRGB;",
  8742. "#endif",
  8743. "varying vec3 vViewPosition;",
  8744. "varying vec3 vNormal;"
  8745. ].join("\n"),
  8746. lights_phong_fragment: [
  8747. "vec3 normal = normalize( vNormal );",
  8748. "vec3 viewPosition = normalize( vViewPosition );",
  8749. "#ifdef DOUBLE_SIDED",
  8750. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8751. "#endif",
  8752. "#ifdef USE_NORMALMAP",
  8753. "normal = perturbNormal2Arb( -viewPosition, normal );",
  8754. "#elif defined( USE_BUMPMAP )",
  8755. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  8756. "#endif",
  8757. "#if MAX_POINT_LIGHTS > 0",
  8758. "vec3 pointDiffuse = vec3( 0.0 );",
  8759. "vec3 pointSpecular = vec3( 0.0 );",
  8760. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8761. "#ifdef PHONG_PER_PIXEL",
  8762. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8763. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8764. "float lDistance = 1.0;",
  8765. "if ( pointLightDistance[ i ] > 0.0 )",
  8766. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8767. "lVector = normalize( lVector );",
  8768. "#else",
  8769. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  8770. "float lDistance = vPointLight[ i ].w;",
  8771. "#endif",
  8772. // diffuse
  8773. "float dotProduct = dot( normal, lVector );",
  8774. "#ifdef WRAP_AROUND",
  8775. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  8776. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8777. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  8778. "#else",
  8779. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  8780. "#endif",
  8781. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  8782. // specular
  8783. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  8784. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  8785. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  8786. "#ifdef PHYSICALLY_BASED_SHADING",
  8787. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8788. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8789. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  8790. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  8791. "#else",
  8792. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  8793. "#endif",
  8794. "}",
  8795. "#endif",
  8796. "#if MAX_SPOT_LIGHTS > 0",
  8797. "vec3 spotDiffuse = vec3( 0.0 );",
  8798. "vec3 spotSpecular = vec3( 0.0 );",
  8799. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8800. "#ifdef PHONG_PER_PIXEL",
  8801. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8802. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8803. "float lDistance = 1.0;",
  8804. "if ( spotLightDistance[ i ] > 0.0 )",
  8805. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8806. "lVector = normalize( lVector );",
  8807. "#else",
  8808. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  8809. "float lDistance = vSpotLight[ i ].w;",
  8810. "#endif",
  8811. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  8812. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8813. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8814. // diffuse
  8815. "float dotProduct = dot( normal, lVector );",
  8816. "#ifdef WRAP_AROUND",
  8817. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  8818. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8819. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  8820. "#else",
  8821. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  8822. "#endif",
  8823. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  8824. // specular
  8825. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  8826. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  8827. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  8828. "#ifdef PHYSICALLY_BASED_SHADING",
  8829. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8830. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8831. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  8832. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  8833. "#else",
  8834. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  8835. "#endif",
  8836. "}",
  8837. "}",
  8838. "#endif",
  8839. "#if MAX_DIR_LIGHTS > 0",
  8840. "vec3 dirDiffuse = vec3( 0.0 );",
  8841. "vec3 dirSpecular = vec3( 0.0 );" ,
  8842. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8843. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8844. "vec3 dirVector = normalize( lDirection.xyz );",
  8845. // diffuse
  8846. "float dotProduct = dot( normal, dirVector );",
  8847. "#ifdef WRAP_AROUND",
  8848. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  8849. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8850. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  8851. "#else",
  8852. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  8853. "#endif",
  8854. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  8855. // specular
  8856. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  8857. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  8858. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  8859. "#ifdef PHYSICALLY_BASED_SHADING",
  8860. /*
  8861. // fresnel term from skin shader
  8862. "const float F0 = 0.128;",
  8863. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  8864. "float exponential = pow( base, 5.0 );",
  8865. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  8866. */
  8867. /*
  8868. // fresnel term from fresnel shader
  8869. "const float mFresnelBias = 0.08;",
  8870. "const float mFresnelScale = 0.3;",
  8871. "const float mFresnelPower = 5.0;",
  8872. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  8873. */
  8874. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8875. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8876. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  8877. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  8878. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  8879. "#else",
  8880. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  8881. "#endif",
  8882. "}",
  8883. "#endif",
  8884. "#if MAX_HEMI_LIGHTS > 0",
  8885. "vec3 hemiDiffuse = vec3( 0.0 );",
  8886. "vec3 hemiSpecular = vec3( 0.0 );" ,
  8887. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8888. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8889. "vec3 lVector = normalize( lDirection.xyz );",
  8890. // diffuse
  8891. "float dotProduct = dot( normal, lVector );",
  8892. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8893. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8894. "hemiDiffuse += diffuse * hemiColor;",
  8895. // specular (sky light)
  8896. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  8897. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  8898. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  8899. // specular (ground light)
  8900. "vec3 lVectorGround = -lVector;",
  8901. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  8902. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  8903. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  8904. "#ifdef PHYSICALLY_BASED_SHADING",
  8905. "float dotProductGround = dot( normal, lVectorGround );",
  8906. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8907. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8908. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  8909. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  8910. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  8911. "#else",
  8912. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  8913. "#endif",
  8914. "}",
  8915. "#endif",
  8916. "vec3 totalDiffuse = vec3( 0.0 );",
  8917. "vec3 totalSpecular = vec3( 0.0 );",
  8918. "#if MAX_DIR_LIGHTS > 0",
  8919. "totalDiffuse += dirDiffuse;",
  8920. "totalSpecular += dirSpecular;",
  8921. "#endif",
  8922. "#if MAX_HEMI_LIGHTS > 0",
  8923. "totalDiffuse += hemiDiffuse;",
  8924. "totalSpecular += hemiSpecular;",
  8925. "#endif",
  8926. "#if MAX_POINT_LIGHTS > 0",
  8927. "totalDiffuse += pointDiffuse;",
  8928. "totalSpecular += pointSpecular;",
  8929. "#endif",
  8930. "#if MAX_SPOT_LIGHTS > 0",
  8931. "totalDiffuse += spotDiffuse;",
  8932. "totalSpecular += spotSpecular;",
  8933. "#endif",
  8934. "#ifdef METAL",
  8935. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  8936. "#else",
  8937. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  8938. "#endif"
  8939. ].join("\n"),
  8940. // VERTEX COLORS
  8941. color_pars_fragment: [
  8942. "#ifdef USE_COLOR",
  8943. "varying vec3 vColor;",
  8944. "#endif"
  8945. ].join("\n"),
  8946. color_fragment: [
  8947. "#ifdef USE_COLOR",
  8948. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  8949. "#endif"
  8950. ].join("\n"),
  8951. color_pars_vertex: [
  8952. "#ifdef USE_COLOR",
  8953. "varying vec3 vColor;",
  8954. "#endif"
  8955. ].join("\n"),
  8956. color_vertex: [
  8957. "#ifdef USE_COLOR",
  8958. "#ifdef GAMMA_INPUT",
  8959. "vColor = color * color;",
  8960. "#else",
  8961. "vColor = color;",
  8962. "#endif",
  8963. "#endif"
  8964. ].join("\n"),
  8965. // SKINNING
  8966. skinning_pars_vertex: [
  8967. "#ifdef USE_SKINNING",
  8968. "#ifdef BONE_TEXTURE",
  8969. "uniform sampler2D boneTexture;",
  8970. "mat4 getBoneMatrix( const in float i ) {",
  8971. "float j = i * 4.0;",
  8972. "float x = mod( j, N_BONE_PIXEL_X );",
  8973. "float y = floor( j / N_BONE_PIXEL_X );",
  8974. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  8975. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  8976. "y = dy * ( y + 0.5 );",
  8977. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  8978. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  8979. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  8980. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  8981. "mat4 bone = mat4( v1, v2, v3, v4 );",
  8982. "return bone;",
  8983. "}",
  8984. "#else",
  8985. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  8986. "mat4 getBoneMatrix( const in float i ) {",
  8987. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  8988. "return bone;",
  8989. "}",
  8990. "#endif",
  8991. "#endif"
  8992. ].join("\n"),
  8993. skinbase_vertex: [
  8994. "#ifdef USE_SKINNING",
  8995. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  8996. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  8997. "#endif"
  8998. ].join("\n"),
  8999. skinning_vertex: [
  9000. "#ifdef USE_SKINNING",
  9001. "#ifdef USE_MORPHTARGETS",
  9002. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9003. "#else",
  9004. "vec4 skinVertex = vec4( position, 1.0 );",
  9005. "#endif",
  9006. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9007. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9008. "#endif"
  9009. ].join("\n"),
  9010. // MORPHING
  9011. morphtarget_pars_vertex: [
  9012. "#ifdef USE_MORPHTARGETS",
  9013. "#ifndef USE_MORPHNORMALS",
  9014. "uniform float morphTargetInfluences[ 8 ];",
  9015. "#else",
  9016. "uniform float morphTargetInfluences[ 4 ];",
  9017. "#endif",
  9018. "#endif"
  9019. ].join("\n"),
  9020. morphtarget_vertex: [
  9021. "#ifdef USE_MORPHTARGETS",
  9022. "vec3 morphed = vec3( 0.0 );",
  9023. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9024. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9025. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9026. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9027. "#ifndef USE_MORPHNORMALS",
  9028. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9029. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9030. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9031. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9032. "#endif",
  9033. "morphed += position;",
  9034. "#endif"
  9035. ].join("\n"),
  9036. default_vertex : [
  9037. "vec4 mvPosition;",
  9038. "#ifdef USE_SKINNING",
  9039. "mvPosition = modelViewMatrix * skinned;",
  9040. "#endif",
  9041. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9042. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9043. "#endif",
  9044. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9045. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9046. "#endif",
  9047. "gl_Position = projectionMatrix * mvPosition;",
  9048. ].join("\n"),
  9049. morphnormal_vertex: [
  9050. "#ifdef USE_MORPHNORMALS",
  9051. "vec3 morphedNormal = vec3( 0.0 );",
  9052. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9053. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9054. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9055. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9056. "morphedNormal += normal;",
  9057. "#endif"
  9058. ].join("\n"),
  9059. skinnormal_vertex: [
  9060. "#ifdef USE_SKINNING",
  9061. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9062. "skinMatrix += skinWeight.y * boneMatY;",
  9063. "#ifdef USE_MORPHNORMALS",
  9064. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9065. "#else",
  9066. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9067. "#endif",
  9068. "#endif"
  9069. ].join("\n"),
  9070. defaultnormal_vertex: [
  9071. "vec3 objectNormal;",
  9072. "#ifdef USE_SKINNING",
  9073. "objectNormal = skinnedNormal.xyz;",
  9074. "#endif",
  9075. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9076. "objectNormal = morphedNormal;",
  9077. "#endif",
  9078. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9079. "objectNormal = normal;",
  9080. "#endif",
  9081. "#ifdef FLIP_SIDED",
  9082. "objectNormal = -objectNormal;",
  9083. "#endif",
  9084. "vec3 transformedNormal = normalMatrix * objectNormal;",
  9085. ].join("\n"),
  9086. // SHADOW MAP
  9087. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9088. // http://spidergl.org/example.php?id=6
  9089. // http://fabiensanglard.net/shadowmapping
  9090. shadowmap_pars_fragment: [
  9091. "#ifdef USE_SHADOWMAP",
  9092. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9093. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9094. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9095. "uniform float shadowBias[ MAX_SHADOWS ];",
  9096. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9097. "float unpackDepth( const in vec4 rgba_depth ) {",
  9098. "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 );",
  9099. "float depth = dot( rgba_depth, bit_shift );",
  9100. "return depth;",
  9101. "}",
  9102. "#endif"
  9103. ].join("\n"),
  9104. shadowmap_fragment: [
  9105. "#ifdef USE_SHADOWMAP",
  9106. "#ifdef SHADOWMAP_DEBUG",
  9107. "vec3 frustumColors[3];",
  9108. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9109. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9110. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9111. "#endif",
  9112. "#ifdef SHADOWMAP_CASCADE",
  9113. "int inFrustumCount = 0;",
  9114. "#endif",
  9115. "float fDepth;",
  9116. "vec3 shadowColor = vec3( 1.0 );",
  9117. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9118. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9119. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9120. // "if ( all( something, something ) )" using this instead
  9121. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9122. "bool inFrustum = all( inFrustumVec );",
  9123. // don't shadow pixels outside of light frustum
  9124. // use just first frustum (for cascades)
  9125. // don't shadow pixels behind far plane of light frustum
  9126. "#ifdef SHADOWMAP_CASCADE",
  9127. "inFrustumCount += int( inFrustum );",
  9128. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9129. "#else",
  9130. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9131. "#endif",
  9132. "bool frustumTest = all( frustumTestVec );",
  9133. "if ( frustumTest ) {",
  9134. "shadowCoord.z += shadowBias[ i ];",
  9135. "#ifdef SHADOWMAP_SOFT",
  9136. // Percentage-close filtering
  9137. // (9 pixel kernel)
  9138. // http://fabiensanglard.net/shadowmappingPCF/
  9139. "float shadow = 0.0;",
  9140. /*
  9141. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9142. // must enroll loop manually
  9143. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9144. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9145. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9146. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9147. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9148. "float fDepth = unpackDepth( rgbaDepth );",
  9149. "if ( fDepth < shadowCoord.z )",
  9150. "shadow += 1.0;",
  9151. "}",
  9152. "shadow /= 9.0;",
  9153. */
  9154. "const float shadowDelta = 1.0 / 9.0;",
  9155. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9156. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9157. "float dx0 = -1.25 * xPixelOffset;",
  9158. "float dy0 = -1.25 * yPixelOffset;",
  9159. "float dx1 = 1.25 * xPixelOffset;",
  9160. "float dy1 = 1.25 * yPixelOffset;",
  9161. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9162. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9163. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9164. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9165. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9166. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9167. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9168. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9169. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9170. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9171. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9172. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9173. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9174. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9175. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9176. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9177. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9178. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9179. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9180. "#else",
  9181. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9182. "float fDepth = unpackDepth( rgbaDepth );",
  9183. "if ( fDepth < shadowCoord.z )",
  9184. // spot with multiple shadows is darker
  9185. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9186. // spot with multiple shadows has the same color as single shadow spot
  9187. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9188. "#endif",
  9189. "}",
  9190. "#ifdef SHADOWMAP_DEBUG",
  9191. "#ifdef SHADOWMAP_CASCADE",
  9192. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9193. "#else",
  9194. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9195. "#endif",
  9196. "#endif",
  9197. "}",
  9198. "#ifdef GAMMA_OUTPUT",
  9199. "shadowColor *= shadowColor;",
  9200. "#endif",
  9201. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9202. "#endif"
  9203. ].join("\n"),
  9204. shadowmap_pars_vertex: [
  9205. "#ifdef USE_SHADOWMAP",
  9206. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9207. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9208. "#endif"
  9209. ].join("\n"),
  9210. shadowmap_vertex: [
  9211. "#ifdef USE_SHADOWMAP",
  9212. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9213. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9214. "}",
  9215. "#endif"
  9216. ].join("\n"),
  9217. // ALPHATEST
  9218. alphatest_fragment: [
  9219. "#ifdef ALPHATEST",
  9220. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9221. "#endif"
  9222. ].join("\n"),
  9223. // LINEAR SPACE
  9224. linear_to_gamma_fragment: [
  9225. "#ifdef GAMMA_OUTPUT",
  9226. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9227. "#endif"
  9228. ].join("\n"),
  9229. };
  9230. THREE.UniformsUtils = {
  9231. merge: function ( uniforms ) {
  9232. var u, p, tmp, merged = {};
  9233. for ( u = 0; u < uniforms.length; u ++ ) {
  9234. tmp = this.clone( uniforms[ u ] );
  9235. for ( p in tmp ) {
  9236. merged[ p ] = tmp[ p ];
  9237. }
  9238. }
  9239. return merged;
  9240. },
  9241. clone: function ( uniforms_src ) {
  9242. var u, p, parameter, parameter_src, uniforms_dst = {};
  9243. for ( u in uniforms_src ) {
  9244. uniforms_dst[ u ] = {};
  9245. for ( p in uniforms_src[ u ] ) {
  9246. parameter_src = uniforms_src[ u ][ p ];
  9247. if ( parameter_src instanceof THREE.Color ||
  9248. parameter_src instanceof THREE.Vector2 ||
  9249. parameter_src instanceof THREE.Vector3 ||
  9250. parameter_src instanceof THREE.Vector4 ||
  9251. parameter_src instanceof THREE.Matrix4 ||
  9252. parameter_src instanceof THREE.Texture ) {
  9253. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9254. } else if ( parameter_src instanceof Array ) {
  9255. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9256. } else {
  9257. uniforms_dst[ u ][ p ] = parameter_src;
  9258. }
  9259. }
  9260. }
  9261. return uniforms_dst;
  9262. }
  9263. };
  9264. THREE.UniformsLib = {
  9265. common: {
  9266. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9267. "opacity" : { type: "f", value: 1.0 },
  9268. "map" : { type: "t", value: null },
  9269. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9270. "lightMap" : { type: "t", value: null },
  9271. "specularMap" : { type: "t", value: null },
  9272. "envMap" : { type: "t", value: null },
  9273. "flipEnvMap" : { type: "f", value: -1 },
  9274. "useRefract" : { type: "i", value: 0 },
  9275. "reflectivity" : { type: "f", value: 1.0 },
  9276. "refractionRatio" : { type: "f", value: 0.98 },
  9277. "combine" : { type: "i", value: 0 },
  9278. "morphTargetInfluences" : { type: "f", value: 0 }
  9279. },
  9280. bump: {
  9281. "bumpMap" : { type: "t", value: null },
  9282. "bumpScale" : { type: "f", value: 1 }
  9283. },
  9284. normalmap: {
  9285. "normalMap" : { type: "t", value: null },
  9286. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9287. },
  9288. fog : {
  9289. "fogDensity" : { type: "f", value: 0.00025 },
  9290. "fogNear" : { type: "f", value: 1 },
  9291. "fogFar" : { type: "f", value: 2000 },
  9292. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9293. },
  9294. lights: {
  9295. "ambientLightColor" : { type: "fv", value: [] },
  9296. "directionalLightDirection" : { type: "fv", value: [] },
  9297. "directionalLightColor" : { type: "fv", value: [] },
  9298. "hemisphereLightDirection" : { type: "fv", value: [] },
  9299. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9300. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9301. "pointLightColor" : { type: "fv", value: [] },
  9302. "pointLightPosition" : { type: "fv", value: [] },
  9303. "pointLightDistance" : { type: "fv1", value: [] },
  9304. "spotLightColor" : { type: "fv", value: [] },
  9305. "spotLightPosition" : { type: "fv", value: [] },
  9306. "spotLightDirection" : { type: "fv", value: [] },
  9307. "spotLightDistance" : { type: "fv1", value: [] },
  9308. "spotLightAngleCos" : { type: "fv1", value: [] },
  9309. "spotLightExponent" : { type: "fv1", value: [] }
  9310. },
  9311. particle: {
  9312. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9313. "opacity" : { type: "f", value: 1.0 },
  9314. "size" : { type: "f", value: 1.0 },
  9315. "scale" : { type: "f", value: 1.0 },
  9316. "map" : { type: "t", value: null },
  9317. "fogDensity" : { type: "f", value: 0.00025 },
  9318. "fogNear" : { type: "f", value: 1 },
  9319. "fogFar" : { type: "f", value: 2000 },
  9320. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9321. },
  9322. shadowmap: {
  9323. "shadowMap": { type: "tv", value: [] },
  9324. "shadowMapSize": { type: "v2v", value: [] },
  9325. "shadowBias" : { type: "fv1", value: [] },
  9326. "shadowDarkness": { type: "fv1", value: [] },
  9327. "shadowMatrix" : { type: "m4v", value: [] },
  9328. }
  9329. };
  9330. THREE.ShaderLib = {
  9331. 'depth': {
  9332. uniforms: {
  9333. "mNear": { type: "f", value: 1.0 },
  9334. "mFar" : { type: "f", value: 2000.0 },
  9335. "opacity" : { type: "f", value: 1.0 }
  9336. },
  9337. vertexShader: [
  9338. "void main() {",
  9339. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9340. "}"
  9341. ].join("\n"),
  9342. fragmentShader: [
  9343. "uniform float mNear;",
  9344. "uniform float mFar;",
  9345. "uniform float opacity;",
  9346. "void main() {",
  9347. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9348. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9349. "gl_FragColor = vec4( vec3( color ), opacity );",
  9350. "}"
  9351. ].join("\n")
  9352. },
  9353. 'normal': {
  9354. uniforms: {
  9355. "opacity" : { type: "f", value: 1.0 }
  9356. },
  9357. vertexShader: [
  9358. "varying vec3 vNormal;",
  9359. "void main() {",
  9360. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9361. "vNormal = normalize( normalMatrix * normal );",
  9362. "gl_Position = projectionMatrix * mvPosition;",
  9363. "}"
  9364. ].join("\n"),
  9365. fragmentShader: [
  9366. "uniform float opacity;",
  9367. "varying vec3 vNormal;",
  9368. "void main() {",
  9369. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9370. "}"
  9371. ].join("\n")
  9372. },
  9373. 'basic': {
  9374. uniforms: THREE.UniformsUtils.merge( [
  9375. THREE.UniformsLib[ "common" ],
  9376. THREE.UniformsLib[ "fog" ],
  9377. THREE.UniformsLib[ "shadowmap" ]
  9378. ] ),
  9379. vertexShader: [
  9380. THREE.ShaderChunk[ "map_pars_vertex" ],
  9381. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9382. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9383. THREE.ShaderChunk[ "color_pars_vertex" ],
  9384. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9385. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9386. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9387. "void main() {",
  9388. THREE.ShaderChunk[ "map_vertex" ],
  9389. THREE.ShaderChunk[ "lightmap_vertex" ],
  9390. THREE.ShaderChunk[ "color_vertex" ],
  9391. "#ifdef USE_ENVMAP",
  9392. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9393. THREE.ShaderChunk[ "skinbase_vertex" ],
  9394. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9395. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9396. "#endif",
  9397. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9398. THREE.ShaderChunk[ "skinning_vertex" ],
  9399. THREE.ShaderChunk[ "default_vertex" ],
  9400. THREE.ShaderChunk[ "worldpos_vertex" ],
  9401. THREE.ShaderChunk[ "envmap_vertex" ],
  9402. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9403. "}"
  9404. ].join("\n"),
  9405. fragmentShader: [
  9406. "uniform vec3 diffuse;",
  9407. "uniform float opacity;",
  9408. THREE.ShaderChunk[ "color_pars_fragment" ],
  9409. THREE.ShaderChunk[ "map_pars_fragment" ],
  9410. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9411. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9412. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9413. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9414. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9415. "void main() {",
  9416. "gl_FragColor = vec4( diffuse, opacity );",
  9417. THREE.ShaderChunk[ "map_fragment" ],
  9418. THREE.ShaderChunk[ "alphatest_fragment" ],
  9419. THREE.ShaderChunk[ "specularmap_fragment" ],
  9420. THREE.ShaderChunk[ "lightmap_fragment" ],
  9421. THREE.ShaderChunk[ "color_fragment" ],
  9422. THREE.ShaderChunk[ "envmap_fragment" ],
  9423. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9424. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9425. THREE.ShaderChunk[ "fog_fragment" ],
  9426. "}"
  9427. ].join("\n")
  9428. },
  9429. 'lambert': {
  9430. uniforms: THREE.UniformsUtils.merge( [
  9431. THREE.UniformsLib[ "common" ],
  9432. THREE.UniformsLib[ "fog" ],
  9433. THREE.UniformsLib[ "lights" ],
  9434. THREE.UniformsLib[ "shadowmap" ],
  9435. {
  9436. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9437. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9438. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9439. }
  9440. ] ),
  9441. vertexShader: [
  9442. "#define LAMBERT",
  9443. "varying vec3 vLightFront;",
  9444. "#ifdef DOUBLE_SIDED",
  9445. "varying vec3 vLightBack;",
  9446. "#endif",
  9447. THREE.ShaderChunk[ "map_pars_vertex" ],
  9448. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9449. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9450. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9451. THREE.ShaderChunk[ "color_pars_vertex" ],
  9452. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9453. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9454. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9455. "void main() {",
  9456. THREE.ShaderChunk[ "map_vertex" ],
  9457. THREE.ShaderChunk[ "lightmap_vertex" ],
  9458. THREE.ShaderChunk[ "color_vertex" ],
  9459. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9460. THREE.ShaderChunk[ "skinbase_vertex" ],
  9461. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9462. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9463. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9464. THREE.ShaderChunk[ "skinning_vertex" ],
  9465. THREE.ShaderChunk[ "default_vertex" ],
  9466. THREE.ShaderChunk[ "worldpos_vertex" ],
  9467. THREE.ShaderChunk[ "envmap_vertex" ],
  9468. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9469. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9470. "}"
  9471. ].join("\n"),
  9472. fragmentShader: [
  9473. "uniform float opacity;",
  9474. "varying vec3 vLightFront;",
  9475. "#ifdef DOUBLE_SIDED",
  9476. "varying vec3 vLightBack;",
  9477. "#endif",
  9478. THREE.ShaderChunk[ "color_pars_fragment" ],
  9479. THREE.ShaderChunk[ "map_pars_fragment" ],
  9480. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9481. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9482. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9483. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9484. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9485. "void main() {",
  9486. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9487. THREE.ShaderChunk[ "map_fragment" ],
  9488. THREE.ShaderChunk[ "alphatest_fragment" ],
  9489. THREE.ShaderChunk[ "specularmap_fragment" ],
  9490. "#ifdef DOUBLE_SIDED",
  9491. //"float isFront = float( gl_FrontFacing );",
  9492. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9493. "if ( gl_FrontFacing )",
  9494. "gl_FragColor.xyz *= vLightFront;",
  9495. "else",
  9496. "gl_FragColor.xyz *= vLightBack;",
  9497. "#else",
  9498. "gl_FragColor.xyz *= vLightFront;",
  9499. "#endif",
  9500. THREE.ShaderChunk[ "lightmap_fragment" ],
  9501. THREE.ShaderChunk[ "color_fragment" ],
  9502. THREE.ShaderChunk[ "envmap_fragment" ],
  9503. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9504. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9505. THREE.ShaderChunk[ "fog_fragment" ],
  9506. "}"
  9507. ].join("\n")
  9508. },
  9509. 'phong': {
  9510. uniforms: THREE.UniformsUtils.merge( [
  9511. THREE.UniformsLib[ "common" ],
  9512. THREE.UniformsLib[ "bump" ],
  9513. THREE.UniformsLib[ "normalmap" ],
  9514. THREE.UniformsLib[ "fog" ],
  9515. THREE.UniformsLib[ "lights" ],
  9516. THREE.UniformsLib[ "shadowmap" ],
  9517. {
  9518. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9519. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9520. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9521. "shininess": { type: "f", value: 30 },
  9522. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9523. }
  9524. ] ),
  9525. vertexShader: [
  9526. "#define PHONG",
  9527. "varying vec3 vViewPosition;",
  9528. "varying vec3 vNormal;",
  9529. THREE.ShaderChunk[ "map_pars_vertex" ],
  9530. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9531. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9532. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9533. THREE.ShaderChunk[ "color_pars_vertex" ],
  9534. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9535. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9536. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9537. "void main() {",
  9538. THREE.ShaderChunk[ "map_vertex" ],
  9539. THREE.ShaderChunk[ "lightmap_vertex" ],
  9540. THREE.ShaderChunk[ "color_vertex" ],
  9541. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9542. THREE.ShaderChunk[ "skinbase_vertex" ],
  9543. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9544. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9545. "vNormal = normalize( transformedNormal );",
  9546. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9547. THREE.ShaderChunk[ "skinning_vertex" ],
  9548. THREE.ShaderChunk[ "default_vertex" ],
  9549. "vViewPosition = -mvPosition.xyz;",
  9550. THREE.ShaderChunk[ "worldpos_vertex" ],
  9551. THREE.ShaderChunk[ "envmap_vertex" ],
  9552. THREE.ShaderChunk[ "lights_phong_vertex" ],
  9553. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9554. "}"
  9555. ].join("\n"),
  9556. fragmentShader: [
  9557. "uniform vec3 diffuse;",
  9558. "uniform float opacity;",
  9559. "uniform vec3 ambient;",
  9560. "uniform vec3 emissive;",
  9561. "uniform vec3 specular;",
  9562. "uniform float shininess;",
  9563. THREE.ShaderChunk[ "color_pars_fragment" ],
  9564. THREE.ShaderChunk[ "map_pars_fragment" ],
  9565. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9566. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9567. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9568. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  9569. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9570. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  9571. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  9572. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9573. "void main() {",
  9574. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9575. THREE.ShaderChunk[ "map_fragment" ],
  9576. THREE.ShaderChunk[ "alphatest_fragment" ],
  9577. THREE.ShaderChunk[ "specularmap_fragment" ],
  9578. THREE.ShaderChunk[ "lights_phong_fragment" ],
  9579. THREE.ShaderChunk[ "lightmap_fragment" ],
  9580. THREE.ShaderChunk[ "color_fragment" ],
  9581. THREE.ShaderChunk[ "envmap_fragment" ],
  9582. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9583. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9584. THREE.ShaderChunk[ "fog_fragment" ],
  9585. "}"
  9586. ].join("\n")
  9587. },
  9588. 'particle_basic': {
  9589. uniforms: THREE.UniformsUtils.merge( [
  9590. THREE.UniformsLib[ "particle" ],
  9591. THREE.UniformsLib[ "shadowmap" ]
  9592. ] ),
  9593. vertexShader: [
  9594. "uniform float size;",
  9595. "uniform float scale;",
  9596. THREE.ShaderChunk[ "color_pars_vertex" ],
  9597. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9598. "void main() {",
  9599. THREE.ShaderChunk[ "color_vertex" ],
  9600. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9601. "#ifdef USE_SIZEATTENUATION",
  9602. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  9603. "#else",
  9604. "gl_PointSize = size;",
  9605. "#endif",
  9606. "gl_Position = projectionMatrix * mvPosition;",
  9607. THREE.ShaderChunk[ "worldpos_vertex" ],
  9608. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9609. "}"
  9610. ].join("\n"),
  9611. fragmentShader: [
  9612. "uniform vec3 psColor;",
  9613. "uniform float opacity;",
  9614. THREE.ShaderChunk[ "color_pars_fragment" ],
  9615. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  9616. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9617. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9618. "void main() {",
  9619. "gl_FragColor = vec4( psColor, opacity );",
  9620. THREE.ShaderChunk[ "map_particle_fragment" ],
  9621. THREE.ShaderChunk[ "alphatest_fragment" ],
  9622. THREE.ShaderChunk[ "color_fragment" ],
  9623. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9624. THREE.ShaderChunk[ "fog_fragment" ],
  9625. "}"
  9626. ].join("\n")
  9627. },
  9628. 'dashed': {
  9629. uniforms: THREE.UniformsUtils.merge( [
  9630. THREE.UniformsLib[ "common" ],
  9631. THREE.UniformsLib[ "fog" ],
  9632. {
  9633. "scale": { type: "f", value: 1 },
  9634. "dashSize": { type: "f", value: 1 },
  9635. "totalSize": { type: "f", value: 2 }
  9636. }
  9637. ] ),
  9638. vertexShader: [
  9639. "uniform float scale;",
  9640. "attribute float lineDistance;",
  9641. "varying float vLineDistance;",
  9642. THREE.ShaderChunk[ "color_pars_vertex" ],
  9643. "void main() {",
  9644. THREE.ShaderChunk[ "color_vertex" ],
  9645. "vLineDistance = scale * lineDistance;",
  9646. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9647. "gl_Position = projectionMatrix * mvPosition;",
  9648. "}"
  9649. ].join("\n"),
  9650. fragmentShader: [
  9651. "uniform vec3 diffuse;",
  9652. "uniform float opacity;",
  9653. "uniform float dashSize;",
  9654. "uniform float totalSize;",
  9655. "varying float vLineDistance;",
  9656. THREE.ShaderChunk[ "color_pars_fragment" ],
  9657. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9658. "void main() {",
  9659. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  9660. "discard;",
  9661. "}",
  9662. "gl_FragColor = vec4( diffuse, opacity );",
  9663. THREE.ShaderChunk[ "color_fragment" ],
  9664. THREE.ShaderChunk[ "fog_fragment" ],
  9665. "}"
  9666. ].join("\n")
  9667. },
  9668. // Depth encoding into RGBA texture
  9669. // based on SpiderGL shadow map example
  9670. // http://spidergl.org/example.php?id=6
  9671. // originally from
  9672. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  9673. // see also here:
  9674. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  9675. 'depthRGBA': {
  9676. uniforms: {},
  9677. vertexShader: [
  9678. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9679. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9680. "void main() {",
  9681. THREE.ShaderChunk[ "skinbase_vertex" ],
  9682. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9683. THREE.ShaderChunk[ "skinning_vertex" ],
  9684. THREE.ShaderChunk[ "default_vertex" ],
  9685. "}"
  9686. ].join("\n"),
  9687. fragmentShader: [
  9688. "vec4 pack_depth( const in float depth ) {",
  9689. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  9690. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  9691. "vec4 res = fract( depth * bit_shift );",
  9692. "res -= res.xxyz * bit_mask;",
  9693. "return res;",
  9694. "}",
  9695. "void main() {",
  9696. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  9697. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  9698. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  9699. //"gl_FragData[ 0 ] = pack_depth( z );",
  9700. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  9701. "}"
  9702. ].join("\n")
  9703. }
  9704. };
  9705. /**
  9706. * @author supereggbert / http://www.paulbrunt.co.uk/
  9707. * @author mrdoob / http://mrdoob.com/
  9708. * @author alteredq / http://alteredqualia.com/
  9709. * @author szimek / https://github.com/szimek/
  9710. */
  9711. THREE.WebGLRenderer = function ( parameters ) {
  9712. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9713. parameters = parameters || {};
  9714. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  9715. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  9716. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  9717. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  9718. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  9719. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  9720. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  9721. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  9722. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  9723. // public properties
  9724. this.domElement = _canvas;
  9725. this.context = null;
  9726. // clearing
  9727. this.autoClear = true;
  9728. this.autoClearColor = true;
  9729. this.autoClearDepth = true;
  9730. this.autoClearStencil = true;
  9731. // scene graph
  9732. this.sortObjects = true;
  9733. this.autoUpdateObjects = true;
  9734. this.autoUpdateScene = true;
  9735. // physically based shading
  9736. this.gammaInput = false;
  9737. this.gammaOutput = false;
  9738. this.physicallyBasedShading = false;
  9739. // shadow map
  9740. this.shadowMapEnabled = false;
  9741. this.shadowMapAutoUpdate = true;
  9742. this.shadowMapSoft = true;
  9743. this.shadowMapCullFrontFaces = true;
  9744. this.shadowMapDebug = false;
  9745. this.shadowMapCascade = false;
  9746. // morphs
  9747. this.maxMorphTargets = 8;
  9748. this.maxMorphNormals = 4;
  9749. // flags
  9750. this.autoScaleCubemaps = true;
  9751. // custom render plugins
  9752. this.renderPluginsPre = [];
  9753. this.renderPluginsPost = [];
  9754. // info
  9755. this.info = {
  9756. memory: {
  9757. programs: 0,
  9758. geometries: 0,
  9759. textures: 0
  9760. },
  9761. render: {
  9762. calls: 0,
  9763. vertices: 0,
  9764. faces: 0,
  9765. points: 0
  9766. }
  9767. };
  9768. // internal properties
  9769. var _this = this,
  9770. _programs = [],
  9771. _programs_counter = 0,
  9772. // internal state cache
  9773. _currentProgram = null,
  9774. _currentFramebuffer = null,
  9775. _currentMaterialId = -1,
  9776. _currentGeometryGroupHash = null,
  9777. _currentCamera = null,
  9778. _geometryGroupCounter = 0,
  9779. _usedTextureUnits = 0,
  9780. // GL state cache
  9781. _oldDoubleSided = -1,
  9782. _oldFlipSided = -1,
  9783. _oldBlending = -1,
  9784. _oldBlendEquation = -1,
  9785. _oldBlendSrc = -1,
  9786. _oldBlendDst = -1,
  9787. _oldDepthTest = -1,
  9788. _oldDepthWrite = -1,
  9789. _oldPolygonOffset = null,
  9790. _oldPolygonOffsetFactor = null,
  9791. _oldPolygonOffsetUnits = null,
  9792. _oldLineWidth = null,
  9793. _viewportX = 0,
  9794. _viewportY = 0,
  9795. _viewportWidth = 0,
  9796. _viewportHeight = 0,
  9797. _currentWidth = 0,
  9798. _currentHeight = 0,
  9799. // frustum
  9800. _frustum = new THREE.Frustum(),
  9801. // camera matrices cache
  9802. _projScreenMatrix = new THREE.Matrix4(),
  9803. _projScreenMatrixPS = new THREE.Matrix4(),
  9804. _vector3 = new THREE.Vector4(),
  9805. // light arrays cache
  9806. _direction = new THREE.Vector3(),
  9807. _lightsNeedUpdate = true,
  9808. _lights = {
  9809. ambient: [ 0, 0, 0 ],
  9810. directional: { length: 0, colors: new Array(), positions: new Array() },
  9811. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  9812. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  9813. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  9814. };
  9815. // initialize
  9816. var _gl;
  9817. var _glExtensionTextureFloat;
  9818. var _glExtensionStandardDerivatives;
  9819. var _glExtensionTextureFilterAnisotropic;
  9820. var _glExtensionCompressedTextureS3TC;
  9821. initGL();
  9822. setDefaultGLState();
  9823. this.context = _gl;
  9824. // GPU capabilities
  9825. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  9826. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9827. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  9828. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9829. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  9830. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  9831. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  9832. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  9833. // API
  9834. this.getContext = function () {
  9835. return _gl;
  9836. };
  9837. this.supportsVertexTextures = function () {
  9838. return _supportsVertexTextures;
  9839. };
  9840. this.getMaxAnisotropy = function () {
  9841. return _maxAnisotropy;
  9842. };
  9843. this.setSize = function ( width, height ) {
  9844. _canvas.width = width;
  9845. _canvas.height = height;
  9846. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  9847. };
  9848. this.setViewport = function ( x, y, width, height ) {
  9849. _viewportX = x !== undefined ? x : 0;
  9850. _viewportY = y !== undefined ? y : 0;
  9851. _viewportWidth = width !== undefined ? width : _canvas.width;
  9852. _viewportHeight = height !== undefined ? height : _canvas.height;
  9853. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  9854. };
  9855. this.setScissor = function ( x, y, width, height ) {
  9856. _gl.scissor( x, y, width, height );
  9857. };
  9858. this.enableScissorTest = function ( enable ) {
  9859. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  9860. };
  9861. // Clearing
  9862. this.setClearColorHex = function ( hex, alpha ) {
  9863. _clearColor.setHex( hex );
  9864. _clearAlpha = alpha;
  9865. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9866. };
  9867. this.setClearColor = function ( color, alpha ) {
  9868. _clearColor.copy( color );
  9869. _clearAlpha = alpha;
  9870. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9871. };
  9872. this.getClearColor = function () {
  9873. return _clearColor;
  9874. };
  9875. this.getClearAlpha = function () {
  9876. return _clearAlpha;
  9877. };
  9878. this.clear = function ( color, depth, stencil ) {
  9879. var bits = 0;
  9880. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  9881. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  9882. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  9883. _gl.clear( bits );
  9884. };
  9885. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  9886. this.setRenderTarget( renderTarget );
  9887. this.clear( color, depth, stencil );
  9888. };
  9889. // Plugins
  9890. this.addPostPlugin = function ( plugin ) {
  9891. plugin.init( this );
  9892. this.renderPluginsPost.push( plugin );
  9893. };
  9894. this.addPrePlugin = function ( plugin ) {
  9895. plugin.init( this );
  9896. this.renderPluginsPre.push( plugin );
  9897. };
  9898. // Deallocation
  9899. this.deallocateObject = function ( object ) {
  9900. if ( ! object.__webglInit ) return;
  9901. object.__webglInit = false;
  9902. delete object._modelViewMatrix;
  9903. delete object._normalMatrix;
  9904. delete object._normalMatrixArray;
  9905. delete object._modelViewMatrixArray;
  9906. delete object._modelMatrixArray;
  9907. if ( object instanceof THREE.Mesh ) {
  9908. for ( var g in object.geometry.geometryGroups ) {
  9909. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  9910. }
  9911. } else if ( object instanceof THREE.Ribbon ) {
  9912. deleteRibbonBuffers( object.geometry );
  9913. } else if ( object instanceof THREE.Line ) {
  9914. deleteLineBuffers( object.geometry );
  9915. } else if ( object instanceof THREE.ParticleSystem ) {
  9916. deleteParticleBuffers( object.geometry );
  9917. }
  9918. };
  9919. this.deallocateTexture = function ( texture ) {
  9920. if ( ! texture.__webglInit ) return;
  9921. texture.__webglInit = false;
  9922. _gl.deleteTexture( texture.__webglTexture );
  9923. _this.info.memory.textures --;
  9924. };
  9925. this.deallocateRenderTarget = function ( renderTarget ) {
  9926. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  9927. _gl.deleteTexture( renderTarget.__webglTexture );
  9928. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9929. for ( var i = 0; i < 6; i ++ ) {
  9930. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  9931. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  9932. }
  9933. } else {
  9934. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  9935. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  9936. }
  9937. };
  9938. this.deallocateMaterial = function ( material ) {
  9939. var program = material.program;
  9940. if ( ! program ) return;
  9941. material.program = undefined;
  9942. // only deallocate GL program if this was the last use of shared program
  9943. // assumed there is only single copy of any program in the _programs list
  9944. // (that's how it's constructed)
  9945. var i, il, programInfo;
  9946. var deleteProgram = false;
  9947. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9948. programInfo = _programs[ i ];
  9949. if ( programInfo.program === program ) {
  9950. programInfo.usedTimes --;
  9951. if ( programInfo.usedTimes === 0 ) {
  9952. deleteProgram = true;
  9953. }
  9954. break;
  9955. }
  9956. }
  9957. if ( deleteProgram ) {
  9958. // avoid using array.splice, this is costlier than creating new array from scratch
  9959. var newPrograms = [];
  9960. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9961. programInfo = _programs[ i ];
  9962. if ( programInfo.program !== program ) {
  9963. newPrograms.push( programInfo );
  9964. }
  9965. }
  9966. _programs = newPrograms;
  9967. _gl.deleteProgram( program );
  9968. _this.info.memory.programs --;
  9969. }
  9970. };
  9971. // Rendering
  9972. this.updateShadowMap = function ( scene, camera ) {
  9973. _currentProgram = null;
  9974. _oldBlending = -1;
  9975. _oldDepthTest = -1;
  9976. _oldDepthWrite = -1;
  9977. _currentGeometryGroupHash = -1;
  9978. _currentMaterialId = -1;
  9979. _lightsNeedUpdate = true;
  9980. _oldDoubleSided = -1;
  9981. _oldFlipSided = -1;
  9982. this.shadowMapPlugin.update( scene, camera );
  9983. };
  9984. // Internal functions
  9985. // Buffer allocation
  9986. function createParticleBuffers ( geometry ) {
  9987. geometry.__webglVertexBuffer = _gl.createBuffer();
  9988. geometry.__webglColorBuffer = _gl.createBuffer();
  9989. _this.info.memory.geometries ++;
  9990. };
  9991. function createLineBuffers ( geometry ) {
  9992. geometry.__webglVertexBuffer = _gl.createBuffer();
  9993. geometry.__webglColorBuffer = _gl.createBuffer();
  9994. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  9995. _this.info.memory.geometries ++;
  9996. };
  9997. function createRibbonBuffers ( geometry ) {
  9998. geometry.__webglVertexBuffer = _gl.createBuffer();
  9999. geometry.__webglColorBuffer = _gl.createBuffer();
  10000. geometry.__webglNormalBuffer = _gl.createBuffer();
  10001. _this.info.memory.geometries ++;
  10002. };
  10003. function createMeshBuffers ( geometryGroup ) {
  10004. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10005. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10006. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10007. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10008. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10009. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10010. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10011. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10012. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10013. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10014. var m, ml;
  10015. if ( geometryGroup.numMorphTargets ) {
  10016. geometryGroup.__webglMorphTargetsBuffers = [];
  10017. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10018. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10019. }
  10020. }
  10021. if ( geometryGroup.numMorphNormals ) {
  10022. geometryGroup.__webglMorphNormalsBuffers = [];
  10023. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10024. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10025. }
  10026. }
  10027. _this.info.memory.geometries ++;
  10028. };
  10029. // Buffer deallocation
  10030. function deleteParticleBuffers ( geometry ) {
  10031. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10032. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10033. deleteCustomAttributesBuffers( geometry );
  10034. _this.info.memory.geometries --;
  10035. };
  10036. function deleteLineBuffers ( geometry ) {
  10037. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10038. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10039. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10040. deleteCustomAttributesBuffers( geometry );
  10041. _this.info.memory.geometries --;
  10042. };
  10043. function deleteRibbonBuffers ( geometry ) {
  10044. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10045. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10046. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10047. deleteCustomAttributesBuffers( geometry );
  10048. _this.info.memory.geometries --;
  10049. };
  10050. function deleteMeshBuffers ( geometryGroup ) {
  10051. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  10052. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  10053. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  10054. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  10055. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  10056. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  10057. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  10058. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  10059. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  10060. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  10061. var m, ml;
  10062. if ( geometryGroup.numMorphTargets ) {
  10063. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10064. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10065. }
  10066. }
  10067. if ( geometryGroup.numMorphNormals ) {
  10068. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10069. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10070. }
  10071. }
  10072. deleteCustomAttributesBuffers( geometryGroup );
  10073. _this.info.memory.geometries --;
  10074. };
  10075. function deleteCustomAttributesBuffers( geometry ) {
  10076. if ( geometry.__webglCustomAttributesList ) {
  10077. for ( var id in geometry.__webglCustomAttributesList ) {
  10078. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  10079. }
  10080. }
  10081. };
  10082. // Buffer initialization
  10083. function initCustomAttributes ( geometry, object ) {
  10084. var nvertices = geometry.vertices.length;
  10085. var material = object.material;
  10086. if ( material.attributes ) {
  10087. if ( geometry.__webglCustomAttributesList === undefined ) {
  10088. geometry.__webglCustomAttributesList = [];
  10089. }
  10090. for ( var a in material.attributes ) {
  10091. var attribute = material.attributes[ a ];
  10092. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10093. attribute.__webglInitialized = true;
  10094. var size = 1; // "f" and "i"
  10095. if ( attribute.type === "v2" ) size = 2;
  10096. else if ( attribute.type === "v3" ) size = 3;
  10097. else if ( attribute.type === "v4" ) size = 4;
  10098. else if ( attribute.type === "c" ) size = 3;
  10099. attribute.size = size;
  10100. attribute.array = new Float32Array( nvertices * size );
  10101. attribute.buffer = _gl.createBuffer();
  10102. attribute.buffer.belongsToAttribute = a;
  10103. attribute.needsUpdate = true;
  10104. }
  10105. geometry.__webglCustomAttributesList.push( attribute );
  10106. }
  10107. }
  10108. };
  10109. function initParticleBuffers ( geometry, object ) {
  10110. var nvertices = geometry.vertices.length;
  10111. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10112. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10113. geometry.__sortArray = [];
  10114. geometry.__webglParticleCount = nvertices;
  10115. initCustomAttributes ( geometry, object );
  10116. };
  10117. function initLineBuffers ( geometry, object ) {
  10118. var nvertices = geometry.vertices.length;
  10119. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10120. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10121. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  10122. geometry.__webglLineCount = nvertices;
  10123. initCustomAttributes ( geometry, object );
  10124. };
  10125. function initRibbonBuffers ( geometry, object ) {
  10126. var nvertices = geometry.vertices.length;
  10127. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10128. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10129. geometry.__normalArray = new Float32Array( nvertices * 3 );
  10130. geometry.__webglVertexCount = nvertices;
  10131. initCustomAttributes ( geometry, object );
  10132. };
  10133. function initMeshBuffers ( geometryGroup, object ) {
  10134. var geometry = object.geometry,
  10135. faces3 = geometryGroup.faces3,
  10136. faces4 = geometryGroup.faces4,
  10137. nvertices = faces3.length * 3 + faces4.length * 4,
  10138. ntris = faces3.length * 1 + faces4.length * 2,
  10139. nlines = faces3.length * 3 + faces4.length * 4,
  10140. material = getBufferMaterial( object, geometryGroup ),
  10141. uvType = bufferGuessUVType( material ),
  10142. normalType = bufferGuessNormalType( material ),
  10143. vertexColorType = bufferGuessVertexColorType( material );
  10144. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  10145. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  10146. if ( normalType ) {
  10147. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  10148. }
  10149. if ( geometry.hasTangents ) {
  10150. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  10151. }
  10152. if ( vertexColorType ) {
  10153. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  10154. }
  10155. if ( uvType ) {
  10156. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  10157. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  10158. }
  10159. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  10160. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  10161. }
  10162. }
  10163. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  10164. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  10165. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  10166. }
  10167. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  10168. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  10169. var m, ml;
  10170. if ( geometryGroup.numMorphTargets ) {
  10171. geometryGroup.__morphTargetsArrays = [];
  10172. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10173. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  10174. }
  10175. }
  10176. if ( geometryGroup.numMorphNormals ) {
  10177. geometryGroup.__morphNormalsArrays = [];
  10178. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10179. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  10180. }
  10181. }
  10182. geometryGroup.__webglFaceCount = ntris * 3;
  10183. geometryGroup.__webglLineCount = nlines * 2;
  10184. // custom attributes
  10185. if ( material.attributes ) {
  10186. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  10187. geometryGroup.__webglCustomAttributesList = [];
  10188. }
  10189. for ( var a in material.attributes ) {
  10190. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  10191. // attribute buffers which are correctly indexed in the setMeshBuffers function
  10192. var originalAttribute = material.attributes[ a ];
  10193. var attribute = {};
  10194. for ( var property in originalAttribute ) {
  10195. attribute[ property ] = originalAttribute[ property ];
  10196. }
  10197. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10198. attribute.__webglInitialized = true;
  10199. var size = 1; // "f" and "i"
  10200. if( attribute.type === "v2" ) size = 2;
  10201. else if( attribute.type === "v3" ) size = 3;
  10202. else if( attribute.type === "v4" ) size = 4;
  10203. else if( attribute.type === "c" ) size = 3;
  10204. attribute.size = size;
  10205. attribute.array = new Float32Array( nvertices * size );
  10206. attribute.buffer = _gl.createBuffer();
  10207. attribute.buffer.belongsToAttribute = a;
  10208. originalAttribute.needsUpdate = true;
  10209. attribute.__original = originalAttribute;
  10210. }
  10211. geometryGroup.__webglCustomAttributesList.push( attribute );
  10212. }
  10213. }
  10214. geometryGroup.__inittedArrays = true;
  10215. };
  10216. function getBufferMaterial( object, geometryGroup ) {
  10217. if ( object.material instanceof THREE.MeshFaceMaterial ) {
  10218. if ( object.material.materials.length > 0 ) {
  10219. return object.material.materials[ geometryGroup.materialIndex ];
  10220. } else {
  10221. return object.geometry.materials[ geometryGroup.materialIndex ];
  10222. }
  10223. } else {
  10224. return object.material;
  10225. }
  10226. };
  10227. function materialNeedsSmoothNormals ( material ) {
  10228. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  10229. };
  10230. function bufferGuessNormalType ( material ) {
  10231. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  10232. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  10233. return false;
  10234. }
  10235. if ( materialNeedsSmoothNormals( material ) ) {
  10236. return THREE.SmoothShading;
  10237. } else {
  10238. return THREE.FlatShading;
  10239. }
  10240. };
  10241. function bufferGuessVertexColorType ( material ) {
  10242. if ( material.vertexColors ) {
  10243. return material.vertexColors;
  10244. }
  10245. return false;
  10246. };
  10247. function bufferGuessUVType ( material ) {
  10248. // material must use some texture to require uvs
  10249. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  10250. return true;
  10251. }
  10252. return false;
  10253. };
  10254. //
  10255. function initDirectBuffers( geometry ) {
  10256. var a, attribute, type;
  10257. for ( a in geometry.attributes ) {
  10258. if ( a === "index" ) {
  10259. type = _gl.ELEMENT_ARRAY_BUFFER;
  10260. } else {
  10261. type = _gl.ARRAY_BUFFER;
  10262. }
  10263. attribute = geometry.attributes[ a ];
  10264. attribute.buffer = _gl.createBuffer();
  10265. _gl.bindBuffer( type, attribute.buffer );
  10266. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  10267. }
  10268. };
  10269. // Buffer setting
  10270. function setParticleBuffers ( geometry, hint, object ) {
  10271. var v, c, vertex, offset, index, color,
  10272. vertices = geometry.vertices,
  10273. vl = vertices.length,
  10274. colors = geometry.colors,
  10275. cl = colors.length,
  10276. vertexArray = geometry.__vertexArray,
  10277. colorArray = geometry.__colorArray,
  10278. sortArray = geometry.__sortArray,
  10279. dirtyVertices = geometry.verticesNeedUpdate,
  10280. dirtyElements = geometry.elementsNeedUpdate,
  10281. dirtyColors = geometry.colorsNeedUpdate,
  10282. customAttributes = geometry.__webglCustomAttributesList,
  10283. i, il,
  10284. a, ca, cal, value,
  10285. customAttribute;
  10286. if ( object.sortParticles ) {
  10287. _projScreenMatrixPS.copy( _projScreenMatrix );
  10288. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  10289. for ( v = 0; v < vl; v ++ ) {
  10290. vertex = vertices[ v ];
  10291. _vector3.copy( vertex );
  10292. _projScreenMatrixPS.multiplyVector3( _vector3 );
  10293. sortArray[ v ] = [ _vector3.z, v ];
  10294. }
  10295. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  10296. for ( v = 0; v < vl; v ++ ) {
  10297. vertex = vertices[ sortArray[v][1] ];
  10298. offset = v * 3;
  10299. vertexArray[ offset ] = vertex.x;
  10300. vertexArray[ offset + 1 ] = vertex.y;
  10301. vertexArray[ offset + 2 ] = vertex.z;
  10302. }
  10303. for ( c = 0; c < cl; c ++ ) {
  10304. offset = c * 3;
  10305. color = colors[ sortArray[c][1] ];
  10306. colorArray[ offset ] = color.r;
  10307. colorArray[ offset + 1 ] = color.g;
  10308. colorArray[ offset + 2 ] = color.b;
  10309. }
  10310. if ( customAttributes ) {
  10311. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10312. customAttribute = customAttributes[ i ];
  10313. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  10314. offset = 0;
  10315. cal = customAttribute.value.length;
  10316. if ( customAttribute.size === 1 ) {
  10317. for ( ca = 0; ca < cal; ca ++ ) {
  10318. index = sortArray[ ca ][ 1 ];
  10319. customAttribute.array[ ca ] = customAttribute.value[ index ];
  10320. }
  10321. } else if ( customAttribute.size === 2 ) {
  10322. for ( ca = 0; ca < cal; ca ++ ) {
  10323. index = sortArray[ ca ][ 1 ];
  10324. value = customAttribute.value[ index ];
  10325. customAttribute.array[ offset ] = value.x;
  10326. customAttribute.array[ offset + 1 ] = value.y;
  10327. offset += 2;
  10328. }
  10329. } else if ( customAttribute.size === 3 ) {
  10330. if ( customAttribute.type === "c" ) {
  10331. for ( ca = 0; ca < cal; ca ++ ) {
  10332. index = sortArray[ ca ][ 1 ];
  10333. value = customAttribute.value[ index ];
  10334. customAttribute.array[ offset ] = value.r;
  10335. customAttribute.array[ offset + 1 ] = value.g;
  10336. customAttribute.array[ offset + 2 ] = value.b;
  10337. offset += 3;
  10338. }
  10339. } else {
  10340. for ( ca = 0; ca < cal; ca ++ ) {
  10341. index = sortArray[ ca ][ 1 ];
  10342. value = customAttribute.value[ index ];
  10343. customAttribute.array[ offset ] = value.x;
  10344. customAttribute.array[ offset + 1 ] = value.y;
  10345. customAttribute.array[ offset + 2 ] = value.z;
  10346. offset += 3;
  10347. }
  10348. }
  10349. } else if ( customAttribute.size === 4 ) {
  10350. for ( ca = 0; ca < cal; ca ++ ) {
  10351. index = sortArray[ ca ][ 1 ];
  10352. value = customAttribute.value[ index ];
  10353. customAttribute.array[ offset ] = value.x;
  10354. customAttribute.array[ offset + 1 ] = value.y;
  10355. customAttribute.array[ offset + 2 ] = value.z;
  10356. customAttribute.array[ offset + 3 ] = value.w;
  10357. offset += 4;
  10358. }
  10359. }
  10360. }
  10361. }
  10362. } else {
  10363. if ( dirtyVertices ) {
  10364. for ( v = 0; v < vl; v ++ ) {
  10365. vertex = vertices[ v ];
  10366. offset = v * 3;
  10367. vertexArray[ offset ] = vertex.x;
  10368. vertexArray[ offset + 1 ] = vertex.y;
  10369. vertexArray[ offset + 2 ] = vertex.z;
  10370. }
  10371. }
  10372. if ( dirtyColors ) {
  10373. for ( c = 0; c < cl; c ++ ) {
  10374. color = colors[ c ];
  10375. offset = c * 3;
  10376. colorArray[ offset ] = color.r;
  10377. colorArray[ offset + 1 ] = color.g;
  10378. colorArray[ offset + 2 ] = color.b;
  10379. }
  10380. }
  10381. if ( customAttributes ) {
  10382. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10383. customAttribute = customAttributes[ i ];
  10384. if ( customAttribute.needsUpdate &&
  10385. ( customAttribute.boundTo === undefined ||
  10386. customAttribute.boundTo === "vertices") ) {
  10387. cal = customAttribute.value.length;
  10388. offset = 0;
  10389. if ( customAttribute.size === 1 ) {
  10390. for ( ca = 0; ca < cal; ca ++ ) {
  10391. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10392. }
  10393. } else if ( customAttribute.size === 2 ) {
  10394. for ( ca = 0; ca < cal; ca ++ ) {
  10395. value = customAttribute.value[ ca ];
  10396. customAttribute.array[ offset ] = value.x;
  10397. customAttribute.array[ offset + 1 ] = value.y;
  10398. offset += 2;
  10399. }
  10400. } else if ( customAttribute.size === 3 ) {
  10401. if ( customAttribute.type === "c" ) {
  10402. for ( ca = 0; ca < cal; ca ++ ) {
  10403. value = customAttribute.value[ ca ];
  10404. customAttribute.array[ offset ] = value.r;
  10405. customAttribute.array[ offset + 1 ] = value.g;
  10406. customAttribute.array[ offset + 2 ] = value.b;
  10407. offset += 3;
  10408. }
  10409. } else {
  10410. for ( ca = 0; ca < cal; ca ++ ) {
  10411. value = customAttribute.value[ ca ];
  10412. customAttribute.array[ offset ] = value.x;
  10413. customAttribute.array[ offset + 1 ] = value.y;
  10414. customAttribute.array[ offset + 2 ] = value.z;
  10415. offset += 3;
  10416. }
  10417. }
  10418. } else if ( customAttribute.size === 4 ) {
  10419. for ( ca = 0; ca < cal; ca ++ ) {
  10420. value = customAttribute.value[ ca ];
  10421. customAttribute.array[ offset ] = value.x;
  10422. customAttribute.array[ offset + 1 ] = value.y;
  10423. customAttribute.array[ offset + 2 ] = value.z;
  10424. customAttribute.array[ offset + 3 ] = value.w;
  10425. offset += 4;
  10426. }
  10427. }
  10428. }
  10429. }
  10430. }
  10431. }
  10432. if ( dirtyVertices || object.sortParticles ) {
  10433. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10434. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10435. }
  10436. if ( dirtyColors || object.sortParticles ) {
  10437. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10438. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10439. }
  10440. if ( customAttributes ) {
  10441. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10442. customAttribute = customAttributes[ i ];
  10443. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10444. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10445. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10446. }
  10447. }
  10448. }
  10449. };
  10450. function setLineBuffers ( geometry, hint ) {
  10451. var v, c, d, vertex, offset, color,
  10452. vertices = geometry.vertices,
  10453. colors = geometry.colors,
  10454. lineDistances = geometry.lineDistances,
  10455. vl = vertices.length,
  10456. cl = colors.length,
  10457. dl = lineDistances.length,
  10458. vertexArray = geometry.__vertexArray,
  10459. colorArray = geometry.__colorArray,
  10460. lineDistanceArray = geometry.__lineDistanceArray,
  10461. dirtyVertices = geometry.verticesNeedUpdate,
  10462. dirtyColors = geometry.colorsNeedUpdate,
  10463. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  10464. customAttributes = geometry.__webglCustomAttributesList,
  10465. i, il,
  10466. a, ca, cal, value,
  10467. customAttribute;
  10468. if ( dirtyVertices ) {
  10469. for ( v = 0; v < vl; v ++ ) {
  10470. vertex = vertices[ v ];
  10471. offset = v * 3;
  10472. vertexArray[ offset ] = vertex.x;
  10473. vertexArray[ offset + 1 ] = vertex.y;
  10474. vertexArray[ offset + 2 ] = vertex.z;
  10475. }
  10476. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10477. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10478. }
  10479. if ( dirtyColors ) {
  10480. for ( c = 0; c < cl; c ++ ) {
  10481. color = colors[ c ];
  10482. offset = c * 3;
  10483. colorArray[ offset ] = color.r;
  10484. colorArray[ offset + 1 ] = color.g;
  10485. colorArray[ offset + 2 ] = color.b;
  10486. }
  10487. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10488. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10489. }
  10490. if ( dirtyLineDistances ) {
  10491. for ( d = 0; d < dl; d ++ ) {
  10492. lineDistanceArray[ d ] = lineDistances[ d ];
  10493. }
  10494. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  10495. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  10496. }
  10497. if ( customAttributes ) {
  10498. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10499. customAttribute = customAttributes[ i ];
  10500. if ( customAttribute.needsUpdate &&
  10501. ( customAttribute.boundTo === undefined ||
  10502. customAttribute.boundTo === "vertices" ) ) {
  10503. offset = 0;
  10504. cal = customAttribute.value.length;
  10505. if ( customAttribute.size === 1 ) {
  10506. for ( ca = 0; ca < cal; ca ++ ) {
  10507. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10508. }
  10509. } else if ( customAttribute.size === 2 ) {
  10510. for ( ca = 0; ca < cal; ca ++ ) {
  10511. value = customAttribute.value[ ca ];
  10512. customAttribute.array[ offset ] = value.x;
  10513. customAttribute.array[ offset + 1 ] = value.y;
  10514. offset += 2;
  10515. }
  10516. } else if ( customAttribute.size === 3 ) {
  10517. if ( customAttribute.type === "c" ) {
  10518. for ( ca = 0; ca < cal; ca ++ ) {
  10519. value = customAttribute.value[ ca ];
  10520. customAttribute.array[ offset ] = value.r;
  10521. customAttribute.array[ offset + 1 ] = value.g;
  10522. customAttribute.array[ offset + 2 ] = value.b;
  10523. offset += 3;
  10524. }
  10525. } else {
  10526. for ( ca = 0; ca < cal; ca ++ ) {
  10527. value = customAttribute.value[ ca ];
  10528. customAttribute.array[ offset ] = value.x;
  10529. customAttribute.array[ offset + 1 ] = value.y;
  10530. customAttribute.array[ offset + 2 ] = value.z;
  10531. offset += 3;
  10532. }
  10533. }
  10534. } else if ( customAttribute.size === 4 ) {
  10535. for ( ca = 0; ca < cal; ca ++ ) {
  10536. value = customAttribute.value[ ca ];
  10537. customAttribute.array[ offset ] = value.x;
  10538. customAttribute.array[ offset + 1 ] = value.y;
  10539. customAttribute.array[ offset + 2 ] = value.z;
  10540. customAttribute.array[ offset + 3 ] = value.w;
  10541. offset += 4;
  10542. }
  10543. }
  10544. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10545. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10546. }
  10547. }
  10548. }
  10549. };
  10550. function setRibbonBuffers ( geometry, hint ) {
  10551. var v, c, n, vertex, offset, color, normal,
  10552. i, il, ca, cal, customAttribute, value,
  10553. vertices = geometry.vertices,
  10554. colors = geometry.colors,
  10555. normals = geometry.normals,
  10556. vl = vertices.length,
  10557. cl = colors.length,
  10558. nl = normals.length,
  10559. vertexArray = geometry.__vertexArray,
  10560. colorArray = geometry.__colorArray,
  10561. normalArray = geometry.__normalArray,
  10562. dirtyVertices = geometry.verticesNeedUpdate,
  10563. dirtyColors = geometry.colorsNeedUpdate,
  10564. dirtyNormals = geometry.normalsNeedUpdate,
  10565. customAttributes = geometry.__webglCustomAttributesList;
  10566. if ( dirtyVertices ) {
  10567. for ( v = 0; v < vl; v ++ ) {
  10568. vertex = vertices[ v ];
  10569. offset = v * 3;
  10570. vertexArray[ offset ] = vertex.x;
  10571. vertexArray[ offset + 1 ] = vertex.y;
  10572. vertexArray[ offset + 2 ] = vertex.z;
  10573. }
  10574. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10575. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10576. }
  10577. if ( dirtyColors ) {
  10578. for ( c = 0; c < cl; c ++ ) {
  10579. color = colors[ c ];
  10580. offset = c * 3;
  10581. colorArray[ offset ] = color.r;
  10582. colorArray[ offset + 1 ] = color.g;
  10583. colorArray[ offset + 2 ] = color.b;
  10584. }
  10585. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10586. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10587. }
  10588. if ( dirtyNormals ) {
  10589. for ( n = 0; n < nl; n ++ ) {
  10590. normal = normals[ n ];
  10591. offset = n * 3;
  10592. normalArray[ offset ] = normal.x;
  10593. normalArray[ offset + 1 ] = normal.y;
  10594. normalArray[ offset + 2 ] = normal.z;
  10595. }
  10596. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  10597. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10598. }
  10599. if ( customAttributes ) {
  10600. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10601. customAttribute = customAttributes[ i ];
  10602. if ( customAttribute.needsUpdate &&
  10603. ( customAttribute.boundTo === undefined ||
  10604. customAttribute.boundTo === "vertices" ) ) {
  10605. offset = 0;
  10606. cal = customAttribute.value.length;
  10607. if ( customAttribute.size === 1 ) {
  10608. for ( ca = 0; ca < cal; ca ++ ) {
  10609. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10610. }
  10611. } else if ( customAttribute.size === 2 ) {
  10612. for ( ca = 0; ca < cal; ca ++ ) {
  10613. value = customAttribute.value[ ca ];
  10614. customAttribute.array[ offset ] = value.x;
  10615. customAttribute.array[ offset + 1 ] = value.y;
  10616. offset += 2;
  10617. }
  10618. } else if ( customAttribute.size === 3 ) {
  10619. if ( customAttribute.type === "c" ) {
  10620. for ( ca = 0; ca < cal; ca ++ ) {
  10621. value = customAttribute.value[ ca ];
  10622. customAttribute.array[ offset ] = value.r;
  10623. customAttribute.array[ offset + 1 ] = value.g;
  10624. customAttribute.array[ offset + 2 ] = value.b;
  10625. offset += 3;
  10626. }
  10627. } else {
  10628. for ( ca = 0; ca < cal; ca ++ ) {
  10629. value = customAttribute.value[ ca ];
  10630. customAttribute.array[ offset ] = value.x;
  10631. customAttribute.array[ offset + 1 ] = value.y;
  10632. customAttribute.array[ offset + 2 ] = value.z;
  10633. offset += 3;
  10634. }
  10635. }
  10636. } else if ( customAttribute.size === 4 ) {
  10637. for ( ca = 0; ca < cal; ca ++ ) {
  10638. value = customAttribute.value[ ca ];
  10639. customAttribute.array[ offset ] = value.x;
  10640. customAttribute.array[ offset + 1 ] = value.y;
  10641. customAttribute.array[ offset + 2 ] = value.z;
  10642. customAttribute.array[ offset + 3 ] = value.w;
  10643. offset += 4;
  10644. }
  10645. }
  10646. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10647. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10648. }
  10649. }
  10650. }
  10651. };
  10652. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  10653. if ( ! geometryGroup.__inittedArrays ) {
  10654. return;
  10655. }
  10656. var normalType = bufferGuessNormalType( material ),
  10657. vertexColorType = bufferGuessVertexColorType( material ),
  10658. uvType = bufferGuessUVType( material ),
  10659. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  10660. var f, fl, fi, face,
  10661. vertexNormals, faceNormal, normal,
  10662. vertexColors, faceColor,
  10663. vertexTangents,
  10664. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  10665. c1, c2, c3, c4,
  10666. sw1, sw2, sw3, sw4,
  10667. si1, si2, si3, si4,
  10668. sa1, sa2, sa3, sa4,
  10669. sb1, sb2, sb3, sb4,
  10670. m, ml, i, il,
  10671. vn, uvi, uv2i,
  10672. vk, vkl, vka,
  10673. nka, chf, faceVertexNormals,
  10674. a,
  10675. vertexIndex = 0,
  10676. offset = 0,
  10677. offset_uv = 0,
  10678. offset_uv2 = 0,
  10679. offset_face = 0,
  10680. offset_normal = 0,
  10681. offset_tangent = 0,
  10682. offset_line = 0,
  10683. offset_color = 0,
  10684. offset_skin = 0,
  10685. offset_morphTarget = 0,
  10686. offset_custom = 0,
  10687. offset_customSrc = 0,
  10688. value,
  10689. vertexArray = geometryGroup.__vertexArray,
  10690. uvArray = geometryGroup.__uvArray,
  10691. uv2Array = geometryGroup.__uv2Array,
  10692. normalArray = geometryGroup.__normalArray,
  10693. tangentArray = geometryGroup.__tangentArray,
  10694. colorArray = geometryGroup.__colorArray,
  10695. skinIndexArray = geometryGroup.__skinIndexArray,
  10696. skinWeightArray = geometryGroup.__skinWeightArray,
  10697. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  10698. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  10699. customAttributes = geometryGroup.__webglCustomAttributesList,
  10700. customAttribute,
  10701. faceArray = geometryGroup.__faceArray,
  10702. lineArray = geometryGroup.__lineArray,
  10703. geometry = object.geometry, // this is shared for all chunks
  10704. dirtyVertices = geometry.verticesNeedUpdate,
  10705. dirtyElements = geometry.elementsNeedUpdate,
  10706. dirtyUvs = geometry.uvsNeedUpdate,
  10707. dirtyNormals = geometry.normalsNeedUpdate,
  10708. dirtyTangents = geometry.tangentsNeedUpdate,
  10709. dirtyColors = geometry.colorsNeedUpdate,
  10710. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  10711. vertices = geometry.vertices,
  10712. chunk_faces3 = geometryGroup.faces3,
  10713. chunk_faces4 = geometryGroup.faces4,
  10714. obj_faces = geometry.faces,
  10715. obj_uvs = geometry.faceVertexUvs[ 0 ],
  10716. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  10717. obj_colors = geometry.colors,
  10718. obj_skinIndices = geometry.skinIndices,
  10719. obj_skinWeights = geometry.skinWeights,
  10720. morphTargets = geometry.morphTargets,
  10721. morphNormals = geometry.morphNormals;
  10722. if ( dirtyVertices ) {
  10723. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10724. face = obj_faces[ chunk_faces3[ f ] ];
  10725. v1 = vertices[ face.a ];
  10726. v2 = vertices[ face.b ];
  10727. v3 = vertices[ face.c ];
  10728. vertexArray[ offset ] = v1.x;
  10729. vertexArray[ offset + 1 ] = v1.y;
  10730. vertexArray[ offset + 2 ] = v1.z;
  10731. vertexArray[ offset + 3 ] = v2.x;
  10732. vertexArray[ offset + 4 ] = v2.y;
  10733. vertexArray[ offset + 5 ] = v2.z;
  10734. vertexArray[ offset + 6 ] = v3.x;
  10735. vertexArray[ offset + 7 ] = v3.y;
  10736. vertexArray[ offset + 8 ] = v3.z;
  10737. offset += 9;
  10738. }
  10739. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10740. face = obj_faces[ chunk_faces4[ f ] ];
  10741. v1 = vertices[ face.a ];
  10742. v2 = vertices[ face.b ];
  10743. v3 = vertices[ face.c ];
  10744. v4 = vertices[ face.d ];
  10745. vertexArray[ offset ] = v1.x;
  10746. vertexArray[ offset + 1 ] = v1.y;
  10747. vertexArray[ offset + 2 ] = v1.z;
  10748. vertexArray[ offset + 3 ] = v2.x;
  10749. vertexArray[ offset + 4 ] = v2.y;
  10750. vertexArray[ offset + 5 ] = v2.z;
  10751. vertexArray[ offset + 6 ] = v3.x;
  10752. vertexArray[ offset + 7 ] = v3.y;
  10753. vertexArray[ offset + 8 ] = v3.z;
  10754. vertexArray[ offset + 9 ] = v4.x;
  10755. vertexArray[ offset + 10 ] = v4.y;
  10756. vertexArray[ offset + 11 ] = v4.z;
  10757. offset += 12;
  10758. }
  10759. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10760. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10761. }
  10762. if ( dirtyMorphTargets ) {
  10763. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  10764. offset_morphTarget = 0;
  10765. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10766. chf = chunk_faces3[ f ];
  10767. face = obj_faces[ chf ];
  10768. // morph positions
  10769. v1 = morphTargets[ vk ].vertices[ face.a ];
  10770. v2 = morphTargets[ vk ].vertices[ face.b ];
  10771. v3 = morphTargets[ vk ].vertices[ face.c ];
  10772. vka = morphTargetsArrays[ vk ];
  10773. vka[ offset_morphTarget ] = v1.x;
  10774. vka[ offset_morphTarget + 1 ] = v1.y;
  10775. vka[ offset_morphTarget + 2 ] = v1.z;
  10776. vka[ offset_morphTarget + 3 ] = v2.x;
  10777. vka[ offset_morphTarget + 4 ] = v2.y;
  10778. vka[ offset_morphTarget + 5 ] = v2.z;
  10779. vka[ offset_morphTarget + 6 ] = v3.x;
  10780. vka[ offset_morphTarget + 7 ] = v3.y;
  10781. vka[ offset_morphTarget + 8 ] = v3.z;
  10782. // morph normals
  10783. if ( material.morphNormals ) {
  10784. if ( needsSmoothNormals ) {
  10785. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10786. n1 = faceVertexNormals.a;
  10787. n2 = faceVertexNormals.b;
  10788. n3 = faceVertexNormals.c;
  10789. } else {
  10790. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10791. n2 = n1;
  10792. n3 = n1;
  10793. }
  10794. nka = morphNormalsArrays[ vk ];
  10795. nka[ offset_morphTarget ] = n1.x;
  10796. nka[ offset_morphTarget + 1 ] = n1.y;
  10797. nka[ offset_morphTarget + 2 ] = n1.z;
  10798. nka[ offset_morphTarget + 3 ] = n2.x;
  10799. nka[ offset_morphTarget + 4 ] = n2.y;
  10800. nka[ offset_morphTarget + 5 ] = n2.z;
  10801. nka[ offset_morphTarget + 6 ] = n3.x;
  10802. nka[ offset_morphTarget + 7 ] = n3.y;
  10803. nka[ offset_morphTarget + 8 ] = n3.z;
  10804. }
  10805. //
  10806. offset_morphTarget += 9;
  10807. }
  10808. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10809. chf = chunk_faces4[ f ];
  10810. face = obj_faces[ chf ];
  10811. // morph positions
  10812. v1 = morphTargets[ vk ].vertices[ face.a ];
  10813. v2 = morphTargets[ vk ].vertices[ face.b ];
  10814. v3 = morphTargets[ vk ].vertices[ face.c ];
  10815. v4 = morphTargets[ vk ].vertices[ face.d ];
  10816. vka = morphTargetsArrays[ vk ];
  10817. vka[ offset_morphTarget ] = v1.x;
  10818. vka[ offset_morphTarget + 1 ] = v1.y;
  10819. vka[ offset_morphTarget + 2 ] = v1.z;
  10820. vka[ offset_morphTarget + 3 ] = v2.x;
  10821. vka[ offset_morphTarget + 4 ] = v2.y;
  10822. vka[ offset_morphTarget + 5 ] = v2.z;
  10823. vka[ offset_morphTarget + 6 ] = v3.x;
  10824. vka[ offset_morphTarget + 7 ] = v3.y;
  10825. vka[ offset_morphTarget + 8 ] = v3.z;
  10826. vka[ offset_morphTarget + 9 ] = v4.x;
  10827. vka[ offset_morphTarget + 10 ] = v4.y;
  10828. vka[ offset_morphTarget + 11 ] = v4.z;
  10829. // morph normals
  10830. if ( material.morphNormals ) {
  10831. if ( needsSmoothNormals ) {
  10832. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10833. n1 = faceVertexNormals.a;
  10834. n2 = faceVertexNormals.b;
  10835. n3 = faceVertexNormals.c;
  10836. n4 = faceVertexNormals.d;
  10837. } else {
  10838. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10839. n2 = n1;
  10840. n3 = n1;
  10841. n4 = n1;
  10842. }
  10843. nka = morphNormalsArrays[ vk ];
  10844. nka[ offset_morphTarget ] = n1.x;
  10845. nka[ offset_morphTarget + 1 ] = n1.y;
  10846. nka[ offset_morphTarget + 2 ] = n1.z;
  10847. nka[ offset_morphTarget + 3 ] = n2.x;
  10848. nka[ offset_morphTarget + 4 ] = n2.y;
  10849. nka[ offset_morphTarget + 5 ] = n2.z;
  10850. nka[ offset_morphTarget + 6 ] = n3.x;
  10851. nka[ offset_morphTarget + 7 ] = n3.y;
  10852. nka[ offset_morphTarget + 8 ] = n3.z;
  10853. nka[ offset_morphTarget + 9 ] = n4.x;
  10854. nka[ offset_morphTarget + 10 ] = n4.y;
  10855. nka[ offset_morphTarget + 11 ] = n4.z;
  10856. }
  10857. //
  10858. offset_morphTarget += 12;
  10859. }
  10860. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  10861. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  10862. if ( material.morphNormals ) {
  10863. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  10864. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  10865. }
  10866. }
  10867. }
  10868. if ( obj_skinWeights.length ) {
  10869. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10870. face = obj_faces[ chunk_faces3[ f ] ];
  10871. // weights
  10872. sw1 = obj_skinWeights[ face.a ];
  10873. sw2 = obj_skinWeights[ face.b ];
  10874. sw3 = obj_skinWeights[ face.c ];
  10875. skinWeightArray[ offset_skin ] = sw1.x;
  10876. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10877. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10878. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10879. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10880. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10881. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10882. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10883. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10884. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10885. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10886. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10887. // indices
  10888. si1 = obj_skinIndices[ face.a ];
  10889. si2 = obj_skinIndices[ face.b ];
  10890. si3 = obj_skinIndices[ face.c ];
  10891. skinIndexArray[ offset_skin ] = si1.x;
  10892. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10893. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10894. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10895. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10896. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10897. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10898. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10899. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10900. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10901. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10902. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10903. offset_skin += 12;
  10904. }
  10905. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10906. face = obj_faces[ chunk_faces4[ f ] ];
  10907. // weights
  10908. sw1 = obj_skinWeights[ face.a ];
  10909. sw2 = obj_skinWeights[ face.b ];
  10910. sw3 = obj_skinWeights[ face.c ];
  10911. sw4 = obj_skinWeights[ face.d ];
  10912. skinWeightArray[ offset_skin ] = sw1.x;
  10913. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10914. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10915. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10916. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10917. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10918. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10919. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10920. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10921. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10922. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10923. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10924. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  10925. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  10926. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  10927. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  10928. // indices
  10929. si1 = obj_skinIndices[ face.a ];
  10930. si2 = obj_skinIndices[ face.b ];
  10931. si3 = obj_skinIndices[ face.c ];
  10932. si4 = obj_skinIndices[ face.d ];
  10933. skinIndexArray[ offset_skin ] = si1.x;
  10934. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10935. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10936. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10937. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10938. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10939. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10940. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10941. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10942. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10943. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10944. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10945. skinIndexArray[ offset_skin + 12 ] = si4.x;
  10946. skinIndexArray[ offset_skin + 13 ] = si4.y;
  10947. skinIndexArray[ offset_skin + 14 ] = si4.z;
  10948. skinIndexArray[ offset_skin + 15 ] = si4.w;
  10949. offset_skin += 16;
  10950. }
  10951. if ( offset_skin > 0 ) {
  10952. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10953. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  10954. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10955. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  10956. }
  10957. }
  10958. if ( dirtyColors && vertexColorType ) {
  10959. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10960. face = obj_faces[ chunk_faces3[ f ] ];
  10961. vertexColors = face.vertexColors;
  10962. faceColor = face.color;
  10963. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  10964. c1 = vertexColors[ 0 ];
  10965. c2 = vertexColors[ 1 ];
  10966. c3 = vertexColors[ 2 ];
  10967. } else {
  10968. c1 = faceColor;
  10969. c2 = faceColor;
  10970. c3 = faceColor;
  10971. }
  10972. colorArray[ offset_color ] = c1.r;
  10973. colorArray[ offset_color + 1 ] = c1.g;
  10974. colorArray[ offset_color + 2 ] = c1.b;
  10975. colorArray[ offset_color + 3 ] = c2.r;
  10976. colorArray[ offset_color + 4 ] = c2.g;
  10977. colorArray[ offset_color + 5 ] = c2.b;
  10978. colorArray[ offset_color + 6 ] = c3.r;
  10979. colorArray[ offset_color + 7 ] = c3.g;
  10980. colorArray[ offset_color + 8 ] = c3.b;
  10981. offset_color += 9;
  10982. }
  10983. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10984. face = obj_faces[ chunk_faces4[ f ] ];
  10985. vertexColors = face.vertexColors;
  10986. faceColor = face.color;
  10987. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  10988. c1 = vertexColors[ 0 ];
  10989. c2 = vertexColors[ 1 ];
  10990. c3 = vertexColors[ 2 ];
  10991. c4 = vertexColors[ 3 ];
  10992. } else {
  10993. c1 = faceColor;
  10994. c2 = faceColor;
  10995. c3 = faceColor;
  10996. c4 = faceColor;
  10997. }
  10998. colorArray[ offset_color ] = c1.r;
  10999. colorArray[ offset_color + 1 ] = c1.g;
  11000. colorArray[ offset_color + 2 ] = c1.b;
  11001. colorArray[ offset_color + 3 ] = c2.r;
  11002. colorArray[ offset_color + 4 ] = c2.g;
  11003. colorArray[ offset_color + 5 ] = c2.b;
  11004. colorArray[ offset_color + 6 ] = c3.r;
  11005. colorArray[ offset_color + 7 ] = c3.g;
  11006. colorArray[ offset_color + 8 ] = c3.b;
  11007. colorArray[ offset_color + 9 ] = c4.r;
  11008. colorArray[ offset_color + 10 ] = c4.g;
  11009. colorArray[ offset_color + 11 ] = c4.b;
  11010. offset_color += 12;
  11011. }
  11012. if ( offset_color > 0 ) {
  11013. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11014. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11015. }
  11016. }
  11017. if ( dirtyTangents && geometry.hasTangents ) {
  11018. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11019. face = obj_faces[ chunk_faces3[ f ] ];
  11020. vertexTangents = face.vertexTangents;
  11021. t1 = vertexTangents[ 0 ];
  11022. t2 = vertexTangents[ 1 ];
  11023. t3 = vertexTangents[ 2 ];
  11024. tangentArray[ offset_tangent ] = t1.x;
  11025. tangentArray[ offset_tangent + 1 ] = t1.y;
  11026. tangentArray[ offset_tangent + 2 ] = t1.z;
  11027. tangentArray[ offset_tangent + 3 ] = t1.w;
  11028. tangentArray[ offset_tangent + 4 ] = t2.x;
  11029. tangentArray[ offset_tangent + 5 ] = t2.y;
  11030. tangentArray[ offset_tangent + 6 ] = t2.z;
  11031. tangentArray[ offset_tangent + 7 ] = t2.w;
  11032. tangentArray[ offset_tangent + 8 ] = t3.x;
  11033. tangentArray[ offset_tangent + 9 ] = t3.y;
  11034. tangentArray[ offset_tangent + 10 ] = t3.z;
  11035. tangentArray[ offset_tangent + 11 ] = t3.w;
  11036. offset_tangent += 12;
  11037. }
  11038. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11039. face = obj_faces[ chunk_faces4[ f ] ];
  11040. vertexTangents = face.vertexTangents;
  11041. t1 = vertexTangents[ 0 ];
  11042. t2 = vertexTangents[ 1 ];
  11043. t3 = vertexTangents[ 2 ];
  11044. t4 = vertexTangents[ 3 ];
  11045. tangentArray[ offset_tangent ] = t1.x;
  11046. tangentArray[ offset_tangent + 1 ] = t1.y;
  11047. tangentArray[ offset_tangent + 2 ] = t1.z;
  11048. tangentArray[ offset_tangent + 3 ] = t1.w;
  11049. tangentArray[ offset_tangent + 4 ] = t2.x;
  11050. tangentArray[ offset_tangent + 5 ] = t2.y;
  11051. tangentArray[ offset_tangent + 6 ] = t2.z;
  11052. tangentArray[ offset_tangent + 7 ] = t2.w;
  11053. tangentArray[ offset_tangent + 8 ] = t3.x;
  11054. tangentArray[ offset_tangent + 9 ] = t3.y;
  11055. tangentArray[ offset_tangent + 10 ] = t3.z;
  11056. tangentArray[ offset_tangent + 11 ] = t3.w;
  11057. tangentArray[ offset_tangent + 12 ] = t4.x;
  11058. tangentArray[ offset_tangent + 13 ] = t4.y;
  11059. tangentArray[ offset_tangent + 14 ] = t4.z;
  11060. tangentArray[ offset_tangent + 15 ] = t4.w;
  11061. offset_tangent += 16;
  11062. }
  11063. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11064. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  11065. }
  11066. if ( dirtyNormals && normalType ) {
  11067. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11068. face = obj_faces[ chunk_faces3[ f ] ];
  11069. vertexNormals = face.vertexNormals;
  11070. faceNormal = face.normal;
  11071. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  11072. for ( i = 0; i < 3; i ++ ) {
  11073. vn = vertexNormals[ i ];
  11074. normalArray[ offset_normal ] = vn.x;
  11075. normalArray[ offset_normal + 1 ] = vn.y;
  11076. normalArray[ offset_normal + 2 ] = vn.z;
  11077. offset_normal += 3;
  11078. }
  11079. } else {
  11080. for ( i = 0; i < 3; i ++ ) {
  11081. normalArray[ offset_normal ] = faceNormal.x;
  11082. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11083. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11084. offset_normal += 3;
  11085. }
  11086. }
  11087. }
  11088. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11089. face = obj_faces[ chunk_faces4[ f ] ];
  11090. vertexNormals = face.vertexNormals;
  11091. faceNormal = face.normal;
  11092. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  11093. for ( i = 0; i < 4; i ++ ) {
  11094. vn = vertexNormals[ i ];
  11095. normalArray[ offset_normal ] = vn.x;
  11096. normalArray[ offset_normal + 1 ] = vn.y;
  11097. normalArray[ offset_normal + 2 ] = vn.z;
  11098. offset_normal += 3;
  11099. }
  11100. } else {
  11101. for ( i = 0; i < 4; i ++ ) {
  11102. normalArray[ offset_normal ] = faceNormal.x;
  11103. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11104. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11105. offset_normal += 3;
  11106. }
  11107. }
  11108. }
  11109. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11110. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11111. }
  11112. if ( dirtyUvs && obj_uvs && uvType ) {
  11113. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11114. fi = chunk_faces3[ f ];
  11115. uv = obj_uvs[ fi ];
  11116. if ( uv === undefined ) continue;
  11117. for ( i = 0; i < 3; i ++ ) {
  11118. uvi = uv[ i ];
  11119. uvArray[ offset_uv ] = uvi.u;
  11120. uvArray[ offset_uv + 1 ] = uvi.v;
  11121. offset_uv += 2;
  11122. }
  11123. }
  11124. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11125. fi = chunk_faces4[ f ];
  11126. uv = obj_uvs[ fi ];
  11127. if ( uv === undefined ) continue;
  11128. for ( i = 0; i < 4; i ++ ) {
  11129. uvi = uv[ i ];
  11130. uvArray[ offset_uv ] = uvi.u;
  11131. uvArray[ offset_uv + 1 ] = uvi.v;
  11132. offset_uv += 2;
  11133. }
  11134. }
  11135. if ( offset_uv > 0 ) {
  11136. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11137. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  11138. }
  11139. }
  11140. if ( dirtyUvs && obj_uvs2 && uvType ) {
  11141. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11142. fi = chunk_faces3[ f ];
  11143. uv2 = obj_uvs2[ fi ];
  11144. if ( uv2 === undefined ) continue;
  11145. for ( i = 0; i < 3; i ++ ) {
  11146. uv2i = uv2[ i ];
  11147. uv2Array[ offset_uv2 ] = uv2i.u;
  11148. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  11149. offset_uv2 += 2;
  11150. }
  11151. }
  11152. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11153. fi = chunk_faces4[ f ];
  11154. uv2 = obj_uvs2[ fi ];
  11155. if ( uv2 === undefined ) continue;
  11156. for ( i = 0; i < 4; i ++ ) {
  11157. uv2i = uv2[ i ];
  11158. uv2Array[ offset_uv2 ] = uv2i.u;
  11159. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  11160. offset_uv2 += 2;
  11161. }
  11162. }
  11163. if ( offset_uv2 > 0 ) {
  11164. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11165. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  11166. }
  11167. }
  11168. if ( dirtyElements ) {
  11169. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11170. faceArray[ offset_face ] = vertexIndex;
  11171. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11172. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  11173. offset_face += 3;
  11174. lineArray[ offset_line ] = vertexIndex;
  11175. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11176. lineArray[ offset_line + 2 ] = vertexIndex;
  11177. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  11178. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11179. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11180. offset_line += 6;
  11181. vertexIndex += 3;
  11182. }
  11183. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11184. faceArray[ offset_face ] = vertexIndex;
  11185. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11186. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  11187. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  11188. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  11189. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  11190. offset_face += 6;
  11191. lineArray[ offset_line ] = vertexIndex;
  11192. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11193. lineArray[ offset_line + 2 ] = vertexIndex;
  11194. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  11195. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11196. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11197. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  11198. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  11199. offset_line += 8;
  11200. vertexIndex += 4;
  11201. }
  11202. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11203. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  11204. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11205. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  11206. }
  11207. if ( customAttributes ) {
  11208. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11209. customAttribute = customAttributes[ i ];
  11210. if ( ! customAttribute.__original.needsUpdate ) continue;
  11211. offset_custom = 0;
  11212. offset_customSrc = 0;
  11213. if ( customAttribute.size === 1 ) {
  11214. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11215. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11216. face = obj_faces[ chunk_faces3[ f ] ];
  11217. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11218. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11219. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11220. offset_custom += 3;
  11221. }
  11222. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11223. face = obj_faces[ chunk_faces4[ f ] ];
  11224. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11225. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11226. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11227. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  11228. offset_custom += 4;
  11229. }
  11230. } else if ( customAttribute.boundTo === "faces" ) {
  11231. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11232. value = customAttribute.value[ chunk_faces3[ f ] ];
  11233. customAttribute.array[ offset_custom ] = value;
  11234. customAttribute.array[ offset_custom + 1 ] = value;
  11235. customAttribute.array[ offset_custom + 2 ] = value;
  11236. offset_custom += 3;
  11237. }
  11238. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11239. value = customAttribute.value[ chunk_faces4[ f ] ];
  11240. customAttribute.array[ offset_custom ] = value;
  11241. customAttribute.array[ offset_custom + 1 ] = value;
  11242. customAttribute.array[ offset_custom + 2 ] = value;
  11243. customAttribute.array[ offset_custom + 3 ] = value;
  11244. offset_custom += 4;
  11245. }
  11246. }
  11247. } else if ( customAttribute.size === 2 ) {
  11248. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11249. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11250. face = obj_faces[ chunk_faces3[ f ] ];
  11251. v1 = customAttribute.value[ face.a ];
  11252. v2 = customAttribute.value[ face.b ];
  11253. v3 = customAttribute.value[ face.c ];
  11254. customAttribute.array[ offset_custom ] = v1.x;
  11255. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11256. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11257. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11258. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11259. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11260. offset_custom += 6;
  11261. }
  11262. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11263. face = obj_faces[ chunk_faces4[ f ] ];
  11264. v1 = customAttribute.value[ face.a ];
  11265. v2 = customAttribute.value[ face.b ];
  11266. v3 = customAttribute.value[ face.c ];
  11267. v4 = customAttribute.value[ face.d ];
  11268. customAttribute.array[ offset_custom ] = v1.x;
  11269. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11270. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11271. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11272. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11273. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11274. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11275. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11276. offset_custom += 8;
  11277. }
  11278. } else if ( customAttribute.boundTo === "faces" ) {
  11279. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11280. value = customAttribute.value[ chunk_faces3[ f ] ];
  11281. v1 = value;
  11282. v2 = value;
  11283. v3 = value;
  11284. customAttribute.array[ offset_custom ] = v1.x;
  11285. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11286. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11287. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11288. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11289. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11290. offset_custom += 6;
  11291. }
  11292. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11293. value = customAttribute.value[ chunk_faces4[ f ] ];
  11294. v1 = value;
  11295. v2 = value;
  11296. v3 = value;
  11297. v4 = value;
  11298. customAttribute.array[ offset_custom ] = v1.x;
  11299. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11300. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11301. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11302. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11303. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11304. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11305. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11306. offset_custom += 8;
  11307. }
  11308. }
  11309. } else if ( customAttribute.size === 3 ) {
  11310. var pp;
  11311. if ( customAttribute.type === "c" ) {
  11312. pp = [ "r", "g", "b" ];
  11313. } else {
  11314. pp = [ "x", "y", "z" ];
  11315. }
  11316. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11317. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11318. face = obj_faces[ chunk_faces3[ f ] ];
  11319. v1 = customAttribute.value[ face.a ];
  11320. v2 = customAttribute.value[ face.b ];
  11321. v3 = customAttribute.value[ face.c ];
  11322. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11323. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11324. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11325. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11326. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11327. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11328. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11329. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11330. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11331. offset_custom += 9;
  11332. }
  11333. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11334. face = obj_faces[ chunk_faces4[ f ] ];
  11335. v1 = customAttribute.value[ face.a ];
  11336. v2 = customAttribute.value[ face.b ];
  11337. v3 = customAttribute.value[ face.c ];
  11338. v4 = customAttribute.value[ face.d ];
  11339. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11340. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11341. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11342. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11343. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11344. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11345. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11346. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11347. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11348. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11349. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11350. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11351. offset_custom += 12;
  11352. }
  11353. } else if ( customAttribute.boundTo === "faces" ) {
  11354. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11355. value = customAttribute.value[ chunk_faces3[ f ] ];
  11356. v1 = value;
  11357. v2 = value;
  11358. v3 = value;
  11359. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11360. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11361. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11362. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11363. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11364. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11365. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11366. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11367. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11368. offset_custom += 9;
  11369. }
  11370. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11371. value = customAttribute.value[ chunk_faces4[ f ] ];
  11372. v1 = value;
  11373. v2 = value;
  11374. v3 = value;
  11375. v4 = value;
  11376. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11377. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11378. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11379. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11380. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11381. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11382. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11383. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11384. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11385. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11386. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11387. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11388. offset_custom += 12;
  11389. }
  11390. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11391. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11392. value = customAttribute.value[ chunk_faces3[ f ] ];
  11393. v1 = value[ 0 ];
  11394. v2 = value[ 1 ];
  11395. v3 = value[ 2 ];
  11396. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11397. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11398. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11399. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11400. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11401. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11402. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11403. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11404. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11405. offset_custom += 9;
  11406. }
  11407. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11408. value = customAttribute.value[ chunk_faces4[ f ] ];
  11409. v1 = value[ 0 ];
  11410. v2 = value[ 1 ];
  11411. v3 = value[ 2 ];
  11412. v4 = value[ 3 ];
  11413. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11414. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11415. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11416. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11417. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11418. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11419. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11420. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11421. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11422. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11423. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11424. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11425. offset_custom += 12;
  11426. }
  11427. }
  11428. } else if ( customAttribute.size === 4 ) {
  11429. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11430. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11431. face = obj_faces[ chunk_faces3[ f ] ];
  11432. v1 = customAttribute.value[ face.a ];
  11433. v2 = customAttribute.value[ face.b ];
  11434. v3 = customAttribute.value[ face.c ];
  11435. customAttribute.array[ offset_custom ] = v1.x;
  11436. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11437. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11438. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11439. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11440. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11441. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11442. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11443. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11444. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11445. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11446. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11447. offset_custom += 12;
  11448. }
  11449. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11450. face = obj_faces[ chunk_faces4[ f ] ];
  11451. v1 = customAttribute.value[ face.a ];
  11452. v2 = customAttribute.value[ face.b ];
  11453. v3 = customAttribute.value[ face.c ];
  11454. v4 = customAttribute.value[ face.d ];
  11455. customAttribute.array[ offset_custom ] = v1.x;
  11456. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11457. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11458. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11459. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11460. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11461. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11462. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11463. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11464. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11465. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11466. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11467. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11468. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11469. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11470. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11471. offset_custom += 16;
  11472. }
  11473. } else if ( customAttribute.boundTo === "faces" ) {
  11474. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11475. value = customAttribute.value[ chunk_faces3[ f ] ];
  11476. v1 = value;
  11477. v2 = value;
  11478. v3 = value;
  11479. customAttribute.array[ offset_custom ] = v1.x;
  11480. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11481. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11482. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11483. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11484. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11485. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11486. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11487. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11488. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11489. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11490. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11491. offset_custom += 12;
  11492. }
  11493. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11494. value = customAttribute.value[ chunk_faces4[ f ] ];
  11495. v1 = value;
  11496. v2 = value;
  11497. v3 = value;
  11498. v4 = value;
  11499. customAttribute.array[ offset_custom ] = v1.x;
  11500. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11501. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11502. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11503. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11504. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11505. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11506. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11507. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11508. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11509. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11510. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11511. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11512. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11513. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11514. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11515. offset_custom += 16;
  11516. }
  11517. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11518. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11519. value = customAttribute.value[ chunk_faces3[ f ] ];
  11520. v1 = value[ 0 ];
  11521. v2 = value[ 1 ];
  11522. v3 = value[ 2 ];
  11523. customAttribute.array[ offset_custom ] = v1.x;
  11524. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11525. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11526. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11527. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11528. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11529. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11530. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11531. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11532. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11533. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11534. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11535. offset_custom += 12;
  11536. }
  11537. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11538. value = customAttribute.value[ chunk_faces4[ f ] ];
  11539. v1 = value[ 0 ];
  11540. v2 = value[ 1 ];
  11541. v3 = value[ 2 ];
  11542. v4 = value[ 3 ];
  11543. customAttribute.array[ offset_custom ] = v1.x;
  11544. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11545. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11546. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11547. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11548. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11549. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11550. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11551. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11552. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11553. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11554. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11555. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11556. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11557. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11558. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11559. offset_custom += 16;
  11560. }
  11561. }
  11562. }
  11563. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11564. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11565. }
  11566. }
  11567. if ( dispose ) {
  11568. delete geometryGroup.__inittedArrays;
  11569. delete geometryGroup.__colorArray;
  11570. delete geometryGroup.__normalArray;
  11571. delete geometryGroup.__tangentArray;
  11572. delete geometryGroup.__uvArray;
  11573. delete geometryGroup.__uv2Array;
  11574. delete geometryGroup.__faceArray;
  11575. delete geometryGroup.__vertexArray;
  11576. delete geometryGroup.__lineArray;
  11577. delete geometryGroup.__skinIndexArray;
  11578. delete geometryGroup.__skinWeightArray;
  11579. }
  11580. };
  11581. function setDirectBuffers ( geometry, hint, dispose ) {
  11582. var attributes = geometry.attributes;
  11583. var index = attributes[ "index" ];
  11584. var position = attributes[ "position" ];
  11585. var normal = attributes[ "normal" ];
  11586. var uv = attributes[ "uv" ];
  11587. var color = attributes[ "color" ];
  11588. var tangent = attributes[ "tangent" ];
  11589. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  11590. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11591. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  11592. }
  11593. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  11594. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11595. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  11596. }
  11597. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  11598. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11599. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  11600. }
  11601. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  11602. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11603. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  11604. }
  11605. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  11606. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11607. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  11608. }
  11609. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  11610. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11611. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  11612. }
  11613. if ( dispose ) {
  11614. for ( var i in geometry.attributes ) {
  11615. delete geometry.attributes[ i ].array;
  11616. }
  11617. }
  11618. };
  11619. // Buffer rendering
  11620. this.renderBufferImmediate = function ( object, program, material ) {
  11621. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11622. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11623. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11624. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11625. if ( object.hasPositions ) {
  11626. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11627. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11628. _gl.enableVertexAttribArray( program.attributes.position );
  11629. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11630. }
  11631. if ( object.hasNormals ) {
  11632. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11633. if ( material.shading === THREE.FlatShading ) {
  11634. var nx, ny, nz,
  11635. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11636. normalArray,
  11637. i, il = object.count * 3;
  11638. for( i = 0; i < il; i += 9 ) {
  11639. normalArray = object.normalArray;
  11640. nax = normalArray[ i ];
  11641. nay = normalArray[ i + 1 ];
  11642. naz = normalArray[ i + 2 ];
  11643. nbx = normalArray[ i + 3 ];
  11644. nby = normalArray[ i + 4 ];
  11645. nbz = normalArray[ i + 5 ];
  11646. ncx = normalArray[ i + 6 ];
  11647. ncy = normalArray[ i + 7 ];
  11648. ncz = normalArray[ i + 8 ];
  11649. nx = ( nax + nbx + ncx ) / 3;
  11650. ny = ( nay + nby + ncy ) / 3;
  11651. nz = ( naz + nbz + ncz ) / 3;
  11652. normalArray[ i ] = nx;
  11653. normalArray[ i + 1 ] = ny;
  11654. normalArray[ i + 2 ] = nz;
  11655. normalArray[ i + 3 ] = nx;
  11656. normalArray[ i + 4 ] = ny;
  11657. normalArray[ i + 5 ] = nz;
  11658. normalArray[ i + 6 ] = nx;
  11659. normalArray[ i + 7 ] = ny;
  11660. normalArray[ i + 8 ] = nz;
  11661. }
  11662. }
  11663. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11664. _gl.enableVertexAttribArray( program.attributes.normal );
  11665. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11666. }
  11667. if ( object.hasUvs && material.map ) {
  11668. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11669. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11670. _gl.enableVertexAttribArray( program.attributes.uv );
  11671. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11672. }
  11673. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11674. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11675. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11676. _gl.enableVertexAttribArray( program.attributes.color );
  11677. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11678. }
  11679. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11680. object.count = 0;
  11681. };
  11682. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  11683. if ( material.visible === false ) return;
  11684. var program, attributes, linewidth, primitives, a, attribute;
  11685. program = setProgram( camera, lights, fog, material, object );
  11686. attributes = program.attributes;
  11687. var updateBuffers = false,
  11688. wireframeBit = material.wireframe ? 1 : 0,
  11689. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11690. if ( geometryHash !== _currentGeometryGroupHash ) {
  11691. _currentGeometryGroupHash = geometryHash;
  11692. updateBuffers = true;
  11693. }
  11694. // render mesh
  11695. if ( object instanceof THREE.Mesh ) {
  11696. var offsets = geometry.offsets;
  11697. // if there is more than 1 chunk
  11698. // must set attribute pointers to use new offsets for each chunk
  11699. // even if geometry and materials didn't change
  11700. if ( offsets.length > 1 ) updateBuffers = true;
  11701. for ( var i = 0, il = offsets.length; i < il; ++ i ) {
  11702. var startIndex = offsets[ i ].index;
  11703. if ( updateBuffers ) {
  11704. // vertices
  11705. var position = geometry.attributes[ "position" ];
  11706. var positionSize = position.itemSize;
  11707. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11708. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  11709. // normals
  11710. var normal = geometry.attributes[ "normal" ];
  11711. if ( attributes.normal >= 0 && normal ) {
  11712. var normalSize = normal.itemSize;
  11713. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11714. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  11715. }
  11716. // uvs
  11717. var uv = geometry.attributes[ "uv" ];
  11718. if ( attributes.uv >= 0 && uv ) {
  11719. if ( uv.buffer ) {
  11720. var uvSize = uv.itemSize;
  11721. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11722. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  11723. _gl.enableVertexAttribArray( attributes.uv );
  11724. } else {
  11725. _gl.disableVertexAttribArray( attributes.uv );
  11726. }
  11727. }
  11728. // colors
  11729. var color = geometry.attributes[ "color" ];
  11730. if ( attributes.color >= 0 && color ) {
  11731. var colorSize = color.itemSize;
  11732. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11733. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  11734. }
  11735. // tangents
  11736. var tangent = geometry.attributes[ "tangent" ];
  11737. if ( attributes.tangent >= 0 && tangent ) {
  11738. var tangentSize = tangent.itemSize;
  11739. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11740. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  11741. }
  11742. // indices
  11743. var index = geometry.attributes[ "index" ];
  11744. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11745. }
  11746. // render indexed triangles
  11747. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  11748. _this.info.render.calls ++;
  11749. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11750. _this.info.render.faces += offsets[ i ].count / 3;
  11751. }
  11752. // render particles
  11753. } else if ( object instanceof THREE.ParticleSystem ) {
  11754. if ( updateBuffers ) {
  11755. // vertices
  11756. var position = geometry.attributes[ "position" ];
  11757. var positionSize = position.itemSize;
  11758. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11759. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  11760. // colors
  11761. var color = geometry.attributes[ "color" ];
  11762. if ( attributes.color >= 0 && color ) {
  11763. var colorSize = color.itemSize;
  11764. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11765. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  11766. }
  11767. // render particles
  11768. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  11769. _this.info.render.calls ++;
  11770. _this.info.render.points += position.numItems / 3;
  11771. }
  11772. }
  11773. };
  11774. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  11775. if ( material.visible === false ) return;
  11776. var program, attributes, linewidth, primitives, a, attribute, i, il;
  11777. program = setProgram( camera, lights, fog, material, object );
  11778. attributes = program.attributes;
  11779. var updateBuffers = false,
  11780. wireframeBit = material.wireframe ? 1 : 0,
  11781. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11782. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  11783. _currentGeometryGroupHash = geometryGroupHash;
  11784. updateBuffers = true;
  11785. }
  11786. // vertices
  11787. if ( !material.morphTargets && attributes.position >= 0 ) {
  11788. if ( updateBuffers ) {
  11789. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11790. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11791. }
  11792. } else {
  11793. if ( object.morphTargetBase ) {
  11794. setupMorphTargets( material, geometryGroup, object );
  11795. }
  11796. }
  11797. if ( updateBuffers ) {
  11798. // custom attributes
  11799. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  11800. if ( geometryGroup.__webglCustomAttributesList ) {
  11801. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  11802. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  11803. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  11804. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  11805. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  11806. }
  11807. }
  11808. }
  11809. // colors
  11810. if ( attributes.color >= 0 ) {
  11811. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11812. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11813. }
  11814. // normals
  11815. if ( attributes.normal >= 0 ) {
  11816. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11817. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11818. }
  11819. // tangents
  11820. if ( attributes.tangent >= 0 ) {
  11821. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11822. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  11823. }
  11824. // uvs
  11825. if ( attributes.uv >= 0 ) {
  11826. if ( geometryGroup.__webglUVBuffer ) {
  11827. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11828. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11829. _gl.enableVertexAttribArray( attributes.uv );
  11830. } else {
  11831. _gl.disableVertexAttribArray( attributes.uv );
  11832. }
  11833. }
  11834. if ( attributes.uv2 >= 0 ) {
  11835. if ( geometryGroup.__webglUV2Buffer ) {
  11836. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11837. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  11838. _gl.enableVertexAttribArray( attributes.uv2 );
  11839. } else {
  11840. _gl.disableVertexAttribArray( attributes.uv2 );
  11841. }
  11842. }
  11843. if ( material.skinning &&
  11844. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11845. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11846. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  11847. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11848. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  11849. }
  11850. // line distances
  11851. if ( attributes.lineDistance >= 0 ) {
  11852. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  11853. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  11854. }
  11855. }
  11856. // render mesh
  11857. if ( object instanceof THREE.Mesh ) {
  11858. // wireframe
  11859. if ( material.wireframe ) {
  11860. setLineWidth( material.wireframeLinewidth );
  11861. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11862. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  11863. // triangles
  11864. } else {
  11865. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11866. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  11867. }
  11868. _this.info.render.calls ++;
  11869. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  11870. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11871. // render lines
  11872. } else if ( object instanceof THREE.Line ) {
  11873. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  11874. setLineWidth( material.linewidth );
  11875. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  11876. _this.info.render.calls ++;
  11877. // render particles
  11878. } else if ( object instanceof THREE.ParticleSystem ) {
  11879. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  11880. _this.info.render.calls ++;
  11881. _this.info.render.points += geometryGroup.__webglParticleCount;
  11882. // render ribbon
  11883. } else if ( object instanceof THREE.Ribbon ) {
  11884. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  11885. _this.info.render.calls ++;
  11886. }
  11887. };
  11888. function setupMorphTargets ( material, geometryGroup, object ) {
  11889. // set base
  11890. var attributes = material.program.attributes;
  11891. if ( object.morphTargetBase !== -1 ) {
  11892. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  11893. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11894. } else if ( attributes.position >= 0 ) {
  11895. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11896. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11897. }
  11898. if ( object.morphTargetForcedOrder.length ) {
  11899. // set forced order
  11900. var m = 0;
  11901. var order = object.morphTargetForcedOrder;
  11902. var influences = object.morphTargetInfluences;
  11903. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11904. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  11905. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11906. if ( material.morphNormals ) {
  11907. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  11908. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11909. }
  11910. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11911. m ++;
  11912. }
  11913. } else {
  11914. // find the most influencing
  11915. var influence, activeInfluenceIndices = [];
  11916. var influences = object.morphTargetInfluences;
  11917. var i, il = influences.length;
  11918. for ( i = 0; i < il; i ++ ) {
  11919. influence = influences[ i ];
  11920. if ( influence > 0 ) {
  11921. activeInfluenceIndices.push( [ i, influence ] );
  11922. }
  11923. }
  11924. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11925. activeInfluenceIndices.sort( numericalSort );
  11926. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11927. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11928. activeInfluenceIndices.sort( numericalSort );
  11929. } else if ( activeInfluenceIndices.length === 0 ) {
  11930. activeInfluenceIndices.push( [ 0, 0 ] );
  11931. };
  11932. var influenceIndex, m = 0;
  11933. while ( m < material.numSupportedMorphTargets ) {
  11934. if ( activeInfluenceIndices[ m ] ) {
  11935. influenceIndex = activeInfluenceIndices[ m ][ 0 ];
  11936. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  11937. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11938. if ( material.morphNormals ) {
  11939. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  11940. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11941. }
  11942. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11943. } else {
  11944. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11945. if ( material.morphNormals ) {
  11946. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11947. }
  11948. object.__webglMorphTargetInfluences[ m ] = 0;
  11949. }
  11950. m ++;
  11951. }
  11952. }
  11953. // load updated influences uniform
  11954. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11955. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11956. }
  11957. };
  11958. // Sorting
  11959. function painterSortStable ( a, b ) {
  11960. if ( a.z !== b.z ) {
  11961. return b.z - a.z;
  11962. } else {
  11963. return b.id - a.id;
  11964. }
  11965. };
  11966. function numericalSort ( a, b ) {
  11967. return b[ 1 ] - a[ 1 ];
  11968. };
  11969. // Rendering
  11970. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11971. if ( camera instanceof THREE.Camera === false ) {
  11972. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11973. return;
  11974. }
  11975. var i, il,
  11976. webglObject, object,
  11977. renderList,
  11978. lights = scene.__lights,
  11979. fog = scene.fog;
  11980. // reset caching for this frame
  11981. _currentMaterialId = -1;
  11982. _lightsNeedUpdate = true;
  11983. // update scene graph
  11984. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11985. // update camera matrices and frustum
  11986. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11987. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  11988. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  11989. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11990. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  11991. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  11992. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11993. _frustum.setFromMatrix( _projScreenMatrix );
  11994. // update WebGL objects
  11995. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11996. // custom render plugins (pre pass)
  11997. renderPlugins( this.renderPluginsPre, scene, camera );
  11998. //
  11999. _this.info.render.calls = 0;
  12000. _this.info.render.vertices = 0;
  12001. _this.info.render.faces = 0;
  12002. _this.info.render.points = 0;
  12003. this.setRenderTarget( renderTarget );
  12004. if ( this.autoClear || forceClear ) {
  12005. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12006. }
  12007. // set matrices for regular objects (frustum culled)
  12008. renderList = scene.__webglObjects;
  12009. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12010. webglObject = renderList[ i ];
  12011. object = webglObject.object;
  12012. webglObject.render = false;
  12013. if ( object.visible ) {
  12014. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  12015. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  12016. setupMatrices( object, camera );
  12017. unrollBufferMaterial( webglObject );
  12018. webglObject.render = true;
  12019. if ( this.sortObjects === true ) {
  12020. if ( object.renderDepth !== null ) {
  12021. webglObject.z = object.renderDepth;
  12022. } else {
  12023. _vector3.copy( object.matrixWorld.getPosition() );
  12024. _projScreenMatrix.multiplyVector3( _vector3 );
  12025. webglObject.z = _vector3.z;
  12026. }
  12027. webglObject.id = object.id;
  12028. }
  12029. }
  12030. }
  12031. }
  12032. if ( this.sortObjects ) {
  12033. renderList.sort( painterSortStable );
  12034. }
  12035. // set matrices for immediate objects
  12036. renderList = scene.__webglObjectsImmediate;
  12037. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12038. webglObject = renderList[ i ];
  12039. object = webglObject.object;
  12040. if ( object.visible ) {
  12041. /*
  12042. if ( object.matrixAutoUpdate ) {
  12043. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  12044. }
  12045. */
  12046. setupMatrices( object, camera );
  12047. unrollImmediateBufferMaterial( webglObject );
  12048. }
  12049. }
  12050. if ( scene.overrideMaterial ) {
  12051. var material = scene.overrideMaterial;
  12052. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12053. this.setDepthTest( material.depthTest );
  12054. this.setDepthWrite( material.depthWrite );
  12055. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12056. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  12057. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  12058. } else {
  12059. // opaque pass (front-to-back order)
  12060. this.setBlending( THREE.NormalBlending );
  12061. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  12062. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  12063. // transparent pass (back-to-front order)
  12064. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  12065. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  12066. }
  12067. // custom render plugins (post pass)
  12068. renderPlugins( this.renderPluginsPost, scene, camera );
  12069. // Generate mipmap if we're using any kind of mipmap filtering
  12070. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12071. updateRenderTargetMipmap( renderTarget );
  12072. }
  12073. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12074. this.setDepthTest( true );
  12075. this.setDepthWrite( true );
  12076. // _gl.finish();
  12077. };
  12078. function renderPlugins( plugins, scene, camera ) {
  12079. if ( ! plugins.length ) return;
  12080. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  12081. // reset state for plugin (to start from clean slate)
  12082. _currentProgram = null;
  12083. _currentCamera = null;
  12084. _oldBlending = -1;
  12085. _oldDepthTest = -1;
  12086. _oldDepthWrite = -1;
  12087. _oldDoubleSided = -1;
  12088. _oldFlipSided = -1;
  12089. _currentGeometryGroupHash = -1;
  12090. _currentMaterialId = -1;
  12091. _lightsNeedUpdate = true;
  12092. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  12093. // reset state after plugin (anything could have changed)
  12094. _currentProgram = null;
  12095. _currentCamera = null;
  12096. _oldBlending = -1;
  12097. _oldDepthTest = -1;
  12098. _oldDepthWrite = -1;
  12099. _oldDoubleSided = -1;
  12100. _oldFlipSided = -1;
  12101. _currentGeometryGroupHash = -1;
  12102. _currentMaterialId = -1;
  12103. _lightsNeedUpdate = true;
  12104. }
  12105. };
  12106. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12107. var webglObject, object, buffer, material, start, end, delta;
  12108. if ( reverse ) {
  12109. start = renderList.length - 1;
  12110. end = -1;
  12111. delta = -1;
  12112. } else {
  12113. start = 0;
  12114. end = renderList.length;
  12115. delta = 1;
  12116. }
  12117. for ( var i = start; i !== end; i += delta ) {
  12118. webglObject = renderList[ i ];
  12119. if ( webglObject.render ) {
  12120. object = webglObject.object;
  12121. buffer = webglObject.buffer;
  12122. if ( overrideMaterial ) {
  12123. material = overrideMaterial;
  12124. } else {
  12125. material = webglObject[ materialType ];
  12126. if ( ! material ) continue;
  12127. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12128. _this.setDepthTest( material.depthTest );
  12129. _this.setDepthWrite( material.depthWrite );
  12130. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12131. }
  12132. _this.setMaterialFaces( material );
  12133. if ( buffer instanceof THREE.BufferGeometry ) {
  12134. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  12135. } else {
  12136. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  12137. }
  12138. }
  12139. }
  12140. };
  12141. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12142. var webglObject, object, material, program;
  12143. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  12144. webglObject = renderList[ i ];
  12145. object = webglObject.object;
  12146. if ( object.visible ) {
  12147. if ( overrideMaterial ) {
  12148. material = overrideMaterial;
  12149. } else {
  12150. material = webglObject[ materialType ];
  12151. if ( ! material ) continue;
  12152. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12153. _this.setDepthTest( material.depthTest );
  12154. _this.setDepthWrite( material.depthWrite );
  12155. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12156. }
  12157. _this.renderImmediateObject( camera, lights, fog, material, object );
  12158. }
  12159. }
  12160. };
  12161. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12162. var program = setProgram( camera, lights, fog, material, object );
  12163. _currentGeometryGroupHash = -1;
  12164. _this.setMaterialFaces( material );
  12165. if ( object.immediateRenderCallback ) {
  12166. object.immediateRenderCallback( program, _gl, _frustum );
  12167. } else {
  12168. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12169. }
  12170. };
  12171. function unrollImmediateBufferMaterial ( globject ) {
  12172. var object = globject.object,
  12173. material = object.material;
  12174. if ( material.transparent ) {
  12175. globject.transparent = material;
  12176. globject.opaque = null;
  12177. } else {
  12178. globject.opaque = material;
  12179. globject.transparent = null;
  12180. }
  12181. };
  12182. function unrollBufferMaterial ( globject ) {
  12183. var object = globject.object,
  12184. buffer = globject.buffer,
  12185. material, materialIndex, meshMaterial;
  12186. meshMaterial = object.material;
  12187. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  12188. materialIndex = buffer.materialIndex;
  12189. if ( materialIndex >= 0 ) {
  12190. if ( meshMaterial.materials.length > 0 ) {
  12191. material = meshMaterial.materials[ materialIndex ];
  12192. } else {
  12193. material = object.geometry.materials[ materialIndex ];
  12194. }
  12195. if ( material.transparent ) {
  12196. globject.transparent = material;
  12197. globject.opaque = null;
  12198. } else {
  12199. globject.opaque = material;
  12200. globject.transparent = null;
  12201. }
  12202. }
  12203. } else {
  12204. material = meshMaterial;
  12205. if ( material ) {
  12206. if ( material.transparent ) {
  12207. globject.transparent = material;
  12208. globject.opaque = null;
  12209. } else {
  12210. globject.opaque = material;
  12211. globject.transparent = null;
  12212. }
  12213. }
  12214. }
  12215. };
  12216. // Geometry splitting
  12217. function sortFacesByMaterial ( geometry ) {
  12218. var f, fl, face, materialIndex, vertices,
  12219. materialHash, groupHash,
  12220. hash_map = {};
  12221. var numMorphTargets = geometry.morphTargets.length;
  12222. var numMorphNormals = geometry.morphNormals.length;
  12223. geometry.geometryGroups = {};
  12224. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12225. face = geometry.faces[ f ];
  12226. materialIndex = face.materialIndex;
  12227. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  12228. if ( hash_map[ materialHash ] === undefined ) {
  12229. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  12230. }
  12231. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  12232. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12233. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12234. }
  12235. vertices = face instanceof THREE.Face3 ? 3 : 4;
  12236. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  12237. hash_map[ materialHash ].counter += 1;
  12238. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  12239. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12240. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12241. }
  12242. }
  12243. if ( face instanceof THREE.Face3 ) {
  12244. geometry.geometryGroups[ groupHash ].faces3.push( f );
  12245. } else {
  12246. geometry.geometryGroups[ groupHash ].faces4.push( f );
  12247. }
  12248. geometry.geometryGroups[ groupHash ].vertices += vertices;
  12249. }
  12250. geometry.geometryGroupsList = [];
  12251. for ( var g in geometry.geometryGroups ) {
  12252. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  12253. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  12254. }
  12255. };
  12256. // Objects refresh
  12257. this.initWebGLObjects = function ( scene ) {
  12258. if ( !scene.__webglObjects ) {
  12259. scene.__webglObjects = [];
  12260. scene.__webglObjectsImmediate = [];
  12261. scene.__webglSprites = [];
  12262. scene.__webglFlares = [];
  12263. }
  12264. while ( scene.__objectsAdded.length ) {
  12265. addObject( scene.__objectsAdded[ 0 ], scene );
  12266. scene.__objectsAdded.splice( 0, 1 );
  12267. }
  12268. while ( scene.__objectsRemoved.length ) {
  12269. removeObject( scene.__objectsRemoved[ 0 ], scene );
  12270. scene.__objectsRemoved.splice( 0, 1 );
  12271. }
  12272. // update must be called after objects adding / removal
  12273. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  12274. updateObject( scene.__webglObjects[ o ].object );
  12275. }
  12276. };
  12277. // Objects adding
  12278. function addObject ( object, scene ) {
  12279. var g, geometry, geometryGroup;
  12280. if ( ! object.__webglInit ) {
  12281. object.__webglInit = true;
  12282. object._modelViewMatrix = new THREE.Matrix4();
  12283. object._normalMatrix = new THREE.Matrix3();
  12284. if ( object instanceof THREE.Mesh ) {
  12285. geometry = object.geometry;
  12286. if ( geometry instanceof THREE.Geometry ) {
  12287. if ( geometry.geometryGroups === undefined ) {
  12288. sortFacesByMaterial( geometry );
  12289. }
  12290. // create separate VBOs per geometry chunk
  12291. for ( g in geometry.geometryGroups ) {
  12292. geometryGroup = geometry.geometryGroups[ g ];
  12293. // initialise VBO on the first access
  12294. if ( ! geometryGroup.__webglVertexBuffer ) {
  12295. createMeshBuffers( geometryGroup );
  12296. initMeshBuffers( geometryGroup, object );
  12297. geometry.verticesNeedUpdate = true;
  12298. geometry.morphTargetsNeedUpdate = true;
  12299. geometry.elementsNeedUpdate = true;
  12300. geometry.uvsNeedUpdate = true;
  12301. geometry.normalsNeedUpdate = true;
  12302. geometry.tangentsNeedUpdate = true;
  12303. geometry.colorsNeedUpdate = true;
  12304. }
  12305. }
  12306. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12307. initDirectBuffers( geometry );
  12308. }
  12309. } else if ( object instanceof THREE.Ribbon ) {
  12310. geometry = object.geometry;
  12311. if ( ! geometry.__webglVertexBuffer ) {
  12312. createRibbonBuffers( geometry );
  12313. initRibbonBuffers( geometry, object );
  12314. geometry.verticesNeedUpdate = true;
  12315. geometry.colorsNeedUpdate = true;
  12316. geometry.normalsNeedUpdate = true;
  12317. }
  12318. } else if ( object instanceof THREE.Line ) {
  12319. geometry = object.geometry;
  12320. if ( ! geometry.__webglVertexBuffer ) {
  12321. createLineBuffers( geometry );
  12322. initLineBuffers( geometry, object );
  12323. geometry.verticesNeedUpdate = true;
  12324. geometry.colorsNeedUpdate = true;
  12325. geometry.lineDistancesNeedUpdate = true;
  12326. }
  12327. } else if ( object instanceof THREE.ParticleSystem ) {
  12328. geometry = object.geometry;
  12329. if ( ! geometry.__webglVertexBuffer ) {
  12330. if ( geometry instanceof THREE.Geometry ) {
  12331. createParticleBuffers( geometry );
  12332. initParticleBuffers( geometry, object );
  12333. geometry.verticesNeedUpdate = true;
  12334. geometry.colorsNeedUpdate = true;
  12335. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12336. initDirectBuffers( geometry );
  12337. }
  12338. }
  12339. }
  12340. }
  12341. if ( ! object.__webglActive ) {
  12342. if ( object instanceof THREE.Mesh ) {
  12343. geometry = object.geometry;
  12344. if ( geometry instanceof THREE.BufferGeometry ) {
  12345. addBuffer( scene.__webglObjects, geometry, object );
  12346. } else {
  12347. for ( g in geometry.geometryGroups ) {
  12348. geometryGroup = geometry.geometryGroups[ g ];
  12349. addBuffer( scene.__webglObjects, geometryGroup, object );
  12350. }
  12351. }
  12352. } else if ( object instanceof THREE.Ribbon ||
  12353. object instanceof THREE.Line ||
  12354. object instanceof THREE.ParticleSystem ) {
  12355. geometry = object.geometry;
  12356. addBuffer( scene.__webglObjects, geometry, object );
  12357. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12358. addBufferImmediate( scene.__webglObjectsImmediate, object );
  12359. } else if ( object instanceof THREE.Sprite ) {
  12360. scene.__webglSprites.push( object );
  12361. } else if ( object instanceof THREE.LensFlare ) {
  12362. scene.__webglFlares.push( object );
  12363. }
  12364. object.__webglActive = true;
  12365. }
  12366. };
  12367. function addBuffer ( objlist, buffer, object ) {
  12368. objlist.push(
  12369. {
  12370. buffer: buffer,
  12371. object: object,
  12372. opaque: null,
  12373. transparent: null
  12374. }
  12375. );
  12376. };
  12377. function addBufferImmediate ( objlist, object ) {
  12378. objlist.push(
  12379. {
  12380. object: object,
  12381. opaque: null,
  12382. transparent: null
  12383. }
  12384. );
  12385. };
  12386. // Objects updates
  12387. function updateObject ( object ) {
  12388. var geometry = object.geometry,
  12389. geometryGroup, customAttributesDirty, material;
  12390. if ( object instanceof THREE.Mesh ) {
  12391. if ( geometry instanceof THREE.BufferGeometry ) {
  12392. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  12393. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12394. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  12395. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12396. }
  12397. geometry.verticesNeedUpdate = false;
  12398. geometry.elementsNeedUpdate = false;
  12399. geometry.uvsNeedUpdate = false;
  12400. geometry.normalsNeedUpdate = false;
  12401. geometry.colorsNeedUpdate = false;
  12402. geometry.tangentsNeedUpdate = false;
  12403. } else {
  12404. // check all geometry groups
  12405. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  12406. geometryGroup = geometry.geometryGroupsList[ i ];
  12407. material = getBufferMaterial( object, geometryGroup );
  12408. if ( geometry.buffersNeedUpdate ) {
  12409. initMeshBuffers( geometryGroup, object );
  12410. }
  12411. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12412. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12413. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12414. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12415. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  12416. }
  12417. }
  12418. geometry.verticesNeedUpdate = false;
  12419. geometry.morphTargetsNeedUpdate = false;
  12420. geometry.elementsNeedUpdate = false;
  12421. geometry.uvsNeedUpdate = false;
  12422. geometry.normalsNeedUpdate = false;
  12423. geometry.colorsNeedUpdate = false;
  12424. geometry.tangentsNeedUpdate = false;
  12425. geometry.buffersNeedUpdate = false;
  12426. material.attributes && clearCustomAttributes( material );
  12427. }
  12428. } else if ( object instanceof THREE.Ribbon ) {
  12429. material = getBufferMaterial( object, geometry );
  12430. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12431. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  12432. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  12433. }
  12434. geometry.verticesNeedUpdate = false;
  12435. geometry.colorsNeedUpdate = false;
  12436. geometry.normalsNeedUpdate = false;
  12437. material.attributes && clearCustomAttributes( material );
  12438. } else if ( object instanceof THREE.Line ) {
  12439. material = getBufferMaterial( object, geometry );
  12440. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12441. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12442. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12443. }
  12444. geometry.verticesNeedUpdate = false;
  12445. geometry.colorsNeedUpdate = false;
  12446. geometry.lineDistancesNeedUpdate = false;
  12447. material.attributes && clearCustomAttributes( material );
  12448. } else if ( object instanceof THREE.ParticleSystem ) {
  12449. if ( geometry instanceof THREE.BufferGeometry ) {
  12450. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12451. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12452. }
  12453. geometry.verticesNeedUpdate = false;
  12454. geometry.colorsNeedUpdate = false;
  12455. } else {
  12456. material = getBufferMaterial( object, geometry );
  12457. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12458. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  12459. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12460. }
  12461. geometry.verticesNeedUpdate = false;
  12462. geometry.colorsNeedUpdate = false;
  12463. material.attributes && clearCustomAttributes( material );
  12464. }
  12465. }
  12466. };
  12467. // Objects updates - custom attributes check
  12468. function areCustomAttributesDirty ( material ) {
  12469. for ( var a in material.attributes ) {
  12470. if ( material.attributes[ a ].needsUpdate ) return true;
  12471. }
  12472. return false;
  12473. };
  12474. function clearCustomAttributes ( material ) {
  12475. for ( var a in material.attributes ) {
  12476. material.attributes[ a ].needsUpdate = false;
  12477. }
  12478. };
  12479. // Objects removal
  12480. function removeObject ( object, scene ) {
  12481. if ( object instanceof THREE.Mesh ||
  12482. object instanceof THREE.ParticleSystem ||
  12483. object instanceof THREE.Ribbon ||
  12484. object instanceof THREE.Line ) {
  12485. removeInstances( scene.__webglObjects, object );
  12486. } else if ( object instanceof THREE.Sprite ) {
  12487. removeInstancesDirect( scene.__webglSprites, object );
  12488. } else if ( object instanceof THREE.LensFlare ) {
  12489. removeInstancesDirect( scene.__webglFlares, object );
  12490. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12491. removeInstances( scene.__webglObjectsImmediate, object );
  12492. }
  12493. object.__webglActive = false;
  12494. };
  12495. function removeInstances ( objlist, object ) {
  12496. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12497. if ( objlist[ o ].object === object ) {
  12498. objlist.splice( o, 1 );
  12499. }
  12500. }
  12501. };
  12502. function removeInstancesDirect ( objlist, object ) {
  12503. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12504. if ( objlist[ o ] === object ) {
  12505. objlist.splice( o, 1 );
  12506. }
  12507. }
  12508. };
  12509. // Materials
  12510. this.initMaterial = function ( material, lights, fog, object ) {
  12511. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  12512. if ( material instanceof THREE.MeshDepthMaterial ) {
  12513. shaderID = 'depth';
  12514. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12515. shaderID = 'normal';
  12516. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  12517. shaderID = 'basic';
  12518. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12519. shaderID = 'lambert';
  12520. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12521. shaderID = 'phong';
  12522. } else if ( material instanceof THREE.LineBasicMaterial ) {
  12523. shaderID = 'basic';
  12524. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12525. shaderID = 'dashed';
  12526. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12527. shaderID = 'particle_basic';
  12528. }
  12529. if ( shaderID ) {
  12530. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  12531. }
  12532. // heuristics to create shader parameters according to lights in the scene
  12533. // (not to blow over maxLights budget)
  12534. maxLightCount = allocateLights( lights );
  12535. maxShadows = allocateShadows( lights );
  12536. maxBones = allocateBones( object );
  12537. parameters = {
  12538. map: !!material.map,
  12539. envMap: !!material.envMap,
  12540. lightMap: !!material.lightMap,
  12541. bumpMap: !!material.bumpMap,
  12542. normalMap: !!material.normalMap,
  12543. specularMap: !!material.specularMap,
  12544. vertexColors: material.vertexColors,
  12545. fog: fog,
  12546. useFog: material.fog,
  12547. fogExp: fog instanceof THREE.FogExp2,
  12548. sizeAttenuation: material.sizeAttenuation,
  12549. skinning: material.skinning,
  12550. maxBones: maxBones,
  12551. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  12552. boneTextureWidth: object && object.boneTextureWidth,
  12553. boneTextureHeight: object && object.boneTextureHeight,
  12554. morphTargets: material.morphTargets,
  12555. morphNormals: material.morphNormals,
  12556. maxMorphTargets: this.maxMorphTargets,
  12557. maxMorphNormals: this.maxMorphNormals,
  12558. maxDirLights: maxLightCount.directional,
  12559. maxPointLights: maxLightCount.point,
  12560. maxSpotLights: maxLightCount.spot,
  12561. maxHemiLights: maxLightCount.hemi,
  12562. maxShadows: maxShadows,
  12563. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  12564. shadowMapSoft: this.shadowMapSoft,
  12565. shadowMapDebug: this.shadowMapDebug,
  12566. shadowMapCascade: this.shadowMapCascade,
  12567. alphaTest: material.alphaTest,
  12568. metal: material.metal,
  12569. perPixel: material.perPixel,
  12570. wrapAround: material.wrapAround,
  12571. doubleSided: material.side === THREE.DoubleSide,
  12572. flipSided: material.side === THREE.BackSide
  12573. };
  12574. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  12575. var attributes = material.program.attributes;
  12576. if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
  12577. if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
  12578. if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
  12579. if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );
  12580. if ( attributes.lineDistance >= 0 ) _gl.enableVertexAttribArray( attributes.lineDistance );
  12581. if ( material.skinning &&
  12582. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12583. _gl.enableVertexAttribArray( attributes.skinIndex );
  12584. _gl.enableVertexAttribArray( attributes.skinWeight );
  12585. }
  12586. if ( material.attributes ) {
  12587. for ( a in material.attributes ) {
  12588. if ( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );
  12589. }
  12590. }
  12591. if ( material.morphTargets ) {
  12592. material.numSupportedMorphTargets = 0;
  12593. var id, base = "morphTarget";
  12594. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  12595. id = base + i;
  12596. if ( attributes[ id ] >= 0 ) {
  12597. _gl.enableVertexAttribArray( attributes[ id ] );
  12598. material.numSupportedMorphTargets ++;
  12599. }
  12600. }
  12601. }
  12602. if ( material.morphNormals ) {
  12603. material.numSupportedMorphNormals = 0;
  12604. var id, base = "morphNormal";
  12605. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  12606. id = base + i;
  12607. if ( attributes[ id ] >= 0 ) {
  12608. _gl.enableVertexAttribArray( attributes[ id ] );
  12609. material.numSupportedMorphNormals ++;
  12610. }
  12611. }
  12612. }
  12613. material.uniformsList = [];
  12614. for ( u in material.uniforms ) {
  12615. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  12616. }
  12617. };
  12618. function setMaterialShaders( material, shaders ) {
  12619. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  12620. material.vertexShader = shaders.vertexShader;
  12621. material.fragmentShader = shaders.fragmentShader;
  12622. };
  12623. function setProgram( camera, lights, fog, material, object ) {
  12624. _usedTextureUnits = 0;
  12625. if ( material.needsUpdate ) {
  12626. if ( material.program ) _this.deallocateMaterial( material );
  12627. _this.initMaterial( material, lights, fog, object );
  12628. material.needsUpdate = false;
  12629. }
  12630. if ( material.morphTargets ) {
  12631. if ( ! object.__webglMorphTargetInfluences ) {
  12632. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  12633. }
  12634. }
  12635. var refreshMaterial = false;
  12636. var program = material.program,
  12637. p_uniforms = program.uniforms,
  12638. m_uniforms = material.uniforms;
  12639. if ( program !== _currentProgram ) {
  12640. _gl.useProgram( program );
  12641. _currentProgram = program;
  12642. refreshMaterial = true;
  12643. }
  12644. if ( material.id !== _currentMaterialId ) {
  12645. _currentMaterialId = material.id;
  12646. refreshMaterial = true;
  12647. }
  12648. if ( refreshMaterial || camera !== _currentCamera ) {
  12649. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  12650. if ( camera !== _currentCamera ) _currentCamera = camera;
  12651. }
  12652. // skinning uniforms must be set even if material didn't change
  12653. // auto-setting of texture unit for bone texture must go before other textures
  12654. // not sure why, but otherwise weird things happen
  12655. if ( material.skinning ) {
  12656. if ( _supportsBoneTextures && object.useVertexTexture ) {
  12657. if ( p_uniforms.boneTexture !== null ) {
  12658. var textureUnit = getTextureUnit();
  12659. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  12660. _this.setTexture( object.boneTexture, textureUnit );
  12661. }
  12662. } else {
  12663. if ( p_uniforms.boneGlobalMatrices !== null ) {
  12664. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  12665. }
  12666. }
  12667. }
  12668. if ( refreshMaterial ) {
  12669. // refresh uniforms common to several materials
  12670. if ( fog && material.fog ) {
  12671. refreshUniformsFog( m_uniforms, fog );
  12672. }
  12673. if ( material instanceof THREE.MeshPhongMaterial ||
  12674. material instanceof THREE.MeshLambertMaterial ||
  12675. material.lights ) {
  12676. if ( _lightsNeedUpdate ) {
  12677. setupLights( program, lights );
  12678. _lightsNeedUpdate = false;
  12679. }
  12680. refreshUniformsLights( m_uniforms, _lights );
  12681. }
  12682. if ( material instanceof THREE.MeshBasicMaterial ||
  12683. material instanceof THREE.MeshLambertMaterial ||
  12684. material instanceof THREE.MeshPhongMaterial ) {
  12685. refreshUniformsCommon( m_uniforms, material );
  12686. }
  12687. // refresh single material specific uniforms
  12688. if ( material instanceof THREE.LineBasicMaterial ) {
  12689. refreshUniformsLine( m_uniforms, material );
  12690. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12691. refreshUniformsLine( m_uniforms, material );
  12692. refreshUniformsDash( m_uniforms, material );
  12693. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12694. refreshUniformsParticle( m_uniforms, material );
  12695. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12696. refreshUniformsPhong( m_uniforms, material );
  12697. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12698. refreshUniformsLambert( m_uniforms, material );
  12699. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  12700. m_uniforms.mNear.value = camera.near;
  12701. m_uniforms.mFar.value = camera.far;
  12702. m_uniforms.opacity.value = material.opacity;
  12703. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12704. m_uniforms.opacity.value = material.opacity;
  12705. }
  12706. if ( object.receiveShadow && ! material._shadowPass ) {
  12707. refreshUniformsShadow( m_uniforms, lights );
  12708. }
  12709. // load common uniforms
  12710. loadUniformsGeneric( program, material.uniformsList );
  12711. // load material specific uniforms
  12712. // (shader material also gets them for the sake of genericity)
  12713. if ( material instanceof THREE.ShaderMaterial ||
  12714. material instanceof THREE.MeshPhongMaterial ||
  12715. material.envMap ) {
  12716. if ( p_uniforms.cameraPosition !== null ) {
  12717. var position = camera.matrixWorld.getPosition();
  12718. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  12719. }
  12720. }
  12721. if ( material instanceof THREE.MeshPhongMaterial ||
  12722. material instanceof THREE.MeshLambertMaterial ||
  12723. material instanceof THREE.ShaderMaterial ||
  12724. material.skinning ) {
  12725. if ( p_uniforms.viewMatrix !== null ) {
  12726. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  12727. }
  12728. }
  12729. }
  12730. loadUniformsMatrices( p_uniforms, object );
  12731. if ( p_uniforms.modelMatrix !== null ) {
  12732. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  12733. }
  12734. return program;
  12735. };
  12736. // Uniforms (refresh uniforms objects)
  12737. function refreshUniformsCommon ( uniforms, material ) {
  12738. uniforms.opacity.value = material.opacity;
  12739. if ( _this.gammaInput ) {
  12740. uniforms.diffuse.value.copyGammaToLinear( material.color );
  12741. } else {
  12742. uniforms.diffuse.value = material.color;
  12743. }
  12744. uniforms.map.value = material.map;
  12745. uniforms.lightMap.value = material.lightMap;
  12746. uniforms.specularMap.value = material.specularMap;
  12747. if ( material.bumpMap ) {
  12748. uniforms.bumpMap.value = material.bumpMap;
  12749. uniforms.bumpScale.value = material.bumpScale;
  12750. }
  12751. if ( material.normalMap ) {
  12752. uniforms.normalMap.value = material.normalMap;
  12753. uniforms.normalScale.value.copy( material.normalScale );
  12754. }
  12755. // uv repeat and offset setting priorities
  12756. // 1. color map
  12757. // 2. specular map
  12758. // 3. normal map
  12759. // 4. bump map
  12760. var uvScaleMap;
  12761. if ( material.map ) {
  12762. uvScaleMap = material.map;
  12763. } else if ( material.specularMap ) {
  12764. uvScaleMap = material.specularMap;
  12765. } else if ( material.normalMap ) {
  12766. uvScaleMap = material.normalMap;
  12767. } else if ( material.bumpMap ) {
  12768. uvScaleMap = material.bumpMap;
  12769. }
  12770. if ( uvScaleMap !== undefined ) {
  12771. var offset = uvScaleMap.offset;
  12772. var repeat = uvScaleMap.repeat;
  12773. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12774. }
  12775. uniforms.envMap.value = material.envMap;
  12776. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  12777. if ( _this.gammaInput ) {
  12778. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  12779. uniforms.reflectivity.value = material.reflectivity;
  12780. } else {
  12781. uniforms.reflectivity.value = material.reflectivity;
  12782. }
  12783. uniforms.refractionRatio.value = material.refractionRatio;
  12784. uniforms.combine.value = material.combine;
  12785. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  12786. };
  12787. function refreshUniformsLine ( uniforms, material ) {
  12788. uniforms.diffuse.value = material.color;
  12789. uniforms.opacity.value = material.opacity;
  12790. };
  12791. function refreshUniformsDash ( uniforms, material ) {
  12792. uniforms.dashSize.value = material.dashSize;
  12793. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12794. uniforms.scale.value = material.scale;
  12795. };
  12796. function refreshUniformsParticle ( uniforms, material ) {
  12797. uniforms.psColor.value = material.color;
  12798. uniforms.opacity.value = material.opacity;
  12799. uniforms.size.value = material.size;
  12800. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  12801. uniforms.map.value = material.map;
  12802. };
  12803. function refreshUniformsFog ( uniforms, fog ) {
  12804. uniforms.fogColor.value = fog.color;
  12805. if ( fog instanceof THREE.Fog ) {
  12806. uniforms.fogNear.value = fog.near;
  12807. uniforms.fogFar.value = fog.far;
  12808. } else if ( fog instanceof THREE.FogExp2 ) {
  12809. uniforms.fogDensity.value = fog.density;
  12810. }
  12811. };
  12812. function refreshUniformsPhong ( uniforms, material ) {
  12813. uniforms.shininess.value = material.shininess;
  12814. if ( _this.gammaInput ) {
  12815. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12816. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12817. uniforms.specular.value.copyGammaToLinear( material.specular );
  12818. } else {
  12819. uniforms.ambient.value = material.ambient;
  12820. uniforms.emissive.value = material.emissive;
  12821. uniforms.specular.value = material.specular;
  12822. }
  12823. if ( material.wrapAround ) {
  12824. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12825. }
  12826. };
  12827. function refreshUniformsLambert ( uniforms, material ) {
  12828. if ( _this.gammaInput ) {
  12829. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12830. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12831. } else {
  12832. uniforms.ambient.value = material.ambient;
  12833. uniforms.emissive.value = material.emissive;
  12834. }
  12835. if ( material.wrapAround ) {
  12836. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12837. }
  12838. };
  12839. function refreshUniformsLights ( uniforms, lights ) {
  12840. uniforms.ambientLightColor.value = lights.ambient;
  12841. uniforms.directionalLightColor.value = lights.directional.colors;
  12842. uniforms.directionalLightDirection.value = lights.directional.positions;
  12843. uniforms.pointLightColor.value = lights.point.colors;
  12844. uniforms.pointLightPosition.value = lights.point.positions;
  12845. uniforms.pointLightDistance.value = lights.point.distances;
  12846. uniforms.spotLightColor.value = lights.spot.colors;
  12847. uniforms.spotLightPosition.value = lights.spot.positions;
  12848. uniforms.spotLightDistance.value = lights.spot.distances;
  12849. uniforms.spotLightDirection.value = lights.spot.directions;
  12850. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  12851. uniforms.spotLightExponent.value = lights.spot.exponents;
  12852. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12853. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12854. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  12855. };
  12856. function refreshUniformsShadow ( uniforms, lights ) {
  12857. if ( uniforms.shadowMatrix ) {
  12858. var j = 0;
  12859. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12860. var light = lights[ i ];
  12861. if ( ! light.castShadow ) continue;
  12862. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12863. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12864. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12865. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12866. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12867. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12868. j ++;
  12869. }
  12870. }
  12871. }
  12872. };
  12873. // Uniforms (load to GPU)
  12874. function loadUniformsMatrices ( uniforms, object ) {
  12875. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  12876. if ( uniforms.normalMatrix ) {
  12877. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  12878. }
  12879. };
  12880. function getTextureUnit() {
  12881. var textureUnit = _usedTextureUnits;
  12882. if ( textureUnit >= _maxTextures ) {
  12883. console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  12884. }
  12885. _usedTextureUnits += 1;
  12886. return textureUnit;
  12887. };
  12888. function loadUniformsGeneric ( program, uniforms ) {
  12889. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  12890. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12891. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  12892. if ( !location ) continue;
  12893. uniform = uniforms[ j ][ 0 ];
  12894. type = uniform.type;
  12895. value = uniform.value;
  12896. if ( type === "i" ) { // single integer
  12897. _gl.uniform1i( location, value );
  12898. } else if ( type === "f" ) { // single float
  12899. _gl.uniform1f( location, value );
  12900. } else if ( type === "v2" ) { // single THREE.Vector2
  12901. _gl.uniform2f( location, value.x, value.y );
  12902. } else if ( type === "v3" ) { // single THREE.Vector3
  12903. _gl.uniform3f( location, value.x, value.y, value.z );
  12904. } else if ( type === "v4" ) { // single THREE.Vector4
  12905. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  12906. } else if ( type === "c" ) { // single THREE.Color
  12907. _gl.uniform3f( location, value.r, value.g, value.b );
  12908. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  12909. _gl.uniform1iv( location, value );
  12910. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  12911. _gl.uniform3iv( location, value );
  12912. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  12913. _gl.uniform1fv( location, value );
  12914. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  12915. _gl.uniform3fv( location, value );
  12916. } else if ( type === "v2v" ) { // array of THREE.Vector2
  12917. if ( uniform._array === undefined ) {
  12918. uniform._array = new Float32Array( 2 * value.length );
  12919. }
  12920. for ( i = 0, il = value.length; i < il; i ++ ) {
  12921. offset = i * 2;
  12922. uniform._array[ offset ] = value[ i ].x;
  12923. uniform._array[ offset + 1 ] = value[ i ].y;
  12924. }
  12925. _gl.uniform2fv( location, uniform._array );
  12926. } else if ( type === "v3v" ) { // array of THREE.Vector3
  12927. if ( uniform._array === undefined ) {
  12928. uniform._array = new Float32Array( 3 * value.length );
  12929. }
  12930. for ( i = 0, il = value.length; i < il; i ++ ) {
  12931. offset = i * 3;
  12932. uniform._array[ offset ] = value[ i ].x;
  12933. uniform._array[ offset + 1 ] = value[ i ].y;
  12934. uniform._array[ offset + 2 ] = value[ i ].z;
  12935. }
  12936. _gl.uniform3fv( location, uniform._array );
  12937. } else if ( type === "v4v" ) { // array of THREE.Vector4
  12938. if ( uniform._array === undefined ) {
  12939. uniform._array = new Float32Array( 4 * value.length );
  12940. }
  12941. for ( i = 0, il = value.length; i < il; i ++ ) {
  12942. offset = i * 4;
  12943. uniform._array[ offset ] = value[ i ].x;
  12944. uniform._array[ offset + 1 ] = value[ i ].y;
  12945. uniform._array[ offset + 2 ] = value[ i ].z;
  12946. uniform._array[ offset + 3 ] = value[ i ].w;
  12947. }
  12948. _gl.uniform4fv( location, uniform._array );
  12949. } else if ( type === "m4") { // single THREE.Matrix4
  12950. if ( uniform._array === undefined ) {
  12951. uniform._array = new Float32Array( 16 );
  12952. }
  12953. value.flattenToArray( uniform._array );
  12954. _gl.uniformMatrix4fv( location, false, uniform._array );
  12955. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  12956. if ( uniform._array === undefined ) {
  12957. uniform._array = new Float32Array( 16 * value.length );
  12958. }
  12959. for ( i = 0, il = value.length; i < il; i ++ ) {
  12960. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12961. }
  12962. _gl.uniformMatrix4fv( location, false, uniform._array );
  12963. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  12964. texture = value;
  12965. textureUnit = getTextureUnit();
  12966. _gl.uniform1i( location, textureUnit );
  12967. if ( !texture ) continue;
  12968. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  12969. setCubeTexture( texture, textureUnit );
  12970. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12971. setCubeTextureDynamic( texture, textureUnit );
  12972. } else {
  12973. _this.setTexture( texture, textureUnit );
  12974. }
  12975. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  12976. if ( uniform._array === undefined ) {
  12977. uniform._array = [];
  12978. }
  12979. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12980. uniform._array[ i ] = getTextureUnit();
  12981. }
  12982. _gl.uniform1iv( location, uniform._array );
  12983. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12984. texture = uniform.value[ i ];
  12985. textureUnit = uniform._array[ i ];
  12986. if ( !texture ) continue;
  12987. _this.setTexture( texture, textureUnit );
  12988. }
  12989. }
  12990. }
  12991. };
  12992. function setupMatrices ( object, camera ) {
  12993. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  12994. object._normalMatrix.getInverse( object._modelViewMatrix );
  12995. object._normalMatrix.transpose();
  12996. };
  12997. //
  12998. function setColorGamma( array, offset, color, intensitySq ) {
  12999. array[ offset ] = color.r * color.r * intensitySq;
  13000. array[ offset + 1 ] = color.g * color.g * intensitySq;
  13001. array[ offset + 2 ] = color.b * color.b * intensitySq;
  13002. };
  13003. function setColorLinear( array, offset, color, intensity ) {
  13004. array[ offset ] = color.r * intensity;
  13005. array[ offset + 1 ] = color.g * intensity;
  13006. array[ offset + 2 ] = color.b * intensity;
  13007. };
  13008. function setupLights ( program, lights ) {
  13009. var l, ll, light, n,
  13010. r = 0, g = 0, b = 0,
  13011. color, skyColor, groundColor,
  13012. intensity, intensitySq,
  13013. position,
  13014. distance,
  13015. zlights = _lights,
  13016. dirColors = zlights.directional.colors,
  13017. dirPositions = zlights.directional.positions,
  13018. pointColors = zlights.point.colors,
  13019. pointPositions = zlights.point.positions,
  13020. pointDistances = zlights.point.distances,
  13021. spotColors = zlights.spot.colors,
  13022. spotPositions = zlights.spot.positions,
  13023. spotDistances = zlights.spot.distances,
  13024. spotDirections = zlights.spot.directions,
  13025. spotAnglesCos = zlights.spot.anglesCos,
  13026. spotExponents = zlights.spot.exponents,
  13027. hemiSkyColors = zlights.hemi.skyColors,
  13028. hemiGroundColors = zlights.hemi.groundColors,
  13029. hemiPositions = zlights.hemi.positions,
  13030. dirLength = 0,
  13031. pointLength = 0,
  13032. spotLength = 0,
  13033. hemiLength = 0,
  13034. dirCount = 0,
  13035. pointCount = 0,
  13036. spotCount = 0,
  13037. hemiCount = 0,
  13038. dirOffset = 0,
  13039. pointOffset = 0,
  13040. spotOffset = 0,
  13041. hemiOffset = 0;
  13042. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13043. light = lights[ l ];
  13044. if ( light.onlyShadow ) continue;
  13045. color = light.color;
  13046. intensity = light.intensity;
  13047. distance = light.distance;
  13048. if ( light instanceof THREE.AmbientLight ) {
  13049. if ( ! light.visible ) continue;
  13050. if ( _this.gammaInput ) {
  13051. r += color.r * color.r;
  13052. g += color.g * color.g;
  13053. b += color.b * color.b;
  13054. } else {
  13055. r += color.r;
  13056. g += color.g;
  13057. b += color.b;
  13058. }
  13059. } else if ( light instanceof THREE.DirectionalLight ) {
  13060. dirCount += 1;
  13061. if ( ! light.visible ) continue;
  13062. dirOffset = dirLength * 3;
  13063. if ( _this.gammaInput ) {
  13064. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  13065. } else {
  13066. setColorLinear( dirColors, dirOffset, color, intensity );
  13067. }
  13068. _direction.copy( light.matrixWorld.getPosition() );
  13069. _direction.subSelf( light.target.matrixWorld.getPosition() );
  13070. _direction.normalize();
  13071. dirPositions[ dirOffset ] = _direction.x;
  13072. dirPositions[ dirOffset + 1 ] = _direction.y;
  13073. dirPositions[ dirOffset + 2 ] = _direction.z;
  13074. dirLength += 1;
  13075. } else if ( light instanceof THREE.PointLight ) {
  13076. pointCount += 1;
  13077. if ( ! light.visible ) continue;
  13078. pointOffset = pointLength * 3;
  13079. if ( _this.gammaInput ) {
  13080. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  13081. } else {
  13082. setColorLinear( pointColors, pointOffset, color, intensity );
  13083. }
  13084. position = light.matrixWorld.getPosition();
  13085. pointPositions[ pointOffset ] = position.x;
  13086. pointPositions[ pointOffset + 1 ] = position.y;
  13087. pointPositions[ pointOffset + 2 ] = position.z;
  13088. pointDistances[ pointLength ] = distance;
  13089. pointLength += 1;
  13090. } else if ( light instanceof THREE.SpotLight ) {
  13091. spotCount += 1;
  13092. if ( ! light.visible ) continue;
  13093. spotOffset = spotLength * 3;
  13094. if ( _this.gammaInput ) {
  13095. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  13096. } else {
  13097. setColorLinear( spotColors, spotOffset, color, intensity );
  13098. }
  13099. position = light.matrixWorld.getPosition();
  13100. spotPositions[ spotOffset ] = position.x;
  13101. spotPositions[ spotOffset + 1 ] = position.y;
  13102. spotPositions[ spotOffset + 2 ] = position.z;
  13103. spotDistances[ spotLength ] = distance;
  13104. _direction.copy( position );
  13105. _direction.subSelf( light.target.matrixWorld.getPosition() );
  13106. _direction.normalize();
  13107. spotDirections[ spotOffset ] = _direction.x;
  13108. spotDirections[ spotOffset + 1 ] = _direction.y;
  13109. spotDirections[ spotOffset + 2 ] = _direction.z;
  13110. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  13111. spotExponents[ spotLength ] = light.exponent;
  13112. spotLength += 1;
  13113. } else if ( light instanceof THREE.HemisphereLight ) {
  13114. hemiCount += 1;
  13115. if ( ! light.visible ) continue;
  13116. skyColor = light.color;
  13117. groundColor = light.groundColor;
  13118. hemiOffset = hemiLength * 3;
  13119. if ( _this.gammaInput ) {
  13120. intensitySq = intensity * intensity;
  13121. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  13122. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  13123. } else {
  13124. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  13125. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  13126. }
  13127. _direction.copy( light.matrixWorld.getPosition() );
  13128. _direction.normalize();
  13129. hemiPositions[ hemiOffset ] = _direction.x;
  13130. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  13131. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  13132. hemiLength += 1;
  13133. }
  13134. }
  13135. // null eventual remains from removed lights
  13136. // (this is to avoid if in shader)
  13137. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  13138. for ( l = dirLength * 3, ll = Math.max( dirPositions.length, dirCount * 3 ); l < ll; l ++ ) dirPositions[ l ] = 0.0;
  13139. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  13140. for ( l = pointLength * 3, ll = Math.max( pointPositions.length, pointCount * 3 ); l < ll; l ++ ) pointPositions[ l ] = 0.0;
  13141. for ( l = pointLength, ll = Math.max( pointDistances.length, pointCount ); l < ll; l ++ ) pointDistances[ l ] = 0.0;
  13142. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  13143. for ( l = spotLength * 3, ll = Math.max( spotPositions.length, spotCount * 3 ); l < ll; l ++ ) spotPositions[ l ] = 0.0;
  13144. for ( l = spotLength * 3, ll = Math.max( spotDirections.length, spotCount * 3 ); l < ll; l ++ ) spotDirections[ l ] = 0.0;
  13145. for ( l = spotLength, ll = Math.max( spotAnglesCos.length, spotCount ); l < ll; l ++ ) spotAnglesCos[ l ] = 0.0;
  13146. for ( l = spotLength, ll = Math.max( spotExponents.length, spotCount ); l < ll; l ++ ) spotExponents[ l ] = 0.0;
  13147. for ( l = spotLength, ll = Math.max( spotDistances.length, spotCount ); l < ll; l ++ ) spotDistances[ l ] = 0.0;
  13148. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  13149. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  13150. for ( l = hemiLength * 3, ll = Math.max( hemiPositions.length, hemiCount * 3 ); l < ll; l ++ ) hemiPositions[ l ] = 0.0;
  13151. zlights.directional.length = dirLength;
  13152. zlights.point.length = pointLength;
  13153. zlights.spot.length = spotLength;
  13154. zlights.hemi.length = hemiLength;
  13155. zlights.ambient[ 0 ] = r;
  13156. zlights.ambient[ 1 ] = g;
  13157. zlights.ambient[ 2 ] = b;
  13158. };
  13159. // GL state setting
  13160. this.setFaceCulling = function ( cullFace, frontFace ) {
  13161. if ( cullFace ) {
  13162. if ( !frontFace || frontFace === "ccw" ) {
  13163. _gl.frontFace( _gl.CCW );
  13164. } else {
  13165. _gl.frontFace( _gl.CW );
  13166. }
  13167. if( cullFace === "back" ) {
  13168. _gl.cullFace( _gl.BACK );
  13169. } else if( cullFace === "front" ) {
  13170. _gl.cullFace( _gl.FRONT );
  13171. } else {
  13172. _gl.cullFace( _gl.FRONT_AND_BACK );
  13173. }
  13174. _gl.enable( _gl.CULL_FACE );
  13175. } else {
  13176. _gl.disable( _gl.CULL_FACE );
  13177. }
  13178. };
  13179. this.setMaterialFaces = function ( material ) {
  13180. var doubleSided = material.side === THREE.DoubleSide;
  13181. var flipSided = material.side === THREE.BackSide;
  13182. if ( _oldDoubleSided !== doubleSided ) {
  13183. if ( doubleSided ) {
  13184. _gl.disable( _gl.CULL_FACE );
  13185. } else {
  13186. _gl.enable( _gl.CULL_FACE );
  13187. }
  13188. _oldDoubleSided = doubleSided;
  13189. }
  13190. if ( _oldFlipSided !== flipSided ) {
  13191. if ( flipSided ) {
  13192. _gl.frontFace( _gl.CW );
  13193. } else {
  13194. _gl.frontFace( _gl.CCW );
  13195. }
  13196. _oldFlipSided = flipSided;
  13197. }
  13198. };
  13199. this.setDepthTest = function ( depthTest ) {
  13200. if ( _oldDepthTest !== depthTest ) {
  13201. if ( depthTest ) {
  13202. _gl.enable( _gl.DEPTH_TEST );
  13203. } else {
  13204. _gl.disable( _gl.DEPTH_TEST );
  13205. }
  13206. _oldDepthTest = depthTest;
  13207. }
  13208. };
  13209. this.setDepthWrite = function ( depthWrite ) {
  13210. if ( _oldDepthWrite !== depthWrite ) {
  13211. _gl.depthMask( depthWrite );
  13212. _oldDepthWrite = depthWrite;
  13213. }
  13214. };
  13215. function setLineWidth ( width ) {
  13216. if ( width !== _oldLineWidth ) {
  13217. _gl.lineWidth( width );
  13218. _oldLineWidth = width;
  13219. }
  13220. };
  13221. function setPolygonOffset ( polygonoffset, factor, units ) {
  13222. if ( _oldPolygonOffset !== polygonoffset ) {
  13223. if ( polygonoffset ) {
  13224. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  13225. } else {
  13226. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  13227. }
  13228. _oldPolygonOffset = polygonoffset;
  13229. }
  13230. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  13231. _gl.polygonOffset( factor, units );
  13232. _oldPolygonOffsetFactor = factor;
  13233. _oldPolygonOffsetUnits = units;
  13234. }
  13235. };
  13236. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  13237. if ( blending !== _oldBlending ) {
  13238. if ( blending === THREE.NoBlending ) {
  13239. _gl.disable( _gl.BLEND );
  13240. } else if ( blending === THREE.AdditiveBlending ) {
  13241. _gl.enable( _gl.BLEND );
  13242. _gl.blendEquation( _gl.FUNC_ADD );
  13243. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  13244. } else if ( blending === THREE.SubtractiveBlending ) {
  13245. // TODO: Find blendFuncSeparate() combination
  13246. _gl.enable( _gl.BLEND );
  13247. _gl.blendEquation( _gl.FUNC_ADD );
  13248. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  13249. } else if ( blending === THREE.MultiplyBlending ) {
  13250. // TODO: Find blendFuncSeparate() combination
  13251. _gl.enable( _gl.BLEND );
  13252. _gl.blendEquation( _gl.FUNC_ADD );
  13253. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  13254. } else if ( blending === THREE.CustomBlending ) {
  13255. _gl.enable( _gl.BLEND );
  13256. } else {
  13257. _gl.enable( _gl.BLEND );
  13258. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  13259. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  13260. }
  13261. _oldBlending = blending;
  13262. }
  13263. if ( blending === THREE.CustomBlending ) {
  13264. if ( blendEquation !== _oldBlendEquation ) {
  13265. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  13266. _oldBlendEquation = blendEquation;
  13267. }
  13268. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  13269. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  13270. _oldBlendSrc = blendSrc;
  13271. _oldBlendDst = blendDst;
  13272. }
  13273. } else {
  13274. _oldBlendEquation = null;
  13275. _oldBlendSrc = null;
  13276. _oldBlendDst = null;
  13277. }
  13278. };
  13279. // Defines
  13280. function generateDefines ( defines ) {
  13281. var value, chunk, chunks = [];
  13282. for ( var d in defines ) {
  13283. value = defines[ d ];
  13284. if ( value === false ) continue;
  13285. chunk = "#define " + d + " " + value;
  13286. chunks.push( chunk );
  13287. }
  13288. return chunks.join( "\n" );
  13289. };
  13290. // Shaders
  13291. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13292. var p, pl, d, program, code;
  13293. var chunks = [];
  13294. // Generate code
  13295. if ( shaderID ) {
  13296. chunks.push( shaderID );
  13297. } else {
  13298. chunks.push( fragmentShader );
  13299. chunks.push( vertexShader );
  13300. }
  13301. for ( d in defines ) {
  13302. chunks.push( d );
  13303. chunks.push( defines[ d ] );
  13304. }
  13305. for ( p in parameters ) {
  13306. chunks.push( p );
  13307. chunks.push( parameters[ p ] );
  13308. }
  13309. code = chunks.join();
  13310. // Check if code has been already compiled
  13311. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  13312. var programInfo = _programs[ p ];
  13313. if ( programInfo.code === code ) {
  13314. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13315. programInfo.usedTimes ++;
  13316. return programInfo.program;
  13317. }
  13318. }
  13319. //console.log( "building new program " );
  13320. //
  13321. var customDefines = generateDefines( defines );
  13322. //
  13323. program = _gl.createProgram();
  13324. var prefix_vertex = [
  13325. "precision " + _precision + " float;",
  13326. customDefines,
  13327. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13328. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13329. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13330. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13331. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13332. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13333. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13334. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13335. "#define MAX_SHADOWS " + parameters.maxShadows,
  13336. "#define MAX_BONES " + parameters.maxBones,
  13337. parameters.map ? "#define USE_MAP" : "",
  13338. parameters.envMap ? "#define USE_ENVMAP" : "",
  13339. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13340. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13341. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13342. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13343. parameters.vertexColors ? "#define USE_COLOR" : "",
  13344. parameters.skinning ? "#define USE_SKINNING" : "",
  13345. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13346. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13347. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13348. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13349. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13350. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13351. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13352. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13353. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13354. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13355. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13356. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13357. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13358. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13359. "uniform mat4 modelMatrix;",
  13360. "uniform mat4 modelViewMatrix;",
  13361. "uniform mat4 projectionMatrix;",
  13362. "uniform mat4 viewMatrix;",
  13363. "uniform mat3 normalMatrix;",
  13364. "uniform vec3 cameraPosition;",
  13365. "attribute vec3 position;",
  13366. "attribute vec3 normal;",
  13367. "attribute vec2 uv;",
  13368. "attribute vec2 uv2;",
  13369. "#ifdef USE_COLOR",
  13370. "attribute vec3 color;",
  13371. "#endif",
  13372. "#ifdef USE_MORPHTARGETS",
  13373. "attribute vec3 morphTarget0;",
  13374. "attribute vec3 morphTarget1;",
  13375. "attribute vec3 morphTarget2;",
  13376. "attribute vec3 morphTarget3;",
  13377. "#ifdef USE_MORPHNORMALS",
  13378. "attribute vec3 morphNormal0;",
  13379. "attribute vec3 morphNormal1;",
  13380. "attribute vec3 morphNormal2;",
  13381. "attribute vec3 morphNormal3;",
  13382. "#else",
  13383. "attribute vec3 morphTarget4;",
  13384. "attribute vec3 morphTarget5;",
  13385. "attribute vec3 morphTarget6;",
  13386. "attribute vec3 morphTarget7;",
  13387. "#endif",
  13388. "#endif",
  13389. "#ifdef USE_SKINNING",
  13390. "attribute vec4 skinIndex;",
  13391. "attribute vec4 skinWeight;",
  13392. "#endif",
  13393. ""
  13394. ].join("\n");
  13395. var prefix_fragment = [
  13396. "precision " + _precision + " float;",
  13397. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13398. customDefines,
  13399. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13400. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13401. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13402. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13403. "#define MAX_SHADOWS " + parameters.maxShadows,
  13404. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13405. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13406. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13407. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13408. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13409. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13410. parameters.map ? "#define USE_MAP" : "",
  13411. parameters.envMap ? "#define USE_ENVMAP" : "",
  13412. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13413. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13414. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13415. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13416. parameters.vertexColors ? "#define USE_COLOR" : "",
  13417. parameters.metal ? "#define METAL" : "",
  13418. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13419. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13420. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13421. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13422. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13423. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13424. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13425. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13426. "uniform mat4 viewMatrix;",
  13427. "uniform vec3 cameraPosition;",
  13428. ""
  13429. ].join("\n");
  13430. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  13431. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  13432. _gl.attachShader( program, glVertexShader );
  13433. _gl.attachShader( program, glFragmentShader );
  13434. _gl.linkProgram( program );
  13435. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13436. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13437. }
  13438. // clean up
  13439. _gl.deleteShader( glFragmentShader );
  13440. _gl.deleteShader( glVertexShader );
  13441. //console.log( prefix_fragment + fragmentShader );
  13442. //console.log( prefix_vertex + vertexShader );
  13443. program.uniforms = {};
  13444. program.attributes = {};
  13445. var identifiers, u, a, i;
  13446. // cache uniform locations
  13447. identifiers = [
  13448. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13449. 'morphTargetInfluences'
  13450. ];
  13451. if ( parameters.useVertexTexture ) {
  13452. identifiers.push( 'boneTexture' );
  13453. } else {
  13454. identifiers.push( 'boneGlobalMatrices' );
  13455. }
  13456. for ( u in uniforms ) {
  13457. identifiers.push( u );
  13458. }
  13459. cacheUniformLocations( program, identifiers );
  13460. // cache attributes locations
  13461. identifiers = [
  13462. "position", "normal", "uv", "uv2", "tangent", "color",
  13463. "skinIndex", "skinWeight", "lineDistance"
  13464. ];
  13465. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13466. identifiers.push( "morphTarget" + i );
  13467. }
  13468. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  13469. identifiers.push( "morphNormal" + i );
  13470. }
  13471. for ( a in attributes ) {
  13472. identifiers.push( a );
  13473. }
  13474. cacheAttributeLocations( program, identifiers );
  13475. program.id = _programs_counter ++;
  13476. _programs.push( { program: program, code: code, usedTimes: 1 } );
  13477. _this.info.memory.programs = _programs.length;
  13478. return program;
  13479. };
  13480. // Shader parameters cache
  13481. function cacheUniformLocations ( program, identifiers ) {
  13482. var i, l, id;
  13483. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13484. id = identifiers[ i ];
  13485. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  13486. }
  13487. };
  13488. function cacheAttributeLocations ( program, identifiers ) {
  13489. var i, l, id;
  13490. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13491. id = identifiers[ i ];
  13492. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  13493. }
  13494. };
  13495. function addLineNumbers ( string ) {
  13496. var chunks = string.split( "\n" );
  13497. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  13498. // Chrome reports shader errors on lines
  13499. // starting counting from 1
  13500. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  13501. }
  13502. return chunks.join( "\n" );
  13503. };
  13504. function getShader ( type, string ) {
  13505. var shader;
  13506. if ( type === "fragment" ) {
  13507. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  13508. } else if ( type === "vertex" ) {
  13509. shader = _gl.createShader( _gl.VERTEX_SHADER );
  13510. }
  13511. _gl.shaderSource( shader, string );
  13512. _gl.compileShader( shader );
  13513. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  13514. console.error( _gl.getShaderInfoLog( shader ) );
  13515. console.error( addLineNumbers( string ) );
  13516. return null;
  13517. }
  13518. return shader;
  13519. };
  13520. // Textures
  13521. function isPowerOfTwo ( value ) {
  13522. return ( value & ( value - 1 ) ) === 0;
  13523. };
  13524. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13525. if ( isImagePowerOfTwo ) {
  13526. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13527. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13528. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13529. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13530. } else {
  13531. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13532. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13533. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13534. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13535. }
  13536. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  13537. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  13538. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  13539. texture.__oldAnisotropy = texture.anisotropy;
  13540. }
  13541. }
  13542. };
  13543. this.setTexture = function ( texture, slot ) {
  13544. if ( texture.needsUpdate ) {
  13545. if ( ! texture.__webglInit ) {
  13546. texture.__webglInit = true;
  13547. texture.__webglTexture = _gl.createTexture();
  13548. _this.info.memory.textures ++;
  13549. }
  13550. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13551. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13552. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13553. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13554. var image = texture.image,
  13555. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13556. glFormat = paramThreeToGL( texture.format ),
  13557. glType = paramThreeToGL( texture.type );
  13558. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13559. if ( texture instanceof THREE.CompressedTexture ) {
  13560. var mipmap, mipmaps = texture.mipmaps;
  13561. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13562. mipmap = mipmaps[ i ];
  13563. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13564. }
  13565. } else if ( texture instanceof THREE.DataTexture ) {
  13566. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13567. } else {
  13568. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13569. }
  13570. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13571. texture.needsUpdate = false;
  13572. if ( texture.onUpdate ) texture.onUpdate();
  13573. } else {
  13574. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13575. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13576. }
  13577. };
  13578. function clampToMaxSize ( image, maxSize ) {
  13579. if ( image.width <= maxSize && image.height <= maxSize ) {
  13580. return image;
  13581. }
  13582. // Warning: Scaling through the canvas will only work with images that use
  13583. // premultiplied alpha.
  13584. var maxDimension = Math.max( image.width, image.height );
  13585. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  13586. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  13587. var canvas = document.createElement( 'canvas' );
  13588. canvas.width = newWidth;
  13589. canvas.height = newHeight;
  13590. var ctx = canvas.getContext( "2d" );
  13591. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  13592. return canvas;
  13593. }
  13594. function setCubeTexture ( texture, slot ) {
  13595. if ( texture.image.length === 6 ) {
  13596. if ( texture.needsUpdate ) {
  13597. if ( ! texture.image.__webglTextureCube ) {
  13598. texture.image.__webglTextureCube = _gl.createTexture();
  13599. }
  13600. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13601. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13602. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13603. var isCompressed = texture instanceof THREE.CompressedTexture;
  13604. var cubeImage = [];
  13605. for ( var i = 0; i < 6; i ++ ) {
  13606. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  13607. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13608. } else {
  13609. cubeImage[ i ] = texture.image[ i ];
  13610. }
  13611. }
  13612. var image = cubeImage[ 0 ],
  13613. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13614. glFormat = paramThreeToGL( texture.format ),
  13615. glType = paramThreeToGL( texture.type );
  13616. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13617. for ( var i = 0; i < 6; i ++ ) {
  13618. if ( isCompressed ) {
  13619. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13620. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13621. mipmap = mipmaps[ j ];
  13622. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13623. }
  13624. } else {
  13625. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13626. }
  13627. }
  13628. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13629. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13630. }
  13631. texture.needsUpdate = false;
  13632. if ( texture.onUpdate ) texture.onUpdate();
  13633. } else {
  13634. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13635. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13636. }
  13637. }
  13638. };
  13639. function setCubeTextureDynamic ( texture, slot ) {
  13640. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13641. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13642. };
  13643. // Render targets
  13644. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13645. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13646. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13647. };
  13648. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13649. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13650. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13651. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13652. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13653. /* For some reason this is not working. Defaulting to RGBA4.
  13654. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13655. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13656. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13657. */
  13658. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13659. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13660. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13661. } else {
  13662. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13663. }
  13664. };
  13665. this.setRenderTarget = function ( renderTarget ) {
  13666. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13667. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  13668. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13669. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13670. renderTarget.__webglTexture = _gl.createTexture();
  13671. // Setup texture, create render and frame buffers
  13672. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  13673. glFormat = paramThreeToGL( renderTarget.format ),
  13674. glType = paramThreeToGL( renderTarget.type );
  13675. if ( isCube ) {
  13676. renderTarget.__webglFramebuffer = [];
  13677. renderTarget.__webglRenderbuffer = [];
  13678. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13679. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13680. for ( var i = 0; i < 6; i ++ ) {
  13681. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13682. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13683. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13684. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13685. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13686. }
  13687. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13688. } else {
  13689. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13690. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13691. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13692. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13693. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13694. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13695. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13696. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13697. }
  13698. // Release everything
  13699. if ( isCube ) {
  13700. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13701. } else {
  13702. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13703. }
  13704. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13705. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  13706. }
  13707. var framebuffer, width, height, vx, vy;
  13708. if ( renderTarget ) {
  13709. if ( isCube ) {
  13710. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13711. } else {
  13712. framebuffer = renderTarget.__webglFramebuffer;
  13713. }
  13714. width = renderTarget.width;
  13715. height = renderTarget.height;
  13716. vx = 0;
  13717. vy = 0;
  13718. } else {
  13719. framebuffer = null;
  13720. width = _viewportWidth;
  13721. height = _viewportHeight;
  13722. vx = _viewportX;
  13723. vy = _viewportY;
  13724. }
  13725. if ( framebuffer !== _currentFramebuffer ) {
  13726. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13727. _gl.viewport( vx, vy, width, height );
  13728. _currentFramebuffer = framebuffer;
  13729. }
  13730. _currentWidth = width;
  13731. _currentHeight = height;
  13732. };
  13733. function updateRenderTargetMipmap ( renderTarget ) {
  13734. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13735. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13736. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13737. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13738. } else {
  13739. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13740. _gl.generateMipmap( _gl.TEXTURE_2D );
  13741. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13742. }
  13743. };
  13744. // Fallback filters for non-power-of-2 textures
  13745. function filterFallback ( f ) {
  13746. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  13747. return _gl.NEAREST;
  13748. }
  13749. return _gl.LINEAR;
  13750. };
  13751. // Map three.js constants to WebGL constants
  13752. function paramThreeToGL ( p ) {
  13753. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13754. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13755. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13756. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13757. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13758. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13759. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13760. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13761. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13762. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13763. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13764. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13765. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13766. if ( p === THREE.ByteType ) return _gl.BYTE;
  13767. if ( p === THREE.ShortType ) return _gl.SHORT;
  13768. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13769. if ( p === THREE.IntType ) return _gl.INT;
  13770. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13771. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13772. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13773. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13774. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13775. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13776. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13777. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13778. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13779. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13780. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13781. if ( p === THREE.OneFactor ) return _gl.ONE;
  13782. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13783. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13784. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13785. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13786. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13787. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13788. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13789. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13790. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13791. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  13792. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13793. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13794. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13795. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13796. }
  13797. return 0;
  13798. };
  13799. // Allocations
  13800. function allocateBones ( object ) {
  13801. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  13802. return 1024;
  13803. } else {
  13804. // default for when object is not specified
  13805. // ( for example when prebuilding shader
  13806. // to be used with multiple objects )
  13807. //
  13808. // - leave some extra space for other uniforms
  13809. // - limit here is ANGLE's 254 max uniform vectors
  13810. // (up to 54 should be safe)
  13811. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  13812. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  13813. var maxBones = nVertexMatrices;
  13814. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  13815. maxBones = Math.min( object.bones.length, maxBones );
  13816. if ( maxBones < object.bones.length ) {
  13817. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  13818. }
  13819. }
  13820. return maxBones;
  13821. }
  13822. };
  13823. function allocateLights ( lights ) {
  13824. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  13825. dirLights = pointLights = spotLights = hemiLights = 0;
  13826. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13827. light = lights[ l ];
  13828. if ( light.onlyShadow ) continue;
  13829. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  13830. if ( light instanceof THREE.PointLight ) pointLights ++;
  13831. if ( light instanceof THREE.SpotLight ) spotLights ++;
  13832. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  13833. }
  13834. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  13835. };
  13836. function allocateShadows ( lights ) {
  13837. var l, ll, light, maxShadows = 0;
  13838. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  13839. light = lights[ l ];
  13840. if ( ! light.castShadow ) continue;
  13841. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  13842. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  13843. }
  13844. return maxShadows;
  13845. };
  13846. // Initialization
  13847. function initGL () {
  13848. try {
  13849. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  13850. throw 'Error creating WebGL context.';
  13851. }
  13852. } catch ( error ) {
  13853. console.error( error );
  13854. }
  13855. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  13856. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  13857. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  13858. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  13859. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13860. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  13861. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  13862. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13863. if ( ! _glExtensionTextureFloat ) {
  13864. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  13865. }
  13866. if ( ! _glExtensionStandardDerivatives ) {
  13867. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  13868. }
  13869. if ( ! _glExtensionTextureFilterAnisotropic ) {
  13870. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  13871. }
  13872. if ( ! _glExtensionCompressedTextureS3TC ) {
  13873. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  13874. }
  13875. };
  13876. function setDefaultGLState () {
  13877. _gl.clearColor( 0, 0, 0, 1 );
  13878. _gl.clearDepth( 1 );
  13879. _gl.clearStencil( 0 );
  13880. _gl.enable( _gl.DEPTH_TEST );
  13881. _gl.depthFunc( _gl.LEQUAL );
  13882. _gl.frontFace( _gl.CCW );
  13883. _gl.cullFace( _gl.BACK );
  13884. _gl.enable( _gl.CULL_FACE );
  13885. _gl.enable( _gl.BLEND );
  13886. _gl.blendEquation( _gl.FUNC_ADD );
  13887. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  13888. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  13889. };
  13890. // default plugins (order is important)
  13891. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  13892. this.addPrePlugin( this.shadowMapPlugin );
  13893. this.addPostPlugin( new THREE.SpritePlugin() );
  13894. this.addPostPlugin( new THREE.LensFlarePlugin() );
  13895. };
  13896. /**
  13897. * @author szimek / https://github.com/szimek/
  13898. * @author alteredq / http://alteredqualia.com/
  13899. */
  13900. THREE.WebGLRenderTarget = function ( width, height, options ) {
  13901. this.width = width;
  13902. this.height = height;
  13903. options = options || {};
  13904. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  13905. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  13906. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  13907. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  13908. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  13909. this.offset = new THREE.Vector2( 0, 0 );
  13910. this.repeat = new THREE.Vector2( 1, 1 );
  13911. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  13912. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  13913. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  13914. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  13915. this.generateMipmaps = true;
  13916. };
  13917. THREE.WebGLRenderTarget.prototype.clone = function() {
  13918. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  13919. tmp.wrapS = this.wrapS;
  13920. tmp.wrapT = this.wrapT;
  13921. tmp.magFilter = this.magFilter;
  13922. tmp.anisotropy = this.anisotropy;
  13923. tmp.minFilter = this.minFilter;
  13924. tmp.offset.copy( this.offset );
  13925. tmp.repeat.copy( this.repeat );
  13926. tmp.format = this.format;
  13927. tmp.type = this.type;
  13928. tmp.depthBuffer = this.depthBuffer;
  13929. tmp.stencilBuffer = this.stencilBuffer;
  13930. tmp.generateMipmaps = this.generateMipmaps;
  13931. return tmp;
  13932. };
  13933. /**
  13934. * @author alteredq / http://alteredqualia.com
  13935. */
  13936. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  13937. THREE.WebGLRenderTarget.call( this, width, height, options );
  13938. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  13939. };
  13940. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  13941. /**
  13942. * @author mrdoob / http://mrdoob.com/
  13943. */
  13944. THREE.RenderableVertex = function () {
  13945. this.positionWorld = new THREE.Vector3();
  13946. this.positionScreen = new THREE.Vector4();
  13947. this.visible = true;
  13948. };
  13949. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  13950. this.positionWorld.copy( vertex.positionWorld );
  13951. this.positionScreen.copy( vertex.positionScreen );
  13952. }
  13953. /**
  13954. * @author mrdoob / http://mrdoob.com/
  13955. */
  13956. THREE.RenderableFace3 = function () {
  13957. this.v1 = new THREE.RenderableVertex();
  13958. this.v2 = new THREE.RenderableVertex();
  13959. this.v3 = new THREE.RenderableVertex();
  13960. this.centroidWorld = new THREE.Vector3();
  13961. this.centroidScreen = new THREE.Vector3();
  13962. this.normalWorld = new THREE.Vector3();
  13963. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13964. this.vertexNormalsLength = 0;
  13965. this.color = null;
  13966. this.material = null;
  13967. this.uvs = [[]];
  13968. this.z = null;
  13969. };
  13970. /**
  13971. * @author mrdoob / http://mrdoob.com/
  13972. */
  13973. THREE.RenderableFace4 = function () {
  13974. this.v1 = new THREE.RenderableVertex();
  13975. this.v2 = new THREE.RenderableVertex();
  13976. this.v3 = new THREE.RenderableVertex();
  13977. this.v4 = new THREE.RenderableVertex();
  13978. this.centroidWorld = new THREE.Vector3();
  13979. this.centroidScreen = new THREE.Vector3();
  13980. this.normalWorld = new THREE.Vector3();
  13981. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13982. this.vertexNormalsLength = 0;
  13983. this.color = null;
  13984. this.material = null;
  13985. this.uvs = [[]];
  13986. this.z = null;
  13987. };
  13988. /**
  13989. * @author mrdoob / http://mrdoob.com/
  13990. */
  13991. THREE.RenderableObject = function () {
  13992. this.object = null;
  13993. this.z = null;
  13994. };
  13995. /**
  13996. * @author mrdoob / http://mrdoob.com/
  13997. */
  13998. THREE.RenderableParticle = function () {
  13999. this.object = null;
  14000. this.x = null;
  14001. this.y = null;
  14002. this.z = null;
  14003. this.rotation = null;
  14004. this.scale = new THREE.Vector2();
  14005. this.material = null;
  14006. };
  14007. /**
  14008. * @author mrdoob / http://mrdoob.com/
  14009. */
  14010. THREE.RenderableLine = function () {
  14011. this.z = null;
  14012. this.v1 = new THREE.RenderableVertex();
  14013. this.v2 = new THREE.RenderableVertex();
  14014. this.material = null;
  14015. };
  14016. /**
  14017. * @author alteredq / http://alteredqualia.com/
  14018. */
  14019. THREE.ColorUtils = {
  14020. adjustHSV : function ( color, h, s, v ) {
  14021. var hsv = THREE.ColorUtils.__hsv;
  14022. color.getHSV( hsv );
  14023. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  14024. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  14025. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  14026. color.setHSV( hsv.h, hsv.s, hsv.v );
  14027. }
  14028. };
  14029. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  14030. * @author mrdoob / http://mrdoob.com/
  14031. * @author alteredq / http://alteredqualia.com/
  14032. */
  14033. THREE.GeometryUtils = {
  14034. // Merge two geometries or geometry and geometry from object (using object's transform)
  14035. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  14036. var matrix, matrixRotation,
  14037. vertexOffset = geometry1.vertices.length,
  14038. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  14039. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  14040. vertices1 = geometry1.vertices,
  14041. vertices2 = geometry2.vertices,
  14042. faces1 = geometry1.faces,
  14043. faces2 = geometry2.faces,
  14044. uvs1 = geometry1.faceVertexUvs[ 0 ],
  14045. uvs2 = geometry2.faceVertexUvs[ 0 ];
  14046. var geo1MaterialsMap = {};
  14047. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  14048. var id = geometry1.materials[ i ].id;
  14049. geo1MaterialsMap[ id ] = i;
  14050. }
  14051. if ( object2 instanceof THREE.Mesh ) {
  14052. object2.matrixAutoUpdate && object2.updateMatrix();
  14053. matrix = object2.matrix;
  14054. matrixRotation = new THREE.Matrix4();
  14055. matrixRotation.extractRotation( matrix, object2.scale );
  14056. }
  14057. // vertices
  14058. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  14059. var vertex = vertices2[ i ];
  14060. var vertexCopy = vertex.clone();
  14061. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  14062. vertices1.push( vertexCopy );
  14063. }
  14064. // faces
  14065. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  14066. var face = faces2[ i ], faceCopy, normal, color,
  14067. faceVertexNormals = face.vertexNormals,
  14068. faceVertexColors = face.vertexColors;
  14069. if ( face instanceof THREE.Face3 ) {
  14070. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  14071. } else if ( face instanceof THREE.Face4 ) {
  14072. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  14073. }
  14074. faceCopy.normal.copy( face.normal );
  14075. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  14076. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  14077. normal = faceVertexNormals[ j ].clone();
  14078. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  14079. faceCopy.vertexNormals.push( normal );
  14080. }
  14081. faceCopy.color.copy( face.color );
  14082. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  14083. color = faceVertexColors[ j ];
  14084. faceCopy.vertexColors.push( color.clone() );
  14085. }
  14086. if ( face.materialIndex !== undefined ) {
  14087. var material2 = geometry2.materials[ face.materialIndex ];
  14088. var materialId2 = material2.id;
  14089. var materialIndex = geo1MaterialsMap[ materialId2 ];
  14090. if ( materialIndex === undefined ) {
  14091. materialIndex = geometry1.materials.length;
  14092. geo1MaterialsMap[ materialId2 ] = materialIndex;
  14093. geometry1.materials.push( material2 );
  14094. }
  14095. faceCopy.materialIndex = materialIndex;
  14096. }
  14097. faceCopy.centroid.copy( face.centroid );
  14098. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  14099. faces1.push( faceCopy );
  14100. }
  14101. // uvs
  14102. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  14103. var uv = uvs2[ i ], uvCopy = [];
  14104. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  14105. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  14106. }
  14107. uvs1.push( uvCopy );
  14108. }
  14109. },
  14110. clone: function ( geometry ) {
  14111. var cloneGeo = new THREE.Geometry();
  14112. var i, il;
  14113. var vertices = geometry.vertices,
  14114. faces = geometry.faces,
  14115. uvs = geometry.faceVertexUvs[ 0 ];
  14116. // materials
  14117. if ( geometry.materials ) {
  14118. cloneGeo.materials = geometry.materials.slice();
  14119. }
  14120. // vertices
  14121. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  14122. var vertex = vertices[ i ];
  14123. cloneGeo.vertices.push( vertex.clone() );
  14124. }
  14125. // faces
  14126. for ( i = 0, il = faces.length; i < il; i ++ ) {
  14127. var face = faces[ i ];
  14128. cloneGeo.faces.push( face.clone() );
  14129. }
  14130. // uvs
  14131. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  14132. var uv = uvs[ i ], uvCopy = [];
  14133. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  14134. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  14135. }
  14136. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  14137. }
  14138. return cloneGeo;
  14139. },
  14140. // Get random point in triangle (via barycentric coordinates)
  14141. // (uniform distribution)
  14142. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  14143. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  14144. var a, b, c,
  14145. point = new THREE.Vector3(),
  14146. tmp = THREE.GeometryUtils.__v1;
  14147. a = THREE.GeometryUtils.random();
  14148. b = THREE.GeometryUtils.random();
  14149. if ( ( a + b ) > 1 ) {
  14150. a = 1 - a;
  14151. b = 1 - b;
  14152. }
  14153. c = 1 - a - b;
  14154. point.copy( vectorA );
  14155. point.multiplyScalar( a );
  14156. tmp.copy( vectorB );
  14157. tmp.multiplyScalar( b );
  14158. point.addSelf( tmp );
  14159. tmp.copy( vectorC );
  14160. tmp.multiplyScalar( c );
  14161. point.addSelf( tmp );
  14162. return point;
  14163. },
  14164. // Get random point in face (triangle / quad)
  14165. // (uniform distribution)
  14166. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  14167. var vA, vB, vC, vD;
  14168. if ( face instanceof THREE.Face3 ) {
  14169. vA = geometry.vertices[ face.a ];
  14170. vB = geometry.vertices[ face.b ];
  14171. vC = geometry.vertices[ face.c ];
  14172. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  14173. } else if ( face instanceof THREE.Face4 ) {
  14174. vA = geometry.vertices[ face.a ];
  14175. vB = geometry.vertices[ face.b ];
  14176. vC = geometry.vertices[ face.c ];
  14177. vD = geometry.vertices[ face.d ];
  14178. var area1, area2;
  14179. if ( useCachedAreas ) {
  14180. if ( face._area1 && face._area2 ) {
  14181. area1 = face._area1;
  14182. area2 = face._area2;
  14183. } else {
  14184. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14185. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14186. face._area1 = area1;
  14187. face._area2 = area2;
  14188. }
  14189. } else {
  14190. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  14191. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14192. }
  14193. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  14194. if ( r < area1 ) {
  14195. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  14196. } else {
  14197. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  14198. }
  14199. }
  14200. },
  14201. // Get uniformly distributed random points in mesh
  14202. // - create array with cumulative sums of face areas
  14203. // - pick random number from 0 to total area
  14204. // - find corresponding place in area array by binary search
  14205. // - get random point in face
  14206. randomPointsInGeometry: function ( geometry, n ) {
  14207. var face, i,
  14208. faces = geometry.faces,
  14209. vertices = geometry.vertices,
  14210. il = faces.length,
  14211. totalArea = 0,
  14212. cumulativeAreas = [],
  14213. vA, vB, vC, vD;
  14214. // precompute face areas
  14215. for ( i = 0; i < il; i ++ ) {
  14216. face = faces[ i ];
  14217. if ( face instanceof THREE.Face3 ) {
  14218. vA = vertices[ face.a ];
  14219. vB = vertices[ face.b ];
  14220. vC = vertices[ face.c ];
  14221. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  14222. } else if ( face instanceof THREE.Face4 ) {
  14223. vA = vertices[ face.a ];
  14224. vB = vertices[ face.b ];
  14225. vC = vertices[ face.c ];
  14226. vD = vertices[ face.d ];
  14227. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14228. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14229. face._area = face._area1 + face._area2;
  14230. }
  14231. totalArea += face._area;
  14232. cumulativeAreas[ i ] = totalArea;
  14233. }
  14234. // binary search cumulative areas array
  14235. function binarySearchIndices( value ) {
  14236. function binarySearch( start, end ) {
  14237. // return closest larger index
  14238. // if exact number is not found
  14239. if ( end < start )
  14240. return start;
  14241. var mid = start + Math.floor( ( end - start ) / 2 );
  14242. if ( cumulativeAreas[ mid ] > value ) {
  14243. return binarySearch( start, mid - 1 );
  14244. } else if ( cumulativeAreas[ mid ] < value ) {
  14245. return binarySearch( mid + 1, end );
  14246. } else {
  14247. return mid;
  14248. }
  14249. }
  14250. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  14251. return result;
  14252. }
  14253. // pick random face weighted by face area
  14254. var r, index,
  14255. result = [];
  14256. var stats = {};
  14257. for ( i = 0; i < n; i ++ ) {
  14258. r = THREE.GeometryUtils.random() * totalArea;
  14259. index = binarySearchIndices( r );
  14260. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  14261. if ( ! stats[ index ] ) {
  14262. stats[ index ] = 1;
  14263. } else {
  14264. stats[ index ] += 1;
  14265. }
  14266. }
  14267. return result;
  14268. },
  14269. // Get triangle area (by Heron's formula)
  14270. // http://en.wikipedia.org/wiki/Heron%27s_formula
  14271. triangleArea: function ( vectorA, vectorB, vectorC ) {
  14272. var s, a, b, c,
  14273. tmp = THREE.GeometryUtils.__v1;
  14274. tmp.sub( vectorA, vectorB );
  14275. a = tmp.length();
  14276. tmp.sub( vectorA, vectorC );
  14277. b = tmp.length();
  14278. tmp.sub( vectorB, vectorC );
  14279. c = tmp.length();
  14280. s = 0.5 * ( a + b + c );
  14281. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  14282. },
  14283. // Center geometry so that 0,0,0 is in center of bounding box
  14284. center: function ( geometry ) {
  14285. geometry.computeBoundingBox();
  14286. var bb = geometry.boundingBox;
  14287. var offset = new THREE.Vector3();
  14288. offset.add( bb.min, bb.max );
  14289. offset.multiplyScalar( -0.5 );
  14290. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  14291. geometry.computeBoundingBox();
  14292. return offset;
  14293. },
  14294. // Normalize UVs to be from <0,1>
  14295. // (for now just the first set of UVs)
  14296. normalizeUVs: function ( geometry ) {
  14297. var uvSet = geometry.faceVertexUvs[ 0 ];
  14298. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  14299. var uvs = uvSet[ i ];
  14300. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  14301. // texture repeat
  14302. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  14303. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  14304. }
  14305. }
  14306. },
  14307. triangulateQuads: function ( geometry ) {
  14308. var i, il, j, jl;
  14309. var faces = [];
  14310. var faceUvs = [];
  14311. var faceVertexUvs = [];
  14312. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  14313. faceUvs[ i ] = [];
  14314. }
  14315. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14316. faceVertexUvs[ i ] = [];
  14317. }
  14318. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14319. var face = geometry.faces[ i ];
  14320. if ( face instanceof THREE.Face4 ) {
  14321. var a = face.a;
  14322. var b = face.b;
  14323. var c = face.c;
  14324. var d = face.d;
  14325. var triA = new THREE.Face3();
  14326. var triB = new THREE.Face3();
  14327. triA.color.copy( face.color );
  14328. triB.color.copy( face.color );
  14329. triA.materialIndex = face.materialIndex;
  14330. triB.materialIndex = face.materialIndex;
  14331. triA.a = a;
  14332. triA.b = b;
  14333. triA.c = d;
  14334. triB.a = b;
  14335. triB.b = c;
  14336. triB.c = d;
  14337. if ( face.vertexColors.length === 4 ) {
  14338. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  14339. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  14340. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14341. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  14342. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  14343. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14344. }
  14345. faces.push( triA, triB );
  14346. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14347. if ( geometry.faceVertexUvs[ j ].length ) {
  14348. var uvs = geometry.faceVertexUvs[ j ][ i ];
  14349. var uvA = uvs[ 0 ];
  14350. var uvB = uvs[ 1 ];
  14351. var uvC = uvs[ 2 ];
  14352. var uvD = uvs[ 3 ];
  14353. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  14354. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  14355. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14356. }
  14357. }
  14358. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14359. if ( geometry.faceUvs[ j ].length ) {
  14360. var faceUv = geometry.faceUvs[ j ][ i ];
  14361. faceUvs[ j ].push( faceUv, faceUv );
  14362. }
  14363. }
  14364. } else {
  14365. faces.push( face );
  14366. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14367. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  14368. }
  14369. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14370. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14371. }
  14372. }
  14373. }
  14374. geometry.faces = faces;
  14375. geometry.faceUvs = faceUvs;
  14376. geometry.faceVertexUvs = faceVertexUvs;
  14377. geometry.computeCentroids();
  14378. geometry.computeFaceNormals();
  14379. geometry.computeVertexNormals();
  14380. if ( geometry.hasTangents ) geometry.computeTangents();
  14381. },
  14382. // Make all faces use unique vertices
  14383. // so that each face can be separated from others
  14384. explode: function( geometry ) {
  14385. var vertices = [];
  14386. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14387. var n = vertices.length;
  14388. var face = geometry.faces[ i ];
  14389. if ( face instanceof THREE.Face4 ) {
  14390. var a = face.a;
  14391. var b = face.b;
  14392. var c = face.c;
  14393. var d = face.d;
  14394. var va = geometry.vertices[ a ];
  14395. var vb = geometry.vertices[ b ];
  14396. var vc = geometry.vertices[ c ];
  14397. var vd = geometry.vertices[ d ];
  14398. vertices.push( va.clone() );
  14399. vertices.push( vb.clone() );
  14400. vertices.push( vc.clone() );
  14401. vertices.push( vd.clone() );
  14402. face.a = n;
  14403. face.b = n + 1;
  14404. face.c = n + 2;
  14405. face.d = n + 3;
  14406. } else {
  14407. var a = face.a;
  14408. var b = face.b;
  14409. var c = face.c;
  14410. var va = geometry.vertices[ a ];
  14411. var vb = geometry.vertices[ b ];
  14412. var vc = geometry.vertices[ c ];
  14413. vertices.push( va.clone() );
  14414. vertices.push( vb.clone() );
  14415. vertices.push( vc.clone() );
  14416. face.a = n;
  14417. face.b = n + 1;
  14418. face.c = n + 2;
  14419. }
  14420. }
  14421. geometry.vertices = vertices;
  14422. delete geometry.__tmpVertices;
  14423. },
  14424. // Break faces with edges longer than maxEdgeLength
  14425. // - not recursive
  14426. tessellate: function ( geometry, maxEdgeLength ) {
  14427. var i, il, face,
  14428. a, b, c, d,
  14429. va, vb, vc, vd,
  14430. dab, dbc, dac, dcd, dad,
  14431. m, m1, m2,
  14432. vm, vm1, vm2,
  14433. vnm, vnm1, vnm2,
  14434. vcm, vcm1, vcm2,
  14435. triA, triB,
  14436. quadA, quadB,
  14437. edge;
  14438. var faces = [];
  14439. var faceVertexUvs = [];
  14440. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14441. faceVertexUvs[ i ] = [];
  14442. }
  14443. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14444. face = geometry.faces[ i ];
  14445. if ( face instanceof THREE.Face3 ) {
  14446. a = face.a;
  14447. b = face.b;
  14448. c = face.c;
  14449. va = geometry.vertices[ a ];
  14450. vb = geometry.vertices[ b ];
  14451. vc = geometry.vertices[ c ];
  14452. dab = va.distanceTo( vb );
  14453. dbc = vb.distanceTo( vc );
  14454. dac = va.distanceTo( vc );
  14455. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  14456. m = geometry.vertices.length;
  14457. triA = face.clone();
  14458. triB = face.clone();
  14459. if ( dab >= dbc && dab >= dac ) {
  14460. vm = va.clone();
  14461. vm.lerpSelf( vb, 0.5 );
  14462. triA.a = a;
  14463. triA.b = m;
  14464. triA.c = c;
  14465. triB.a = m;
  14466. triB.b = b;
  14467. triB.c = c;
  14468. if ( face.vertexNormals.length === 3 ) {
  14469. vnm = face.vertexNormals[ 0 ].clone();
  14470. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14471. triA.vertexNormals[ 1 ].copy( vnm );
  14472. triB.vertexNormals[ 0 ].copy( vnm );
  14473. }
  14474. if ( face.vertexColors.length === 3 ) {
  14475. vcm = face.vertexColors[ 0 ].clone();
  14476. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14477. triA.vertexColors[ 1 ].copy( vcm );
  14478. triB.vertexColors[ 0 ].copy( vcm );
  14479. }
  14480. edge = 0;
  14481. } else if ( dbc >= dab && dbc >= dac ) {
  14482. vm = vb.clone();
  14483. vm.lerpSelf( vc, 0.5 );
  14484. triA.a = a;
  14485. triA.b = b;
  14486. triA.c = m;
  14487. triB.a = m;
  14488. triB.b = c;
  14489. triB.c = a;
  14490. if ( face.vertexNormals.length === 3 ) {
  14491. vnm = face.vertexNormals[ 1 ].clone();
  14492. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14493. triA.vertexNormals[ 2 ].copy( vnm );
  14494. triB.vertexNormals[ 0 ].copy( vnm );
  14495. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  14496. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  14497. }
  14498. if ( face.vertexColors.length === 3 ) {
  14499. vcm = face.vertexColors[ 1 ].clone();
  14500. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14501. triA.vertexColors[ 2 ].copy( vcm );
  14502. triB.vertexColors[ 0 ].copy( vcm );
  14503. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  14504. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  14505. }
  14506. edge = 1;
  14507. } else {
  14508. vm = va.clone();
  14509. vm.lerpSelf( vc, 0.5 );
  14510. triA.a = a;
  14511. triA.b = b;
  14512. triA.c = m;
  14513. triB.a = m;
  14514. triB.b = b;
  14515. triB.c = c;
  14516. if ( face.vertexNormals.length === 3 ) {
  14517. vnm = face.vertexNormals[ 0 ].clone();
  14518. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14519. triA.vertexNormals[ 2 ].copy( vnm );
  14520. triB.vertexNormals[ 0 ].copy( vnm );
  14521. }
  14522. if ( face.vertexColors.length === 3 ) {
  14523. vcm = face.vertexColors[ 0 ].clone();
  14524. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14525. triA.vertexColors[ 2 ].copy( vcm );
  14526. triB.vertexColors[ 0 ].copy( vcm );
  14527. }
  14528. edge = 2;
  14529. }
  14530. faces.push( triA, triB );
  14531. geometry.vertices.push( vm );
  14532. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  14533. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14534. if ( geometry.faceVertexUvs[ j ].length ) {
  14535. uvs = geometry.faceVertexUvs[ j ][ i ];
  14536. uvA = uvs[ 0 ];
  14537. uvB = uvs[ 1 ];
  14538. uvC = uvs[ 2 ];
  14539. // AB
  14540. if ( edge === 0 ) {
  14541. uvM = uvA.clone();
  14542. uvM.lerpSelf( uvB, 0.5 );
  14543. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  14544. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14545. // BC
  14546. } else if ( edge === 1 ) {
  14547. uvM = uvB.clone();
  14548. uvM.lerpSelf( uvC, 0.5 );
  14549. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14550. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  14551. // AC
  14552. } else {
  14553. uvM = uvA.clone();
  14554. uvM.lerpSelf( uvC, 0.5 );
  14555. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14556. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14557. }
  14558. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14559. }
  14560. }
  14561. } else {
  14562. faces.push( face );
  14563. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14564. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14565. }
  14566. }
  14567. } else {
  14568. a = face.a;
  14569. b = face.b;
  14570. c = face.c;
  14571. d = face.d;
  14572. va = geometry.vertices[ a ];
  14573. vb = geometry.vertices[ b ];
  14574. vc = geometry.vertices[ c ];
  14575. vd = geometry.vertices[ d ];
  14576. dab = va.distanceTo( vb );
  14577. dbc = vb.distanceTo( vc );
  14578. dcd = vc.distanceTo( vd );
  14579. dad = va.distanceTo( vd );
  14580. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  14581. m1 = geometry.vertices.length;
  14582. m2 = geometry.vertices.length + 1;
  14583. quadA = face.clone();
  14584. quadB = face.clone();
  14585. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  14586. vm1 = va.clone();
  14587. vm1.lerpSelf( vb, 0.5 );
  14588. vm2 = vc.clone();
  14589. vm2.lerpSelf( vd, 0.5 );
  14590. quadA.a = a;
  14591. quadA.b = m1;
  14592. quadA.c = m2;
  14593. quadA.d = d;
  14594. quadB.a = m1;
  14595. quadB.b = b;
  14596. quadB.c = c;
  14597. quadB.d = m2;
  14598. if ( face.vertexNormals.length === 4 ) {
  14599. vnm1 = face.vertexNormals[ 0 ].clone();
  14600. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14601. vnm2 = face.vertexNormals[ 2 ].clone();
  14602. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  14603. quadA.vertexNormals[ 1 ].copy( vnm1 );
  14604. quadA.vertexNormals[ 2 ].copy( vnm2 );
  14605. quadB.vertexNormals[ 0 ].copy( vnm1 );
  14606. quadB.vertexNormals[ 3 ].copy( vnm2 );
  14607. }
  14608. if ( face.vertexColors.length === 4 ) {
  14609. vcm1 = face.vertexColors[ 0 ].clone();
  14610. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14611. vcm2 = face.vertexColors[ 2 ].clone();
  14612. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  14613. quadA.vertexColors[ 1 ].copy( vcm1 );
  14614. quadA.vertexColors[ 2 ].copy( vcm2 );
  14615. quadB.vertexColors[ 0 ].copy( vcm1 );
  14616. quadB.vertexColors[ 3 ].copy( vcm2 );
  14617. }
  14618. edge = 0;
  14619. } else {
  14620. vm1 = vb.clone();
  14621. vm1.lerpSelf( vc, 0.5 );
  14622. vm2 = vd.clone();
  14623. vm2.lerpSelf( va, 0.5 );
  14624. quadA.a = a;
  14625. quadA.b = b;
  14626. quadA.c = m1;
  14627. quadA.d = m2;
  14628. quadB.a = m2;
  14629. quadB.b = m1;
  14630. quadB.c = c;
  14631. quadB.d = d;
  14632. if ( face.vertexNormals.length === 4 ) {
  14633. vnm1 = face.vertexNormals[ 1 ].clone();
  14634. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14635. vnm2 = face.vertexNormals[ 3 ].clone();
  14636. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  14637. quadA.vertexNormals[ 2 ].copy( vnm1 );
  14638. quadA.vertexNormals[ 3 ].copy( vnm2 );
  14639. quadB.vertexNormals[ 0 ].copy( vnm2 );
  14640. quadB.vertexNormals[ 1 ].copy( vnm1 );
  14641. }
  14642. if ( face.vertexColors.length === 4 ) {
  14643. vcm1 = face.vertexColors[ 1 ].clone();
  14644. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14645. vcm2 = face.vertexColors[ 3 ].clone();
  14646. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  14647. quadA.vertexColors[ 2 ].copy( vcm1 );
  14648. quadA.vertexColors[ 3 ].copy( vcm2 );
  14649. quadB.vertexColors[ 0 ].copy( vcm2 );
  14650. quadB.vertexColors[ 1 ].copy( vcm1 );
  14651. }
  14652. edge = 1;
  14653. }
  14654. faces.push( quadA, quadB );
  14655. geometry.vertices.push( vm1, vm2 );
  14656. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  14657. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14658. if ( geometry.faceVertexUvs[ j ].length ) {
  14659. uvs = geometry.faceVertexUvs[ j ][ i ];
  14660. uvA = uvs[ 0 ];
  14661. uvB = uvs[ 1 ];
  14662. uvC = uvs[ 2 ];
  14663. uvD = uvs[ 3 ];
  14664. // AB + CD
  14665. if ( edge === 0 ) {
  14666. uvM1 = uvA.clone();
  14667. uvM1.lerpSelf( uvB, 0.5 );
  14668. uvM2 = uvC.clone();
  14669. uvM2.lerpSelf( uvD, 0.5 );
  14670. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  14671. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  14672. // BC + AD
  14673. } else {
  14674. uvM1 = uvB.clone();
  14675. uvM1.lerpSelf( uvC, 0.5 );
  14676. uvM2 = uvD.clone();
  14677. uvM2.lerpSelf( uvA, 0.5 );
  14678. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  14679. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  14680. }
  14681. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  14682. }
  14683. }
  14684. } else {
  14685. faces.push( face );
  14686. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14687. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14688. }
  14689. }
  14690. }
  14691. }
  14692. geometry.faces = faces;
  14693. geometry.faceVertexUvs = faceVertexUvs;
  14694. }
  14695. };
  14696. THREE.GeometryUtils.random = THREE.Math.random16;
  14697. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  14698. /**
  14699. * @author alteredq / http://alteredqualia.com/
  14700. * @author mrdoob / http://mrdoob.com/
  14701. */
  14702. THREE.ImageUtils = {
  14703. crossOrigin: 'anonymous',
  14704. loadTexture: function ( url, mapping, onLoad, onError ) {
  14705. var image = new Image();
  14706. var texture = new THREE.Texture( image, mapping );
  14707. var loader = new THREE.ImageLoader();
  14708. loader.addEventListener( 'load', function ( event ) {
  14709. texture.image = event.content;
  14710. texture.needsUpdate = true;
  14711. if ( onLoad ) onLoad( texture );
  14712. } );
  14713. loader.addEventListener( 'error', function ( event ) {
  14714. if ( onError ) onError( event.message );
  14715. } );
  14716. loader.crossOrigin = this.crossOrigin;
  14717. loader.load( url, image );
  14718. texture.sourceFile = url;
  14719. return texture;
  14720. },
  14721. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  14722. var texture = new THREE.CompressedTexture();
  14723. texture.mapping = mapping;
  14724. var request = new XMLHttpRequest();
  14725. request.onload = function () {
  14726. var buffer = request.response;
  14727. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14728. texture.format = dds.format;
  14729. texture.mipmaps = dds.mipmaps;
  14730. texture.image.width = dds.width;
  14731. texture.image.height = dds.height;
  14732. // gl.generateMipmap fails for compressed textures
  14733. // mipmaps must be embedded in the DDS file
  14734. // or texture filters must not use mipmapping
  14735. texture.generateMipmaps = false;
  14736. texture.needsUpdate = true;
  14737. if ( onLoad ) onLoad( texture );
  14738. }
  14739. request.onerror = onError;
  14740. request.open( 'GET', url, true );
  14741. request.responseType = "arraybuffer";
  14742. request.send( null );
  14743. return texture;
  14744. },
  14745. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  14746. var images = [];
  14747. images.loadCount = 0;
  14748. var texture = new THREE.Texture();
  14749. texture.image = images;
  14750. if ( mapping !== undefined ) texture.mapping = mapping;
  14751. // no flipping needed for cube textures
  14752. texture.flipY = false;
  14753. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14754. var cubeImage = new Image();
  14755. images[ i ] = cubeImage;
  14756. cubeImage.onload = function () {
  14757. images.loadCount += 1;
  14758. if ( images.loadCount === 6 ) {
  14759. texture.needsUpdate = true;
  14760. if ( onLoad ) onLoad();
  14761. }
  14762. };
  14763. cubeImage.onerror = onError;
  14764. cubeImage.crossOrigin = this.crossOrigin;
  14765. cubeImage.src = array[ i ];
  14766. }
  14767. return texture;
  14768. },
  14769. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  14770. var images = [];
  14771. images.loadCount = 0;
  14772. var texture = new THREE.CompressedTexture();
  14773. texture.image = images;
  14774. if ( mapping !== undefined ) texture.mapping = mapping;
  14775. // no flipping for cube textures
  14776. // (also flipping doesn't work for compressed textures )
  14777. texture.flipY = false;
  14778. // can't generate mipmaps for compressed textures
  14779. // mips must be embedded in DDS files
  14780. texture.generateMipmaps = false;
  14781. var generateCubeFaceCallback = function ( rq, img ) {
  14782. return function () {
  14783. var buffer = rq.response;
  14784. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14785. img.format = dds.format;
  14786. img.mipmaps = dds.mipmaps;
  14787. img.width = dds.width;
  14788. img.height = dds.height;
  14789. images.loadCount += 1;
  14790. if ( images.loadCount === 6 ) {
  14791. texture.format = dds.format;
  14792. texture.needsUpdate = true;
  14793. if ( onLoad ) onLoad();
  14794. }
  14795. }
  14796. }
  14797. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14798. var cubeImage = {};
  14799. images[ i ] = cubeImage;
  14800. var request = new XMLHttpRequest();
  14801. request.onload = generateCubeFaceCallback( request, cubeImage );
  14802. request.onerror = onError;
  14803. var url = array[ i ];
  14804. request.open( 'GET', url, true );
  14805. request.responseType = "arraybuffer";
  14806. request.send( null );
  14807. }
  14808. return texture;
  14809. },
  14810. parseDDS: function ( buffer, loadMipmaps ) {
  14811. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  14812. // Adapted from @toji's DDS utils
  14813. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  14814. // All values and structures referenced from:
  14815. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  14816. var DDS_MAGIC = 0x20534444;
  14817. var DDSD_CAPS = 0x1,
  14818. DDSD_HEIGHT = 0x2,
  14819. DDSD_WIDTH = 0x4,
  14820. DDSD_PITCH = 0x8,
  14821. DDSD_PIXELFORMAT = 0x1000,
  14822. DDSD_MIPMAPCOUNT = 0x20000,
  14823. DDSD_LINEARSIZE = 0x80000,
  14824. DDSD_DEPTH = 0x800000;
  14825. var DDSCAPS_COMPLEX = 0x8,
  14826. DDSCAPS_MIPMAP = 0x400000,
  14827. DDSCAPS_TEXTURE = 0x1000;
  14828. var DDSCAPS2_CUBEMAP = 0x200,
  14829. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  14830. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  14831. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  14832. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  14833. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  14834. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  14835. DDSCAPS2_VOLUME = 0x200000;
  14836. var DDPF_ALPHAPIXELS = 0x1,
  14837. DDPF_ALPHA = 0x2,
  14838. DDPF_FOURCC = 0x4,
  14839. DDPF_RGB = 0x40,
  14840. DDPF_YUV = 0x200,
  14841. DDPF_LUMINANCE = 0x20000;
  14842. function fourCCToInt32( value ) {
  14843. return value.charCodeAt(0) +
  14844. (value.charCodeAt(1) << 8) +
  14845. (value.charCodeAt(2) << 16) +
  14846. (value.charCodeAt(3) << 24);
  14847. }
  14848. function int32ToFourCC( value ) {
  14849. return String.fromCharCode(
  14850. value & 0xff,
  14851. (value >> 8) & 0xff,
  14852. (value >> 16) & 0xff,
  14853. (value >> 24) & 0xff
  14854. );
  14855. }
  14856. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  14857. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  14858. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  14859. var headerLengthInt = 31; // The header length in 32 bit ints
  14860. // Offsets into the header array
  14861. var off_magic = 0;
  14862. var off_size = 1;
  14863. var off_flags = 2;
  14864. var off_height = 3;
  14865. var off_width = 4;
  14866. var off_mipmapCount = 7;
  14867. var off_pfFlags = 20;
  14868. var off_pfFourCC = 21;
  14869. // Parse header
  14870. var header = new Int32Array( buffer, 0, headerLengthInt );
  14871. if ( header[ off_magic ] !== DDS_MAGIC ) {
  14872. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  14873. return dds;
  14874. }
  14875. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  14876. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  14877. return dds;
  14878. }
  14879. var blockBytes;
  14880. var fourCC = header[ off_pfFourCC ];
  14881. switch ( fourCC ) {
  14882. case FOURCC_DXT1:
  14883. blockBytes = 8;
  14884. dds.format = THREE.RGB_S3TC_DXT1_Format;
  14885. break;
  14886. case FOURCC_DXT3:
  14887. blockBytes = 16;
  14888. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  14889. break;
  14890. case FOURCC_DXT5:
  14891. blockBytes = 16;
  14892. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  14893. break;
  14894. default:
  14895. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  14896. return dds;
  14897. }
  14898. dds.mipmapCount = 1;
  14899. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  14900. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  14901. }
  14902. dds.width = header[ off_width ];
  14903. dds.height = header[ off_height ];
  14904. var dataOffset = header[ off_size ] + 4;
  14905. // Extract mipmaps buffers
  14906. var width = dds.width;
  14907. var height = dds.height;
  14908. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  14909. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  14910. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  14911. var mipmap = { "data": byteArray, "width": width, "height": height };
  14912. dds.mipmaps.push( mipmap );
  14913. dataOffset += dataLength;
  14914. width = Math.max( width * 0.5, 1 );
  14915. height = Math.max( height * 0.5, 1 );
  14916. }
  14917. return dds;
  14918. },
  14919. getNormalMap: function ( image, depth ) {
  14920. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  14921. var cross = function ( a, b ) {
  14922. 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 ] ];
  14923. }
  14924. var subtract = function ( a, b ) {
  14925. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  14926. }
  14927. var normalize = function ( a ) {
  14928. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  14929. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  14930. }
  14931. depth = depth | 1;
  14932. var width = image.width;
  14933. var height = image.height;
  14934. var canvas = document.createElement( 'canvas' );
  14935. canvas.width = width;
  14936. canvas.height = height;
  14937. var context = canvas.getContext( '2d' );
  14938. context.drawImage( image, 0, 0 );
  14939. var data = context.getImageData( 0, 0, width, height ).data;
  14940. var imageData = context.createImageData( width, height );
  14941. var output = imageData.data;
  14942. for ( var x = 0; x < width; x ++ ) {
  14943. for ( var y = 0; y < height; y ++ ) {
  14944. var ly = y - 1 < 0 ? 0 : y - 1;
  14945. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  14946. var lx = x - 1 < 0 ? 0 : x - 1;
  14947. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  14948. var points = [];
  14949. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  14950. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  14951. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  14952. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  14953. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  14954. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  14955. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  14956. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  14957. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  14958. var normals = [];
  14959. var num_points = points.length;
  14960. for ( var i = 0; i < num_points; i ++ ) {
  14961. var v1 = points[ i ];
  14962. var v2 = points[ ( i + 1 ) % num_points ];
  14963. v1 = subtract( v1, origin );
  14964. v2 = subtract( v2, origin );
  14965. normals.push( normalize( cross( v1, v2 ) ) );
  14966. }
  14967. var normal = [ 0, 0, 0 ];
  14968. for ( var i = 0; i < normals.length; i ++ ) {
  14969. normal[ 0 ] += normals[ i ][ 0 ];
  14970. normal[ 1 ] += normals[ i ][ 1 ];
  14971. normal[ 2 ] += normals[ i ][ 2 ];
  14972. }
  14973. normal[ 0 ] /= normals.length;
  14974. normal[ 1 ] /= normals.length;
  14975. normal[ 2 ] /= normals.length;
  14976. var idx = ( y * width + x ) * 4;
  14977. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14978. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14979. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  14980. output[ idx + 3 ] = 255;
  14981. }
  14982. }
  14983. context.putImageData( imageData, 0, 0 );
  14984. return canvas;
  14985. },
  14986. generateDataTexture: function ( width, height, color ) {
  14987. var size = width * height;
  14988. var data = new Uint8Array( 3 * size );
  14989. var r = Math.floor( color.r * 255 );
  14990. var g = Math.floor( color.g * 255 );
  14991. var b = Math.floor( color.b * 255 );
  14992. for ( var i = 0; i < size; i ++ ) {
  14993. data[ i * 3 ] = r;
  14994. data[ i * 3 + 1 ] = g;
  14995. data[ i * 3 + 2 ] = b;
  14996. }
  14997. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  14998. texture.needsUpdate = true;
  14999. return texture;
  15000. }
  15001. };
  15002. /**
  15003. * @author alteredq / http://alteredqualia.com/
  15004. */
  15005. THREE.SceneUtils = {
  15006. createMultiMaterialObject: function ( geometry, materials ) {
  15007. var group = new THREE.Object3D();
  15008. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15009. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15010. }
  15011. return group;
  15012. },
  15013. detach : function ( child, parent, scene ) {
  15014. child.applyMatrix( parent.matrixWorld );
  15015. parent.remove( child );
  15016. scene.add( child );
  15017. },
  15018. attach: function ( child, scene, parent ) {
  15019. var matrixWorldInverse = new THREE.Matrix4();
  15020. matrixWorldInverse.getInverse( parent.matrixWorld );
  15021. child.applyMatrix( matrixWorldInverse );
  15022. scene.remove( child );
  15023. parent.add( child );
  15024. }
  15025. };
  15026. /**
  15027. * @author alteredq / http://alteredqualia.com/
  15028. * @author mrdoob / http://mrdoob.com/
  15029. *
  15030. * ShaderUtils currently contains:
  15031. *
  15032. * fresnel
  15033. * normal
  15034. * cube
  15035. *
  15036. */
  15037. THREE.ShaderUtils = {
  15038. lib: {
  15039. /* -------------------------------------------------------------------------
  15040. // Fresnel shader
  15041. // - based on Nvidia Cg tutorial
  15042. ------------------------------------------------------------------------- */
  15043. 'fresnel': {
  15044. uniforms: {
  15045. "mRefractionRatio": { type: "f", value: 1.02 },
  15046. "mFresnelBias": { type: "f", value: 0.1 },
  15047. "mFresnelPower": { type: "f", value: 2.0 },
  15048. "mFresnelScale": { type: "f", value: 1.0 },
  15049. "tCube": { type: "t", value: null }
  15050. },
  15051. fragmentShader: [
  15052. "uniform samplerCube tCube;",
  15053. "varying vec3 vReflect;",
  15054. "varying vec3 vRefract[3];",
  15055. "varying float vReflectionFactor;",
  15056. "void main() {",
  15057. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15058. "vec4 refractedColor = vec4( 1.0 );",
  15059. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  15060. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  15061. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  15062. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  15063. "}"
  15064. ].join("\n"),
  15065. vertexShader: [
  15066. "uniform float mRefractionRatio;",
  15067. "uniform float mFresnelBias;",
  15068. "uniform float mFresnelScale;",
  15069. "uniform float mFresnelPower;",
  15070. "varying vec3 vReflect;",
  15071. "varying vec3 vRefract[3];",
  15072. "varying float vReflectionFactor;",
  15073. "void main() {",
  15074. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  15075. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15076. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  15077. "vec3 I = worldPosition.xyz - cameraPosition;",
  15078. "vReflect = reflect( I, worldNormal );",
  15079. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  15080. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  15081. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  15082. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  15083. "gl_Position = projectionMatrix * mvPosition;",
  15084. "}"
  15085. ].join("\n")
  15086. },
  15087. /* -------------------------------------------------------------------------
  15088. // Normal map shader
  15089. // - Blinn-Phong
  15090. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  15091. // - point and directional lights (use with "lights: true" material option)
  15092. ------------------------------------------------------------------------- */
  15093. 'normal' : {
  15094. uniforms: THREE.UniformsUtils.merge( [
  15095. THREE.UniformsLib[ "fog" ],
  15096. THREE.UniformsLib[ "lights" ],
  15097. THREE.UniformsLib[ "shadowmap" ],
  15098. {
  15099. "enableAO" : { type: "i", value: 0 },
  15100. "enableDiffuse" : { type: "i", value: 0 },
  15101. "enableSpecular" : { type: "i", value: 0 },
  15102. "enableReflection": { type: "i", value: 0 },
  15103. "enableDisplacement": { type: "i", value: 0 },
  15104. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  15105. "tDiffuse" : { type: "t", value: null },
  15106. "tCube" : { type: "t", value: null },
  15107. "tNormal" : { type: "t", value: null },
  15108. "tSpecular" : { type: "t", value: null },
  15109. "tAO" : { type: "t", value: null },
  15110. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15111. "uDisplacementBias": { type: "f", value: 0.0 },
  15112. "uDisplacementScale": { type: "f", value: 1.0 },
  15113. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15114. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  15115. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15116. "uShininess": { type: "f", value: 30 },
  15117. "uOpacity": { type: "f", value: 1 },
  15118. "useRefract": { type: "i", value: 0 },
  15119. "uRefractionRatio": { type: "f", value: 0.98 },
  15120. "uReflectivity": { type: "f", value: 0.5 },
  15121. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  15122. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15123. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  15124. }
  15125. ] ),
  15126. fragmentShader: [
  15127. "uniform vec3 uAmbientColor;",
  15128. "uniform vec3 uDiffuseColor;",
  15129. "uniform vec3 uSpecularColor;",
  15130. "uniform float uShininess;",
  15131. "uniform float uOpacity;",
  15132. "uniform bool enableDiffuse;",
  15133. "uniform bool enableSpecular;",
  15134. "uniform bool enableAO;",
  15135. "uniform bool enableReflection;",
  15136. "uniform sampler2D tDiffuse;",
  15137. "uniform sampler2D tNormal;",
  15138. "uniform sampler2D tSpecular;",
  15139. "uniform sampler2D tAO;",
  15140. "uniform samplerCube tCube;",
  15141. "uniform vec2 uNormalScale;",
  15142. "uniform bool useRefract;",
  15143. "uniform float uRefractionRatio;",
  15144. "uniform float uReflectivity;",
  15145. "varying vec3 vTangent;",
  15146. "varying vec3 vBinormal;",
  15147. "varying vec3 vNormal;",
  15148. "varying vec2 vUv;",
  15149. "uniform vec3 ambientLightColor;",
  15150. "#if MAX_DIR_LIGHTS > 0",
  15151. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  15152. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  15153. "#endif",
  15154. "#if MAX_HEMI_LIGHTS > 0",
  15155. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  15156. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  15157. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  15158. "#endif",
  15159. "#if MAX_POINT_LIGHTS > 0",
  15160. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  15161. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  15162. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  15163. "#endif",
  15164. "#if MAX_SPOT_LIGHTS > 0",
  15165. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  15166. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  15167. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  15168. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  15169. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  15170. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  15171. "#endif",
  15172. "#ifdef WRAP_AROUND",
  15173. "uniform vec3 wrapRGB;",
  15174. "#endif",
  15175. "varying vec3 vWorldPosition;",
  15176. "varying vec3 vViewPosition;",
  15177. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  15178. THREE.ShaderChunk[ "fog_pars_fragment" ],
  15179. "void main() {",
  15180. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  15181. "vec3 specularTex = vec3( 1.0 );",
  15182. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  15183. "normalTex.xy *= uNormalScale;",
  15184. "normalTex = normalize( normalTex );",
  15185. "if( enableDiffuse ) {",
  15186. "#ifdef GAMMA_INPUT",
  15187. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  15188. "texelColor.xyz *= texelColor.xyz;",
  15189. "gl_FragColor = gl_FragColor * texelColor;",
  15190. "#else",
  15191. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  15192. "#endif",
  15193. "}",
  15194. "if( enableAO ) {",
  15195. "#ifdef GAMMA_INPUT",
  15196. "vec4 aoColor = texture2D( tAO, vUv );",
  15197. "aoColor.xyz *= aoColor.xyz;",
  15198. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  15199. "#else",
  15200. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  15201. "#endif",
  15202. "}",
  15203. "if( enableSpecular )",
  15204. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  15205. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  15206. "vec3 finalNormal = tsb * normalTex;",
  15207. "#ifdef FLIP_SIDED",
  15208. "finalNormal = -finalNormal;",
  15209. "#endif",
  15210. "vec3 normal = normalize( finalNormal );",
  15211. "vec3 viewPosition = normalize( vViewPosition );",
  15212. // point lights
  15213. "#if MAX_POINT_LIGHTS > 0",
  15214. "vec3 pointDiffuse = vec3( 0.0 );",
  15215. "vec3 pointSpecular = vec3( 0.0 );",
  15216. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  15217. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  15218. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  15219. "float pointDistance = 1.0;",
  15220. "if ( pointLightDistance[ i ] > 0.0 )",
  15221. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  15222. "pointVector = normalize( pointVector );",
  15223. // diffuse
  15224. "#ifdef WRAP_AROUND",
  15225. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  15226. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  15227. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  15228. "#else",
  15229. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  15230. "#endif",
  15231. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  15232. // specular
  15233. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  15234. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  15235. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  15236. "#ifdef PHYSICALLY_BASED_SHADING",
  15237. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15238. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15239. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  15240. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  15241. "#else",
  15242. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  15243. "#endif",
  15244. "}",
  15245. "#endif",
  15246. // spot lights
  15247. "#if MAX_SPOT_LIGHTS > 0",
  15248. "vec3 spotDiffuse = vec3( 0.0 );",
  15249. "vec3 spotSpecular = vec3( 0.0 );",
  15250. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  15251. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  15252. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  15253. "float spotDistance = 1.0;",
  15254. "if ( spotLightDistance[ i ] > 0.0 )",
  15255. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  15256. "spotVector = normalize( spotVector );",
  15257. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  15258. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  15259. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  15260. // diffuse
  15261. "#ifdef WRAP_AROUND",
  15262. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  15263. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  15264. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  15265. "#else",
  15266. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  15267. "#endif",
  15268. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  15269. // specular
  15270. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  15271. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  15272. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  15273. "#ifdef PHYSICALLY_BASED_SHADING",
  15274. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15275. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15276. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  15277. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  15278. "#else",
  15279. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  15280. "#endif",
  15281. "}",
  15282. "}",
  15283. "#endif",
  15284. // directional lights
  15285. "#if MAX_DIR_LIGHTS > 0",
  15286. "vec3 dirDiffuse = vec3( 0.0 );",
  15287. "vec3 dirSpecular = vec3( 0.0 );",
  15288. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  15289. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  15290. "vec3 dirVector = normalize( lDirection.xyz );",
  15291. // diffuse
  15292. "#ifdef WRAP_AROUND",
  15293. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  15294. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  15295. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  15296. "#else",
  15297. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  15298. "#endif",
  15299. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  15300. // specular
  15301. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  15302. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  15303. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  15304. "#ifdef PHYSICALLY_BASED_SHADING",
  15305. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15306. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15307. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  15308. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  15309. "#else",
  15310. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  15311. "#endif",
  15312. "}",
  15313. "#endif",
  15314. // hemisphere lights
  15315. "#if MAX_HEMI_LIGHTS > 0",
  15316. "vec3 hemiDiffuse = vec3( 0.0 );",
  15317. "vec3 hemiSpecular = vec3( 0.0 );" ,
  15318. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  15319. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  15320. "vec3 lVector = normalize( lDirection.xyz );",
  15321. // diffuse
  15322. "float dotProduct = dot( normal, lVector );",
  15323. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  15324. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  15325. "hemiDiffuse += uDiffuseColor * hemiColor;",
  15326. // specular (sky light)
  15327. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  15328. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  15329. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  15330. // specular (ground light)
  15331. "vec3 lVectorGround = -lVector;",
  15332. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  15333. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  15334. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  15335. "#ifdef PHYSICALLY_BASED_SHADING",
  15336. "float dotProductGround = dot( normal, lVectorGround );",
  15337. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15338. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15339. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  15340. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  15341. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  15342. "#else",
  15343. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  15344. "#endif",
  15345. "}",
  15346. "#endif",
  15347. // all lights contribution summation
  15348. "vec3 totalDiffuse = vec3( 0.0 );",
  15349. "vec3 totalSpecular = vec3( 0.0 );",
  15350. "#if MAX_DIR_LIGHTS > 0",
  15351. "totalDiffuse += dirDiffuse;",
  15352. "totalSpecular += dirSpecular;",
  15353. "#endif",
  15354. "#if MAX_HEMI_LIGHTS > 0",
  15355. "totalDiffuse += hemiDiffuse;",
  15356. "totalSpecular += hemiSpecular;",
  15357. "#endif",
  15358. "#if MAX_POINT_LIGHTS > 0",
  15359. "totalDiffuse += pointDiffuse;",
  15360. "totalSpecular += pointSpecular;",
  15361. "#endif",
  15362. "#if MAX_SPOT_LIGHTS > 0",
  15363. "totalDiffuse += spotDiffuse;",
  15364. "totalSpecular += spotSpecular;",
  15365. "#endif",
  15366. "#ifdef METAL",
  15367. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  15368. "#else",
  15369. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  15370. "#endif",
  15371. "if ( enableReflection ) {",
  15372. "vec3 vReflect;",
  15373. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  15374. "if ( useRefract ) {",
  15375. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  15376. "} else {",
  15377. "vReflect = reflect( cameraToVertex, normal );",
  15378. "}",
  15379. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15380. "#ifdef GAMMA_INPUT",
  15381. "cubeColor.xyz *= cubeColor.xyz;",
  15382. "#endif",
  15383. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  15384. "}",
  15385. THREE.ShaderChunk[ "shadowmap_fragment" ],
  15386. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  15387. THREE.ShaderChunk[ "fog_fragment" ],
  15388. "}"
  15389. ].join("\n"),
  15390. vertexShader: [
  15391. "attribute vec4 tangent;",
  15392. "uniform vec2 uOffset;",
  15393. "uniform vec2 uRepeat;",
  15394. "uniform bool enableDisplacement;",
  15395. "#ifdef VERTEX_TEXTURES",
  15396. "uniform sampler2D tDisplacement;",
  15397. "uniform float uDisplacementScale;",
  15398. "uniform float uDisplacementBias;",
  15399. "#endif",
  15400. "varying vec3 vTangent;",
  15401. "varying vec3 vBinormal;",
  15402. "varying vec3 vNormal;",
  15403. "varying vec2 vUv;",
  15404. "varying vec3 vWorldPosition;",
  15405. "varying vec3 vViewPosition;",
  15406. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  15407. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  15408. "void main() {",
  15409. THREE.ShaderChunk[ "skinbase_vertex" ],
  15410. THREE.ShaderChunk[ "skinnormal_vertex" ],
  15411. // normal, tangent and binormal vectors
  15412. "#ifdef USE_SKINNING",
  15413. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  15414. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  15415. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  15416. "#else",
  15417. "vNormal = normalize( normalMatrix * normal );",
  15418. "vTangent = normalize( normalMatrix * tangent.xyz );",
  15419. "#endif",
  15420. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  15421. "vUv = uv * uRepeat + uOffset;",
  15422. // displacement mapping
  15423. "vec3 displacedPosition;",
  15424. "#ifdef VERTEX_TEXTURES",
  15425. "if ( enableDisplacement ) {",
  15426. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  15427. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  15428. "displacedPosition = position + normalize( normal ) * df;",
  15429. "} else {",
  15430. "#ifdef USE_SKINNING",
  15431. "vec4 skinVertex = vec4( position, 1.0 );",
  15432. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15433. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15434. "displacedPosition = skinned.xyz;",
  15435. "#else",
  15436. "displacedPosition = position;",
  15437. "#endif",
  15438. "}",
  15439. "#else",
  15440. "#ifdef USE_SKINNING",
  15441. "vec4 skinVertex = vec4( position, 1.0 );",
  15442. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15443. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15444. "displacedPosition = skinned.xyz;",
  15445. "#else",
  15446. "displacedPosition = position;",
  15447. "#endif",
  15448. "#endif",
  15449. //
  15450. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  15451. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  15452. "gl_Position = projectionMatrix * mvPosition;",
  15453. //
  15454. "vWorldPosition = worldPosition.xyz;",
  15455. "vViewPosition = -mvPosition.xyz;",
  15456. // shadows
  15457. "#ifdef USE_SHADOWMAP",
  15458. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  15459. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  15460. "}",
  15461. "#endif",
  15462. "}"
  15463. ].join("\n")
  15464. },
  15465. /* -------------------------------------------------------------------------
  15466. // Cube map shader
  15467. ------------------------------------------------------------------------- */
  15468. 'cube': {
  15469. uniforms: { "tCube": { type: "t", value: null },
  15470. "tFlip": { type: "f", value: -1 } },
  15471. vertexShader: [
  15472. "varying vec3 vWorldPosition;",
  15473. "void main() {",
  15474. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15475. "vWorldPosition = worldPosition.xyz;",
  15476. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  15477. "}"
  15478. ].join("\n"),
  15479. fragmentShader: [
  15480. "uniform samplerCube tCube;",
  15481. "uniform float tFlip;",
  15482. "varying vec3 vWorldPosition;",
  15483. "void main() {",
  15484. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  15485. "}"
  15486. ].join("\n")
  15487. }
  15488. }
  15489. };
  15490. /**
  15491. * @author zz85 / http://www.lab4games.net/zz85/blog
  15492. * @author alteredq / http://alteredqualia.com/
  15493. *
  15494. * For Text operations in three.js (See TextGeometry)
  15495. *
  15496. * It uses techniques used in:
  15497. *
  15498. * typeface.js and canvastext
  15499. * For converting fonts and rendering with javascript
  15500. * http://typeface.neocracy.org
  15501. *
  15502. * Triangulation ported from AS3
  15503. * Simple Polygon Triangulation
  15504. * http://actionsnippet.com/?p=1462
  15505. *
  15506. * A Method to triangulate shapes with holes
  15507. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15508. *
  15509. */
  15510. THREE.FontUtils = {
  15511. faces : {},
  15512. // Just for now. face[weight][style]
  15513. face : "helvetiker",
  15514. weight: "normal",
  15515. style : "normal",
  15516. size : 150,
  15517. divisions : 10,
  15518. getFace : function() {
  15519. return this.faces[ this.face ][ this.weight ][ this.style ];
  15520. },
  15521. loadFace : function( data ) {
  15522. var family = data.familyName.toLowerCase();
  15523. var ThreeFont = this;
  15524. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15525. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15526. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15527. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15528. return data;
  15529. },
  15530. drawText : function( text ) {
  15531. var characterPts = [], allPts = [];
  15532. // RenderText
  15533. var i, p,
  15534. face = this.getFace(),
  15535. scale = this.size / face.resolution,
  15536. offset = 0,
  15537. chars = String( text ).split( '' ),
  15538. length = chars.length;
  15539. var fontPaths = [];
  15540. for ( i = 0; i < length; i ++ ) {
  15541. var path = new THREE.Path();
  15542. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15543. offset += ret.offset;
  15544. fontPaths.push( ret.path );
  15545. }
  15546. // get the width
  15547. var width = offset / 2;
  15548. //
  15549. // for ( p = 0; p < allPts.length; p++ ) {
  15550. //
  15551. // allPts[ p ].x -= width;
  15552. //
  15553. // }
  15554. //var extract = this.extractPoints( allPts, characterPts );
  15555. //extract.contour = allPts;
  15556. //extract.paths = fontPaths;
  15557. //extract.offset = width;
  15558. return { paths : fontPaths, offset : width };
  15559. },
  15560. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15561. var pts = [];
  15562. var i, i2, divisions,
  15563. outline, action, length,
  15564. scaleX, scaleY,
  15565. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15566. laste,
  15567. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15568. if ( !glyph ) return;
  15569. if ( glyph.o ) {
  15570. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15571. length = outline.length;
  15572. scaleX = scale;
  15573. scaleY = scale;
  15574. for ( i = 0; i < length; ) {
  15575. action = outline[ i ++ ];
  15576. //console.log( action );
  15577. switch( action ) {
  15578. case 'm':
  15579. // Move To
  15580. x = outline[ i++ ] * scaleX + offset;
  15581. y = outline[ i++ ] * scaleY;
  15582. path.moveTo( x, y );
  15583. break;
  15584. case 'l':
  15585. // Line To
  15586. x = outline[ i++ ] * scaleX + offset;
  15587. y = outline[ i++ ] * scaleY;
  15588. path.lineTo(x,y);
  15589. break;
  15590. case 'q':
  15591. // QuadraticCurveTo
  15592. cpx = outline[ i++ ] * scaleX + offset;
  15593. cpy = outline[ i++ ] * scaleY;
  15594. cpx1 = outline[ i++ ] * scaleX + offset;
  15595. cpy1 = outline[ i++ ] * scaleY;
  15596. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15597. laste = pts[ pts.length - 1 ];
  15598. if ( laste ) {
  15599. cpx0 = laste.x;
  15600. cpy0 = laste.y;
  15601. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15602. var t = i2 / divisions;
  15603. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15604. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15605. }
  15606. }
  15607. break;
  15608. case 'b':
  15609. // Cubic Bezier Curve
  15610. cpx = outline[ i++ ] * scaleX + offset;
  15611. cpy = outline[ i++ ] * scaleY;
  15612. cpx1 = outline[ i++ ] * scaleX + offset;
  15613. cpy1 = outline[ i++ ] * -scaleY;
  15614. cpx2 = outline[ i++ ] * scaleX + offset;
  15615. cpy2 = outline[ i++ ] * -scaleY;
  15616. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15617. laste = pts[ pts.length - 1 ];
  15618. if ( laste ) {
  15619. cpx0 = laste.x;
  15620. cpy0 = laste.y;
  15621. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15622. var t = i2 / divisions;
  15623. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15624. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15625. }
  15626. }
  15627. break;
  15628. }
  15629. }
  15630. }
  15631. return { offset: glyph.ha*scale, path:path};
  15632. }
  15633. };
  15634. THREE.FontUtils.generateShapes = function( text, parameters ) {
  15635. // Parameters
  15636. parameters = parameters || {};
  15637. var size = parameters.size !== undefined ? parameters.size : 100;
  15638. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  15639. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  15640. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  15641. var style = parameters.style !== undefined ? parameters.style : "normal";
  15642. THREE.FontUtils.size = size;
  15643. THREE.FontUtils.divisions = curveSegments;
  15644. THREE.FontUtils.face = font;
  15645. THREE.FontUtils.weight = weight;
  15646. THREE.FontUtils.style = style;
  15647. // Get a Font data json object
  15648. var data = THREE.FontUtils.drawText( text );
  15649. var paths = data.paths;
  15650. var shapes = [];
  15651. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15652. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15653. }
  15654. return shapes;
  15655. };
  15656. /**
  15657. * This code is a quick port of code written in C++ which was submitted to
  15658. * flipcode.com by John W. Ratcliff // July 22, 2000
  15659. * See original code and more information here:
  15660. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15661. *
  15662. * ported to actionscript by Zevan Rosser
  15663. * www.actionsnippet.com
  15664. *
  15665. * ported to javascript by Joshua Koo
  15666. * http://www.lab4games.net/zz85/blog
  15667. *
  15668. */
  15669. ( function( namespace ) {
  15670. var EPSILON = 0.0000000001;
  15671. // takes in an contour array and returns
  15672. var process = function( contour, indices ) {
  15673. var n = contour.length;
  15674. if ( n < 3 ) return null;
  15675. var result = [],
  15676. verts = [],
  15677. vertIndices = [];
  15678. /* we want a counter-clockwise polygon in verts */
  15679. var u, v, w;
  15680. if ( area( contour ) > 0.0 ) {
  15681. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15682. } else {
  15683. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15684. }
  15685. var nv = n;
  15686. /* remove nv - 2 vertices, creating 1 triangle every time */
  15687. var count = 2 * nv; /* error detection */
  15688. for( v = nv - 1; nv > 2; ) {
  15689. /* if we loop, it is probably a non-simple polygon */
  15690. if ( ( count-- ) <= 0 ) {
  15691. //** Triangulate: ERROR - probable bad polygon!
  15692. //throw ( "Warning, unable to triangulate polygon!" );
  15693. //return null;
  15694. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15695. console.log( "Warning, unable to triangulate polygon!" );
  15696. if ( indices ) return vertIndices;
  15697. return result;
  15698. }
  15699. /* three consecutive vertices in current polygon, <u,v,w> */
  15700. u = v; if ( nv <= u ) u = 0; /* previous */
  15701. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15702. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15703. if ( snip( contour, u, v, w, nv, verts ) ) {
  15704. var a, b, c, s, t;
  15705. /* true names of the vertices */
  15706. a = verts[ u ];
  15707. b = verts[ v ];
  15708. c = verts[ w ];
  15709. /* output Triangle */
  15710. /*
  15711. result.push( contour[ a ] );
  15712. result.push( contour[ b ] );
  15713. result.push( contour[ c ] );
  15714. */
  15715. result.push( [ contour[ a ],
  15716. contour[ b ],
  15717. contour[ c ] ] );
  15718. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15719. /* remove v from the remaining polygon */
  15720. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15721. verts[ s ] = verts[ t ];
  15722. }
  15723. nv--;
  15724. /* reset error detection counter */
  15725. count = 2 * nv;
  15726. }
  15727. }
  15728. if ( indices ) return vertIndices;
  15729. return result;
  15730. };
  15731. // calculate area of the contour polygon
  15732. var area = function ( contour ) {
  15733. var n = contour.length;
  15734. var a = 0.0;
  15735. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15736. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15737. }
  15738. return a * 0.5;
  15739. };
  15740. // see if p is inside triangle abc
  15741. var insideTriangle = function( ax, ay,
  15742. bx, by,
  15743. cx, cy,
  15744. px, py ) {
  15745. var aX, aY, bX, bY;
  15746. var cX, cY, apx, apy;
  15747. var bpx, bpy, cpx, cpy;
  15748. var cCROSSap, bCROSScp, aCROSSbp;
  15749. aX = cx - bx; aY = cy - by;
  15750. bX = ax - cx; bY = ay - cy;
  15751. cX = bx - ax; cY = by - ay;
  15752. apx= px -ax; apy= py - ay;
  15753. bpx= px - bx; bpy= py - by;
  15754. cpx= px - cx; cpy= py - cy;
  15755. aCROSSbp = aX*bpy - aY*bpx;
  15756. cCROSSap = cX*apy - cY*apx;
  15757. bCROSScp = bX*cpy - bY*cpx;
  15758. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  15759. };
  15760. var snip = function ( contour, u, v, w, n, verts ) {
  15761. var p;
  15762. var ax, ay, bx, by;
  15763. var cx, cy, px, py;
  15764. ax = contour[ verts[ u ] ].x;
  15765. ay = contour[ verts[ u ] ].y;
  15766. bx = contour[ verts[ v ] ].x;
  15767. by = contour[ verts[ v ] ].y;
  15768. cx = contour[ verts[ w ] ].x;
  15769. cy = contour[ verts[ w ] ].y;
  15770. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  15771. for ( p = 0; p < n; p++ ) {
  15772. if( (p == u) || (p == v) || (p == w) ) continue;
  15773. px = contour[ verts[ p ] ].x
  15774. py = contour[ verts[ p ] ].y
  15775. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  15776. }
  15777. return true;
  15778. };
  15779. namespace.Triangulate = process;
  15780. namespace.Triangulate.area = area;
  15781. return namespace;
  15782. })(THREE.FontUtils);
  15783. // To use the typeface.js face files, hook up the API
  15784. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  15785. * @author zz85 / http://www.lab4games.net/zz85/blog
  15786. * Extensible curve object
  15787. *
  15788. * Some common of Curve methods
  15789. * .getPoint(t), getTangent(t)
  15790. * .getPointAt(u), getTagentAt(u)
  15791. * .getPoints(), .getSpacedPoints()
  15792. * .getLength()
  15793. * .updateArcLengths()
  15794. *
  15795. * This file contains following classes:
  15796. *
  15797. * -- 2d classes --
  15798. * THREE.Curve
  15799. * THREE.LineCurve
  15800. * THREE.QuadraticBezierCurve
  15801. * THREE.CubicBezierCurve
  15802. * THREE.SplineCurve
  15803. * THREE.ArcCurve
  15804. * THREE.EllipseCurve
  15805. *
  15806. * -- 3d classes --
  15807. * THREE.LineCurve3
  15808. * THREE.QuadraticBezierCurve3
  15809. * THREE.CubicBezierCurve3
  15810. * THREE.SplineCurve3
  15811. * THREE.ClosedSplineCurve3
  15812. *
  15813. * A series of curves can be represented as a THREE.CurvePath
  15814. *
  15815. **/
  15816. /**************************************************************
  15817. * Abstract Curve base class
  15818. **************************************************************/
  15819. THREE.Curve = function () {
  15820. };
  15821. // Virtual base class method to overwrite and implement in subclasses
  15822. // - t [0 .. 1]
  15823. THREE.Curve.prototype.getPoint = function ( t ) {
  15824. console.log( "Warning, getPoint() not implemented!" );
  15825. return null;
  15826. };
  15827. // Get point at relative position in curve according to arc length
  15828. // - u [0 .. 1]
  15829. THREE.Curve.prototype.getPointAt = function ( u ) {
  15830. var t = this.getUtoTmapping( u );
  15831. return this.getPoint( t );
  15832. };
  15833. // Get sequence of points using getPoint( t )
  15834. THREE.Curve.prototype.getPoints = function ( divisions ) {
  15835. if ( !divisions ) divisions = 5;
  15836. var d, pts = [];
  15837. for ( d = 0; d <= divisions; d ++ ) {
  15838. pts.push( this.getPoint( d / divisions ) );
  15839. }
  15840. return pts;
  15841. };
  15842. // Get sequence of points using getPointAt( u )
  15843. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  15844. if ( !divisions ) divisions = 5;
  15845. var d, pts = [];
  15846. for ( d = 0; d <= divisions; d ++ ) {
  15847. pts.push( this.getPointAt( d / divisions ) );
  15848. }
  15849. return pts;
  15850. };
  15851. // Get total curve arc length
  15852. THREE.Curve.prototype.getLength = function () {
  15853. var lengths = this.getLengths();
  15854. return lengths[ lengths.length - 1 ];
  15855. };
  15856. // Get list of cumulative segment lengths
  15857. THREE.Curve.prototype.getLengths = function ( divisions ) {
  15858. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  15859. if ( this.cacheArcLengths
  15860. && ( this.cacheArcLengths.length == divisions + 1 )
  15861. && !this.needsUpdate) {
  15862. //console.log( "cached", this.cacheArcLengths );
  15863. return this.cacheArcLengths;
  15864. }
  15865. this.needsUpdate = false;
  15866. var cache = [];
  15867. var current, last = this.getPoint( 0 );
  15868. var p, sum = 0;
  15869. cache.push( 0 );
  15870. for ( p = 1; p <= divisions; p ++ ) {
  15871. current = this.getPoint ( p / divisions );
  15872. sum += current.distanceTo( last );
  15873. cache.push( sum );
  15874. last = current;
  15875. }
  15876. this.cacheArcLengths = cache;
  15877. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  15878. };
  15879. THREE.Curve.prototype.updateArcLengths = function() {
  15880. this.needsUpdate = true;
  15881. this.getLengths();
  15882. };
  15883. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  15884. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  15885. var arcLengths = this.getLengths();
  15886. var i = 0, il = arcLengths.length;
  15887. var targetArcLength; // The targeted u distance value to get
  15888. if ( distance ) {
  15889. targetArcLength = distance;
  15890. } else {
  15891. targetArcLength = u * arcLengths[ il - 1 ];
  15892. }
  15893. //var time = Date.now();
  15894. // binary search for the index with largest value smaller than target u distance
  15895. var low = 0, high = il - 1, comparison;
  15896. while ( low <= high ) {
  15897. 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
  15898. comparison = arcLengths[ i ] - targetArcLength;
  15899. if ( comparison < 0 ) {
  15900. low = i + 1;
  15901. continue;
  15902. } else if ( comparison > 0 ) {
  15903. high = i - 1;
  15904. continue;
  15905. } else {
  15906. high = i;
  15907. break;
  15908. // DONE
  15909. }
  15910. }
  15911. i = high;
  15912. //console.log('b' , i, low, high, Date.now()- time);
  15913. if ( arcLengths[ i ] == targetArcLength ) {
  15914. var t = i / ( il - 1 );
  15915. return t;
  15916. }
  15917. // we could get finer grain at lengths, or use simple interpolatation between two points
  15918. var lengthBefore = arcLengths[ i ];
  15919. var lengthAfter = arcLengths[ i + 1 ];
  15920. var segmentLength = lengthAfter - lengthBefore;
  15921. // determine where we are between the 'before' and 'after' points
  15922. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  15923. // add that fractional amount to t
  15924. var t = ( i + segmentFraction ) / ( il -1 );
  15925. return t;
  15926. };
  15927. // In 2D space, there are actually 2 normal vectors,
  15928. // and in 3D space, infinte
  15929. // TODO this should be depreciated.
  15930. THREE.Curve.prototype.getNormalVector = function( t ) {
  15931. var vec = this.getTangent( t );
  15932. return new THREE.Vector2( -vec.y , vec.x );
  15933. };
  15934. // Returns a unit vector tangent at t
  15935. // In case any sub curve does not implement its tangent / normal finding,
  15936. // we get 2 points with a small delta and find a gradient of the 2 points
  15937. // which seems to make a reasonable approximation
  15938. THREE.Curve.prototype.getTangent = function( t ) {
  15939. var delta = 0.0001;
  15940. var t1 = t - delta;
  15941. var t2 = t + delta;
  15942. // Capping in case of danger
  15943. if ( t1 < 0 ) t1 = 0;
  15944. if ( t2 > 1 ) t2 = 1;
  15945. var pt1 = this.getPoint( t1 );
  15946. var pt2 = this.getPoint( t2 );
  15947. var vec = pt2.clone().subSelf(pt1);
  15948. return vec.normalize();
  15949. };
  15950. THREE.Curve.prototype.getTangentAt = function ( u ) {
  15951. var t = this.getUtoTmapping( u );
  15952. return this.getTangent( t );
  15953. };
  15954. /**************************************************************
  15955. * Line
  15956. **************************************************************/
  15957. THREE.LineCurve = function ( v1, v2 ) {
  15958. this.v1 = v1;
  15959. this.v2 = v2;
  15960. };
  15961. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  15962. THREE.LineCurve.prototype.getPoint = function ( t ) {
  15963. var point = this.v2.clone().subSelf(this.v1);
  15964. point.multiplyScalar( t ).addSelf( this.v1 );
  15965. return point;
  15966. };
  15967. // Line curve is linear, so we can overwrite default getPointAt
  15968. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  15969. return this.getPoint( u );
  15970. };
  15971. THREE.LineCurve.prototype.getTangent = function( t ) {
  15972. var tangent = this.v2.clone().subSelf(this.v1);
  15973. return tangent.normalize();
  15974. };
  15975. /**************************************************************
  15976. * Quadratic Bezier curve
  15977. **************************************************************/
  15978. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  15979. this.v0 = v0;
  15980. this.v1 = v1;
  15981. this.v2 = v2;
  15982. };
  15983. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15984. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  15985. var tx, ty;
  15986. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15987. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15988. return new THREE.Vector2( tx, ty );
  15989. };
  15990. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  15991. var tx, ty;
  15992. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  15993. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  15994. // returns unit vector
  15995. var tangent = new THREE.Vector2( tx, ty );
  15996. tangent.normalize();
  15997. return tangent;
  15998. };
  15999. /**************************************************************
  16000. * Cubic Bezier curve
  16001. **************************************************************/
  16002. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16003. this.v0 = v0;
  16004. this.v1 = v1;
  16005. this.v2 = v2;
  16006. this.v3 = v3;
  16007. };
  16008. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16009. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16010. var tx, ty;
  16011. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16012. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16013. return new THREE.Vector2( tx, ty );
  16014. };
  16015. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16016. var tx, ty;
  16017. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16018. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16019. var tangent = new THREE.Vector2( tx, ty );
  16020. tangent.normalize();
  16021. return tangent;
  16022. };
  16023. /**************************************************************
  16024. * Spline curve
  16025. **************************************************************/
  16026. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16027. this.points = (points == undefined) ? [] : points;
  16028. };
  16029. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16030. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16031. var v = new THREE.Vector2();
  16032. var c = [];
  16033. var points = this.points, point, intPoint, weight;
  16034. point = ( points.length - 1 ) * t;
  16035. intPoint = Math.floor( point );
  16036. weight = point - intPoint;
  16037. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16038. c[ 1 ] = intPoint;
  16039. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16040. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16041. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16042. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16043. return v;
  16044. };
  16045. /**************************************************************
  16046. * Ellipse curve
  16047. **************************************************************/
  16048. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16049. aStartAngle, aEndAngle,
  16050. aClockwise ) {
  16051. this.aX = aX;
  16052. this.aY = aY;
  16053. this.xRadius = xRadius;
  16054. this.yRadius = yRadius;
  16055. this.aStartAngle = aStartAngle;
  16056. this.aEndAngle = aEndAngle;
  16057. this.aClockwise = aClockwise;
  16058. };
  16059. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16060. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16061. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16062. if ( !this.aClockwise ) {
  16063. t = 1 - t;
  16064. }
  16065. var angle = this.aStartAngle + t * deltaAngle;
  16066. var tx = this.aX + this.xRadius * Math.cos( angle );
  16067. var ty = this.aY + this.yRadius * Math.sin( angle );
  16068. return new THREE.Vector2( tx, ty );
  16069. };
  16070. /**************************************************************
  16071. * Arc curve
  16072. **************************************************************/
  16073. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16074. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16075. };
  16076. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16077. /**************************************************************
  16078. * Utils
  16079. **************************************************************/
  16080. THREE.Curve.Utils = {
  16081. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16082. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16083. },
  16084. // Puay Bing, thanks for helping with this derivative!
  16085. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16086. return -3 * p0 * (1 - t) * (1 - t) +
  16087. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16088. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16089. 3 * t * t * p3;
  16090. },
  16091. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16092. // To check if my formulas are correct
  16093. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16094. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16095. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16096. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16097. return h00 + h10 + h01 + h11;
  16098. },
  16099. // Catmull-Rom
  16100. interpolate: function( p0, p1, p2, p3, t ) {
  16101. var v0 = ( p2 - p0 ) * 0.5;
  16102. var v1 = ( p3 - p1 ) * 0.5;
  16103. var t2 = t * t;
  16104. var t3 = t * t2;
  16105. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16106. }
  16107. };
  16108. // TODO: Transformation for Curves?
  16109. /**************************************************************
  16110. * 3D Curves
  16111. **************************************************************/
  16112. // A Factory method for creating new curve subclasses
  16113. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16114. constructor.prototype = Object.create( THREE.Curve.prototype );
  16115. constructor.prototype.getPoint = getPointFunc;
  16116. return constructor;
  16117. };
  16118. /**************************************************************
  16119. * Line3D
  16120. **************************************************************/
  16121. THREE.LineCurve3 = THREE.Curve.create(
  16122. function ( v1, v2 ) {
  16123. this.v1 = v1;
  16124. this.v2 = v2;
  16125. },
  16126. function ( t ) {
  16127. var r = new THREE.Vector3();
  16128. r.sub( this.v2, this.v1 ); // diff
  16129. r.multiplyScalar( t );
  16130. r.addSelf( this.v1 );
  16131. return r;
  16132. }
  16133. );
  16134. /**************************************************************
  16135. * Quadratic Bezier 3D curve
  16136. **************************************************************/
  16137. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16138. function ( v0, v1, v2 ) {
  16139. this.v0 = v0;
  16140. this.v1 = v1;
  16141. this.v2 = v2;
  16142. },
  16143. function ( t ) {
  16144. var tx, ty, tz;
  16145. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16146. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16147. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16148. return new THREE.Vector3( tx, ty, tz );
  16149. }
  16150. );
  16151. /**************************************************************
  16152. * Cubic Bezier 3D curve
  16153. **************************************************************/
  16154. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16155. function ( v0, v1, v2, v3 ) {
  16156. this.v0 = v0;
  16157. this.v1 = v1;
  16158. this.v2 = v2;
  16159. this.v3 = v3;
  16160. },
  16161. function ( t ) {
  16162. var tx, ty, tz;
  16163. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16164. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16165. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16166. return new THREE.Vector3( tx, ty, tz );
  16167. }
  16168. );
  16169. /**************************************************************
  16170. * Spline 3D curve
  16171. **************************************************************/
  16172. THREE.SplineCurve3 = THREE.Curve.create(
  16173. function ( points /* array of Vector3 */) {
  16174. this.points = (points == undefined) ? [] : points;
  16175. },
  16176. function ( t ) {
  16177. var v = new THREE.Vector3();
  16178. var c = [];
  16179. var points = this.points, point, intPoint, weight;
  16180. point = ( points.length - 1 ) * t;
  16181. intPoint = Math.floor( point );
  16182. weight = point - intPoint;
  16183. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16184. c[ 1 ] = intPoint;
  16185. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16186. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16187. var pt0 = points[ c[0] ],
  16188. pt1 = points[ c[1] ],
  16189. pt2 = points[ c[2] ],
  16190. pt3 = points[ c[3] ];
  16191. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16192. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16193. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16194. return v;
  16195. }
  16196. );
  16197. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16198. // var v = new THREE.Vector3();
  16199. // var c = [];
  16200. // var points = this.points, point, intPoint, weight;
  16201. // point = ( points.length - 1 ) * t;
  16202. // intPoint = Math.floor( point );
  16203. // weight = point - intPoint;
  16204. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16205. // c[ 1 ] = intPoint;
  16206. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16207. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16208. // var pt0 = points[ c[0] ],
  16209. // pt1 = points[ c[1] ],
  16210. // pt2 = points[ c[2] ],
  16211. // pt3 = points[ c[3] ];
  16212. // // t = weight;
  16213. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16214. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16215. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16216. // return v;
  16217. // }
  16218. /**************************************************************
  16219. * Closed Spline 3D curve
  16220. **************************************************************/
  16221. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16222. function ( points /* array of Vector3 */) {
  16223. this.points = (points == undefined) ? [] : points;
  16224. },
  16225. function ( t ) {
  16226. var v = new THREE.Vector3();
  16227. var c = [];
  16228. var points = this.points, point, intPoint, weight;
  16229. point = ( points.length - 0 ) * t;
  16230. // This needs to be from 0-length +1
  16231. intPoint = Math.floor( point );
  16232. weight = point - intPoint;
  16233. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16234. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16235. c[ 1 ] = ( intPoint ) % points.length;
  16236. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16237. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16238. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16239. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16240. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16241. return v;
  16242. }
  16243. );
  16244. /**
  16245. * @author zz85 / http://www.lab4games.net/zz85/blog
  16246. *
  16247. **/
  16248. /**************************************************************
  16249. * Curved Path - a curve path is simply a array of connected
  16250. * curves, but retains the api of a curve
  16251. **************************************************************/
  16252. THREE.CurvePath = function () {
  16253. this.curves = [];
  16254. this.bends = [];
  16255. this.autoClose = false; // Automatically closes the path
  16256. };
  16257. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16258. THREE.CurvePath.prototype.add = function ( curve ) {
  16259. this.curves.push( curve );
  16260. };
  16261. THREE.CurvePath.prototype.checkConnection = function() {
  16262. // TODO
  16263. // If the ending of curve is not connected to the starting
  16264. // or the next curve, then, this is not a real path
  16265. };
  16266. THREE.CurvePath.prototype.closePath = function() {
  16267. // TODO Test
  16268. // and verify for vector3 (needs to implement equals)
  16269. // Add a line curve if start and end of lines are not connected
  16270. var startPoint = this.curves[0].getPoint(0);
  16271. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16272. if (!startPoint.equals(endPoint)) {
  16273. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16274. }
  16275. };
  16276. // To get accurate point with reference to
  16277. // entire path distance at time t,
  16278. // following has to be done:
  16279. // 1. Length of each sub path have to be known
  16280. // 2. Locate and identify type of curve
  16281. // 3. Get t for the curve
  16282. // 4. Return curve.getPointAt(t')
  16283. THREE.CurvePath.prototype.getPoint = function( t ) {
  16284. var d = t * this.getLength();
  16285. var curveLengths = this.getCurveLengths();
  16286. var i = 0, diff, curve;
  16287. // To think about boundaries points.
  16288. while ( i < curveLengths.length ) {
  16289. if ( curveLengths[ i ] >= d ) {
  16290. diff = curveLengths[ i ] - d;
  16291. curve = this.curves[ i ];
  16292. var u = 1 - diff / curve.getLength();
  16293. return curve.getPointAt( u );
  16294. break;
  16295. }
  16296. i ++;
  16297. }
  16298. return null;
  16299. // loop where sum != 0, sum > d , sum+1 <d
  16300. };
  16301. /*
  16302. THREE.CurvePath.prototype.getTangent = function( t ) {
  16303. };*/
  16304. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16305. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16306. // getPoint() depends on getLength
  16307. THREE.CurvePath.prototype.getLength = function() {
  16308. var lens = this.getCurveLengths();
  16309. return lens[ lens.length - 1 ];
  16310. };
  16311. // Compute lengths and cache them
  16312. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16313. THREE.CurvePath.prototype.getCurveLengths = function() {
  16314. // We use cache values if curves and cache array are same length
  16315. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16316. return this.cacheLengths;
  16317. };
  16318. // Get length of subsurve
  16319. // Push sums into cached array
  16320. var lengths = [], sums = 0;
  16321. var i, il = this.curves.length;
  16322. for ( i = 0; i < il; i ++ ) {
  16323. sums += this.curves[ i ].getLength();
  16324. lengths.push( sums );
  16325. }
  16326. this.cacheLengths = lengths;
  16327. return lengths;
  16328. };
  16329. // Returns min and max coordinates, as well as centroid
  16330. THREE.CurvePath.prototype.getBoundingBox = function () {
  16331. var points = this.getPoints();
  16332. var maxX, maxY, maxZ;
  16333. var minX, minY, minZ;
  16334. maxX = maxY = Number.NEGATIVE_INFINITY;
  16335. minX = minY = Number.POSITIVE_INFINITY;
  16336. var p, i, il, sum;
  16337. var v3 = points[0] instanceof THREE.Vector3;
  16338. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16339. for ( i = 0, il = points.length; i < il; i ++ ) {
  16340. p = points[ i ];
  16341. if ( p.x > maxX ) maxX = p.x;
  16342. else if ( p.x < minX ) minX = p.x;
  16343. if ( p.y > maxY ) maxY = p.y;
  16344. else if ( p.y < minY ) minY = p.y;
  16345. if (v3) {
  16346. if ( p.z > maxZ ) maxZ = p.z;
  16347. else if ( p.z < minZ ) minZ = p.z;
  16348. }
  16349. sum.addSelf( p );
  16350. }
  16351. var ret = {
  16352. minX: minX,
  16353. minY: minY,
  16354. maxX: maxX,
  16355. maxY: maxY,
  16356. centroid: sum.divideScalar( il )
  16357. };
  16358. if (v3) {
  16359. ret.maxZ = maxZ;
  16360. ret.minZ = minZ;
  16361. }
  16362. return ret;
  16363. };
  16364. /**************************************************************
  16365. * Create Geometries Helpers
  16366. **************************************************************/
  16367. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16368. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16369. var pts = this.getPoints( divisions, true );
  16370. return this.createGeometry( pts );
  16371. };
  16372. // Generate geometry from equidistance sampling along the path
  16373. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16374. var pts = this.getSpacedPoints( divisions, true );
  16375. return this.createGeometry( pts );
  16376. };
  16377. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16378. var geometry = new THREE.Geometry();
  16379. for ( var i = 0; i < points.length; i ++ ) {
  16380. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16381. }
  16382. return geometry;
  16383. };
  16384. /**************************************************************
  16385. * Bend / Wrap Helper Methods
  16386. **************************************************************/
  16387. // Wrap path / Bend modifiers?
  16388. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16389. this.bends.push( bendpath );
  16390. };
  16391. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16392. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16393. var i, il;
  16394. if ( !bends ) {
  16395. bends = this.bends;
  16396. }
  16397. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16398. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16399. }
  16400. return oldPts;
  16401. };
  16402. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16403. var oldPts = this.getSpacedPoints( segments );
  16404. var i, il;
  16405. if ( !bends ) {
  16406. bends = this.bends;
  16407. }
  16408. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16409. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16410. }
  16411. return oldPts;
  16412. };
  16413. // This returns getPoints() bend/wrapped around the contour of a path.
  16414. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16415. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16416. var bounds = this.getBoundingBox();
  16417. var i, il, p, oldX, oldY, xNorm;
  16418. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16419. p = oldPts[ i ];
  16420. oldX = p.x;
  16421. oldY = p.y;
  16422. xNorm = oldX / bounds.maxX;
  16423. // If using actual distance, for length > path, requires line extrusions
  16424. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16425. xNorm = path.getUtoTmapping( xNorm, oldX );
  16426. // check for out of bounds?
  16427. var pathPt = path.getPoint( xNorm );
  16428. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16429. p.x = pathPt.x + normal.x;
  16430. p.y = pathPt.y + normal.y;
  16431. }
  16432. return oldPts;
  16433. };
  16434. /**
  16435. * @author alteredq / http://alteredqualia.com/
  16436. */
  16437. THREE.Gyroscope = function () {
  16438. THREE.Object3D.call( this );
  16439. };
  16440. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16441. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16442. this.matrixAutoUpdate && this.updateMatrix();
  16443. // update matrixWorld
  16444. if ( this.matrixWorldNeedsUpdate || force ) {
  16445. if ( this.parent ) {
  16446. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  16447. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16448. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16449. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16450. } else {
  16451. this.matrixWorld.copy( this.matrix );
  16452. }
  16453. this.matrixWorldNeedsUpdate = false;
  16454. force = true;
  16455. }
  16456. // update children
  16457. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16458. this.children[ i ].updateMatrixWorld( force );
  16459. }
  16460. };
  16461. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16462. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16463. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16464. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16465. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16466. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16467. /**
  16468. * @author zz85 / http://www.lab4games.net/zz85/blog
  16469. * Creates free form 2d path using series of points, lines or curves.
  16470. *
  16471. **/
  16472. THREE.Path = function ( points ) {
  16473. THREE.CurvePath.call(this);
  16474. this.actions = [];
  16475. if ( points ) {
  16476. this.fromPoints( points );
  16477. }
  16478. };
  16479. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16480. THREE.PathActions = {
  16481. MOVE_TO: 'moveTo',
  16482. LINE_TO: 'lineTo',
  16483. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16484. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16485. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16486. ARC: 'arc', // Circle
  16487. ELLIPSE: 'ellipse'
  16488. };
  16489. // TODO Clean up PATH API
  16490. // Create path using straight lines to connect all points
  16491. // - vectors: array of Vector2
  16492. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16493. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16494. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16495. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16496. };
  16497. };
  16498. // startPath() endPath()?
  16499. THREE.Path.prototype.moveTo = function ( x, y ) {
  16500. var args = Array.prototype.slice.call( arguments );
  16501. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16502. };
  16503. THREE.Path.prototype.lineTo = function ( x, y ) {
  16504. var args = Array.prototype.slice.call( arguments );
  16505. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16506. var x0 = lastargs[ lastargs.length - 2 ];
  16507. var y0 = lastargs[ lastargs.length - 1 ];
  16508. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16509. this.curves.push( curve );
  16510. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16511. };
  16512. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16513. var args = Array.prototype.slice.call( arguments );
  16514. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16515. var x0 = lastargs[ lastargs.length - 2 ];
  16516. var y0 = lastargs[ lastargs.length - 1 ];
  16517. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16518. new THREE.Vector2( aCPx, aCPy ),
  16519. new THREE.Vector2( aX, aY ) );
  16520. this.curves.push( curve );
  16521. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16522. };
  16523. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16524. aCP2x, aCP2y,
  16525. aX, aY ) {
  16526. var args = Array.prototype.slice.call( arguments );
  16527. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16528. var x0 = lastargs[ lastargs.length - 2 ];
  16529. var y0 = lastargs[ lastargs.length - 1 ];
  16530. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16531. new THREE.Vector2( aCP1x, aCP1y ),
  16532. new THREE.Vector2( aCP2x, aCP2y ),
  16533. new THREE.Vector2( aX, aY ) );
  16534. this.curves.push( curve );
  16535. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16536. };
  16537. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16538. var args = Array.prototype.slice.call( arguments );
  16539. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16540. var x0 = lastargs[ lastargs.length - 2 ];
  16541. var y0 = lastargs[ lastargs.length - 1 ];
  16542. //---
  16543. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16544. Array.prototype.push.apply( npts, pts );
  16545. var curve = new THREE.SplineCurve( npts );
  16546. this.curves.push( curve );
  16547. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16548. };
  16549. // FUTURE: Change the API or follow canvas API?
  16550. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16551. aStartAngle, aEndAngle, aClockwise ) {
  16552. var lastargs = this.actions[ this.actions.length - 1].args;
  16553. var x0 = lastargs[ lastargs.length - 2 ];
  16554. var y0 = lastargs[ lastargs.length - 1 ];
  16555. this.absarc(aX + x0, aY + y0, aRadius,
  16556. aStartAngle, aEndAngle, aClockwise );
  16557. };
  16558. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16559. aStartAngle, aEndAngle, aClockwise ) {
  16560. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16561. };
  16562. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16563. aStartAngle, aEndAngle, aClockwise ) {
  16564. var lastargs = this.actions[ this.actions.length - 1].args;
  16565. var x0 = lastargs[ lastargs.length - 2 ];
  16566. var y0 = lastargs[ lastargs.length - 1 ];
  16567. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16568. aStartAngle, aEndAngle, aClockwise );
  16569. };
  16570. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16571. aStartAngle, aEndAngle, aClockwise ) {
  16572. var args = Array.prototype.slice.call( arguments );
  16573. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16574. aStartAngle, aEndAngle, aClockwise );
  16575. this.curves.push( curve );
  16576. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16577. args.push(lastPoint.x);
  16578. args.push(lastPoint.y);
  16579. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16580. };
  16581. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16582. if ( ! divisions ) divisions = 40;
  16583. var points = [];
  16584. for ( var i = 0; i < divisions; i ++ ) {
  16585. points.push( this.getPoint( i / divisions ) );
  16586. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16587. }
  16588. // if ( closedPath ) {
  16589. //
  16590. // points.push( points[ 0 ] );
  16591. //
  16592. // }
  16593. return points;
  16594. };
  16595. /* Return an array of vectors based on contour of the path */
  16596. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16597. if (this.useSpacedPoints) {
  16598. console.log('tata');
  16599. return this.getSpacedPoints( divisions, closedPath );
  16600. }
  16601. divisions = divisions || 12;
  16602. var points = [];
  16603. var i, il, item, action, args;
  16604. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16605. laste, j,
  16606. t, tx, ty;
  16607. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16608. item = this.actions[ i ];
  16609. action = item.action;
  16610. args = item.args;
  16611. switch( action ) {
  16612. case THREE.PathActions.MOVE_TO:
  16613. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16614. break;
  16615. case THREE.PathActions.LINE_TO:
  16616. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16617. break;
  16618. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16619. cpx = args[ 2 ];
  16620. cpy = args[ 3 ];
  16621. cpx1 = args[ 0 ];
  16622. cpy1 = args[ 1 ];
  16623. if ( points.length > 0 ) {
  16624. laste = points[ points.length - 1 ];
  16625. cpx0 = laste.x;
  16626. cpy0 = laste.y;
  16627. } else {
  16628. laste = this.actions[ i - 1 ].args;
  16629. cpx0 = laste[ laste.length - 2 ];
  16630. cpy0 = laste[ laste.length - 1 ];
  16631. }
  16632. for ( j = 1; j <= divisions; j ++ ) {
  16633. t = j / divisions;
  16634. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16635. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16636. points.push( new THREE.Vector2( tx, ty ) );
  16637. }
  16638. break;
  16639. case THREE.PathActions.BEZIER_CURVE_TO:
  16640. cpx = args[ 4 ];
  16641. cpy = args[ 5 ];
  16642. cpx1 = args[ 0 ];
  16643. cpy1 = args[ 1 ];
  16644. cpx2 = args[ 2 ];
  16645. cpy2 = args[ 3 ];
  16646. if ( points.length > 0 ) {
  16647. laste = points[ points.length - 1 ];
  16648. cpx0 = laste.x;
  16649. cpy0 = laste.y;
  16650. } else {
  16651. laste = this.actions[ i - 1 ].args;
  16652. cpx0 = laste[ laste.length - 2 ];
  16653. cpy0 = laste[ laste.length - 1 ];
  16654. }
  16655. for ( j = 1; j <= divisions; j ++ ) {
  16656. t = j / divisions;
  16657. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16658. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16659. points.push( new THREE.Vector2( tx, ty ) );
  16660. }
  16661. break;
  16662. case THREE.PathActions.CSPLINE_THRU:
  16663. laste = this.actions[ i - 1 ].args;
  16664. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16665. var spts = [ last ];
  16666. var n = divisions * args[ 0 ].length;
  16667. spts = spts.concat( args[ 0 ] );
  16668. var spline = new THREE.SplineCurve( spts );
  16669. for ( j = 1; j <= n; j ++ ) {
  16670. points.push( spline.getPointAt( j / n ) ) ;
  16671. }
  16672. break;
  16673. case THREE.PathActions.ARC:
  16674. var aX = args[ 0 ], aY = args[ 1 ],
  16675. aRadius = args[ 2 ],
  16676. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16677. aClockwise = !!args[ 5 ];
  16678. var deltaAngle = aEndAngle - aStartAngle;
  16679. var angle;
  16680. var tdivisions = divisions * 2;
  16681. for ( j = 1; j <= tdivisions; j ++ ) {
  16682. t = j / tdivisions;
  16683. if ( ! aClockwise ) {
  16684. t = 1 - t;
  16685. }
  16686. angle = aStartAngle + t * deltaAngle;
  16687. tx = aX + aRadius * Math.cos( angle );
  16688. ty = aY + aRadius * Math.sin( angle );
  16689. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16690. points.push( new THREE.Vector2( tx, ty ) );
  16691. }
  16692. //console.log(points);
  16693. break;
  16694. case THREE.PathActions.ELLIPSE:
  16695. var aX = args[ 0 ], aY = args[ 1 ],
  16696. xRadius = args[ 2 ],
  16697. yRadius = args[ 3 ],
  16698. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16699. aClockwise = !!args[ 6 ];
  16700. var deltaAngle = aEndAngle - aStartAngle;
  16701. var angle;
  16702. var tdivisions = divisions * 2;
  16703. for ( j = 1; j <= tdivisions; j ++ ) {
  16704. t = j / tdivisions;
  16705. if ( ! aClockwise ) {
  16706. t = 1 - t;
  16707. }
  16708. angle = aStartAngle + t * deltaAngle;
  16709. tx = aX + xRadius * Math.cos( angle );
  16710. ty = aY + yRadius * Math.sin( angle );
  16711. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16712. points.push( new THREE.Vector2( tx, ty ) );
  16713. }
  16714. //console.log(points);
  16715. break;
  16716. } // end switch
  16717. }
  16718. // Normalize to remove the closing point by default.
  16719. var lastPoint = points[ points.length - 1];
  16720. var EPSILON = 0.0000000001;
  16721. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16722. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16723. points.splice( points.length - 1, 1);
  16724. if ( closedPath ) {
  16725. points.push( points[ 0 ] );
  16726. }
  16727. return points;
  16728. };
  16729. // Breaks path into shapes
  16730. THREE.Path.prototype.toShapes = function() {
  16731. var i, il, item, action, args;
  16732. var subPaths = [], lastPath = new THREE.Path();
  16733. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16734. item = this.actions[ i ];
  16735. args = item.args;
  16736. action = item.action;
  16737. if ( action == THREE.PathActions.MOVE_TO ) {
  16738. if ( lastPath.actions.length != 0 ) {
  16739. subPaths.push( lastPath );
  16740. lastPath = new THREE.Path();
  16741. }
  16742. }
  16743. lastPath[ action ].apply( lastPath, args );
  16744. }
  16745. if ( lastPath.actions.length != 0 ) {
  16746. subPaths.push( lastPath );
  16747. }
  16748. // console.log(subPaths);
  16749. if ( subPaths.length == 0 ) return [];
  16750. var tmpPath, tmpShape, shapes = [];
  16751. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16752. // console.log("Holes first", holesFirst);
  16753. if ( subPaths.length == 1) {
  16754. tmpPath = subPaths[0];
  16755. tmpShape = new THREE.Shape();
  16756. tmpShape.actions = tmpPath.actions;
  16757. tmpShape.curves = tmpPath.curves;
  16758. shapes.push( tmpShape );
  16759. return shapes;
  16760. };
  16761. if ( holesFirst ) {
  16762. tmpShape = new THREE.Shape();
  16763. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16764. tmpPath = subPaths[ i ];
  16765. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16766. tmpShape.actions = tmpPath.actions;
  16767. tmpShape.curves = tmpPath.curves;
  16768. shapes.push( tmpShape );
  16769. tmpShape = new THREE.Shape();
  16770. //console.log('cw', i);
  16771. } else {
  16772. tmpShape.holes.push( tmpPath );
  16773. //console.log('ccw', i);
  16774. }
  16775. }
  16776. } else {
  16777. // Shapes first
  16778. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16779. tmpPath = subPaths[ i ];
  16780. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16781. if ( tmpShape ) shapes.push( tmpShape );
  16782. tmpShape = new THREE.Shape();
  16783. tmpShape.actions = tmpPath.actions;
  16784. tmpShape.curves = tmpPath.curves;
  16785. } else {
  16786. tmpShape.holes.push( tmpPath );
  16787. }
  16788. }
  16789. shapes.push( tmpShape );
  16790. }
  16791. //console.log("shape", shapes);
  16792. return shapes;
  16793. };
  16794. /**
  16795. * @author zz85 / http://www.lab4games.net/zz85/blog
  16796. * Defines a 2d shape plane using paths.
  16797. **/
  16798. // STEP 1 Create a path.
  16799. // STEP 2 Turn path into shape.
  16800. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16801. // STEP 3a - Extract points from each shape, turn to vertices
  16802. // STEP 3b - Triangulate each shape, add faces.
  16803. THREE.Shape = function ( ) {
  16804. THREE.Path.apply( this, arguments );
  16805. this.holes = [];
  16806. };
  16807. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  16808. // Convenience method to return ExtrudeGeometry
  16809. THREE.Shape.prototype.extrude = function ( options ) {
  16810. var extruded = new THREE.ExtrudeGeometry( this, options );
  16811. return extruded;
  16812. };
  16813. // Convenience method to return ShapeGeometry
  16814. THREE.Shape.prototype.makeGeometry = function ( options ) {
  16815. var geometry = new THREE.ShapeGeometry( this, options );
  16816. return geometry;
  16817. };
  16818. // Get points of holes
  16819. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  16820. var i, il = this.holes.length, holesPts = [];
  16821. for ( i = 0; i < il; i ++ ) {
  16822. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  16823. }
  16824. return holesPts;
  16825. };
  16826. // Get points of holes (spaced by regular distance)
  16827. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  16828. var i, il = this.holes.length, holesPts = [];
  16829. for ( i = 0; i < il; i ++ ) {
  16830. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  16831. }
  16832. return holesPts;
  16833. };
  16834. // Get points of shape and holes (keypoints based on segments parameter)
  16835. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  16836. return {
  16837. shape: this.getTransformedPoints( divisions ),
  16838. holes: this.getPointsHoles( divisions )
  16839. };
  16840. };
  16841. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  16842. if (this.useSpacedPoints) {
  16843. return this.extractAllSpacedPoints(divisions);
  16844. }
  16845. return this.extractAllPoints(divisions);
  16846. };
  16847. //
  16848. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  16849. //
  16850. // return {
  16851. //
  16852. // shape: this.transform( bend, divisions ),
  16853. // holes: this.getPointsHoles( divisions, bend )
  16854. //
  16855. // };
  16856. //
  16857. // };
  16858. // Get points of shape and holes (spaced by regular distance)
  16859. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  16860. return {
  16861. shape: this.getTransformedSpacedPoints( divisions ),
  16862. holes: this.getSpacedPointsHoles( divisions )
  16863. };
  16864. };
  16865. /**************************************************************
  16866. * Utils
  16867. **************************************************************/
  16868. THREE.Shape.Utils = {
  16869. /*
  16870. contour - array of vector2 for contour
  16871. holes - array of array of vector2
  16872. */
  16873. removeHoles: function ( contour, holes ) {
  16874. var shape = contour.concat(); // work on this shape
  16875. var allpoints = shape.concat();
  16876. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  16877. var prevShapeVert, nextShapeVert,
  16878. prevHoleVert, nextHoleVert,
  16879. holeIndex, shapeIndex,
  16880. shapeId, shapeGroup,
  16881. h, h2,
  16882. hole, shortest, d,
  16883. p, pts1, pts2,
  16884. tmpShape1, tmpShape2,
  16885. tmpHole1, tmpHole2,
  16886. verts = [];
  16887. for ( h = 0; h < holes.length; h ++ ) {
  16888. hole = holes[ h ];
  16889. /*
  16890. shapeholes[ h ].concat(); // preserves original
  16891. holes.push( hole );
  16892. */
  16893. Array.prototype.push.apply( allpoints, hole );
  16894. shortest = Number.POSITIVE_INFINITY;
  16895. // Find the shortest pair of pts between shape and hole
  16896. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  16897. // Using distanceToSquared() intead of distanceTo() should speed a little
  16898. // since running square roots operations are reduced.
  16899. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  16900. pts1 = hole[ h2 ];
  16901. var dist = [];
  16902. for ( p = 0; p < shape.length; p++ ) {
  16903. pts2 = shape[ p ];
  16904. d = pts1.distanceToSquared( pts2 );
  16905. dist.push( d );
  16906. if ( d < shortest ) {
  16907. shortest = d;
  16908. holeIndex = h2;
  16909. shapeIndex = p;
  16910. }
  16911. }
  16912. }
  16913. //console.log("shortest", shortest, dist);
  16914. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16915. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16916. var areaapts = [
  16917. hole[ holeIndex ],
  16918. shape[ shapeIndex ],
  16919. shape[ prevShapeVert ]
  16920. ];
  16921. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  16922. var areabpts = [
  16923. hole[ holeIndex ],
  16924. hole[ prevHoleVert ],
  16925. shape[ shapeIndex ]
  16926. ];
  16927. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  16928. var shapeOffset = 1;
  16929. var holeOffset = -1;
  16930. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  16931. shapeIndex += shapeOffset;
  16932. holeIndex += holeOffset;
  16933. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16934. shapeIndex %= shape.length;
  16935. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16936. holeIndex %= hole.length;
  16937. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16938. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16939. areaapts = [
  16940. hole[ holeIndex ],
  16941. shape[ shapeIndex ],
  16942. shape[ prevShapeVert ]
  16943. ];
  16944. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  16945. areabpts = [
  16946. hole[ holeIndex ],
  16947. hole[ prevHoleVert ],
  16948. shape[ shapeIndex ]
  16949. ];
  16950. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  16951. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  16952. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  16953. // In case areas are not correct.
  16954. //console.log("USE THIS");
  16955. shapeIndex = oldShapeIndex;
  16956. holeIndex = oldHoleIndex ;
  16957. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16958. shapeIndex %= shape.length;
  16959. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16960. holeIndex %= hole.length;
  16961. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16962. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16963. } else {
  16964. //console.log("USE THAT ")
  16965. }
  16966. tmpShape1 = shape.slice( 0, shapeIndex );
  16967. tmpShape2 = shape.slice( shapeIndex );
  16968. tmpHole1 = hole.slice( holeIndex );
  16969. tmpHole2 = hole.slice( 0, holeIndex );
  16970. // Should check orders here again?
  16971. var trianglea = [
  16972. hole[ holeIndex ],
  16973. shape[ shapeIndex ],
  16974. shape[ prevShapeVert ]
  16975. ];
  16976. var triangleb = [
  16977. hole[ holeIndex ] ,
  16978. hole[ prevHoleVert ],
  16979. shape[ shapeIndex ]
  16980. ];
  16981. verts.push( trianglea );
  16982. verts.push( triangleb );
  16983. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  16984. }
  16985. return {
  16986. shape:shape, /* shape with no holes */
  16987. isolatedPts: verts, /* isolated faces */
  16988. allpoints: allpoints
  16989. }
  16990. },
  16991. triangulateShape: function ( contour, holes ) {
  16992. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  16993. var shape = shapeWithoutHoles.shape,
  16994. allpoints = shapeWithoutHoles.allpoints,
  16995. isolatedPts = shapeWithoutHoles.isolatedPts;
  16996. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  16997. // 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.
  16998. //console.log( "triangles",triangles, triangles.length );
  16999. //console.log( "allpoints",allpoints, allpoints.length );
  17000. var i, il, f, face,
  17001. key, index,
  17002. allPointsMap = {},
  17003. isolatedPointsMap = {};
  17004. // prepare all points map
  17005. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17006. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17007. if ( allPointsMap[ key ] !== undefined ) {
  17008. console.log( "Duplicate point", key );
  17009. }
  17010. allPointsMap[ key ] = i;
  17011. }
  17012. // check all face vertices against all points map
  17013. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17014. face = triangles[ i ];
  17015. for ( f = 0; f < 3; f ++ ) {
  17016. key = face[ f ].x + ":" + face[ f ].y;
  17017. index = allPointsMap[ key ];
  17018. if ( index !== undefined ) {
  17019. face[ f ] = index;
  17020. }
  17021. }
  17022. }
  17023. // check isolated points vertices against all points map
  17024. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17025. face = isolatedPts[ i ];
  17026. for ( f = 0; f < 3; f ++ ) {
  17027. key = face[ f ].x + ":" + face[ f ].y;
  17028. index = allPointsMap[ key ];
  17029. if ( index !== undefined ) {
  17030. face[ f ] = index;
  17031. }
  17032. }
  17033. }
  17034. return triangles.concat( isolatedPts );
  17035. }, // end triangulate shapes
  17036. /*
  17037. triangulate2 : function( pts, holes ) {
  17038. // For use with Poly2Tri.js
  17039. var allpts = pts.concat();
  17040. var shape = [];
  17041. for (var p in pts) {
  17042. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17043. }
  17044. var swctx = new js.poly2tri.SweepContext(shape);
  17045. for (var h in holes) {
  17046. var aHole = holes[h];
  17047. var newHole = []
  17048. for (i in aHole) {
  17049. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17050. allpts.push(aHole[i]);
  17051. }
  17052. swctx.AddHole(newHole);
  17053. }
  17054. var find;
  17055. var findIndexForPt = function (pt) {
  17056. find = new THREE.Vector2(pt.x, pt.y);
  17057. var p;
  17058. for (p=0, pl = allpts.length; p<pl; p++) {
  17059. if (allpts[p].equals(find)) return p;
  17060. }
  17061. return -1;
  17062. };
  17063. // triangulate
  17064. js.poly2tri.sweep.Triangulate(swctx);
  17065. var triangles = swctx.GetTriangles();
  17066. var tr ;
  17067. var facesPts = [];
  17068. for (var t in triangles) {
  17069. tr = triangles[t];
  17070. facesPts.push([
  17071. findIndexForPt(tr.GetPoint(0)),
  17072. findIndexForPt(tr.GetPoint(1)),
  17073. findIndexForPt(tr.GetPoint(2))
  17074. ]);
  17075. }
  17076. // console.log(facesPts);
  17077. // console.log("triangles", triangles.length, triangles);
  17078. // Returns array of faces with 3 element each
  17079. return facesPts;
  17080. },
  17081. */
  17082. isClockWise: function ( pts ) {
  17083. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17084. },
  17085. // Bezier Curves formulas obtained from
  17086. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17087. // Quad Bezier Functions
  17088. b2p0: function ( t, p ) {
  17089. var k = 1 - t;
  17090. return k * k * p;
  17091. },
  17092. b2p1: function ( t, p ) {
  17093. return 2 * ( 1 - t ) * t * p;
  17094. },
  17095. b2p2: function ( t, p ) {
  17096. return t * t * p;
  17097. },
  17098. b2: function ( t, p0, p1, p2 ) {
  17099. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17100. },
  17101. // Cubic Bezier Functions
  17102. b3p0: function ( t, p ) {
  17103. var k = 1 - t;
  17104. return k * k * k * p;
  17105. },
  17106. b3p1: function ( t, p ) {
  17107. var k = 1 - t;
  17108. return 3 * k * k * t * p;
  17109. },
  17110. b3p2: function ( t, p ) {
  17111. var k = 1 - t;
  17112. return 3 * k * t * t * p;
  17113. },
  17114. b3p3: function ( t, p ) {
  17115. return t * t * t * p;
  17116. },
  17117. b3: function ( t, p0, p1, p2, p3 ) {
  17118. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17119. }
  17120. };
  17121. /**
  17122. * @author mikael emtinger / http://gomo.se/
  17123. */
  17124. THREE.AnimationHandler = (function() {
  17125. var playing = [];
  17126. var library = {};
  17127. var that = {};
  17128. //--- update ---
  17129. that.update = function( deltaTimeMS ) {
  17130. for( var i = 0; i < playing.length; i ++ )
  17131. playing[ i ].update( deltaTimeMS );
  17132. };
  17133. //--- add ---
  17134. that.addToUpdate = function( animation ) {
  17135. if ( playing.indexOf( animation ) === -1 )
  17136. playing.push( animation );
  17137. };
  17138. //--- remove ---
  17139. that.removeFromUpdate = function( animation ) {
  17140. var index = playing.indexOf( animation );
  17141. if( index !== -1 )
  17142. playing.splice( index, 1 );
  17143. };
  17144. //--- add ---
  17145. that.add = function( data ) {
  17146. if ( library[ data.name ] !== undefined )
  17147. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17148. library[ data.name ] = data;
  17149. initData( data );
  17150. };
  17151. //--- get ---
  17152. that.get = function( name ) {
  17153. if ( typeof name === "string" ) {
  17154. if ( library[ name ] ) {
  17155. return library[ name ];
  17156. } else {
  17157. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17158. return null;
  17159. }
  17160. } else {
  17161. // todo: add simple tween library
  17162. }
  17163. };
  17164. //--- parse ---
  17165. that.parse = function( root ) {
  17166. // setup hierarchy
  17167. var hierarchy = [];
  17168. if ( root instanceof THREE.SkinnedMesh ) {
  17169. for( var b = 0; b < root.bones.length; b++ ) {
  17170. hierarchy.push( root.bones[ b ] );
  17171. }
  17172. } else {
  17173. parseRecurseHierarchy( root, hierarchy );
  17174. }
  17175. return hierarchy;
  17176. };
  17177. var parseRecurseHierarchy = function( root, hierarchy ) {
  17178. hierarchy.push( root );
  17179. for( var c = 0; c < root.children.length; c++ )
  17180. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17181. }
  17182. //--- init data ---
  17183. var initData = function( data ) {
  17184. if( data.initialized === true )
  17185. return;
  17186. // loop through all keys
  17187. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17188. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17189. // remove minus times
  17190. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17191. data.hierarchy[ h ].keys[ k ].time = 0;
  17192. // create quaternions
  17193. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17194. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17195. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17196. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17197. }
  17198. }
  17199. // prepare morph target keys
  17200. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17201. // get all used
  17202. var usedMorphTargets = {};
  17203. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17204. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17205. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17206. usedMorphTargets[ morphTargetName ] = -1;
  17207. }
  17208. }
  17209. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17210. // set all used on all frames
  17211. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17212. var influences = {};
  17213. for ( var morphTargetName in usedMorphTargets ) {
  17214. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17215. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17216. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17217. break;
  17218. }
  17219. }
  17220. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17221. influences[ morphTargetName ] = 0;
  17222. }
  17223. }
  17224. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17225. }
  17226. }
  17227. // remove all keys that are on the same time
  17228. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17229. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17230. data.hierarchy[ h ].keys.splice( k, 1 );
  17231. k --;
  17232. }
  17233. }
  17234. // set index
  17235. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17236. data.hierarchy[ h ].keys[ k ].index = k;
  17237. }
  17238. }
  17239. // JIT
  17240. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17241. data.JIT = {};
  17242. data.JIT.hierarchy = [];
  17243. for( var h = 0; h < data.hierarchy.length; h ++ )
  17244. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17245. // done
  17246. data.initialized = true;
  17247. };
  17248. // interpolation types
  17249. that.LINEAR = 0;
  17250. that.CATMULLROM = 1;
  17251. that.CATMULLROM_FORWARD = 2;
  17252. return that;
  17253. }());
  17254. /**
  17255. * @author mikael emtinger / http://gomo.se/
  17256. * @author mrdoob / http://mrdoob.com/
  17257. * @author alteredq / http://alteredqualia.com/
  17258. */
  17259. THREE.Animation = function ( root, name, interpolationType ) {
  17260. this.root = root;
  17261. this.data = THREE.AnimationHandler.get( name );
  17262. this.hierarchy = THREE.AnimationHandler.parse( root );
  17263. this.currentTime = 0;
  17264. this.timeScale = 1;
  17265. this.isPlaying = false;
  17266. this.isPaused = true;
  17267. this.loop = true;
  17268. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17269. this.points = [];
  17270. this.target = new THREE.Vector3();
  17271. };
  17272. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17273. if ( this.isPlaying === false ) {
  17274. this.isPlaying = true;
  17275. this.loop = loop !== undefined ? loop : true;
  17276. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17277. // reset key cache
  17278. var h, hl = this.hierarchy.length,
  17279. object;
  17280. for ( h = 0; h < hl; h ++ ) {
  17281. object = this.hierarchy[ h ];
  17282. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17283. object.useQuaternion = true;
  17284. }
  17285. object.matrixAutoUpdate = true;
  17286. if ( object.animationCache === undefined ) {
  17287. object.animationCache = {};
  17288. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17289. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17290. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17291. }
  17292. var prevKey = object.animationCache.prevKey;
  17293. var nextKey = object.animationCache.nextKey;
  17294. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17295. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17296. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17297. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17298. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17299. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17300. }
  17301. this.update( 0 );
  17302. }
  17303. this.isPaused = false;
  17304. THREE.AnimationHandler.addToUpdate( this );
  17305. };
  17306. THREE.Animation.prototype.pause = function() {
  17307. if ( this.isPaused === true ) {
  17308. THREE.AnimationHandler.addToUpdate( this );
  17309. } else {
  17310. THREE.AnimationHandler.removeFromUpdate( this );
  17311. }
  17312. this.isPaused = !this.isPaused;
  17313. };
  17314. THREE.Animation.prototype.stop = function() {
  17315. this.isPlaying = false;
  17316. this.isPaused = false;
  17317. THREE.AnimationHandler.removeFromUpdate( this );
  17318. };
  17319. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17320. // early out
  17321. if ( this.isPlaying === false ) return;
  17322. // vars
  17323. var types = [ "pos", "rot", "scl" ];
  17324. var type;
  17325. var scale;
  17326. var vector;
  17327. var prevXYZ, nextXYZ;
  17328. var prevKey, nextKey;
  17329. var object;
  17330. var animationCache;
  17331. var frame;
  17332. var JIThierarchy = this.data.JIT.hierarchy;
  17333. var currentTime, unloopedCurrentTime;
  17334. var currentPoint, forwardPoint, angle;
  17335. this.currentTime += deltaTimeMS * this.timeScale;
  17336. unloopedCurrentTime = this.currentTime;
  17337. currentTime = this.currentTime = this.currentTime % this.data.length;
  17338. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17339. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17340. object = this.hierarchy[ h ];
  17341. animationCache = object.animationCache;
  17342. // loop through pos/rot/scl
  17343. for ( var t = 0; t < 3; t ++ ) {
  17344. // get keys
  17345. type = types[ t ];
  17346. prevKey = animationCache.prevKey[ type ];
  17347. nextKey = animationCache.nextKey[ type ];
  17348. // switch keys?
  17349. if ( nextKey.time <= unloopedCurrentTime ) {
  17350. // did we loop?
  17351. if ( currentTime < unloopedCurrentTime ) {
  17352. if ( this.loop ) {
  17353. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17354. nextKey = this.getNextKeyWith( type, h, 1 );
  17355. while( nextKey.time < currentTime ) {
  17356. prevKey = nextKey;
  17357. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17358. }
  17359. } else {
  17360. this.stop();
  17361. return;
  17362. }
  17363. } else {
  17364. do {
  17365. prevKey = nextKey;
  17366. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17367. } while( nextKey.time < currentTime )
  17368. }
  17369. animationCache.prevKey[ type ] = prevKey;
  17370. animationCache.nextKey[ type ] = nextKey;
  17371. }
  17372. object.matrixAutoUpdate = true;
  17373. object.matrixWorldNeedsUpdate = true;
  17374. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17375. prevXYZ = prevKey[ type ];
  17376. nextXYZ = nextKey[ type ];
  17377. // check scale error
  17378. if ( scale < 0 || scale > 1 ) {
  17379. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17380. scale = scale < 0 ? 0 : 1;
  17381. }
  17382. // interpolate
  17383. if ( type === "pos" ) {
  17384. vector = object.position;
  17385. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17386. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17387. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17388. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17389. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17390. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17391. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17392. this.points[ 1 ] = prevXYZ;
  17393. this.points[ 2 ] = nextXYZ;
  17394. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17395. scale = scale * 0.33 + 0.33;
  17396. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17397. vector.x = currentPoint[ 0 ];
  17398. vector.y = currentPoint[ 1 ];
  17399. vector.z = currentPoint[ 2 ];
  17400. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17401. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17402. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17403. this.target.subSelf( vector );
  17404. this.target.y = 0;
  17405. this.target.normalize();
  17406. angle = Math.atan2( this.target.x, this.target.z );
  17407. object.rotation.set( 0, angle, 0 );
  17408. }
  17409. }
  17410. } else if ( type === "rot" ) {
  17411. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17412. } else if ( type === "scl" ) {
  17413. vector = object.scale;
  17414. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17415. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17416. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17417. }
  17418. }
  17419. }
  17420. };
  17421. // Catmull-Rom spline
  17422. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17423. var c = [], v3 = [],
  17424. point, intPoint, weight, w2, w3,
  17425. pa, pb, pc, pd;
  17426. point = ( points.length - 1 ) * scale;
  17427. intPoint = Math.floor( point );
  17428. weight = point - intPoint;
  17429. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17430. c[ 1 ] = intPoint;
  17431. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17432. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17433. pa = points[ c[ 0 ] ];
  17434. pb = points[ c[ 1 ] ];
  17435. pc = points[ c[ 2 ] ];
  17436. pd = points[ c[ 3 ] ];
  17437. w2 = weight * weight;
  17438. w3 = weight * w2;
  17439. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17440. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17441. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17442. return v3;
  17443. };
  17444. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17445. var v0 = ( p2 - p0 ) * 0.5,
  17446. v1 = ( p3 - p1 ) * 0.5;
  17447. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17448. };
  17449. // Get next key with
  17450. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17451. var keys = this.data.hierarchy[ h ].keys;
  17452. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17453. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17454. key = key < keys.length - 1 ? key : keys.length - 1;
  17455. } else {
  17456. key = key % keys.length;
  17457. }
  17458. for ( ; key < keys.length; key++ ) {
  17459. if ( keys[ key ][ type ] !== undefined ) {
  17460. return keys[ key ];
  17461. }
  17462. }
  17463. return this.data.hierarchy[ h ].keys[ 0 ];
  17464. };
  17465. // Get previous key with
  17466. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17467. var keys = this.data.hierarchy[ h ].keys;
  17468. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17469. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17470. key = key > 0 ? key : 0;
  17471. } else {
  17472. key = key >= 0 ? key : key + keys.length;
  17473. }
  17474. for ( ; key >= 0; key -- ) {
  17475. if ( keys[ key ][ type ] !== undefined ) {
  17476. return keys[ key ];
  17477. }
  17478. }
  17479. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17480. };
  17481. /**
  17482. * @author mikael emtinger / http://gomo.se/
  17483. * @author mrdoob / http://mrdoob.com/
  17484. * @author alteredq / http://alteredqualia.com/
  17485. * @author khang duong
  17486. * @author erik kitson
  17487. */
  17488. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17489. this.root = root;
  17490. this.data = THREE.AnimationHandler.get( data );
  17491. this.hierarchy = THREE.AnimationHandler.parse( root );
  17492. this.currentTime = 0;
  17493. this.timeScale = 0.001;
  17494. this.isPlaying = false;
  17495. this.isPaused = true;
  17496. this.loop = true;
  17497. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17498. // initialize to first keyframes
  17499. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17500. var keys = this.data.hierarchy[h].keys,
  17501. sids = this.data.hierarchy[h].sids,
  17502. obj = this.hierarchy[h];
  17503. if ( keys.length && sids ) {
  17504. for ( var s = 0; s < sids.length; s++ ) {
  17505. var sid = sids[ s ],
  17506. next = this.getNextKeyWith( sid, h, 0 );
  17507. if ( next ) {
  17508. next.apply( sid );
  17509. }
  17510. }
  17511. obj.matrixAutoUpdate = false;
  17512. this.data.hierarchy[h].node.updateMatrix();
  17513. obj.matrixWorldNeedsUpdate = true;
  17514. }
  17515. }
  17516. };
  17517. // Play
  17518. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17519. if( !this.isPlaying ) {
  17520. this.isPlaying = true;
  17521. this.loop = loop !== undefined ? loop : true;
  17522. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17523. this.startTimeMs = startTimeMS;
  17524. this.startTime = 10000000;
  17525. this.endTime = -this.startTime;
  17526. // reset key cache
  17527. var h, hl = this.hierarchy.length,
  17528. object,
  17529. node;
  17530. for ( h = 0; h < hl; h++ ) {
  17531. object = this.hierarchy[ h ];
  17532. node = this.data.hierarchy[ h ];
  17533. object.useQuaternion = true;
  17534. if ( node.animationCache === undefined ) {
  17535. node.animationCache = {};
  17536. node.animationCache.prevKey = null;
  17537. node.animationCache.nextKey = null;
  17538. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17539. }
  17540. var keys = this.data.hierarchy[h].keys;
  17541. if (keys.length) {
  17542. node.animationCache.prevKey = keys[ 0 ];
  17543. node.animationCache.nextKey = keys[ 1 ];
  17544. this.startTime = Math.min( keys[0].time, this.startTime );
  17545. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17546. }
  17547. }
  17548. this.update( 0 );
  17549. }
  17550. this.isPaused = false;
  17551. THREE.AnimationHandler.addToUpdate( this );
  17552. };
  17553. // Pause
  17554. THREE.KeyFrameAnimation.prototype.pause = function() {
  17555. if( this.isPaused ) {
  17556. THREE.AnimationHandler.addToUpdate( this );
  17557. } else {
  17558. THREE.AnimationHandler.removeFromUpdate( this );
  17559. }
  17560. this.isPaused = !this.isPaused;
  17561. };
  17562. // Stop
  17563. THREE.KeyFrameAnimation.prototype.stop = function() {
  17564. this.isPlaying = false;
  17565. this.isPaused = false;
  17566. THREE.AnimationHandler.removeFromUpdate( this );
  17567. // reset JIT matrix and remove cache
  17568. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17569. var obj = this.hierarchy[ h ];
  17570. var node = this.data.hierarchy[ h ];
  17571. if ( node.animationCache !== undefined ) {
  17572. var original = node.animationCache.originalMatrix;
  17573. if( obj instanceof THREE.Bone ) {
  17574. original.copy( obj.skinMatrix );
  17575. obj.skinMatrix = original;
  17576. } else {
  17577. original.copy( obj.matrix );
  17578. obj.matrix = original;
  17579. }
  17580. delete node.animationCache;
  17581. }
  17582. }
  17583. };
  17584. // Update
  17585. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17586. // early out
  17587. if( !this.isPlaying ) return;
  17588. // vars
  17589. var prevKey, nextKey;
  17590. var object;
  17591. var node;
  17592. var frame;
  17593. var JIThierarchy = this.data.JIT.hierarchy;
  17594. var currentTime, unloopedCurrentTime;
  17595. var looped;
  17596. // update
  17597. this.currentTime += deltaTimeMS * this.timeScale;
  17598. unloopedCurrentTime = this.currentTime;
  17599. currentTime = this.currentTime = this.currentTime % this.data.length;
  17600. // if looped around, the current time should be based on the startTime
  17601. if ( currentTime < this.startTimeMs ) {
  17602. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17603. }
  17604. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17605. looped = currentTime < unloopedCurrentTime;
  17606. if ( looped && !this.loop ) {
  17607. // Set the animation to the last keyframes and stop
  17608. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17609. var keys = this.data.hierarchy[h].keys,
  17610. sids = this.data.hierarchy[h].sids,
  17611. end = keys.length-1,
  17612. obj = this.hierarchy[h];
  17613. if ( keys.length ) {
  17614. for ( var s = 0; s < sids.length; s++ ) {
  17615. var sid = sids[ s ],
  17616. prev = this.getPrevKeyWith( sid, h, end );
  17617. if ( prev ) {
  17618. prev.apply( sid );
  17619. }
  17620. }
  17621. this.data.hierarchy[h].node.updateMatrix();
  17622. obj.matrixWorldNeedsUpdate = true;
  17623. }
  17624. }
  17625. this.stop();
  17626. return;
  17627. }
  17628. // check pre-infinity
  17629. if ( currentTime < this.startTime ) {
  17630. return;
  17631. }
  17632. // update
  17633. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17634. object = this.hierarchy[ h ];
  17635. node = this.data.hierarchy[ h ];
  17636. var keys = node.keys,
  17637. animationCache = node.animationCache;
  17638. // use JIT?
  17639. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  17640. if( object instanceof THREE.Bone ) {
  17641. object.skinMatrix = JIThierarchy[ h ][ frame ];
  17642. object.matrixWorldNeedsUpdate = false;
  17643. } else {
  17644. object.matrix = JIThierarchy[ h ][ frame ];
  17645. object.matrixWorldNeedsUpdate = true;
  17646. }
  17647. // use interpolation
  17648. } else if ( keys.length ) {
  17649. // make sure so original matrix and not JIT matrix is set
  17650. if ( this.JITCompile && animationCache ) {
  17651. if( object instanceof THREE.Bone ) {
  17652. object.skinMatrix = animationCache.originalMatrix;
  17653. } else {
  17654. object.matrix = animationCache.originalMatrix;
  17655. }
  17656. }
  17657. prevKey = animationCache.prevKey;
  17658. nextKey = animationCache.nextKey;
  17659. if ( prevKey && nextKey ) {
  17660. // switch keys?
  17661. if ( nextKey.time <= unloopedCurrentTime ) {
  17662. // did we loop?
  17663. if ( looped && this.loop ) {
  17664. prevKey = keys[ 0 ];
  17665. nextKey = keys[ 1 ];
  17666. while ( nextKey.time < currentTime ) {
  17667. prevKey = nextKey;
  17668. nextKey = keys[ prevKey.index + 1 ];
  17669. }
  17670. } else if ( !looped ) {
  17671. var lastIndex = keys.length - 1;
  17672. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  17673. prevKey = nextKey;
  17674. nextKey = keys[ prevKey.index + 1 ];
  17675. }
  17676. }
  17677. animationCache.prevKey = prevKey;
  17678. animationCache.nextKey = nextKey;
  17679. }
  17680. if(nextKey.time >= currentTime)
  17681. prevKey.interpolate( nextKey, currentTime );
  17682. else
  17683. prevKey.interpolate( nextKey, nextKey.time);
  17684. }
  17685. this.data.hierarchy[h].node.updateMatrix();
  17686. object.matrixWorldNeedsUpdate = true;
  17687. }
  17688. }
  17689. // update JIT?
  17690. if ( this.JITCompile ) {
  17691. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  17692. this.hierarchy[ 0 ].updateMatrixWorld( true );
  17693. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  17694. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  17695. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  17696. } else {
  17697. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  17698. }
  17699. }
  17700. }
  17701. }
  17702. };
  17703. // Get next key with
  17704. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  17705. var keys = this.data.hierarchy[ h ].keys;
  17706. key = key % keys.length;
  17707. for ( ; key < keys.length; key++ ) {
  17708. if ( keys[ key ].hasTarget( sid ) ) {
  17709. return keys[ key ];
  17710. }
  17711. }
  17712. return keys[ 0 ];
  17713. };
  17714. // Get previous key with
  17715. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  17716. var keys = this.data.hierarchy[ h ].keys;
  17717. key = key >= 0 ? key : key + keys.length;
  17718. for ( ; key >= 0; key-- ) {
  17719. if ( keys[ key ].hasTarget( sid ) ) {
  17720. return keys[ key ];
  17721. }
  17722. }
  17723. return keys[ keys.length - 1 ];
  17724. };
  17725. /**
  17726. * Camera for rendering cube maps
  17727. * - renders scene into axis-aligned cube
  17728. *
  17729. * @author alteredq / http://alteredqualia.com/
  17730. */
  17731. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  17732. THREE.Object3D.call( this );
  17733. var fov = 90, aspect = 1;
  17734. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17735. cameraPX.up.set( 0, -1, 0 );
  17736. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  17737. this.add( cameraPX );
  17738. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17739. cameraNX.up.set( 0, -1, 0 );
  17740. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  17741. this.add( cameraNX );
  17742. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17743. cameraPY.up.set( 0, 0, 1 );
  17744. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  17745. this.add( cameraPY );
  17746. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17747. cameraNY.up.set( 0, 0, -1 );
  17748. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  17749. this.add( cameraNY );
  17750. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17751. cameraPZ.up.set( 0, -1, 0 );
  17752. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  17753. this.add( cameraPZ );
  17754. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17755. cameraNZ.up.set( 0, -1, 0 );
  17756. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  17757. this.add( cameraNZ );
  17758. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  17759. this.updateCubeMap = function ( renderer, scene ) {
  17760. var renderTarget = this.renderTarget;
  17761. var generateMipmaps = renderTarget.generateMipmaps;
  17762. renderTarget.generateMipmaps = false;
  17763. renderTarget.activeCubeFace = 0;
  17764. renderer.render( scene, cameraPX, renderTarget );
  17765. renderTarget.activeCubeFace = 1;
  17766. renderer.render( scene, cameraNX, renderTarget );
  17767. renderTarget.activeCubeFace = 2;
  17768. renderer.render( scene, cameraPY, renderTarget );
  17769. renderTarget.activeCubeFace = 3;
  17770. renderer.render( scene, cameraNY, renderTarget );
  17771. renderTarget.activeCubeFace = 4;
  17772. renderer.render( scene, cameraPZ, renderTarget );
  17773. renderTarget.generateMipmaps = generateMipmaps;
  17774. renderTarget.activeCubeFace = 5;
  17775. renderer.render( scene, cameraNZ, renderTarget );
  17776. };
  17777. };
  17778. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  17779. /*
  17780. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  17781. *
  17782. * A general perpose camera, for setting FOV, Lens Focal Length,
  17783. * and switching between perspective and orthographic views easily.
  17784. * Use this only if you do not wish to manage
  17785. * both a Orthographic and Perspective Camera
  17786. *
  17787. */
  17788. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  17789. THREE.Camera.call( this );
  17790. this.fov = fov;
  17791. this.left = -width / 2;
  17792. this.right = width / 2
  17793. this.top = height / 2;
  17794. this.bottom = -height / 2;
  17795. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  17796. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  17797. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  17798. this.zoom = 1;
  17799. this.toPerspective();
  17800. var aspect = width/height;
  17801. };
  17802. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  17803. THREE.CombinedCamera.prototype.toPerspective = function () {
  17804. // Switches to the Perspective Camera
  17805. this.near = this.cameraP.near;
  17806. this.far = this.cameraP.far;
  17807. this.cameraP.fov = this.fov / this.zoom ;
  17808. this.cameraP.updateProjectionMatrix();
  17809. this.projectionMatrix = this.cameraP.projectionMatrix;
  17810. this.inPerspectiveMode = true;
  17811. this.inOrthographicMode = false;
  17812. };
  17813. THREE.CombinedCamera.prototype.toOrthographic = function () {
  17814. // Switches to the Orthographic camera estimating viewport from Perspective
  17815. var fov = this.fov;
  17816. var aspect = this.cameraP.aspect;
  17817. var near = this.cameraP.near;
  17818. var far = this.cameraP.far;
  17819. // The size that we set is the mid plane of the viewing frustum
  17820. var hyperfocus = ( near + far ) / 2;
  17821. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  17822. var planeHeight = 2 * halfHeight;
  17823. var planeWidth = planeHeight * aspect;
  17824. var halfWidth = planeWidth / 2;
  17825. halfHeight /= this.zoom;
  17826. halfWidth /= this.zoom;
  17827. this.cameraO.left = -halfWidth;
  17828. this.cameraO.right = halfWidth;
  17829. this.cameraO.top = halfHeight;
  17830. this.cameraO.bottom = -halfHeight;
  17831. // this.cameraO.left = -farHalfWidth;
  17832. // this.cameraO.right = farHalfWidth;
  17833. // this.cameraO.top = farHalfHeight;
  17834. // this.cameraO.bottom = -farHalfHeight;
  17835. // this.cameraO.left = this.left / this.zoom;
  17836. // this.cameraO.right = this.right / this.zoom;
  17837. // this.cameraO.top = this.top / this.zoom;
  17838. // this.cameraO.bottom = this.bottom / this.zoom;
  17839. this.cameraO.updateProjectionMatrix();
  17840. this.near = this.cameraO.near;
  17841. this.far = this.cameraO.far;
  17842. this.projectionMatrix = this.cameraO.projectionMatrix;
  17843. this.inPerspectiveMode = false;
  17844. this.inOrthographicMode = true;
  17845. };
  17846. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  17847. this.cameraP.aspect = width / height;
  17848. this.left = -width / 2;
  17849. this.right = width / 2
  17850. this.top = height / 2;
  17851. this.bottom = -height / 2;
  17852. };
  17853. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  17854. this.fov = fov;
  17855. if ( this.inPerspectiveMode ) {
  17856. this.toPerspective();
  17857. } else {
  17858. this.toOrthographic();
  17859. }
  17860. };
  17861. // For mantaining similar API with PerspectiveCamera
  17862. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  17863. if ( this.inPerspectiveMode ) {
  17864. this.toPerspective();
  17865. } else {
  17866. this.toPerspective();
  17867. this.toOrthographic();
  17868. }
  17869. };
  17870. /*
  17871. * Uses Focal Length (in mm) to estimate and set FOV
  17872. * 35mm (fullframe) camera is used if frame size is not specified;
  17873. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  17874. */
  17875. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  17876. if ( frameHeight === undefined ) frameHeight = 24;
  17877. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  17878. this.setFov( fov );
  17879. return fov;
  17880. };
  17881. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  17882. this.zoom = zoom;
  17883. if ( this.inPerspectiveMode ) {
  17884. this.toPerspective();
  17885. } else {
  17886. this.toOrthographic();
  17887. }
  17888. };
  17889. THREE.CombinedCamera.prototype.toFrontView = function() {
  17890. this.rotation.x = 0;
  17891. this.rotation.y = 0;
  17892. this.rotation.z = 0;
  17893. // should we be modifing the matrix instead?
  17894. this.rotationAutoUpdate = false;
  17895. };
  17896. THREE.CombinedCamera.prototype.toBackView = function() {
  17897. this.rotation.x = 0;
  17898. this.rotation.y = Math.PI;
  17899. this.rotation.z = 0;
  17900. this.rotationAutoUpdate = false;
  17901. };
  17902. THREE.CombinedCamera.prototype.toLeftView = function() {
  17903. this.rotation.x = 0;
  17904. this.rotation.y = - Math.PI / 2;
  17905. this.rotation.z = 0;
  17906. this.rotationAutoUpdate = false;
  17907. };
  17908. THREE.CombinedCamera.prototype.toRightView = function() {
  17909. this.rotation.x = 0;
  17910. this.rotation.y = Math.PI / 2;
  17911. this.rotation.z = 0;
  17912. this.rotationAutoUpdate = false;
  17913. };
  17914. THREE.CombinedCamera.prototype.toTopView = function() {
  17915. this.rotation.x = - Math.PI / 2;
  17916. this.rotation.y = 0;
  17917. this.rotation.z = 0;
  17918. this.rotationAutoUpdate = false;
  17919. };
  17920. THREE.CombinedCamera.prototype.toBottomView = function() {
  17921. this.rotation.x = Math.PI / 2;
  17922. this.rotation.y = 0;
  17923. this.rotation.z = 0;
  17924. this.rotationAutoUpdate = false;
  17925. };
  17926. /**
  17927. * @author alteredq / http://alteredqualia.com/
  17928. *
  17929. * - 3d asterisk shape (for line pieces THREE.Line)
  17930. */
  17931. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  17932. THREE.Geometry.call( this );
  17933. var sd = innerRadius;
  17934. var ed = outerRadius;
  17935. var sd2 = 0.707 * sd;
  17936. var ed2 = 0.707 * ed;
  17937. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  17938. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  17939. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  17940. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  17941. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  17942. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  17943. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  17944. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  17945. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  17946. ];
  17947. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  17948. var x = rays[ i ][ 0 ];
  17949. var y = rays[ i ][ 1 ];
  17950. var z = rays[ i ][ 2 ];
  17951. this.vertices.push( new THREE.Vector3( x, y, z ) );
  17952. }
  17953. };
  17954. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  17955. * @author hughes
  17956. */
  17957. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  17958. THREE.Geometry.call( this );
  17959. radius = radius || 50;
  17960. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17961. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17962. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17963. var i, uvs = [],
  17964. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  17965. this.vertices.push(center);
  17966. uvs.push( centerUV );
  17967. for ( i = 0; i <= segments; i ++ ) {
  17968. var vertex = new THREE.Vector3();
  17969. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  17970. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  17971. this.vertices.push( vertex );
  17972. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  17973. }
  17974. var n = new THREE.Vector3( 0, 0, -1 );
  17975. for ( i = 1; i <= segments; i ++ ) {
  17976. var v1 = i;
  17977. var v2 = i + 1 ;
  17978. var v3 = 0;
  17979. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  17980. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  17981. }
  17982. this.computeCentroids();
  17983. this.computeFaceNormals();
  17984. this.boundingSphere = { radius: radius };
  17985. };
  17986. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17987. /**
  17988. * @author mrdoob / http://mrdoob.com/
  17989. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  17990. */
  17991. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments, materials, sides ) {
  17992. THREE.Geometry.call( this );
  17993. var scope = this;
  17994. this.width = width;
  17995. this.height = height;
  17996. this.depth = depth;
  17997. this.widthSegments = widthSegments || 1;
  17998. this.heightSegments = heightSegments || 1;
  17999. this.depthSegments = depthSegments || 1;
  18000. var width_half = this.width / 2;
  18001. var height_half = this.height / 2;
  18002. var depth_half = this.depth / 2;
  18003. var mpx, mpy, mpz, mnx, mny, mnz;
  18004. if ( materials !== undefined ) {
  18005. if ( materials instanceof Array ) {
  18006. this.materials = materials;
  18007. } else {
  18008. this.materials = [];
  18009. for ( var i = 0; i < 6; i ++ ) {
  18010. this.materials.push( materials );
  18011. }
  18012. }
  18013. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  18014. } else {
  18015. this.materials = [];
  18016. }
  18017. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  18018. if ( sides != undefined ) {
  18019. for ( var s in sides ) {
  18020. if ( this.sides[ s ] !== undefined ) {
  18021. this.sides[ s ] = sides[ s ];
  18022. }
  18023. }
  18024. }
  18025. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, mpx ); // px
  18026. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, mnx ); // nx
  18027. this.sides.py && buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, mpy ); // py
  18028. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, mny ); // ny
  18029. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, mpz ); // pz
  18030. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, mnz ); // nz
  18031. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  18032. var w, ix, iy,
  18033. gridX = scope.widthSegments,
  18034. gridY = scope.heightSegments,
  18035. width_half = width / 2,
  18036. height_half = height / 2,
  18037. offset = scope.vertices.length;
  18038. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18039. w = 'z';
  18040. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18041. w = 'y';
  18042. gridY = scope.depthSegments;
  18043. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18044. w = 'x';
  18045. gridX = scope.depthSegments;
  18046. }
  18047. var gridX1 = gridX + 1,
  18048. gridY1 = gridY + 1,
  18049. segment_width = width / gridX,
  18050. segment_height = height / gridY,
  18051. normal = new THREE.Vector3();
  18052. normal[ w ] = depth > 0 ? 1 : - 1;
  18053. for ( iy = 0; iy < gridY1; iy ++ ) {
  18054. for ( ix = 0; ix < gridX1; ix ++ ) {
  18055. var vector = new THREE.Vector3();
  18056. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18057. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18058. vector[ w ] = depth;
  18059. scope.vertices.push( vector );
  18060. }
  18061. }
  18062. for ( iy = 0; iy < gridY; iy++ ) {
  18063. for ( ix = 0; ix < gridX; ix++ ) {
  18064. var a = ix + gridX1 * iy;
  18065. var b = ix + gridX1 * ( iy + 1 );
  18066. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18067. var d = ( ix + 1 ) + gridX1 * iy;
  18068. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18069. face.normal.copy( normal );
  18070. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18071. face.materialIndex = material;
  18072. scope.faces.push( face );
  18073. scope.faceVertexUvs[ 0 ].push( [
  18074. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  18075. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18076. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18077. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18078. ] );
  18079. }
  18080. }
  18081. }
  18082. this.computeCentroids();
  18083. this.mergeVertices();
  18084. };
  18085. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18086. /**
  18087. * @author mrdoob / http://mrdoob.com/
  18088. */
  18089. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18090. THREE.Geometry.call( this );
  18091. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18092. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18093. height = height !== undefined ? height : 100;
  18094. var heightHalf = height / 2;
  18095. var segmentsX = radiusSegments || 8;
  18096. var segmentsY = heightSegments || 1;
  18097. var x, y, vertices = [], uvs = [];
  18098. for ( y = 0; y <= segmentsY; y ++ ) {
  18099. var verticesRow = [];
  18100. var uvsRow = [];
  18101. var v = y / segmentsY;
  18102. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18103. for ( x = 0; x <= segmentsX; x ++ ) {
  18104. var u = x / segmentsX;
  18105. var vertex = new THREE.Vector3();
  18106. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18107. vertex.y = - v * height + heightHalf;
  18108. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18109. this.vertices.push( vertex );
  18110. verticesRow.push( this.vertices.length - 1 );
  18111. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18112. }
  18113. vertices.push( verticesRow );
  18114. uvs.push( uvsRow );
  18115. }
  18116. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18117. var na, nb;
  18118. for ( x = 0; x < segmentsX; x ++ ) {
  18119. if ( radiusTop !== 0 ) {
  18120. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18121. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18122. } else {
  18123. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18124. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18125. }
  18126. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18127. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18128. for ( y = 0; y < segmentsY; y ++ ) {
  18129. var v1 = vertices[ y ][ x ];
  18130. var v2 = vertices[ y + 1 ][ x ];
  18131. var v3 = vertices[ y + 1 ][ x + 1 ];
  18132. var v4 = vertices[ y ][ x + 1 ];
  18133. var n1 = na.clone();
  18134. var n2 = na.clone();
  18135. var n3 = nb.clone();
  18136. var n4 = nb.clone();
  18137. var uv1 = uvs[ y ][ x ].clone();
  18138. var uv2 = uvs[ y + 1 ][ x ].clone();
  18139. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18140. var uv4 = uvs[ y ][ x + 1 ].clone();
  18141. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18142. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18143. }
  18144. }
  18145. // top cap
  18146. if ( !openEnded && radiusTop > 0 ) {
  18147. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18148. for ( x = 0; x < segmentsX; x ++ ) {
  18149. var v1 = vertices[ 0 ][ x ];
  18150. var v2 = vertices[ 0 ][ x + 1 ];
  18151. var v3 = this.vertices.length - 1;
  18152. var n1 = new THREE.Vector3( 0, 1, 0 );
  18153. var n2 = new THREE.Vector3( 0, 1, 0 );
  18154. var n3 = new THREE.Vector3( 0, 1, 0 );
  18155. var uv1 = uvs[ 0 ][ x ].clone();
  18156. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18157. var uv3 = new THREE.UV( uv2.u, 0 );
  18158. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18159. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18160. }
  18161. }
  18162. // bottom cap
  18163. if ( !openEnded && radiusBottom > 0 ) {
  18164. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18165. for ( x = 0; x < segmentsX; x ++ ) {
  18166. var v1 = vertices[ y ][ x + 1 ];
  18167. var v2 = vertices[ y ][ x ];
  18168. var v3 = this.vertices.length - 1;
  18169. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18170. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18171. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18172. var uv1 = uvs[ y ][ x + 1 ].clone();
  18173. var uv2 = uvs[ y ][ x ].clone();
  18174. var uv3 = new THREE.UV( uv2.u, 1 );
  18175. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18176. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18177. }
  18178. }
  18179. this.computeCentroids();
  18180. this.computeFaceNormals();
  18181. }
  18182. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18183. /**
  18184. * @author zz85 / http://www.lab4games.net/zz85/blog
  18185. *
  18186. * Creates extruded geometry from a path shape.
  18187. *
  18188. * parameters = {
  18189. *
  18190. * size: <float>, // size of the text
  18191. * height: <float>, // thickness to extrude text
  18192. * curveSegments: <int>, // number of points on the curves
  18193. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18194. * amount: <int>, // Amount
  18195. *
  18196. * bevelEnabled: <bool>, // turn on bevel
  18197. * bevelThickness: <float>, // how deep into text bevel goes
  18198. * bevelSize: <float>, // how far from text outline is bevel
  18199. * bevelSegments: <int>, // number of bevel layers
  18200. *
  18201. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18202. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18203. *
  18204. * material: <int> // material index for front and back faces
  18205. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18206. * uvGenerator: <Object> // object that provides UV generator functions
  18207. *
  18208. * }
  18209. **/
  18210. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18211. if ( typeof( shapes ) === "undefined" ) {
  18212. shapes = [];
  18213. return;
  18214. }
  18215. THREE.Geometry.call( this );
  18216. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18217. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18218. this.addShapeList( shapes, options );
  18219. this.computeCentroids();
  18220. this.computeFaceNormals();
  18221. // can't really use automatic vertex normals
  18222. // as then front and back sides get smoothed too
  18223. // should do separate smoothing just for sides
  18224. //this.computeVertexNormals();
  18225. //console.log( "took", ( Date.now() - startTime ) );
  18226. };
  18227. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18228. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18229. var sl = shapes.length;
  18230. for ( var s = 0; s < sl; s ++ ) {
  18231. var shape = shapes[ s ];
  18232. this.addShape( shape, options );
  18233. }
  18234. };
  18235. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18236. var amount = options.amount !== undefined ? options.amount : 100;
  18237. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18238. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18239. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18240. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18241. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18242. var steps = options.steps !== undefined ? options.steps : 1;
  18243. var extrudePath = options.extrudePath;
  18244. var extrudePts, extrudeByPath = false;
  18245. var material = options.material;
  18246. var extrudeMaterial = options.extrudeMaterial;
  18247. // Use default WorldUVGenerator if no UV generators are specified.
  18248. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18249. var shapebb = this.shapebb;
  18250. //shapebb = shape.getBoundingBox();
  18251. var splineTube, binormal, normal, position2;
  18252. if ( extrudePath ) {
  18253. extrudePts = extrudePath.getSpacedPoints( steps );
  18254. extrudeByPath = true;
  18255. bevelEnabled = false; // bevels not supported for path extrusion
  18256. // SETUP TNB variables
  18257. // Reuse TNB from TubeGeomtry for now.
  18258. // TODO1 - have a .isClosed in spline?
  18259. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18260. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18261. binormal = new THREE.Vector3();
  18262. normal = new THREE.Vector3();
  18263. position2 = new THREE.Vector3();
  18264. }
  18265. // Safeguards if bevels are not enabled
  18266. if ( ! bevelEnabled ) {
  18267. bevelSegments = 0;
  18268. bevelThickness = 0;
  18269. bevelSize = 0;
  18270. }
  18271. // Variables initalization
  18272. var ahole, h, hl; // looping of holes
  18273. var scope = this;
  18274. var bevelPoints = [];
  18275. var shapesOffset = this.vertices.length;
  18276. var shapePoints = shape.extractPoints();
  18277. var vertices = shapePoints.shape;
  18278. var holes = shapePoints.holes;
  18279. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18280. if ( reverse ) {
  18281. vertices = vertices.reverse();
  18282. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18283. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18284. ahole = holes[ h ];
  18285. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18286. holes[ h ] = ahole.reverse();
  18287. }
  18288. }
  18289. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18290. }
  18291. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18292. /* Vertices */
  18293. var contour = vertices; // vertices has all points but contour has only points of circumference
  18294. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18295. ahole = holes[ h ];
  18296. vertices = vertices.concat( ahole );
  18297. }
  18298. function scalePt2 ( pt, vec, size ) {
  18299. if ( !vec ) console.log( "die" );
  18300. return vec.clone().multiplyScalar( size ).addSelf( pt );
  18301. }
  18302. var b, bs, t, z,
  18303. vert, vlen = vertices.length,
  18304. face, flen = faces.length,
  18305. cont, clen = contour.length;
  18306. // Find directions for point movement
  18307. var RAD_TO_DEGREES = 180 / Math.PI;
  18308. function getBevelVec( pt_i, pt_j, pt_k ) {
  18309. // Algorithm 2
  18310. return getBevelVec2( pt_i, pt_j, pt_k );
  18311. }
  18312. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18313. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18314. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18315. if ( anglea > angleb ) {
  18316. angleb += Math.PI * 2;
  18317. }
  18318. var anglec = ( anglea + angleb ) / 2;
  18319. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18320. var x = - Math.cos( anglec );
  18321. var y = - Math.sin( anglec );
  18322. var vec = new THREE.Vector2( x, y ); //.normalize();
  18323. return vec;
  18324. }
  18325. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18326. var a = THREE.ExtrudeGeometry.__v1,
  18327. b = THREE.ExtrudeGeometry.__v2,
  18328. v_hat = THREE.ExtrudeGeometry.__v3,
  18329. w_hat = THREE.ExtrudeGeometry.__v4,
  18330. p = THREE.ExtrudeGeometry.__v5,
  18331. q = THREE.ExtrudeGeometry.__v6,
  18332. v, w,
  18333. v_dot_w_hat, q_sub_p_dot_w_hat,
  18334. s, intersection;
  18335. // good reading for line-line intersection
  18336. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18337. // define a as vector j->i
  18338. // define b as vectot k->i
  18339. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18340. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18341. // get unit vectors
  18342. v = a.normalize();
  18343. w = b.normalize();
  18344. // normals from pt i
  18345. v_hat.set( -v.y, v.x );
  18346. w_hat.set( w.y, -w.x );
  18347. // pts from i
  18348. p.copy( pt_i ).addSelf( v_hat );
  18349. q.copy( pt_i ).addSelf( w_hat );
  18350. if ( p.equals( q ) ) {
  18351. //console.log("Warning: lines are straight");
  18352. return w_hat.clone();
  18353. }
  18354. // Points from j, k. helps prevents points cross overover most of the time
  18355. p.copy( pt_j ).addSelf( v_hat );
  18356. q.copy( pt_k ).addSelf( w_hat );
  18357. v_dot_w_hat = v.dot( w_hat );
  18358. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18359. // We should not reach these conditions
  18360. if ( v_dot_w_hat === 0 ) {
  18361. console.log( "Either infinite or no solutions!" );
  18362. if ( q_sub_p_dot_w_hat === 0 ) {
  18363. console.log( "Its finite solutions." );
  18364. } else {
  18365. console.log( "Too bad, no solutions." );
  18366. }
  18367. }
  18368. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18369. if ( s < 0 ) {
  18370. // in case of emergecy, revert to algorithm 1.
  18371. return getBevelVec1( pt_i, pt_j, pt_k );
  18372. }
  18373. intersection = v.multiplyScalar( s ).addSelf( p );
  18374. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18375. }
  18376. var contourMovements = [];
  18377. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18378. if ( j === il ) j = 0;
  18379. if ( k === il ) k = 0;
  18380. // (j)---(i)---(k)
  18381. // console.log('i,j,k', i, j , k)
  18382. var pt_i = contour[ i ];
  18383. var pt_j = contour[ j ];
  18384. var pt_k = contour[ k ];
  18385. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18386. }
  18387. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18388. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18389. ahole = holes[ h ];
  18390. oneHoleMovements = [];
  18391. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18392. if ( j === il ) j = 0;
  18393. if ( k === il ) k = 0;
  18394. // (j)---(i)---(k)
  18395. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18396. }
  18397. holesMovements.push( oneHoleMovements );
  18398. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18399. }
  18400. // Loop bevelSegments, 1 for the front, 1 for the back
  18401. for ( b = 0; b < bevelSegments; b ++ ) {
  18402. //for ( b = bevelSegments; b > 0; b -- ) {
  18403. t = b / bevelSegments;
  18404. z = bevelThickness * ( 1 - t );
  18405. //z = bevelThickness * t;
  18406. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18407. //bs = bevelSize * t ; // linear
  18408. // contract shape
  18409. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18410. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18411. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18412. v( vert.x, vert.y, - z );
  18413. }
  18414. // expand holes
  18415. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18416. ahole = holes[ h ];
  18417. oneHoleMovements = holesMovements[ h ];
  18418. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18419. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18420. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18421. v( vert.x, vert.y, -z );
  18422. }
  18423. }
  18424. }
  18425. bs = bevelSize;
  18426. // Back facing vertices
  18427. for ( i = 0; i < vlen; i ++ ) {
  18428. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18429. if ( !extrudeByPath ) {
  18430. v( vert.x, vert.y, 0 );
  18431. } else {
  18432. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18433. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18434. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18435. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  18436. v( position2.x, position2.y, position2.z );
  18437. }
  18438. }
  18439. // Add stepped vertices...
  18440. // Including front facing vertices
  18441. var s;
  18442. for ( s = 1; s <= steps; s ++ ) {
  18443. for ( i = 0; i < vlen; i ++ ) {
  18444. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18445. if ( !extrudeByPath ) {
  18446. v( vert.x, vert.y, amount / steps * s );
  18447. } else {
  18448. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18449. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18450. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18451. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  18452. v( position2.x, position2.y, position2.z );
  18453. }
  18454. }
  18455. }
  18456. // Add bevel segments planes
  18457. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18458. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18459. t = b / bevelSegments;
  18460. z = bevelThickness * ( 1 - t );
  18461. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18462. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18463. // contract shape
  18464. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18465. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18466. v( vert.x, vert.y, amount + z );
  18467. }
  18468. // expand holes
  18469. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18470. ahole = holes[ h ];
  18471. oneHoleMovements = holesMovements[ h ];
  18472. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18473. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18474. if ( !extrudeByPath ) {
  18475. v( vert.x, vert.y, amount + z );
  18476. } else {
  18477. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18478. }
  18479. }
  18480. }
  18481. }
  18482. /* Faces */
  18483. // Top and bottom faces
  18484. buildLidFaces();
  18485. // Sides faces
  18486. buildSideFaces();
  18487. ///// Internal functions
  18488. function buildLidFaces() {
  18489. if ( bevelEnabled ) {
  18490. var layer = 0 ; // steps + 1
  18491. var offset = vlen * layer;
  18492. // Bottom faces
  18493. for ( i = 0; i < flen; i ++ ) {
  18494. face = faces[ i ];
  18495. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18496. }
  18497. layer = steps + bevelSegments * 2;
  18498. offset = vlen * layer;
  18499. // Top faces
  18500. for ( i = 0; i < flen; i ++ ) {
  18501. face = faces[ i ];
  18502. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18503. }
  18504. } else {
  18505. // Bottom faces
  18506. for ( i = 0; i < flen; i++ ) {
  18507. face = faces[ i ];
  18508. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18509. }
  18510. // Top faces
  18511. for ( i = 0; i < flen; i ++ ) {
  18512. face = faces[ i ];
  18513. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18514. }
  18515. }
  18516. }
  18517. // Create faces for the z-sides of the shape
  18518. function buildSideFaces() {
  18519. var layeroffset = 0;
  18520. sidewalls( contour, layeroffset );
  18521. layeroffset += contour.length;
  18522. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18523. ahole = holes[ h ];
  18524. sidewalls( ahole, layeroffset );
  18525. //, true
  18526. layeroffset += ahole.length;
  18527. }
  18528. }
  18529. function sidewalls( contour, layeroffset ) {
  18530. var j, k;
  18531. i = contour.length;
  18532. while ( --i >= 0 ) {
  18533. j = i;
  18534. k = i - 1;
  18535. if ( k < 0 ) k = contour.length - 1;
  18536. //console.log('b', i,j, i-1, k,vertices.length);
  18537. var s = 0, sl = steps + bevelSegments * 2;
  18538. for ( s = 0; s < sl; s ++ ) {
  18539. var slen1 = vlen * s;
  18540. var slen2 = vlen * ( s + 1 );
  18541. var a = layeroffset + j + slen1,
  18542. b = layeroffset + k + slen1,
  18543. c = layeroffset + k + slen2,
  18544. d = layeroffset + j + slen2;
  18545. f4( a, b, c, d, contour, s, sl, j, k );
  18546. }
  18547. }
  18548. }
  18549. function v( x, y, z ) {
  18550. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18551. }
  18552. function f3( a, b, c, isBottom ) {
  18553. a += shapesOffset;
  18554. b += shapesOffset;
  18555. c += shapesOffset;
  18556. // normal, color, material
  18557. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18558. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18559. scope.faceVertexUvs[ 0 ].push( uvs );
  18560. }
  18561. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18562. a += shapesOffset;
  18563. b += shapesOffset;
  18564. c += shapesOffset;
  18565. d += shapesOffset;
  18566. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18567. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18568. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18569. scope.faceVertexUvs[ 0 ].push( uvs );
  18570. }
  18571. };
  18572. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18573. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18574. var ax = geometry.vertices[ indexA ].x,
  18575. ay = geometry.vertices[ indexA ].y,
  18576. bx = geometry.vertices[ indexB ].x,
  18577. by = geometry.vertices[ indexB ].y,
  18578. cx = geometry.vertices[ indexC ].x,
  18579. cy = geometry.vertices[ indexC ].y;
  18580. return [
  18581. new THREE.UV( ax, ay ),
  18582. new THREE.UV( bx, by ),
  18583. new THREE.UV( cx, cy )
  18584. ];
  18585. },
  18586. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18587. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18588. },
  18589. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18590. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18591. contourIndex1, contourIndex2 ) {
  18592. var ax = geometry.vertices[ indexA ].x,
  18593. ay = geometry.vertices[ indexA ].y,
  18594. az = geometry.vertices[ indexA ].z,
  18595. bx = geometry.vertices[ indexB ].x,
  18596. by = geometry.vertices[ indexB ].y,
  18597. bz = geometry.vertices[ indexB ].z,
  18598. cx = geometry.vertices[ indexC ].x,
  18599. cy = geometry.vertices[ indexC ].y,
  18600. cz = geometry.vertices[ indexC ].z,
  18601. dx = geometry.vertices[ indexD ].x,
  18602. dy = geometry.vertices[ indexD ].y,
  18603. dz = geometry.vertices[ indexD ].z;
  18604. if ( Math.abs( ay - by ) < 0.01 ) {
  18605. return [
  18606. new THREE.UV( ax, 1 - az ),
  18607. new THREE.UV( bx, 1 - bz ),
  18608. new THREE.UV( cx, 1 - cz ),
  18609. new THREE.UV( dx, 1 - dz )
  18610. ];
  18611. } else {
  18612. return [
  18613. new THREE.UV( ay, 1 - az ),
  18614. new THREE.UV( by, 1 - bz ),
  18615. new THREE.UV( cy, 1 - cz ),
  18616. new THREE.UV( dy, 1 - dz )
  18617. ];
  18618. }
  18619. }
  18620. };
  18621. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18622. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18623. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18624. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18625. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18626. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18627. /**
  18628. * @author jonobr1 / http://jonobr1.com
  18629. *
  18630. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18631. * ExtrudeGeometry.
  18632. *
  18633. * parameters = {
  18634. *
  18635. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18636. *
  18637. * material: <int> // material index for front and back faces
  18638. * uvGenerator: <Object> // object that provides UV generator functions
  18639. *
  18640. * }
  18641. **/
  18642. THREE.ShapeGeometry = function ( shapes, options ) {
  18643. THREE.Geometry.call( this );
  18644. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18645. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18646. this.addShapeList( shapes, options );
  18647. this.computeCentroids();
  18648. this.computeFaceNormals();
  18649. };
  18650. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18651. /**
  18652. * Add an array of shapes to THREE.ShapeGeometry.
  18653. */
  18654. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18655. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  18656. this.addShape( shapes[ i ], options );
  18657. }
  18658. return this;
  18659. };
  18660. /**
  18661. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18662. */
  18663. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18664. if ( options === undefined ) options = {};
  18665. var material = options.material;
  18666. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18667. var shapebb = this.shapebb;
  18668. //
  18669. var i, l, hole, s;
  18670. var shapesOffset = this.vertices.length;
  18671. var shapePoints = shape.extractPoints();
  18672. var vertices = shapePoints.shape;
  18673. var holes = shapePoints.holes;
  18674. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  18675. if ( reverse ) {
  18676. vertices = vertices.reverse();
  18677. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18678. for ( i = 0, l = holes.length; i < l; i++ ) {
  18679. hole = holes[ i ];
  18680. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18681. holes[ i ] = hole.reverse();
  18682. }
  18683. }
  18684. reverse = false;
  18685. }
  18686. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18687. // Vertices
  18688. var contour = vertices;
  18689. for ( i = 0, l = holes.length; i < l; i++ ) {
  18690. hole = holes[ i ];
  18691. vertices = vertices.concat( hole );
  18692. }
  18693. //
  18694. var vert, vlen = vertices.length;
  18695. var face, flen = faces.length;
  18696. var cont, clen = contour.length;
  18697. for ( i = 0; i < vlen; i++ ) {
  18698. vert = vertices[ i ];
  18699. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18700. }
  18701. for ( i = 0; i < flen; i++ ) {
  18702. face = faces[ i ];
  18703. var a = face[ 0 ] + shapesOffset;
  18704. var b = face[ 1 ] + shapesOffset;
  18705. var c = face[ 2 ] + shapesOffset;
  18706. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18707. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  18708. }
  18709. };
  18710. /**
  18711. * @author astrodud / http://astrodud.isgreat.org/
  18712. * @author zz85 / https://github.com/zz85
  18713. */
  18714. THREE.LatheGeometry = function ( points, steps, angle ) {
  18715. THREE.Geometry.call( this );
  18716. var _steps = steps || 12;
  18717. var _angle = angle || 2 * Math.PI;
  18718. var _newV = [];
  18719. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  18720. for ( var j = 0; j < points.length; j ++ ) {
  18721. _newV[ j ] = points[ j ].clone();
  18722. this.vertices.push( _newV[ j ] );
  18723. }
  18724. var i, il = _steps + 1;
  18725. for ( i = 0; i < il; i ++ ) {
  18726. for ( var j = 0; j < _newV.length; j ++ ) {
  18727. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  18728. this.vertices.push( _newV[ j ] );
  18729. }
  18730. }
  18731. for ( i = 0; i < _steps; i ++ ) {
  18732. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  18733. var a = i * kl + k;
  18734. var b = ( ( i + 1 ) % il ) * kl + k;
  18735. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  18736. var d = i * kl + ( k + 1 ) % kl;
  18737. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18738. this.faceVertexUvs[ 0 ].push( [
  18739. new THREE.UV( 1 - i / _steps, k / kl ),
  18740. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  18741. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  18742. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  18743. ] );
  18744. }
  18745. }
  18746. this.computeCentroids();
  18747. this.computeFaceNormals();
  18748. this.computeVertexNormals();
  18749. };
  18750. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18751. /**
  18752. * @author mrdoob / http://mrdoob.com/
  18753. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18754. */
  18755. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  18756. THREE.Geometry.call( this );
  18757. this.width = width;
  18758. this.height = height;
  18759. this.widthSegments = widthSegments || 1;
  18760. this.heightSegments = heightSegments || 1;
  18761. var ix, iz;
  18762. var width_half = width / 2;
  18763. var height_half = height / 2;
  18764. var gridX = this.widthSegments;
  18765. var gridZ = this.heightSegments;
  18766. var gridX1 = gridX + 1;
  18767. var gridZ1 = gridZ + 1;
  18768. var segment_width = this.width / gridX;
  18769. var segment_height = this.height / gridZ;
  18770. var normal = new THREE.Vector3( 0, 0, 1 );
  18771. for ( iz = 0; iz < gridZ1; iz ++ ) {
  18772. for ( ix = 0; ix < gridX1; ix ++ ) {
  18773. var x = ix * segment_width - width_half;
  18774. var y = iz * segment_height - height_half;
  18775. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  18776. }
  18777. }
  18778. for ( iz = 0; iz < gridZ; iz ++ ) {
  18779. for ( ix = 0; ix < gridX; ix ++ ) {
  18780. var a = ix + gridX1 * iz;
  18781. var b = ix + gridX1 * ( iz + 1 );
  18782. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  18783. var d = ( ix + 1 ) + gridX1 * iz;
  18784. var face = new THREE.Face4( a, b, c, d );
  18785. face.normal.copy( normal );
  18786. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18787. this.faces.push( face );
  18788. this.faceVertexUvs[ 0 ].push( [
  18789. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  18790. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  18791. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  18792. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  18793. ] );
  18794. }
  18795. }
  18796. this.computeCentroids();
  18797. };
  18798. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18799. /**
  18800. * @author mrdoob / http://mrdoob.com/
  18801. */
  18802. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  18803. THREE.Geometry.call( this );
  18804. this.radius = radius || 50;
  18805. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  18806. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  18807. phiStart = phiStart !== undefined ? phiStart : 0;
  18808. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18809. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18810. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18811. var x, y, vertices = [], uvs = [];
  18812. for ( y = 0; y <= this.heightSegments; y ++ ) {
  18813. var verticesRow = [];
  18814. var uvsRow = [];
  18815. for ( x = 0; x <= this.widthSegments; x ++ ) {
  18816. var u = x / this.widthSegments;
  18817. var v = y / this.heightSegments;
  18818. var vertex = new THREE.Vector3();
  18819. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18820. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  18821. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18822. this.vertices.push( vertex );
  18823. verticesRow.push( this.vertices.length - 1 );
  18824. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18825. }
  18826. vertices.push( verticesRow );
  18827. uvs.push( uvsRow );
  18828. }
  18829. for ( y = 0; y < this.heightSegments; y ++ ) {
  18830. for ( x = 0; x < this.widthSegments; x ++ ) {
  18831. var v1 = vertices[ y ][ x + 1 ];
  18832. var v2 = vertices[ y ][ x ];
  18833. var v3 = vertices[ y + 1 ][ x ];
  18834. var v4 = vertices[ y + 1 ][ x + 1 ];
  18835. var n1 = this.vertices[ v1 ].clone().normalize();
  18836. var n2 = this.vertices[ v2 ].clone().normalize();
  18837. var n3 = this.vertices[ v3 ].clone().normalize();
  18838. var n4 = this.vertices[ v4 ].clone().normalize();
  18839. var uv1 = uvs[ y ][ x + 1 ].clone();
  18840. var uv2 = uvs[ y ][ x ].clone();
  18841. var uv3 = uvs[ y + 1 ][ x ].clone();
  18842. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  18843. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  18844. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  18845. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  18846. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  18847. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18848. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18849. } else {
  18850. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18851. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18852. }
  18853. }
  18854. }
  18855. this.computeCentroids();
  18856. this.computeFaceNormals();
  18857. this.boundingSphere = { radius: this.radius };
  18858. };
  18859. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18860. /**
  18861. * @author zz85 / http://www.lab4games.net/zz85/blog
  18862. * @author alteredq / http://alteredqualia.com/
  18863. *
  18864. * For creating 3D text geometry in three.js
  18865. *
  18866. * Text = 3D Text
  18867. *
  18868. * parameters = {
  18869. * size: <float>, // size of the text
  18870. * height: <float>, // thickness to extrude text
  18871. * curveSegments: <int>, // number of points on the curves
  18872. *
  18873. * font: <string>, // font name
  18874. * weight: <string>, // font weight (normal, bold)
  18875. * style: <string>, // font style (normal, italics)
  18876. *
  18877. * bevelEnabled: <bool>, // turn on bevel
  18878. * bevelThickness: <float>, // how deep into text bevel goes
  18879. * bevelSize: <float>, // how far from text outline is bevel
  18880. * }
  18881. *
  18882. */
  18883. /* Usage Examples
  18884. // TextGeometry wrapper
  18885. var text3d = new TextGeometry( text, options );
  18886. // Complete manner
  18887. var textShapes = THREE.FontUtils.generateShapes( text, options );
  18888. var text3d = new ExtrudeGeometry( textShapes, options );
  18889. */
  18890. THREE.TextGeometry = function ( text, parameters ) {
  18891. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  18892. // translate parameters to ExtrudeGeometry API
  18893. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  18894. // defaults
  18895. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18896. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18897. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18898. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  18899. };
  18900. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  18901. /**
  18902. * @author oosmoxiecode
  18903. * @author mrdoob / http://mrdoob.com/
  18904. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  18905. */
  18906. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  18907. THREE.Geometry.call( this );
  18908. var scope = this;
  18909. this.radius = radius || 100;
  18910. this.tube = tube || 40;
  18911. this.radialSegments = radialSegments || 8;
  18912. this.tubularSegments = tubularSegments || 6;
  18913. this.arc = arc || Math.PI * 2;
  18914. var center = new THREE.Vector3(), uvs = [], normals = [];
  18915. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  18916. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  18917. var u = i / this.tubularSegments * this.arc;
  18918. var v = j / this.radialSegments * Math.PI * 2;
  18919. center.x = this.radius * Math.cos( u );
  18920. center.y = this.radius * Math.sin( u );
  18921. var vertex = new THREE.Vector3();
  18922. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  18923. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  18924. vertex.z = this.tube * Math.sin( v );
  18925. this.vertices.push( vertex );
  18926. uvs.push( new THREE.UV( i / this.tubularSegments, j / this.radialSegments ) );
  18927. normals.push( vertex.clone().subSelf( center ).normalize() );
  18928. }
  18929. }
  18930. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  18931. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  18932. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  18933. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  18934. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  18935. var d = ( this.tubularSegments + 1 ) * j + i;
  18936. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  18937. face.normal.addSelf( normals[ a ] );
  18938. face.normal.addSelf( normals[ b ] );
  18939. face.normal.addSelf( normals[ c ] );
  18940. face.normal.addSelf( normals[ d ] );
  18941. face.normal.normalize();
  18942. this.faces.push( face );
  18943. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  18944. }
  18945. }
  18946. this.computeCentroids();
  18947. };
  18948. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18949. /**
  18950. * @author oosmoxiecode
  18951. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  18952. */
  18953. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  18954. THREE.Geometry.call( this );
  18955. var scope = this;
  18956. this.radius = radius || 200;
  18957. this.tube = tube || 40;
  18958. this.radialSegments = radialSegments || 64;
  18959. this.tubularSegments = tubularSegments || 8;
  18960. this.p = p || 2;
  18961. this.q = q || 3;
  18962. this.heightScale = heightScale || 1;
  18963. this.grid = new Array(this.radialSegments);
  18964. var tang = new THREE.Vector3();
  18965. var n = new THREE.Vector3();
  18966. var bitan = new THREE.Vector3();
  18967. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18968. this.grid[ i ] = new Array( this.tubularSegments );
  18969. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18970. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  18971. var v = j / this.tubularSegments * 2 * Math.PI;
  18972. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  18973. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  18974. var cx, cy;
  18975. tang.sub( p2, p1 );
  18976. n.add( p2, p1 );
  18977. bitan.cross( tang, n );
  18978. n.cross( bitan, tang );
  18979. bitan.normalize();
  18980. n.normalize();
  18981. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18982. cy = this.tube * Math.sin( v );
  18983. p1.x += cx * n.x + cy * bitan.x;
  18984. p1.y += cx * n.y + cy * bitan.y;
  18985. p1.z += cx * n.z + cy * bitan.z;
  18986. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  18987. }
  18988. }
  18989. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18990. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18991. var ip = ( i + 1 ) % this.radialSegments;
  18992. var jp = ( j + 1 ) % this.tubularSegments;
  18993. var a = this.grid[ i ][ j ];
  18994. var b = this.grid[ ip ][ j ];
  18995. var c = this.grid[ ip ][ jp ];
  18996. var d = this.grid[ i ][ jp ];
  18997. var uva = new THREE.UV( i / this.radialSegments, j / this.tubularSegments );
  18998. var uvb = new THREE.UV( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  18999. var uvc = new THREE.UV( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19000. var uvd = new THREE.UV( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19001. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19002. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19003. }
  19004. }
  19005. this.computeCentroids();
  19006. this.computeFaceNormals();
  19007. this.computeVertexNormals();
  19008. function vert( x, y, z ) {
  19009. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19010. }
  19011. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19012. var cu = Math.cos( u );
  19013. var cv = Math.cos( v );
  19014. var su = Math.sin( u );
  19015. var quOverP = in_q / in_p * u;
  19016. var cs = Math.cos( quOverP );
  19017. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19018. var ty = radius * ( 2 + cs ) * su * 0.5;
  19019. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19020. return new THREE.Vector3( tx, ty, tz );
  19021. }
  19022. };
  19023. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19024. /**
  19025. * @author WestLangley / https://github.com/WestLangley
  19026. * @author zz85 / https://github.com/zz85
  19027. * @author miningold / https://github.com/miningold
  19028. *
  19029. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19030. *
  19031. * Creates a tube which extrudes along a 3d spline
  19032. *
  19033. * Uses parallel transport frames as described in
  19034. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19035. */
  19036. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19037. THREE.Geometry.call( this );
  19038. this.path = path;
  19039. this.segments = segments || 64;
  19040. this.radius = radius || 1;
  19041. this.radiusSegments = radiusSegments || 8;
  19042. this.closed = closed || false;
  19043. if ( debug ) this.debug = new THREE.Object3D();
  19044. this.grid = [];
  19045. var scope = this,
  19046. tangent,
  19047. normal,
  19048. binormal,
  19049. numpoints = this.segments + 1,
  19050. x, y, z,
  19051. tx, ty, tz,
  19052. u, v,
  19053. cx, cy,
  19054. pos, pos2 = new THREE.Vector3(),
  19055. i, j,
  19056. ip, jp,
  19057. a, b, c, d,
  19058. uva, uvb, uvc, uvd;
  19059. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  19060. tangents = frames.tangents,
  19061. normals = frames.normals,
  19062. binormals = frames.binormals;
  19063. // proxy internals
  19064. this.tangents = tangents;
  19065. this.normals = normals;
  19066. this.binormals = binormals;
  19067. function vert( x, y, z ) {
  19068. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19069. }
  19070. // consruct the grid
  19071. for ( i = 0; i < numpoints; i++ ) {
  19072. this.grid[ i ] = [];
  19073. u = i / ( numpoints - 1 );
  19074. pos = path.getPointAt( u );
  19075. tangent = tangents[ i ];
  19076. normal = normals[ i ];
  19077. binormal = binormals[ i ];
  19078. if ( this.debug ) {
  19079. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19080. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19081. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19082. }
  19083. for ( j = 0; j < this.radiusSegments; j++ ) {
  19084. v = j / this.radiusSegments * 2 * Math.PI;
  19085. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19086. cy = this.radius * Math.sin( v );
  19087. pos2.copy( pos );
  19088. pos2.x += cx * normal.x + cy * binormal.x;
  19089. pos2.y += cx * normal.y + cy * binormal.y;
  19090. pos2.z += cx * normal.z + cy * binormal.z;
  19091. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19092. }
  19093. }
  19094. // construct the mesh
  19095. for ( i = 0; i < this.segments; i++ ) {
  19096. for ( j = 0; j < this.radiusSegments; j++ ) {
  19097. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  19098. jp = (j + 1) % this.radiusSegments;
  19099. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19100. b = this.grid[ ip ][ j ];
  19101. c = this.grid[ ip ][ jp ];
  19102. d = this.grid[ i ][ jp ];
  19103. uva = new THREE.UV( i / this.segments, j / this.radiusSegments );
  19104. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19105. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19106. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19107. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19108. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19109. }
  19110. }
  19111. this.computeCentroids();
  19112. this.computeFaceNormals();
  19113. this.computeVertexNormals();
  19114. };
  19115. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19116. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19117. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19118. var
  19119. tangent = new THREE.Vector3(),
  19120. normal = new THREE.Vector3(),
  19121. binormal = new THREE.Vector3(),
  19122. tangents = [],
  19123. normals = [],
  19124. binormals = [],
  19125. vec = new THREE.Vector3(),
  19126. mat = new THREE.Matrix4(),
  19127. numpoints = segments + 1,
  19128. theta,
  19129. epsilon = 0.0001,
  19130. smallest,
  19131. tx, ty, tz,
  19132. i, u, v;
  19133. // expose internals
  19134. this.tangents = tangents;
  19135. this.normals = normals;
  19136. this.binormals = binormals;
  19137. // compute the tangent vectors for each segment on the path
  19138. for ( i = 0; i < numpoints; i++ ) {
  19139. u = i / ( numpoints - 1 );
  19140. tangents[ i ] = path.getTangentAt( u );
  19141. tangents[ i ].normalize();
  19142. }
  19143. initialNormal3();
  19144. function initialNormal1(lastBinormal) {
  19145. // fixed start binormal. Has dangers of 0 vectors
  19146. normals[ 0 ] = new THREE.Vector3();
  19147. binormals[ 0 ] = new THREE.Vector3();
  19148. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19149. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  19150. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19151. }
  19152. function initialNormal2() {
  19153. // This uses the Frenet-Serret formula for deriving binormal
  19154. var t2 = path.getTangentAt( epsilon );
  19155. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  19156. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  19157. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19158. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19159. }
  19160. function initialNormal3() {
  19161. // select an initial normal vector perpenicular to the first tangent vector,
  19162. // and in the direction of the smallest tangent xyz component
  19163. normals[ 0 ] = new THREE.Vector3();
  19164. binormals[ 0 ] = new THREE.Vector3();
  19165. smallest = Number.MAX_VALUE;
  19166. tx = Math.abs( tangents[ 0 ].x );
  19167. ty = Math.abs( tangents[ 0 ].y );
  19168. tz = Math.abs( tangents[ 0 ].z );
  19169. if ( tx <= smallest ) {
  19170. smallest = tx;
  19171. normal.set( 1, 0, 0 );
  19172. }
  19173. if ( ty <= smallest ) {
  19174. smallest = ty;
  19175. normal.set( 0, 1, 0 );
  19176. }
  19177. if ( tz <= smallest ) {
  19178. normal.set( 0, 0, 1 );
  19179. }
  19180. vec.cross( tangents[ 0 ], normal ).normalize();
  19181. normals[ 0 ].cross( tangents[ 0 ], vec );
  19182. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  19183. }
  19184. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19185. for ( i = 1; i < numpoints; i++ ) {
  19186. normals[ i ] = normals[ i-1 ].clone();
  19187. binormals[ i ] = binormals[ i-1 ].clone();
  19188. vec.cross( tangents[ i-1 ], tangents[ i ] );
  19189. if ( vec.length() > epsilon ) {
  19190. vec.normalize();
  19191. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19192. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  19193. }
  19194. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19195. }
  19196. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19197. if ( closed ) {
  19198. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19199. theta /= ( numpoints - 1 );
  19200. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19201. theta = -theta;
  19202. }
  19203. for ( i = 1; i < numpoints; i++ ) {
  19204. // twist a little...
  19205. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  19206. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19207. }
  19208. }
  19209. };
  19210. /**
  19211. * @author clockworkgeek / https://github.com/clockworkgeek
  19212. * @author timothypratley / https://github.com/timothypratley
  19213. */
  19214. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19215. THREE.Geometry.call( this );
  19216. radius = radius || 1;
  19217. detail = detail || 0;
  19218. var that = this;
  19219. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19220. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19221. }
  19222. var midpoints = [], p = this.vertices;
  19223. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19224. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19225. }
  19226. this.mergeVertices();
  19227. // Apply radius
  19228. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19229. this.vertices[ i ].multiplyScalar( radius );
  19230. }
  19231. // Project vector onto sphere's surface
  19232. function prepare( vector ) {
  19233. var vertex = vector.normalize().clone();
  19234. vertex.index = that.vertices.push( vertex ) - 1;
  19235. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19236. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19237. var v = inclination( vector ) / Math.PI + 0.5;
  19238. vertex.uv = new THREE.UV( u, 1 - v );
  19239. return vertex;
  19240. }
  19241. // Approximate a curved face with recursively sub-divided triangles.
  19242. function make( v1, v2, v3, detail ) {
  19243. if ( detail < 1 ) {
  19244. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19245. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  19246. face.normal = face.centroid.clone().normalize();
  19247. that.faces.push( face );
  19248. var azi = azimuth( face.centroid );
  19249. that.faceVertexUvs[ 0 ].push( [
  19250. correctUV( v1.uv, v1, azi ),
  19251. correctUV( v2.uv, v2, azi ),
  19252. correctUV( v3.uv, v3, azi )
  19253. ] );
  19254. } else {
  19255. detail -= 1;
  19256. // split triangle into 4 smaller triangles
  19257. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19258. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19259. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19260. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19261. }
  19262. }
  19263. function midpoint( v1, v2 ) {
  19264. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19265. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19266. var mid = midpoints[ v1.index ][ v2.index ];
  19267. if ( mid === undefined ) {
  19268. // generate mean point and project to surface with prepare()
  19269. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19270. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  19271. );
  19272. }
  19273. return mid;
  19274. }
  19275. // Angle around the Y axis, counter-clockwise when looking from above.
  19276. function azimuth( vector ) {
  19277. return Math.atan2( vector.z, -vector.x );
  19278. }
  19279. // Angle above the XZ plane.
  19280. function inclination( vector ) {
  19281. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19282. }
  19283. // Texture fixing helper. Spheres have some odd behaviours.
  19284. function correctUV( uv, vector, azimuth ) {
  19285. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  19286. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  19287. return uv;
  19288. }
  19289. this.computeCentroids();
  19290. this.boundingSphere = { radius: radius };
  19291. };
  19292. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19293. /**
  19294. * @author timothypratley / https://github.com/timothypratley
  19295. */
  19296. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19297. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19298. var vertices = [
  19299. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19300. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19301. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19302. ];
  19303. var faces = [
  19304. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19305. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19306. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19307. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19308. ];
  19309. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19310. };
  19311. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19312. /**
  19313. * @author timothypratley / https://github.com/timothypratley
  19314. */
  19315. THREE.OctahedronGeometry = function ( radius, detail ) {
  19316. var vertices = [
  19317. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19318. ];
  19319. var faces = [
  19320. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19321. ];
  19322. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19323. };
  19324. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19325. /**
  19326. * @author timothypratley / https://github.com/timothypratley
  19327. */
  19328. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19329. var vertices = [
  19330. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19331. ];
  19332. var faces = [
  19333. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19334. ];
  19335. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19336. };
  19337. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19338. /**
  19339. * @author zz85 / https://github.com/zz85
  19340. * Parametric Surfaces Geometry
  19341. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19342. *
  19343. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19344. *
  19345. */
  19346. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19347. THREE.Geometry.call( this );
  19348. var verts = this.vertices;
  19349. var faces = this.faces;
  19350. var uvs = this.faceVertexUvs[ 0 ];
  19351. useTris = (useTris === undefined) ? false : useTris;
  19352. var i, il, j, p;
  19353. var u, v;
  19354. var stackCount = stacks + 1;
  19355. var sliceCount = slices + 1;
  19356. for ( i = 0; i <= stacks; i ++ ) {
  19357. v = i / stacks;
  19358. for ( j = 0; j <= slices; j ++ ) {
  19359. u = j / slices;
  19360. p = func( u, v );
  19361. verts.push( p );
  19362. }
  19363. }
  19364. var a, b, c, d;
  19365. var uva, uvb, uvc, uvd;
  19366. for ( i = 0; i < stacks; i ++ ) {
  19367. for ( j = 0; j < slices; j ++ ) {
  19368. a = i * sliceCount + j;
  19369. b = i * sliceCount + j + 1;
  19370. c = (i + 1) * sliceCount + j;
  19371. d = (i + 1) * sliceCount + j + 1;
  19372. uva = new THREE.UV( j / slices, i / stacks );
  19373. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  19374. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  19375. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19376. if ( useTris ) {
  19377. faces.push( new THREE.Face3( a, b, c ) );
  19378. faces.push( new THREE.Face3( b, d, c ) );
  19379. uvs.push( [ uva, uvb, uvc ] );
  19380. uvs.push( [ uvb, uvd, uvc ] );
  19381. } else {
  19382. faces.push( new THREE.Face4( a, b, d, c ) );
  19383. uvs.push( [ uva, uvb, uvd, uvc ] );
  19384. }
  19385. }
  19386. }
  19387. // console.log(this);
  19388. // magic bullet
  19389. // var diff = this.mergeVertices();
  19390. // console.log('removed ', diff, ' vertices by merging');
  19391. this.computeCentroids();
  19392. this.computeFaceNormals();
  19393. this.computeVertexNormals();
  19394. };
  19395. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19396. /**
  19397. * @author qiao / https://github.com/qiao
  19398. * @fileoverview This is a convex hull generator using the incremental method.
  19399. * The complexity is O(n^2) where n is the number of vertices.
  19400. * O(nlogn) algorithms do exist, but they are much more complicated.
  19401. *
  19402. * Benchmark:
  19403. *
  19404. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19405. *
  19406. * Num Vertices Time(ms)
  19407. *
  19408. * 10 1
  19409. * 20 3
  19410. * 30 19
  19411. * 40 48
  19412. * 50 107
  19413. */
  19414. THREE.ConvexGeometry = function( vertices ) {
  19415. THREE.Geometry.call( this );
  19416. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19417. for ( var i = 3; i < vertices.length; i++ ) {
  19418. addPoint( i );
  19419. }
  19420. function addPoint( vertexId ) {
  19421. var vertex = vertices[ vertexId ].clone();
  19422. var mag = vertex.length();
  19423. vertex.x += mag * randomOffset();
  19424. vertex.y += mag * randomOffset();
  19425. vertex.z += mag * randomOffset();
  19426. var hole = [];
  19427. for ( var f = 0; f < faces.length; ) {
  19428. var face = faces[ f ];
  19429. // for each face, if the vertex can see it,
  19430. // then we try to add the face's edges into the hole.
  19431. if ( visible( face, vertex ) ) {
  19432. for ( var e = 0; e < 3; e++ ) {
  19433. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19434. var boundary = true;
  19435. // remove duplicated edges.
  19436. for ( var h = 0; h < hole.length; h++ ) {
  19437. if ( equalEdge( hole[ h ], edge ) ) {
  19438. hole[ h ] = hole[ hole.length - 1 ];
  19439. hole.pop();
  19440. boundary = false;
  19441. break;
  19442. }
  19443. }
  19444. if ( boundary ) {
  19445. hole.push( edge );
  19446. }
  19447. }
  19448. // remove faces[ f ]
  19449. faces[ f ] = faces[ faces.length - 1 ];
  19450. faces.pop();
  19451. } else { // not visible
  19452. f++;
  19453. }
  19454. }
  19455. // construct the new faces formed by the edges of the hole and the vertex
  19456. for ( var h = 0; h < hole.length; h++ ) {
  19457. faces.push( [
  19458. hole[ h ][ 0 ],
  19459. hole[ h ][ 1 ],
  19460. vertexId
  19461. ] );
  19462. }
  19463. }
  19464. /**
  19465. * Whether the face is visible from the vertex
  19466. */
  19467. function visible( face, vertex ) {
  19468. var va = vertices[ face[ 0 ] ];
  19469. var vb = vertices[ face[ 1 ] ];
  19470. var vc = vertices[ face[ 2 ] ];
  19471. var n = normal( va, vb, vc );
  19472. // distance from face to origin
  19473. var dist = n.dot( va );
  19474. return n.dot( vertex ) >= dist;
  19475. }
  19476. /**
  19477. * Face normal
  19478. */
  19479. function normal( va, vb, vc ) {
  19480. var cb = new THREE.Vector3();
  19481. var ab = new THREE.Vector3();
  19482. cb.sub( vc, vb );
  19483. ab.sub( va, vb );
  19484. cb.crossSelf( ab );
  19485. if ( !cb.isZero() ) {
  19486. cb.normalize();
  19487. }
  19488. return cb;
  19489. }
  19490. /**
  19491. * Detect whether two edges are equal.
  19492. * Note that when constructing the convex hull, two same edges can only
  19493. * be of the negative direction.
  19494. */
  19495. function equalEdge( ea, eb ) {
  19496. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19497. }
  19498. /**
  19499. * Create a random offset between -1e-6 and 1e-6.
  19500. */
  19501. function randomOffset() {
  19502. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19503. }
  19504. /**
  19505. * XXX: Not sure if this is the correct approach. Need someone to review.
  19506. */
  19507. function vertexUv( vertex ) {
  19508. var mag = vertex.length();
  19509. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  19510. }
  19511. // Push vertices into `this.vertices`, skipping those inside the hull
  19512. var id = 0;
  19513. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19514. for ( var i = 0; i < faces.length; i++ ) {
  19515. var face = faces[ i ];
  19516. for ( var j = 0; j < 3; j++ ) {
  19517. if ( newId[ face[ j ] ] === undefined ) {
  19518. newId[ face[ j ] ] = id++;
  19519. this.vertices.push( vertices[ face[ j ] ] );
  19520. }
  19521. face[ j ] = newId[ face[ j ] ];
  19522. }
  19523. }
  19524. // Convert faces into instances of THREE.Face3
  19525. for ( var i = 0; i < faces.length; i++ ) {
  19526. this.faces.push( new THREE.Face3(
  19527. faces[ i ][ 0 ],
  19528. faces[ i ][ 1 ],
  19529. faces[ i ][ 2 ]
  19530. ) );
  19531. }
  19532. // Compute UVs
  19533. for ( var i = 0; i < this.faces.length; i++ ) {
  19534. var face = this.faces[ i ];
  19535. this.faceVertexUvs[ 0 ].push( [
  19536. vertexUv( this.vertices[ face.a ] ),
  19537. vertexUv( this.vertices[ face.b ] ),
  19538. vertexUv( this.vertices[ face.c ])
  19539. ] );
  19540. }
  19541. this.computeCentroids();
  19542. this.computeFaceNormals();
  19543. this.computeVertexNormals();
  19544. };
  19545. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19546. /**
  19547. * @author sroucheray / http://sroucheray.org/
  19548. * @author mrdoob / http://mrdoob.com/
  19549. */
  19550. THREE.AxisHelper = function ( size ) {
  19551. var geometry = new THREE.Geometry();
  19552. geometry.vertices.push(
  19553. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19554. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19555. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19556. );
  19557. geometry.colors.push(
  19558. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19559. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19560. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19561. );
  19562. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19563. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19564. };
  19565. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19566. /**
  19567. * @author WestLangley / http://github.com/WestLangley
  19568. * @author zz85 / https://github.com/zz85
  19569. *
  19570. * Creates an arrow for visualizing directions
  19571. *
  19572. * Parameters:
  19573. * dir - Vector3
  19574. * origin - Vector3
  19575. * length - Number
  19576. * hex - color in hex value
  19577. */
  19578. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19579. THREE.Object3D.call( this );
  19580. if ( hex === undefined ) hex = 0xffff00;
  19581. if ( length === undefined ) length = 20;
  19582. var lineGeometry = new THREE.Geometry();
  19583. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19584. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19585. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19586. this.add( this.line );
  19587. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19588. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19589. this.cone.position.set( 0, 1, 0 );
  19590. this.add( this.cone );
  19591. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19592. this.setDirection( dir );
  19593. this.setLength( length );
  19594. };
  19595. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19596. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19597. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  19598. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  19599. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  19600. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  19601. };
  19602. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19603. this.scale.set( length, length, length );
  19604. };
  19605. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19606. this.line.material.color.setHex( hex );
  19607. this.cone.material.color.setHex( hex );
  19608. };
  19609. /**
  19610. * @author alteredq / http://alteredqualia.com/
  19611. *
  19612. * - shows frustum, line of sight and up of the camera
  19613. * - suitable for fast updates
  19614. * - based on frustum visualization in lightgl.js shadowmap example
  19615. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19616. */
  19617. THREE.CameraHelper = function ( camera ) {
  19618. THREE.Line.call( this );
  19619. var scope = this;
  19620. this.geometry = new THREE.Geometry();
  19621. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19622. this.type = THREE.LinePieces;
  19623. this.matrixWorld = camera.matrixWorld;
  19624. this.matrixAutoUpdate = false;
  19625. this.pointMap = {};
  19626. // colors
  19627. var hexFrustum = 0xffaa00;
  19628. var hexCone = 0xff0000;
  19629. var hexUp = 0x00aaff;
  19630. var hexTarget = 0xffffff;
  19631. var hexCross = 0x333333;
  19632. // near
  19633. addLine( "n1", "n2", hexFrustum );
  19634. addLine( "n2", "n4", hexFrustum );
  19635. addLine( "n4", "n3", hexFrustum );
  19636. addLine( "n3", "n1", hexFrustum );
  19637. // far
  19638. addLine( "f1", "f2", hexFrustum );
  19639. addLine( "f2", "f4", hexFrustum );
  19640. addLine( "f4", "f3", hexFrustum );
  19641. addLine( "f3", "f1", hexFrustum );
  19642. // sides
  19643. addLine( "n1", "f1", hexFrustum );
  19644. addLine( "n2", "f2", hexFrustum );
  19645. addLine( "n3", "f3", hexFrustum );
  19646. addLine( "n4", "f4", hexFrustum );
  19647. // cone
  19648. addLine( "p", "n1", hexCone );
  19649. addLine( "p", "n2", hexCone );
  19650. addLine( "p", "n3", hexCone );
  19651. addLine( "p", "n4", hexCone );
  19652. // up
  19653. addLine( "u1", "u2", hexUp );
  19654. addLine( "u2", "u3", hexUp );
  19655. addLine( "u3", "u1", hexUp );
  19656. // target
  19657. addLine( "c", "t", hexTarget );
  19658. addLine( "p", "c", hexCross );
  19659. // cross
  19660. addLine( "cn1", "cn2", hexCross );
  19661. addLine( "cn3", "cn4", hexCross );
  19662. addLine( "cf1", "cf2", hexCross );
  19663. addLine( "cf3", "cf4", hexCross );
  19664. this.camera = camera;
  19665. function addLine( a, b, hex ) {
  19666. addPoint( a, hex );
  19667. addPoint( b, hex );
  19668. }
  19669. function addPoint( id, hex ) {
  19670. scope.geometry.vertices.push( new THREE.Vector3() );
  19671. scope.geometry.colors.push( new THREE.Color( hex ) );
  19672. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  19673. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  19674. }
  19675. this.update( camera );
  19676. };
  19677. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  19678. THREE.CameraHelper.prototype.update = function () {
  19679. var scope = this;
  19680. var w = 1, h = 1;
  19681. // we need just camera projection matrix
  19682. // world matrix must be identity
  19683. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  19684. // center / target
  19685. setPoint( "c", 0, 0, -1 );
  19686. setPoint( "t", 0, 0, 1 );
  19687. // near
  19688. setPoint( "n1", -w, -h, -1 );
  19689. setPoint( "n2", w, -h, -1 );
  19690. setPoint( "n3", -w, h, -1 );
  19691. setPoint( "n4", w, h, -1 );
  19692. // far
  19693. setPoint( "f1", -w, -h, 1 );
  19694. setPoint( "f2", w, -h, 1 );
  19695. setPoint( "f3", -w, h, 1 );
  19696. setPoint( "f4", w, h, 1 );
  19697. // up
  19698. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19699. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19700. setPoint( "u3", 0, h * 2, -1 );
  19701. // cross
  19702. setPoint( "cf1", -w, 0, 1 );
  19703. setPoint( "cf2", w, 0, 1 );
  19704. setPoint( "cf3", 0, -h, 1 );
  19705. setPoint( "cf4", 0, h, 1 );
  19706. setPoint( "cn1", -w, 0, -1 );
  19707. setPoint( "cn2", w, 0, -1 );
  19708. setPoint( "cn3", 0, -h, -1 );
  19709. setPoint( "cn4", 0, h, -1 );
  19710. function setPoint( point, x, y, z ) {
  19711. THREE.CameraHelper.__v.set( x, y, z );
  19712. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19713. var points = scope.pointMap[ point ];
  19714. if ( points !== undefined ) {
  19715. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19716. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  19717. }
  19718. }
  19719. }
  19720. this.geometry.verticesNeedUpdate = true;
  19721. };
  19722. THREE.CameraHelper.__projector = new THREE.Projector();
  19723. THREE.CameraHelper.__v = new THREE.Vector3();
  19724. THREE.CameraHelper.__c = new THREE.Camera();
  19725. /**
  19726. * @author alteredq / http://alteredqualia.com/
  19727. *
  19728. * - shows directional light color, intensity, position, orientation and target
  19729. */
  19730. THREE.DirectionalLightHelper = function ( light, sphereSize, arrowLength ) {
  19731. THREE.Object3D.call( this );
  19732. this.light = light;
  19733. // position
  19734. this.position = light.position;
  19735. // direction
  19736. this.direction = new THREE.Vector3();
  19737. this.direction.sub( light.target.position, light.position );
  19738. // color
  19739. this.color = light.color.clone();
  19740. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19741. this.color.r *= intensity;
  19742. this.color.g *= intensity;
  19743. this.color.b *= intensity;
  19744. var hexColor = this.color.getHex();
  19745. // light helper
  19746. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19747. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19748. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19749. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19750. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19751. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19752. this.lightArrow.cone.material.fog = false;
  19753. this.lightArrow.line.material.fog = false;
  19754. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19755. this.add( this.lightArrow );
  19756. this.add( this.lightSphere );
  19757. this.add( this.lightRays );
  19758. this.lightSphere.properties.isGizmo = true;
  19759. this.lightSphere.properties.gizmoSubject = light;
  19760. this.lightSphere.properties.gizmoRoot = this;
  19761. // light target helper
  19762. this.targetSphere = null;
  19763. if ( light.target.properties.targetInverse ) {
  19764. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19765. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  19766. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  19767. this.targetSphere.position = light.target.position;
  19768. this.targetSphere.properties.isGizmo = true;
  19769. this.targetSphere.properties.gizmoSubject = light.target;
  19770. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  19771. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  19772. var lineGeometry = new THREE.Geometry();
  19773. lineGeometry.vertices.push( this.position.clone() );
  19774. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  19775. lineGeometry.computeLineDistances();
  19776. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  19777. this.targetLine.properties.isGizmo = true;
  19778. }
  19779. //
  19780. this.properties.isGizmo = true;
  19781. }
  19782. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19783. THREE.DirectionalLightHelper.prototype.update = function () {
  19784. // update arrow orientation
  19785. // pointing from light to target
  19786. this.direction.sub( this.light.target.position, this.light.position );
  19787. this.lightArrow.setDirection( this.direction );
  19788. // update arrow, spheres, rays and line colors to light color * light intensity
  19789. this.color.copy( this.light.color );
  19790. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19791. this.color.r *= intensity;
  19792. this.color.g *= intensity;
  19793. this.color.b *= intensity;
  19794. this.lightArrow.setColor( this.color.getHex() );
  19795. this.lightSphere.material.color.copy( this.color );
  19796. this.lightRays.material.color.copy( this.color );
  19797. this.targetSphere.material.color.copy( this.color );
  19798. this.targetLine.material.color.copy( this.color );
  19799. // update target line vertices
  19800. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  19801. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  19802. this.targetLine.geometry.computeLineDistances();
  19803. this.targetLine.geometry.verticesNeedUpdate = true;
  19804. }
  19805. /**
  19806. * @author alteredq / http://alteredqualia.com/
  19807. *
  19808. * - shows hemisphere light intensity, sky and ground colors and directions
  19809. */
  19810. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  19811. THREE.Object3D.call( this );
  19812. this.light = light;
  19813. // position
  19814. this.position = light.position;
  19815. //
  19816. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19817. // sky color
  19818. this.color = light.color.clone();
  19819. this.color.r *= intensity;
  19820. this.color.g *= intensity;
  19821. this.color.b *= intensity;
  19822. var hexColor = this.color.getHex();
  19823. // ground color
  19824. this.groundColor = light.groundColor.clone();
  19825. this.groundColor.r *= intensity;
  19826. this.groundColor.g *= intensity;
  19827. this.groundColor.b *= intensity;
  19828. var hexColorGround = this.groundColor.getHex();
  19829. // double colored light bulb
  19830. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  19831. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  19832. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19833. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  19834. bulbGeometry.materials[ 0 ] = bulbSkyMaterial;
  19835. bulbGroundGeometry.materials[ 0 ] = bulbGroundMaterial;
  19836. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  19837. bulbGeometry.faces[ i ].materialIndex = 0;
  19838. }
  19839. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  19840. bulbGroundGeometry.faces[ i ].materialIndex = 0;
  19841. }
  19842. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  19843. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial() );
  19844. // arrows for sky and ground light directions
  19845. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  19846. this.lightArrow.rotation.x = Math.PI;
  19847. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  19848. var joint = new THREE.Object3D();
  19849. joint.rotation.x = -Math.PI * 0.5;
  19850. joint.add( this.lightSphere );
  19851. joint.add( this.lightArrow );
  19852. joint.add( this.lightArrowGround );
  19853. this.add( joint );
  19854. //
  19855. this.lightSphere.properties.isGizmo = true;
  19856. this.lightSphere.properties.gizmoSubject = light;
  19857. this.lightSphere.properties.gizmoRoot = this;
  19858. //
  19859. this.properties.isGizmo = true;
  19860. //
  19861. this.target = new THREE.Vector3();
  19862. this.lookAt( this.target );
  19863. }
  19864. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19865. THREE.HemisphereLightHelper.prototype.update = function () {
  19866. // update sphere sky and ground colors to light color * light intensity
  19867. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19868. this.color.copy( this.light.color );
  19869. this.groundColor.copy( this.light.groundColor );
  19870. this.color.r *= intensity;
  19871. this.color.g *= intensity;
  19872. this.color.b *= intensity;
  19873. this.groundColor.r *= intensity;
  19874. this.groundColor.g *= intensity;
  19875. this.groundColor.b *= intensity;
  19876. this.lightSphere.geometry.materials[ 0 ].color.copy( this.color );
  19877. this.lightSphere.geometry.materials[ 1 ].color.copy( this.groundColor );
  19878. this.lightArrow.setColor( this.color.getHex() );
  19879. this.lightArrowGround.setColor( this.groundColor.getHex() );
  19880. this.lookAt( this.target );
  19881. }
  19882. /**
  19883. * @author alteredq / http://alteredqualia.com/
  19884. *
  19885. * - shows point light color, intensity, position and distance
  19886. */
  19887. THREE.PointLightHelper = function ( light, sphereSize ) {
  19888. THREE.Object3D.call( this );
  19889. this.light = light;
  19890. // position
  19891. this.position = light.position;
  19892. // color
  19893. this.color = light.color.clone();
  19894. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19895. this.color.r *= intensity;
  19896. this.color.g *= intensity;
  19897. this.color.b *= intensity;
  19898. var hexColor = this.color.getHex();
  19899. // light helper
  19900. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19901. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19902. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  19903. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19904. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19905. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  19906. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19907. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19908. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  19909. var d = light.distance;
  19910. if ( d === 0.0 ) {
  19911. this.lightDistance.visible = false;
  19912. } else {
  19913. this.lightDistance.scale.set( d, d, d );
  19914. }
  19915. this.add( this.lightSphere );
  19916. this.add( this.lightRays );
  19917. this.add( this.lightDistance );
  19918. //
  19919. this.lightSphere.properties.isGizmo = true;
  19920. this.lightSphere.properties.gizmoSubject = light;
  19921. this.lightSphere.properties.gizmoRoot = this;
  19922. //
  19923. this.properties.isGizmo = true;
  19924. }
  19925. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19926. THREE.PointLightHelper.prototype.update = function () {
  19927. // update sphere and rays colors to light color * light intensity
  19928. this.color.copy( this.light.color );
  19929. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19930. this.color.r *= intensity;
  19931. this.color.g *= intensity;
  19932. this.color.b *= intensity;
  19933. this.lightSphere.material.color.copy( this.color );
  19934. this.lightRays.material.color.copy( this.color );
  19935. this.lightDistance.material.color.copy( this.color );
  19936. //
  19937. var d = this.light.distance;
  19938. if ( d === 0.0 ) {
  19939. this.lightDistance.visible = false;
  19940. } else {
  19941. this.lightDistance.visible = true;
  19942. this.lightDistance.scale.set( d, d, d );
  19943. }
  19944. }
  19945. /**
  19946. * @author alteredq / http://alteredqualia.com/
  19947. *
  19948. * - shows spot light color, intensity, position, orientation, light cone and target
  19949. */
  19950. THREE.SpotLightHelper = function ( light, sphereSize, arrowLength ) {
  19951. THREE.Object3D.call( this );
  19952. this.light = light;
  19953. // position
  19954. this.position = light.position;
  19955. // direction
  19956. this.direction = new THREE.Vector3();
  19957. this.direction.sub( light.target.position, light.position );
  19958. // color
  19959. this.color = light.color.clone();
  19960. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19961. this.color.r *= intensity;
  19962. this.color.g *= intensity;
  19963. this.color.b *= intensity;
  19964. var hexColor = this.color.getHex();
  19965. // light helper
  19966. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19967. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19968. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  19969. var coneMatrix = new THREE.Matrix4();
  19970. coneMatrix.rotateX( -Math.PI/2 );
  19971. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  19972. coneGeometry.applyMatrix( coneMatrix );
  19973. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19974. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19975. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  19976. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19977. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19978. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  19979. var coneLength = light.distance ? light.distance : 10000;
  19980. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  19981. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  19982. this.lightArrow.cone.material.fog = false;
  19983. this.lightArrow.line.material.fog = false;
  19984. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19985. this.gyroscope = new THREE.Gyroscope();
  19986. this.gyroscope.add( this.lightArrow );
  19987. this.gyroscope.add( this.lightSphere );
  19988. this.gyroscope.add( this.lightRays );
  19989. this.add( this.gyroscope );
  19990. this.add( this.lightCone );
  19991. this.lookAt( light.target.position );
  19992. this.lightSphere.properties.isGizmo = true;
  19993. this.lightSphere.properties.gizmoSubject = light;
  19994. this.lightSphere.properties.gizmoRoot = this;
  19995. // light target helper
  19996. this.targetSphere = null;
  19997. if ( light.target.properties.targetInverse ) {
  19998. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19999. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20000. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20001. this.targetSphere.position = light.target.position;
  20002. this.targetSphere.properties.isGizmo = true;
  20003. this.targetSphere.properties.gizmoSubject = light.target;
  20004. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20005. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20006. var lineGeometry = new THREE.Geometry();
  20007. lineGeometry.vertices.push( this.position.clone() );
  20008. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20009. lineGeometry.computeLineDistances();
  20010. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20011. this.targetLine.properties.isGizmo = true;
  20012. }
  20013. //
  20014. this.properties.isGizmo = true;
  20015. }
  20016. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20017. THREE.SpotLightHelper.prototype.update = function () {
  20018. // update arrow orientation
  20019. // pointing from light to target
  20020. this.direction.sub( this.light.target.position, this.light.position );
  20021. this.lightArrow.setDirection( this.direction );
  20022. // update light cone orientation and size
  20023. this.lookAt( this.light.target.position );
  20024. var coneLength = this.light.distance ? this.light.distance : 10000;
  20025. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20026. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20027. // update arrow, spheres, rays and line colors to light color * light intensity
  20028. this.color.copy( this.light.color );
  20029. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20030. this.color.r *= intensity;
  20031. this.color.g *= intensity;
  20032. this.color.b *= intensity;
  20033. this.lightArrow.setColor( this.color.getHex() );
  20034. this.lightSphere.material.color.copy( this.color );
  20035. this.lightRays.material.color.copy( this.color );
  20036. this.lightCone.material.color.copy( this.color );
  20037. this.targetSphere.material.color.copy( this.color );
  20038. this.targetLine.material.color.copy( this.color );
  20039. // update target line vertices
  20040. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20041. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20042. this.targetLine.geometry.computeLineDistances();
  20043. this.targetLine.geometry.verticesNeedUpdate = true;
  20044. }
  20045. /*
  20046. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  20047. *
  20048. * Subdivision Geometry Modifier
  20049. * using Catmull-Clark Subdivision Surfaces
  20050. * for creating smooth geometry meshes
  20051. *
  20052. * Note: a modifier modifies vertices and faces of geometry,
  20053. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  20054. *
  20055. * Readings:
  20056. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  20057. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  20058. * http://xrt.wikidot.com/blog:31
  20059. * "Subdivision Surfaces in Character Animation"
  20060. *
  20061. * (on boundary edges)
  20062. * http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  20063. * https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description
  20064. *
  20065. * Supports:
  20066. * Closed and Open geometries.
  20067. *
  20068. * TODO:
  20069. * crease vertex and "semi-sharp" features
  20070. * selective subdivision
  20071. */
  20072. THREE.SubdivisionModifier = function( subdivisions ) {
  20073. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  20074. // Settings
  20075. this.useOldVertexColors = false;
  20076. this.supportUVs = true;
  20077. this.debug = false;
  20078. };
  20079. // Applies the "modify" pattern
  20080. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  20081. var repeats = this.subdivisions;
  20082. while ( repeats-- > 0 ) {
  20083. this.smooth( geometry );
  20084. }
  20085. };
  20086. /// REFACTORING THIS OUT
  20087. THREE.GeometryUtils.orderedKey = function ( a, b ) {
  20088. return Math.min( a, b ) + "_" + Math.max( a, b );
  20089. };
  20090. // Returns a hashmap - of { edge_key: face_index }
  20091. THREE.GeometryUtils.computeEdgeFaces = function ( geometry ) {
  20092. var i, il, v1, v2, j, k,
  20093. face, faceIndices, faceIndex,
  20094. edge,
  20095. hash,
  20096. edgeFaceMap = {};
  20097. var orderedKey = THREE.GeometryUtils.orderedKey;
  20098. function mapEdgeHash( hash, i ) {
  20099. if ( edgeFaceMap[ hash ] === undefined ) {
  20100. edgeFaceMap[ hash ] = [];
  20101. }
  20102. edgeFaceMap[ hash ].push( i );
  20103. }
  20104. // construct vertex -> face map
  20105. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  20106. face = geometry.faces[ i ];
  20107. if ( face instanceof THREE.Face3 ) {
  20108. hash = orderedKey( face.a, face.b );
  20109. mapEdgeHash( hash, i );
  20110. hash = orderedKey( face.b, face.c );
  20111. mapEdgeHash( hash, i );
  20112. hash = orderedKey( face.c, face.a );
  20113. mapEdgeHash( hash, i );
  20114. } else if ( face instanceof THREE.Face4 ) {
  20115. hash = orderedKey( face.a, face.b );
  20116. mapEdgeHash( hash, i );
  20117. hash = orderedKey( face.b, face.c );
  20118. mapEdgeHash( hash, i );
  20119. hash = orderedKey( face.c, face.d );
  20120. mapEdgeHash( hash, i );
  20121. hash = orderedKey( face.d, face.a );
  20122. mapEdgeHash( hash, i );
  20123. }
  20124. }
  20125. // extract faces
  20126. // var edges = [];
  20127. //
  20128. // var numOfEdges = 0;
  20129. // for (i in edgeFaceMap) {
  20130. // numOfEdges++;
  20131. //
  20132. // edge = edgeFaceMap[i];
  20133. // edges.push(edge);
  20134. //
  20135. // }
  20136. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  20137. return edgeFaceMap;
  20138. }
  20139. /////////////////////////////
  20140. // Performs an iteration of Catmull-Clark Subdivision
  20141. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  20142. //debug( 'running smooth' );
  20143. // New set of vertices, faces and uvs
  20144. var newVertices = [], newFaces = [], newUVs = [];
  20145. function v( x, y, z ) {
  20146. newVertices.push( new THREE.Vector3( x, y, z ) );
  20147. }
  20148. var scope = this;
  20149. var orderedKey = THREE.GeometryUtils.orderedKey;
  20150. var computeEdgeFaces = THREE.GeometryUtils.computeEdgeFaces;
  20151. function assert() {
  20152. if (scope.debug && console && console.assert) console.assert.apply(console, arguments);
  20153. }
  20154. function debug() {
  20155. if (scope.debug) console.log.apply(console, arguments);
  20156. }
  20157. function warn() {
  20158. if (console)
  20159. console.log.apply(console, arguments);
  20160. }
  20161. function f4( a, b, c, d, oldFace, orders, facei ) {
  20162. // TODO move vertex selection over here!
  20163. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  20164. if (scope.useOldVertexColors) {
  20165. newFace.vertexColors = [];
  20166. var color, tmpColor, order;
  20167. for (var i=0;i<4;i++) {
  20168. order = orders[i];
  20169. color = new THREE.Color(),
  20170. color.setRGB(0,0,0);
  20171. for (var j=0, jl=0; j<order.length;j++) {
  20172. tmpColor = oldFace.vertexColors[order[j]-1];
  20173. color.r += tmpColor.r;
  20174. color.g += tmpColor.g;
  20175. color.b += tmpColor.b;
  20176. }
  20177. color.r /= order.length;
  20178. color.g /= order.length;
  20179. color.b /= order.length;
  20180. newFace.vertexColors[i] = color;
  20181. }
  20182. }
  20183. newFaces.push( newFace );
  20184. if (scope.supportUVs) {
  20185. var aUv = [
  20186. getUV(a, ''),
  20187. getUV(b, facei),
  20188. getUV(c, facei),
  20189. getUV(d, facei)
  20190. ];
  20191. if (!aUv[0]) debug('a :( ', a+':'+facei);
  20192. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  20193. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  20194. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  20195. else
  20196. newUVs.push( aUv );
  20197. }
  20198. }
  20199. var originalPoints = oldGeometry.vertices;
  20200. var originalFaces = oldGeometry.faces;
  20201. var originalVerticesLength = originalPoints.length;
  20202. var newPoints = originalPoints.concat(); // New set of vertices to work on
  20203. var facePoints = [], // these are new points on exisiting faces
  20204. edgePoints = {}; // these are new points on exisiting edges
  20205. var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them
  20206. // TODO: handle this correctly.
  20207. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  20208. function debugCoreStuff() {
  20209. console.log('facePoints', facePoints, 'edgePoints', edgePoints);
  20210. console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap);
  20211. }
  20212. function getUV(vertexNo, oldFaceNo) {
  20213. var j,jl;
  20214. var key = vertexNo+':'+oldFaceNo;
  20215. var theUV = uvForVertices[key];
  20216. if (!theUV) {
  20217. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  20218. debug('face pt');
  20219. } else {
  20220. debug('edge pt');
  20221. }
  20222. warn('warning, UV not found for', key);
  20223. return null;
  20224. }
  20225. return theUV;
  20226. // Original faces -> Vertex Nos.
  20227. // new Facepoint -> Vertex Nos.
  20228. // edge Points
  20229. }
  20230. function addUV(vertexNo, oldFaceNo, value) {
  20231. var key = vertexNo+':'+oldFaceNo;
  20232. if (!(key in uvForVertices)) {
  20233. uvForVertices[key] = value;
  20234. } else {
  20235. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  20236. }
  20237. }
  20238. // Step 1
  20239. // For each face, add a face point
  20240. // Set each face point to be the centroid of all original points for the respective face.
  20241. // debug(oldGeometry);
  20242. var i, il, j, jl, face;
  20243. // For Uvs
  20244. var uvs = oldGeometry.faceVertexUvs[0];
  20245. var abcd = 'abcd', vertice;
  20246. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  20247. if (scope.supportUVs)
  20248. for (i=0, il = uvs.length; i<il; i++ ) {
  20249. for (j=0,jl=uvs[i].length;j<jl;j++) {
  20250. vertice = originalFaces[i][abcd.charAt(j)];
  20251. addUV(vertice, i, uvs[i][j]);
  20252. }
  20253. }
  20254. if (uvs.length == 0) scope.supportUVs = false;
  20255. // Additional UVs check, if we index original
  20256. var uvCount = 0;
  20257. for (var u in uvForVertices) {
  20258. uvCount++;
  20259. }
  20260. if (!uvCount) {
  20261. scope.supportUVs = false;
  20262. debug('no uvs');
  20263. }
  20264. var avgUv ;
  20265. for (i=0, il = originalFaces.length; i<il ;i++) {
  20266. face = originalFaces[ i ];
  20267. facePoints.push( face.centroid );
  20268. newPoints.push( face.centroid );
  20269. if (!scope.supportUVs) continue;
  20270. // Prepare subdivided uv
  20271. avgUv = new THREE.UV();
  20272. if ( face instanceof THREE.Face3 ) {
  20273. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  20274. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  20275. avgUv.u /= 3;
  20276. avgUv.v /= 3;
  20277. } else if ( face instanceof THREE.Face4 ) {
  20278. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  20279. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  20280. avgUv.u /= 4;
  20281. avgUv.v /= 4;
  20282. }
  20283. addUV(originalVerticesLength + i, '', avgUv);
  20284. }
  20285. // Step 2
  20286. // For each edge, add an edge point.
  20287. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  20288. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]}
  20289. var edge, faceIndexA, faceIndexB, avg;
  20290. // debug('edgeFaceMap', edgeFaceMap);
  20291. var edgeCount = 0;
  20292. var edgeVertex, edgeVertexA, edgeVertexB;
  20293. ////
  20294. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  20295. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  20296. function addVertexEdgeMap(vertex, edge) {
  20297. if (vertexEdgeMap[vertex]===undefined) {
  20298. vertexEdgeMap[vertex] = [];
  20299. }
  20300. vertexEdgeMap[vertex].push(edge);
  20301. }
  20302. function addVertexFaceMap(vertex, face, edge) {
  20303. if (vertexFaceMap[vertex]===undefined) {
  20304. vertexFaceMap[vertex] = {};
  20305. }
  20306. vertexFaceMap[vertex][face] = edge;
  20307. // vertexFaceMap[vertex][face] = null;
  20308. }
  20309. // Prepares vertexEdgeMap and vertexFaceMap
  20310. for (i in edgeFaceMap) { // This is for every edge
  20311. edge = edgeFaceMap[i];
  20312. edgeVertex = i.split('_');
  20313. edgeVertexA = edgeVertex[0];
  20314. edgeVertexB = edgeVertex[1];
  20315. // Maps an edgeVertex to connecting edges
  20316. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  20317. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  20318. for (j=0,jl=edge.length;j<jl;j++) {
  20319. face = edge[j];
  20320. addVertexFaceMap(edgeVertexA, face, i);
  20321. addVertexFaceMap(edgeVertexB, face, i);
  20322. }
  20323. // {edge vertex: { face1: edge_key, face2: edge_key.. } }
  20324. // this thing is fishy right now.
  20325. if (edge.length < 2) {
  20326. // edge is "sharp";
  20327. sharpEdges[i] = true;
  20328. sharpVertices[edgeVertexA] = true;
  20329. sharpVertices[edgeVertexB] = true;
  20330. }
  20331. }
  20332. for (i in edgeFaceMap) {
  20333. edge = edgeFaceMap[i];
  20334. faceIndexA = edge[0]; // face index a
  20335. faceIndexB = edge[1]; // face index b
  20336. edgeVertex = i.split('_');
  20337. edgeVertexA = edgeVertex[0];
  20338. edgeVertexB = edgeVertex[1];
  20339. avg = new THREE.Vector3();
  20340. //debug(i, faceIndexB,facePoints[faceIndexB]);
  20341. assert(edge.length > 0, 'an edge without faces?!');
  20342. if (edge.length==1) {
  20343. avg.addSelf(originalPoints[edgeVertexA]);
  20344. avg.addSelf(originalPoints[edgeVertexB]);
  20345. avg.multiplyScalar(0.5);
  20346. sharpVertices[newPoints.length] = true;
  20347. } else {
  20348. avg.addSelf(facePoints[faceIndexA]);
  20349. avg.addSelf(facePoints[faceIndexB]);
  20350. avg.addSelf(originalPoints[edgeVertexA]);
  20351. avg.addSelf(originalPoints[edgeVertexB]);
  20352. avg.multiplyScalar(0.25);
  20353. }
  20354. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  20355. newPoints.push( avg );
  20356. edgeCount ++;
  20357. if (!scope.supportUVs) {
  20358. continue;
  20359. }
  20360. // Prepare subdivided uv
  20361. avgUv = new THREE.UV();
  20362. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  20363. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  20364. avgUv.u /= 2;
  20365. avgUv.v /= 2;
  20366. addUV(edgePoints[i], faceIndexA, avgUv);
  20367. if (edge.length>=2) {
  20368. assert(edge.length == 2, 'did we plan for more than 2 edges?');
  20369. avgUv = new THREE.UV();
  20370. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  20371. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  20372. avgUv.u /= 2;
  20373. avgUv.v /= 2;
  20374. addUV(edgePoints[i], faceIndexB, avgUv);
  20375. }
  20376. }
  20377. debug('-- Step 2 done');
  20378. // Step 3
  20379. // For each face point, add an edge for every edge of the face,
  20380. // connecting the face point to each edge point for the face.
  20381. var facePt, currentVerticeIndex;
  20382. var hashAB, hashBC, hashCD, hashDA, hashCA;
  20383. var abc123 = ['123', '12', '2', '23'];
  20384. var bca123 = ['123', '23', '3', '31'];
  20385. var cab123 = ['123', '31', '1', '12'];
  20386. var abc1234 = ['1234', '12', '2', '23'];
  20387. var bcd1234 = ['1234', '23', '3', '34'];
  20388. var cda1234 = ['1234', '34', '4', '41'];
  20389. var dab1234 = ['1234', '41', '1', '12'];
  20390. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  20391. facePt = facePoints[i];
  20392. face = originalFaces[i];
  20393. currentVerticeIndex = originalVerticesLength+ i;
  20394. if ( face instanceof THREE.Face3 ) {
  20395. // create 3 face4s
  20396. hashAB = orderedKey( face.a, face.b );
  20397. hashBC = orderedKey( face.b, face.c );
  20398. hashCA = orderedKey( face.c, face.a );
  20399. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  20400. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  20401. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  20402. } else if ( face instanceof THREE.Face4 ) {
  20403. // create 4 face4s
  20404. hashAB = orderedKey( face.a, face.b );
  20405. hashBC = orderedKey( face.b, face.c );
  20406. hashCD = orderedKey( face.c, face.d );
  20407. hashDA = orderedKey( face.d, face.a );
  20408. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  20409. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  20410. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  20411. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  20412. } else {
  20413. debug('face should be a face!', face);
  20414. }
  20415. }
  20416. newVertices = newPoints;
  20417. // Step 4
  20418. // For each original point P,
  20419. // take the average F of all n face points for faces touching P,
  20420. // and take the average R of all n edge midpoints for edges touching P,
  20421. // where each edge midpoint is the average of its two endpoint vertices.
  20422. // Move each original point to the point
  20423. var F = new THREE.Vector3();
  20424. var R = new THREE.Vector3();
  20425. var n;
  20426. for (i=0, il = originalPoints.length; i<il; i++) {
  20427. // (F + 2R + (n-3)P) / n
  20428. if (vertexEdgeMap[i]===undefined) continue;
  20429. F.set(0,0,0);
  20430. R.set(0,0,0);
  20431. var newPos = new THREE.Vector3(0,0,0);
  20432. var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?)
  20433. for (j in vertexFaceMap[i]) {
  20434. F.addSelf(facePoints[j]);
  20435. f++;
  20436. }
  20437. var sharpEdgeCount = 0;
  20438. n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges
  20439. // Are we on the border?
  20440. var boundary_case = f != n;
  20441. // if (boundary_case) {
  20442. // console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2);
  20443. // }
  20444. for (j=0;j<n;j++) {
  20445. if (
  20446. sharpEdges[
  20447. orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  20448. ]) {
  20449. sharpEdgeCount++;
  20450. }
  20451. }
  20452. // if ( sharpEdgeCount==2 ) {
  20453. // continue;
  20454. // // Do not move vertex if there's 2 connecting sharp edges.
  20455. // }
  20456. /*
  20457. if (sharpEdgeCount>2) {
  20458. // TODO
  20459. }
  20460. */
  20461. F.divideScalar(f);
  20462. var boundary_edges = 0;
  20463. if (boundary_case) {
  20464. var bb_edge;
  20465. for (j=0; j<n;j++) {
  20466. edge = vertexEdgeMap[i][j];
  20467. bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1
  20468. if (bb_edge) {
  20469. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20470. R.addSelf(midPt);
  20471. boundary_edges++;
  20472. }
  20473. }
  20474. R.divideScalar(4);
  20475. // console.log(j + ' --- ' + n + ' --- ' + boundary_edges);
  20476. assert(boundary_edges == 2, 'should have only 2 boundary edges');
  20477. } else {
  20478. for (j=0; j<n;j++) {
  20479. edge = vertexEdgeMap[i][j];
  20480. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20481. R.addSelf(midPt);
  20482. }
  20483. R.divideScalar(n);
  20484. }
  20485. // Sum the formula
  20486. newPos.addSelf(originalPoints[i]);
  20487. if (boundary_case) {
  20488. newPos.divideScalar(2);
  20489. newPos.addSelf(R);
  20490. } else {
  20491. newPos.multiplyScalar(n - 3);
  20492. newPos.addSelf(F);
  20493. newPos.addSelf(R.multiplyScalar(2));
  20494. newPos.divideScalar(n);
  20495. }
  20496. newVertices[i] = newPos;
  20497. }
  20498. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  20499. newGeometry.vertices = newVertices;
  20500. newGeometry.faces = newFaces;
  20501. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  20502. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  20503. newGeometry.computeCentroids();
  20504. newGeometry.computeFaceNormals();
  20505. newGeometry.computeVertexNormals();
  20506. };/**
  20507. * @author alteredq / http://alteredqualia.com/
  20508. */
  20509. THREE.ImmediateRenderObject = function ( ) {
  20510. THREE.Object3D.call( this );
  20511. this.render = function ( renderCallback ) { };
  20512. };
  20513. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20514. /**
  20515. * @author mikael emtinger / http://gomo.se/
  20516. * @author alteredq / http://alteredqualia.com/
  20517. */
  20518. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20519. THREE.Object3D.call( this );
  20520. this.lensFlares = [];
  20521. this.positionScreen = new THREE.Vector3();
  20522. this.customUpdateCallback = undefined;
  20523. if( texture !== undefined ) {
  20524. this.add( texture, size, distance, blending, color );
  20525. }
  20526. };
  20527. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20528. /*
  20529. * Add: adds another flare
  20530. */
  20531. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20532. if( size === undefined ) size = -1;
  20533. if( distance === undefined ) distance = 0;
  20534. if( opacity === undefined ) opacity = 1;
  20535. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20536. if( blending === undefined ) blending = THREE.NormalBlending;
  20537. distance = Math.min( distance, Math.max( 0, distance ) );
  20538. this.lensFlares.push( { texture: texture, // THREE.Texture
  20539. size: size, // size in pixels (-1 = use texture.width)
  20540. distance: distance, // distance (0-1) from light source (0=at light source)
  20541. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20542. scale: 1, // scale
  20543. rotation: 1, // rotation
  20544. opacity: opacity, // opacity
  20545. color: color, // color
  20546. blending: blending } ); // blending
  20547. };
  20548. /*
  20549. * Update lens flares update positions on all flares based on the screen position
  20550. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20551. */
  20552. THREE.LensFlare.prototype.updateLensFlares = function () {
  20553. var f, fl = this.lensFlares.length;
  20554. var flare;
  20555. var vecX = -this.positionScreen.x * 2;
  20556. var vecY = -this.positionScreen.y * 2;
  20557. for( f = 0; f < fl; f ++ ) {
  20558. flare = this.lensFlares[ f ];
  20559. flare.x = this.positionScreen.x + vecX * flare.distance;
  20560. flare.y = this.positionScreen.y + vecY * flare.distance;
  20561. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20562. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20563. }
  20564. };
  20565. /**
  20566. * @author alteredq / http://alteredqualia.com/
  20567. */
  20568. THREE.MorphBlendMesh = function( geometry, material ) {
  20569. THREE.Mesh.call( this, geometry, material );
  20570. this.animationsMap = {};
  20571. this.animationsList = [];
  20572. // prepare default animation
  20573. // (all frames played together in 1 second)
  20574. var numFrames = this.geometry.morphTargets.length;
  20575. var name = "__default";
  20576. var startFrame = 0;
  20577. var endFrame = numFrames - 1;
  20578. var fps = numFrames / 1;
  20579. this.createAnimation( name, startFrame, endFrame, fps );
  20580. this.setAnimationWeight( name, 1 );
  20581. };
  20582. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20583. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20584. var animation = {
  20585. startFrame: start,
  20586. endFrame: end,
  20587. length: end - start + 1,
  20588. fps: fps,
  20589. duration: ( end - start ) / fps,
  20590. lastFrame: 0,
  20591. currentFrame: 0,
  20592. active: false,
  20593. time: 0,
  20594. direction: 1,
  20595. weight: 1,
  20596. directionBackwards: false,
  20597. mirroredLoop: false
  20598. };
  20599. this.animationsMap[ name ] = animation;
  20600. this.animationsList.push( animation );
  20601. };
  20602. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20603. var pattern = /([a-z]+)(\d+)/;
  20604. var firstAnimation, frameRanges = {};
  20605. var geometry = this.geometry;
  20606. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20607. var morph = geometry.morphTargets[ i ];
  20608. var chunks = morph.name.match( pattern );
  20609. if ( chunks && chunks.length > 1 ) {
  20610. var name = chunks[ 1 ];
  20611. var num = chunks[ 2 ];
  20612. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20613. var range = frameRanges[ name ];
  20614. if ( i < range.start ) range.start = i;
  20615. if ( i > range.end ) range.end = i;
  20616. if ( ! firstAnimation ) firstAnimation = name;
  20617. }
  20618. }
  20619. for ( var name in frameRanges ) {
  20620. var range = frameRanges[ name ];
  20621. this.createAnimation( name, range.start, range.end, fps );
  20622. }
  20623. this.firstAnimation = firstAnimation;
  20624. };
  20625. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20626. var animation = this.animationsMap[ name ];
  20627. if ( animation ) {
  20628. animation.direction = 1;
  20629. animation.directionBackwards = false;
  20630. }
  20631. };
  20632. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20633. var animation = this.animationsMap[ name ];
  20634. if ( animation ) {
  20635. animation.direction = -1;
  20636. animation.directionBackwards = true;
  20637. }
  20638. };
  20639. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20640. var animation = this.animationsMap[ name ];
  20641. if ( animation ) {
  20642. animation.fps = fps;
  20643. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20644. }
  20645. };
  20646. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20647. var animation = this.animationsMap[ name ];
  20648. if ( animation ) {
  20649. animation.duration = duration;
  20650. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20651. }
  20652. };
  20653. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20654. var animation = this.animationsMap[ name ];
  20655. if ( animation ) {
  20656. animation.weight = weight;
  20657. }
  20658. };
  20659. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20660. var animation = this.animationsMap[ name ];
  20661. if ( animation ) {
  20662. animation.time = time;
  20663. }
  20664. };
  20665. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20666. var time = 0;
  20667. var animation = this.animationsMap[ name ];
  20668. if ( animation ) {
  20669. time = animation.time;
  20670. }
  20671. return time;
  20672. };
  20673. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20674. var duration = -1;
  20675. var animation = this.animationsMap[ name ];
  20676. if ( animation ) {
  20677. duration = animation.duration;
  20678. }
  20679. return duration;
  20680. };
  20681. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20682. var animation = this.animationsMap[ name ];
  20683. if ( animation ) {
  20684. animation.time = 0;
  20685. animation.active = true;
  20686. } else {
  20687. console.warn( "animation[" + name + "] undefined" );
  20688. }
  20689. };
  20690. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20691. var animation = this.animationsMap[ name ];
  20692. if ( animation ) {
  20693. animation.active = false;
  20694. }
  20695. };
  20696. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20697. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20698. var animation = this.animationsList[ i ];
  20699. if ( ! animation.active ) continue;
  20700. var frameTime = animation.duration / animation.length;
  20701. animation.time += animation.direction * delta;
  20702. if ( animation.mirroredLoop ) {
  20703. if ( animation.time > animation.duration || animation.time < 0 ) {
  20704. animation.direction *= -1;
  20705. if ( animation.time > animation.duration ) {
  20706. animation.time = animation.duration;
  20707. animation.directionBackwards = true;
  20708. }
  20709. if ( animation.time < 0 ) {
  20710. animation.time = 0;
  20711. animation.directionBackwards = false;
  20712. }
  20713. }
  20714. } else {
  20715. animation.time = animation.time % animation.duration;
  20716. if ( animation.time < 0 ) animation.time += animation.duration;
  20717. }
  20718. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20719. var weight = animation.weight;
  20720. if ( keyframe !== animation.currentFrame ) {
  20721. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20722. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20723. this.morphTargetInfluences[ keyframe ] = 0;
  20724. animation.lastFrame = animation.currentFrame;
  20725. animation.currentFrame = keyframe;
  20726. }
  20727. var mix = ( animation.time % frameTime ) / frameTime;
  20728. if ( animation.directionBackwards ) mix = 1 - mix;
  20729. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20730. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20731. }
  20732. };
  20733. /**
  20734. * @author mikael emtinger / http://gomo.se/
  20735. * @author alteredq / http://alteredqualia.com/
  20736. */
  20737. THREE.LensFlarePlugin = function ( ) {
  20738. var _gl, _renderer, _lensFlare = {};
  20739. this.init = function ( renderer ) {
  20740. _gl = renderer.context;
  20741. _renderer = renderer;
  20742. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20743. _lensFlare.faces = new Uint16Array( 6 );
  20744. var i = 0;
  20745. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20746. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20747. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20748. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20749. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20750. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20751. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20752. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20753. i = 0;
  20754. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20755. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20756. // buffers
  20757. _lensFlare.vertexBuffer = _gl.createBuffer();
  20758. _lensFlare.elementBuffer = _gl.createBuffer();
  20759. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20760. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20761. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20762. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20763. // textures
  20764. _lensFlare.tempTexture = _gl.createTexture();
  20765. _lensFlare.occlusionTexture = _gl.createTexture();
  20766. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20767. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20768. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20769. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20770. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20771. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20772. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20773. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20774. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20775. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20776. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20777. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20778. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20779. _lensFlare.hasVertexTexture = false;
  20780. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20781. } else {
  20782. _lensFlare.hasVertexTexture = true;
  20783. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20784. }
  20785. _lensFlare.attributes = {};
  20786. _lensFlare.uniforms = {};
  20787. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20788. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20789. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20790. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20791. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20792. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20793. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20794. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20795. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20796. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20797. _lensFlare.attributesEnabled = false;
  20798. };
  20799. /*
  20800. * Render lens flares
  20801. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20802. * reads these back and calculates occlusion.
  20803. * Then _lensFlare.update_lensFlares() is called to re-position and
  20804. * update transparency of flares. Then they are rendered.
  20805. *
  20806. */
  20807. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20808. var flares = scene.__webglFlares,
  20809. nFlares = flares.length;
  20810. if ( ! nFlares ) return;
  20811. var tempPosition = new THREE.Vector3();
  20812. var invAspect = viewportHeight / viewportWidth,
  20813. halfViewportWidth = viewportWidth * 0.5,
  20814. halfViewportHeight = viewportHeight * 0.5;
  20815. var size = 16 / viewportHeight,
  20816. scale = new THREE.Vector2( size * invAspect, size );
  20817. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20818. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20819. var uniforms = _lensFlare.uniforms,
  20820. attributes = _lensFlare.attributes;
  20821. // set _lensFlare program and reset blending
  20822. _gl.useProgram( _lensFlare.program );
  20823. if ( ! _lensFlare.attributesEnabled ) {
  20824. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20825. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20826. _lensFlare.attributesEnabled = true;
  20827. }
  20828. // loop through all lens flares to update their occlusion and positions
  20829. // setup gl and common used attribs/unforms
  20830. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20831. _gl.uniform1i( uniforms.map, 1 );
  20832. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20833. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20834. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20835. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20836. _gl.disable( _gl.CULL_FACE );
  20837. _gl.depthMask( false );
  20838. var i, j, jl, flare, sprite;
  20839. for ( i = 0; i < nFlares; i ++ ) {
  20840. size = 16 / viewportHeight;
  20841. scale.set( size * invAspect, size );
  20842. // calc object screen position
  20843. flare = flares[ i ];
  20844. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20845. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  20846. camera.projectionMatrix.multiplyVector3( tempPosition );
  20847. // setup arrays for gl programs
  20848. screenPosition.copy( tempPosition )
  20849. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20850. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20851. // screen cull
  20852. if ( _lensFlare.hasVertexTexture || (
  20853. screenPositionPixels.x > 0 &&
  20854. screenPositionPixels.x < viewportWidth &&
  20855. screenPositionPixels.y > 0 &&
  20856. screenPositionPixels.y < viewportHeight ) ) {
  20857. // save current RGB to temp texture
  20858. _gl.activeTexture( _gl.TEXTURE1 );
  20859. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20860. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20861. // render pink quad
  20862. _gl.uniform1i( uniforms.renderType, 0 );
  20863. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20864. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20865. _gl.disable( _gl.BLEND );
  20866. _gl.enable( _gl.DEPTH_TEST );
  20867. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20868. // copy result to occlusionMap
  20869. _gl.activeTexture( _gl.TEXTURE0 );
  20870. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20871. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20872. // restore graphics
  20873. _gl.uniform1i( uniforms.renderType, 1 );
  20874. _gl.disable( _gl.DEPTH_TEST );
  20875. _gl.activeTexture( _gl.TEXTURE1 );
  20876. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20877. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20878. // update object positions
  20879. flare.positionScreen.copy( screenPosition )
  20880. if ( flare.customUpdateCallback ) {
  20881. flare.customUpdateCallback( flare );
  20882. } else {
  20883. flare.updateLensFlares();
  20884. }
  20885. // render flares
  20886. _gl.uniform1i( uniforms.renderType, 2 );
  20887. _gl.enable( _gl.BLEND );
  20888. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20889. sprite = flare.lensFlares[ j ];
  20890. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20891. screenPosition.x = sprite.x;
  20892. screenPosition.y = sprite.y;
  20893. screenPosition.z = sprite.z;
  20894. size = sprite.size * sprite.scale / viewportHeight;
  20895. scale.x = size * invAspect;
  20896. scale.y = size;
  20897. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20898. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20899. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20900. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20901. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20902. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20903. _renderer.setTexture( sprite.texture, 1 );
  20904. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20905. }
  20906. }
  20907. }
  20908. }
  20909. // restore gl
  20910. _gl.enable( _gl.CULL_FACE );
  20911. _gl.enable( _gl.DEPTH_TEST );
  20912. _gl.depthMask( true );
  20913. };
  20914. function createProgram ( shader ) {
  20915. var program = _gl.createProgram();
  20916. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20917. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20918. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20919. _gl.shaderSource( vertexShader, shader.vertexShader );
  20920. _gl.compileShader( fragmentShader );
  20921. _gl.compileShader( vertexShader );
  20922. _gl.attachShader( program, fragmentShader );
  20923. _gl.attachShader( program, vertexShader );
  20924. _gl.linkProgram( program );
  20925. return program;
  20926. };
  20927. };/**
  20928. * @author alteredq / http://alteredqualia.com/
  20929. */
  20930. THREE.ShadowMapPlugin = function ( ) {
  20931. var _gl,
  20932. _renderer,
  20933. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20934. _frustum = new THREE.Frustum(),
  20935. _projScreenMatrix = new THREE.Matrix4(),
  20936. _min = new THREE.Vector3(),
  20937. _max = new THREE.Vector3();
  20938. this.init = function ( renderer ) {
  20939. _gl = renderer.context;
  20940. _renderer = renderer;
  20941. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20942. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20943. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20944. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20945. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20946. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20947. _depthMaterial._shadowPass = true;
  20948. _depthMaterialMorph._shadowPass = true;
  20949. _depthMaterialSkin._shadowPass = true;
  20950. _depthMaterialMorphSkin._shadowPass = true;
  20951. };
  20952. this.render = function ( scene, camera ) {
  20953. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20954. this.update( scene, camera );
  20955. };
  20956. this.update = function ( scene, camera ) {
  20957. var i, il, j, jl, n,
  20958. shadowMap, shadowMatrix, shadowCamera,
  20959. program, buffer, material,
  20960. webglObject, object, light,
  20961. renderList,
  20962. lights = [],
  20963. k = 0,
  20964. fog = null;
  20965. // set GL state for depth map
  20966. _gl.clearColor( 1, 1, 1, 1 );
  20967. _gl.disable( _gl.BLEND );
  20968. _gl.enable( _gl.CULL_FACE );
  20969. _gl.frontFace( _gl.CCW );
  20970. if ( _renderer.shadowMapCullFrontFaces ) {
  20971. _gl.cullFace( _gl.FRONT );
  20972. } else {
  20973. _gl.cullFace( _gl.BACK );
  20974. }
  20975. _renderer.setDepthTest( true );
  20976. // preprocess lights
  20977. // - skip lights that are not casting shadows
  20978. // - create virtual lights for cascaded shadow maps
  20979. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20980. light = scene.__lights[ i ];
  20981. if ( ! light.castShadow ) continue;
  20982. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20983. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20984. var virtualLight;
  20985. if ( ! light.shadowCascadeArray[ n ] ) {
  20986. virtualLight = createVirtualLight( light, n );
  20987. virtualLight.originalCamera = camera;
  20988. var gyro = new THREE.Gyroscope();
  20989. gyro.position = light.shadowCascadeOffset;
  20990. gyro.add( virtualLight );
  20991. gyro.add( virtualLight.target );
  20992. camera.add( gyro );
  20993. light.shadowCascadeArray[ n ] = virtualLight;
  20994. console.log( "Created virtualLight", virtualLight );
  20995. } else {
  20996. virtualLight = light.shadowCascadeArray[ n ];
  20997. }
  20998. updateVirtualLight( light, n );
  20999. lights[ k ] = virtualLight;
  21000. k ++;
  21001. }
  21002. } else {
  21003. lights[ k ] = light;
  21004. k ++;
  21005. }
  21006. }
  21007. // render depth map
  21008. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21009. light = lights[ i ];
  21010. if ( ! light.shadowMap ) {
  21011. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  21012. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21013. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21014. light.shadowMatrix = new THREE.Matrix4();
  21015. }
  21016. if ( ! light.shadowCamera ) {
  21017. if ( light instanceof THREE.SpotLight ) {
  21018. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21019. } else if ( light instanceof THREE.DirectionalLight ) {
  21020. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21021. } else {
  21022. console.error( "Unsupported light type for shadow" );
  21023. continue;
  21024. }
  21025. scene.add( light.shadowCamera );
  21026. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21027. }
  21028. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21029. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21030. light.shadowCamera.add( light.cameraHelper );
  21031. }
  21032. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21033. updateShadowCamera( camera, light );
  21034. }
  21035. shadowMap = light.shadowMap;
  21036. shadowMatrix = light.shadowMatrix;
  21037. shadowCamera = light.shadowCamera;
  21038. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  21039. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  21040. shadowCamera.updateMatrixWorld();
  21041. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21042. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21043. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21044. // compute shadow matrix
  21045. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21046. 0.0, 0.5, 0.0, 0.5,
  21047. 0.0, 0.0, 0.5, 0.5,
  21048. 0.0, 0.0, 0.0, 1.0 );
  21049. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  21050. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  21051. // update camera matrices and frustum
  21052. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  21053. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  21054. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  21055. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  21056. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21057. _frustum.setFromMatrix( _projScreenMatrix );
  21058. // render shadow map
  21059. _renderer.setRenderTarget( shadowMap );
  21060. _renderer.clear();
  21061. // set object matrices & frustum culling
  21062. renderList = scene.__webglObjects;
  21063. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21064. webglObject = renderList[ j ];
  21065. object = webglObject.object;
  21066. webglObject.render = false;
  21067. if ( object.visible && object.castShadow ) {
  21068. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21069. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21070. webglObject.render = true;
  21071. }
  21072. }
  21073. }
  21074. // render regular objects
  21075. var objectMaterial, useMorphing, useSkinning;
  21076. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21077. webglObject = renderList[ j ];
  21078. if ( webglObject.render ) {
  21079. object = webglObject.object;
  21080. buffer = webglObject.buffer;
  21081. // culling is overriden globally for all objects
  21082. // while rendering depth map
  21083. // need to deal with MeshFaceMaterial somehow
  21084. // in that case just use the first of geometry.materials for now
  21085. // (proper solution would require to break objects by materials
  21086. // similarly to regular rendering and then set corresponding
  21087. // depth materials per each chunk instead of just once per object)
  21088. objectMaterial = getObjectMaterial( object );
  21089. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21090. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21091. if ( object.customDepthMaterial ) {
  21092. material = object.customDepthMaterial;
  21093. } else if ( useSkinning ) {
  21094. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21095. } else if ( useMorphing ) {
  21096. material = _depthMaterialMorph;
  21097. } else {
  21098. material = _depthMaterial;
  21099. }
  21100. if ( buffer instanceof THREE.BufferGeometry ) {
  21101. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21102. } else {
  21103. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21104. }
  21105. }
  21106. }
  21107. // set matrices and render immediate objects
  21108. renderList = scene.__webglObjectsImmediate;
  21109. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21110. webglObject = renderList[ j ];
  21111. object = webglObject.object;
  21112. if ( object.visible && object.castShadow ) {
  21113. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21114. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21115. }
  21116. }
  21117. }
  21118. // restore GL state
  21119. var clearColor = _renderer.getClearColor(),
  21120. clearAlpha = _renderer.getClearAlpha();
  21121. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21122. _gl.enable( _gl.BLEND );
  21123. if ( _renderer.shadowMapCullFrontFaces ) {
  21124. _gl.cullFace( _gl.BACK );
  21125. }
  21126. };
  21127. function createVirtualLight( light, cascade ) {
  21128. var virtualLight = new THREE.DirectionalLight();
  21129. virtualLight.isVirtual = true;
  21130. virtualLight.onlyShadow = true;
  21131. virtualLight.castShadow = true;
  21132. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21133. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21134. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21135. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21136. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21137. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21138. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21139. virtualLight.shadowDarkness = light.shadowDarkness;
  21140. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21141. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21142. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21143. virtualLight.pointsWorld = [];
  21144. virtualLight.pointsFrustum = [];
  21145. var pointsWorld = virtualLight.pointsWorld,
  21146. pointsFrustum = virtualLight.pointsFrustum;
  21147. for ( var i = 0; i < 8; i ++ ) {
  21148. pointsWorld[ i ] = new THREE.Vector3();
  21149. pointsFrustum[ i ] = new THREE.Vector3();
  21150. }
  21151. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21152. var farZ = light.shadowCascadeFarZ[ cascade ];
  21153. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21154. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21155. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21156. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21157. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21158. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21159. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21160. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21161. return virtualLight;
  21162. }
  21163. // Synchronize virtual light with the original light
  21164. function updateVirtualLight( light, cascade ) {
  21165. var virtualLight = light.shadowCascadeArray[ cascade ];
  21166. virtualLight.position.copy( light.position );
  21167. virtualLight.target.position.copy( light.target.position );
  21168. virtualLight.lookAt( virtualLight.target );
  21169. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21170. virtualLight.shadowDarkness = light.shadowDarkness;
  21171. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21172. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21173. var farZ = light.shadowCascadeFarZ[ cascade ];
  21174. var pointsFrustum = virtualLight.pointsFrustum;
  21175. pointsFrustum[ 0 ].z = nearZ;
  21176. pointsFrustum[ 1 ].z = nearZ;
  21177. pointsFrustum[ 2 ].z = nearZ;
  21178. pointsFrustum[ 3 ].z = nearZ;
  21179. pointsFrustum[ 4 ].z = farZ;
  21180. pointsFrustum[ 5 ].z = farZ;
  21181. pointsFrustum[ 6 ].z = farZ;
  21182. pointsFrustum[ 7 ].z = farZ;
  21183. }
  21184. // Fit shadow camera's ortho frustum to camera frustum
  21185. function updateShadowCamera( camera, light ) {
  21186. var shadowCamera = light.shadowCamera,
  21187. pointsFrustum = light.pointsFrustum,
  21188. pointsWorld = light.pointsWorld;
  21189. _min.set( Infinity, Infinity, Infinity );
  21190. _max.set( -Infinity, -Infinity, -Infinity );
  21191. for ( var i = 0; i < 8; i ++ ) {
  21192. var p = pointsWorld[ i ];
  21193. p.copy( pointsFrustum[ i ] );
  21194. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21195. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  21196. if ( p.x < _min.x ) _min.x = p.x;
  21197. if ( p.x > _max.x ) _max.x = p.x;
  21198. if ( p.y < _min.y ) _min.y = p.y;
  21199. if ( p.y > _max.y ) _max.y = p.y;
  21200. if ( p.z < _min.z ) _min.z = p.z;
  21201. if ( p.z > _max.z ) _max.z = p.z;
  21202. }
  21203. shadowCamera.left = _min.x;
  21204. shadowCamera.right = _max.x;
  21205. shadowCamera.top = _max.y;
  21206. shadowCamera.bottom = _min.y;
  21207. // can't really fit near/far
  21208. //shadowCamera.near = _min.z;
  21209. //shadowCamera.far = _max.z;
  21210. shadowCamera.updateProjectionMatrix();
  21211. }
  21212. // For the moment just ignore objects that have multiple materials with different animation methods
  21213. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21214. function getObjectMaterial( object ) {
  21215. if ( object.material instanceof THREE.MeshFaceMaterial ) {
  21216. if ( object.material.materials.length > 0 ) {
  21217. return object.material.materials[ 0 ];
  21218. } else {
  21219. return object.geometry.materials[ 0 ];
  21220. }
  21221. } else {
  21222. return object.material;
  21223. }
  21224. };
  21225. };
  21226. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21227. /**
  21228. * @author mikael emtinger / http://gomo.se/
  21229. * @author alteredq / http://alteredqualia.com/
  21230. */
  21231. THREE.SpritePlugin = function ( ) {
  21232. var _gl, _renderer, _sprite = {};
  21233. this.init = function ( renderer ) {
  21234. _gl = renderer.context;
  21235. _renderer = renderer;
  21236. _sprite.vertices = new Float32Array( 8 + 8 );
  21237. _sprite.faces = new Uint16Array( 6 );
  21238. var i = 0;
  21239. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21240. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21241. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21242. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21243. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21244. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21245. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21246. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21247. i = 0;
  21248. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21249. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21250. _sprite.vertexBuffer = _gl.createBuffer();
  21251. _sprite.elementBuffer = _gl.createBuffer();
  21252. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21253. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21254. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21255. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21256. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  21257. _sprite.attributes = {};
  21258. _sprite.uniforms = {};
  21259. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21260. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21261. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21262. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21263. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21264. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21265. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21266. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21267. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21268. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21269. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21270. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  21271. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21272. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21273. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21274. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21275. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21276. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21277. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21278. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21279. _sprite.attributesEnabled = false;
  21280. };
  21281. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21282. var sprites = scene.__webglSprites,
  21283. nSprites = sprites.length;
  21284. if ( ! nSprites ) return;
  21285. var attributes = _sprite.attributes,
  21286. uniforms = _sprite.uniforms;
  21287. var invAspect = viewportHeight / viewportWidth;
  21288. var halfViewportWidth = viewportWidth * 0.5,
  21289. halfViewportHeight = viewportHeight * 0.5;
  21290. var mergeWith3D = true;
  21291. // setup gl
  21292. _gl.useProgram( _sprite.program );
  21293. if ( ! _sprite.attributesEnabled ) {
  21294. _gl.enableVertexAttribArray( attributes.position );
  21295. _gl.enableVertexAttribArray( attributes.uv );
  21296. _sprite.attributesEnabled = true;
  21297. }
  21298. _gl.disable( _gl.CULL_FACE );
  21299. _gl.enable( _gl.BLEND );
  21300. _gl.depthMask( true );
  21301. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21302. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21303. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21304. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21305. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  21306. _gl.activeTexture( _gl.TEXTURE0 );
  21307. _gl.uniform1i( uniforms.map, 0 );
  21308. var oldFogType = 0;
  21309. var sceneFogType = 0;
  21310. var fog = scene.fog;
  21311. if ( fog ) {
  21312. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21313. if ( fog instanceof THREE.Fog ) {
  21314. _gl.uniform1f( uniforms.fogNear, fog.near );
  21315. _gl.uniform1f( uniforms.fogFar, fog.far );
  21316. _gl.uniform1i( uniforms.fogType, 1 );
  21317. oldFogType = 1;
  21318. sceneFogType = 1;
  21319. } else if ( fog instanceof THREE.FogExp2 ) {
  21320. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21321. _gl.uniform1i( uniforms.fogType, 2 );
  21322. oldFogType = 2;
  21323. sceneFogType = 2;
  21324. }
  21325. } else {
  21326. _gl.uniform1i( uniforms.fogType, 0 );
  21327. oldFogType = 0;
  21328. sceneFogType = 0;
  21329. }
  21330. // update positions and sort
  21331. var i, sprite, screenPosition, size, fogType, scale = [];
  21332. for( i = 0; i < nSprites; i ++ ) {
  21333. sprite = sprites[ i ];
  21334. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  21335. if ( ! sprite.useScreenCoordinates ) {
  21336. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  21337. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21338. } else {
  21339. sprite.z = - sprite.position.z;
  21340. }
  21341. }
  21342. sprites.sort( painterSortStable );
  21343. // render all sprites
  21344. for( i = 0; i < nSprites; i ++ ) {
  21345. sprite = sprites[ i ];
  21346. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  21347. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  21348. if ( sprite.useScreenCoordinates ) {
  21349. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21350. _gl.uniform3f(
  21351. uniforms.screenPosition,
  21352. ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21353. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21354. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21355. );
  21356. } else {
  21357. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21358. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  21359. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21360. }
  21361. if ( scene.fog && sprite.fog ) {
  21362. fogType = sceneFogType;
  21363. } else {
  21364. fogType = 0;
  21365. }
  21366. if ( oldFogType !== fogType ) {
  21367. _gl.uniform1i( uniforms.fogType, fogType );
  21368. oldFogType = fogType;
  21369. }
  21370. size = 1 / ( sprite.scaleByViewport ? viewportHeight : 1 );
  21371. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21372. scale[ 1 ] = size * sprite.scale.y;
  21373. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  21374. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  21375. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  21376. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21377. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21378. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21379. _gl.uniform2fv( uniforms.scale, scale );
  21380. if ( sprite.mergeWith3D && !mergeWith3D ) {
  21381. _gl.enable( _gl.DEPTH_TEST );
  21382. mergeWith3D = true;
  21383. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  21384. _gl.disable( _gl.DEPTH_TEST );
  21385. mergeWith3D = false;
  21386. }
  21387. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21388. _renderer.setTexture( sprite.map, 0 );
  21389. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21390. }
  21391. }
  21392. // restore gl
  21393. _gl.enable( _gl.CULL_FACE );
  21394. _gl.enable( _gl.DEPTH_TEST );
  21395. _gl.depthMask( true );
  21396. };
  21397. function createProgram ( shader ) {
  21398. var program = _gl.createProgram();
  21399. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21400. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21401. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21402. _gl.shaderSource( vertexShader, shader.vertexShader );
  21403. _gl.compileShader( fragmentShader );
  21404. _gl.compileShader( vertexShader );
  21405. _gl.attachShader( program, fragmentShader );
  21406. _gl.attachShader( program, vertexShader );
  21407. _gl.linkProgram( program );
  21408. return program;
  21409. };
  21410. function painterSortStable ( a, b ) {
  21411. if ( a.z !== b.z ) {
  21412. return b.z - a.z;
  21413. } else {
  21414. return b.id - a.id;
  21415. }
  21416. };
  21417. };/**
  21418. * @author alteredq / http://alteredqualia.com/
  21419. */
  21420. THREE.DepthPassPlugin = function ( ) {
  21421. this.enabled = false;
  21422. this.renderTarget = null;
  21423. var _gl,
  21424. _renderer,
  21425. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21426. _frustum = new THREE.Frustum(),
  21427. _projScreenMatrix = new THREE.Matrix4();
  21428. this.init = function ( renderer ) {
  21429. _gl = renderer.context;
  21430. _renderer = renderer;
  21431. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21432. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21433. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21434. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21435. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21436. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21437. _depthMaterial._shadowPass = true;
  21438. _depthMaterialMorph._shadowPass = true;
  21439. _depthMaterialSkin._shadowPass = true;
  21440. _depthMaterialMorphSkin._shadowPass = true;
  21441. };
  21442. this.render = function ( scene, camera ) {
  21443. if ( ! this.enabled ) return;
  21444. this.update( scene, camera );
  21445. };
  21446. this.update = function ( scene, camera ) {
  21447. var i, il, j, jl, n,
  21448. program, buffer, material,
  21449. webglObject, object, light,
  21450. renderList,
  21451. fog = null;
  21452. // set GL state for depth map
  21453. _gl.clearColor( 1, 1, 1, 1 );
  21454. _gl.disable( _gl.BLEND );
  21455. _renderer.setDepthTest( true );
  21456. // update scene
  21457. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21458. // update camera matrices and frustum
  21459. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  21460. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  21461. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21462. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  21463. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  21464. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21465. _frustum.setFromMatrix( _projScreenMatrix );
  21466. // render depth map
  21467. _renderer.setRenderTarget( this.renderTarget );
  21468. _renderer.clear();
  21469. // set object matrices & frustum culling
  21470. renderList = scene.__webglObjects;
  21471. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21472. webglObject = renderList[ j ];
  21473. object = webglObject.object;
  21474. webglObject.render = false;
  21475. if ( object.visible ) {
  21476. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21477. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21478. webglObject.render = true;
  21479. }
  21480. }
  21481. }
  21482. // render regular objects
  21483. var objectMaterial, useMorphing, useSkinning;
  21484. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21485. webglObject = renderList[ j ];
  21486. if ( webglObject.render ) {
  21487. object = webglObject.object;
  21488. buffer = webglObject.buffer;
  21489. // todo: create proper depth material for particles
  21490. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21491. objectMaterial = getObjectMaterial( object );
  21492. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21493. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21494. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21495. if ( object.customDepthMaterial ) {
  21496. material = object.customDepthMaterial;
  21497. } else if ( useSkinning ) {
  21498. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21499. } else if ( useMorphing ) {
  21500. material = _depthMaterialMorph;
  21501. } else {
  21502. material = _depthMaterial;
  21503. }
  21504. if ( buffer instanceof THREE.BufferGeometry ) {
  21505. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21506. } else {
  21507. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21508. }
  21509. }
  21510. }
  21511. // set matrices and render immediate objects
  21512. renderList = scene.__webglObjectsImmediate;
  21513. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21514. webglObject = renderList[ j ];
  21515. object = webglObject.object;
  21516. if ( object.visible ) {
  21517. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21518. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21519. }
  21520. }
  21521. // restore GL state
  21522. var clearColor = _renderer.getClearColor(),
  21523. clearAlpha = _renderer.getClearAlpha();
  21524. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21525. _gl.enable( _gl.BLEND );
  21526. };
  21527. // For the moment just ignore objects that have multiple materials with different animation methods
  21528. // Only the first material will be taken into account for deciding which depth material to use
  21529. function getObjectMaterial( object ) {
  21530. if ( object.material instanceof THREE.MeshFaceMaterial ) {
  21531. if ( object.material.materials.length > 0 ) {
  21532. return object.material.materials[ 0 ];
  21533. } else {
  21534. return object.geometry.materials[ 0 ];
  21535. }
  21536. } else {
  21537. return object.material;
  21538. }
  21539. };
  21540. };
  21541. /**
  21542. * @author mikael emtinger / http://gomo.se/
  21543. *
  21544. */
  21545. THREE.ShaderFlares = {
  21546. 'lensFlareVertexTexture': {
  21547. vertexShader: [
  21548. "uniform vec3 screenPosition;",
  21549. "uniform vec2 scale;",
  21550. "uniform float rotation;",
  21551. "uniform int renderType;",
  21552. "uniform sampler2D occlusionMap;",
  21553. "attribute vec2 position;",
  21554. "attribute vec2 uv;",
  21555. "varying vec2 vUV;",
  21556. "varying float vVisibility;",
  21557. "void main() {",
  21558. "vUV = uv;",
  21559. "vec2 pos = position;",
  21560. "if( renderType == 2 ) {",
  21561. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21562. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21563. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21564. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21565. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21566. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21567. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21568. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21569. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21570. "vVisibility = ( visibility.r / 9.0 ) *",
  21571. "( 1.0 - visibility.g / 9.0 ) *",
  21572. "( visibility.b / 9.0 ) *",
  21573. "( 1.0 - visibility.a / 9.0 );",
  21574. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21575. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21576. "}",
  21577. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21578. "}"
  21579. ].join( "\n" ),
  21580. fragmentShader: [
  21581. "precision mediump float;",
  21582. "uniform sampler2D map;",
  21583. "uniform float opacity;",
  21584. "uniform int renderType;",
  21585. "uniform vec3 color;",
  21586. "varying vec2 vUV;",
  21587. "varying float vVisibility;",
  21588. "void main() {",
  21589. // pink square
  21590. "if( renderType == 0 ) {",
  21591. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21592. // restore
  21593. "} else if( renderType == 1 ) {",
  21594. "gl_FragColor = texture2D( map, vUV );",
  21595. // flare
  21596. "} else {",
  21597. "vec4 texture = texture2D( map, vUV );",
  21598. "texture.a *= opacity * vVisibility;",
  21599. "gl_FragColor = texture;",
  21600. "gl_FragColor.rgb *= color;",
  21601. "}",
  21602. "}"
  21603. ].join( "\n" )
  21604. },
  21605. 'lensFlare': {
  21606. vertexShader: [
  21607. "uniform vec3 screenPosition;",
  21608. "uniform vec2 scale;",
  21609. "uniform float rotation;",
  21610. "uniform int renderType;",
  21611. "attribute vec2 position;",
  21612. "attribute vec2 uv;",
  21613. "varying vec2 vUV;",
  21614. "void main() {",
  21615. "vUV = uv;",
  21616. "vec2 pos = position;",
  21617. "if( renderType == 2 ) {",
  21618. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21619. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21620. "}",
  21621. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21622. "}"
  21623. ].join( "\n" ),
  21624. fragmentShader: [
  21625. "precision mediump float;",
  21626. "uniform sampler2D map;",
  21627. "uniform sampler2D occlusionMap;",
  21628. "uniform float opacity;",
  21629. "uniform int renderType;",
  21630. "uniform vec3 color;",
  21631. "varying vec2 vUV;",
  21632. "void main() {",
  21633. // pink square
  21634. "if( renderType == 0 ) {",
  21635. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21636. // restore
  21637. "} else if( renderType == 1 ) {",
  21638. "gl_FragColor = texture2D( map, vUV );",
  21639. // flare
  21640. "} else {",
  21641. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21642. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21643. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21644. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21645. "visibility = ( 1.0 - visibility / 4.0 );",
  21646. "vec4 texture = texture2D( map, vUV );",
  21647. "texture.a *= opacity * visibility;",
  21648. "gl_FragColor = texture;",
  21649. "gl_FragColor.rgb *= color;",
  21650. "}",
  21651. "}"
  21652. ].join( "\n" )
  21653. }
  21654. };
  21655. /**
  21656. * @author mikael emtinger / http://gomo.se/
  21657. * @author alteredq / http://alteredqualia.com/
  21658. *
  21659. */
  21660. THREE.ShaderSprite = {
  21661. 'sprite': {
  21662. vertexShader: [
  21663. "uniform int useScreenCoordinates;",
  21664. "uniform int affectedByDistance;",
  21665. "uniform vec3 screenPosition;",
  21666. "uniform mat4 modelViewMatrix;",
  21667. "uniform mat4 projectionMatrix;",
  21668. "uniform float rotation;",
  21669. "uniform vec2 scale;",
  21670. "uniform vec2 alignment;",
  21671. "uniform vec2 uvOffset;",
  21672. "uniform vec2 uvScale;",
  21673. "attribute vec2 position;",
  21674. "attribute vec2 uv;",
  21675. "varying vec2 vUV;",
  21676. "void main() {",
  21677. "vUV = uvOffset + uv * uvScale;",
  21678. "vec2 alignedPosition = position + alignment;",
  21679. "vec2 rotatedPosition;",
  21680. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21681. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21682. "vec4 finalPosition;",
  21683. "if( useScreenCoordinates != 0 ) {",
  21684. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21685. "} else {",
  21686. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21687. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  21688. "}",
  21689. "gl_Position = finalPosition;",
  21690. "}"
  21691. ].join( "\n" ),
  21692. fragmentShader: [
  21693. "precision mediump float;",
  21694. "uniform vec3 color;",
  21695. "uniform sampler2D map;",
  21696. "uniform float opacity;",
  21697. "uniform int fogType;",
  21698. "uniform vec3 fogColor;",
  21699. "uniform float fogDensity;",
  21700. "uniform float fogNear;",
  21701. "uniform float fogFar;",
  21702. "varying vec2 vUV;",
  21703. "void main() {",
  21704. "vec4 texture = texture2D( map, vUV );",
  21705. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21706. "if ( fogType > 0 ) {",
  21707. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21708. "float fogFactor = 0.0;",
  21709. "if ( fogType == 1 ) {",
  21710. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21711. "} else {",
  21712. "const float LOG2 = 1.442695;",
  21713. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21714. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21715. "}",
  21716. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21717. "}",
  21718. "}"
  21719. ].join( "\n" )
  21720. }
  21721. };
粤ICP备19079148号