three.js 805 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. var THREE = THREE || { REVISION: '51dev' };
  5. if ( self.console === undefined ) {
  6. self.console = {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. }
  14. if ( self.Int32Array === undefined ) {
  15. self.Int32Array = Array;
  16. self.Float32Array = Array;
  17. }
  18. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  19. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  20. // requestAnimationFrame polyfill by Erik Möller
  21. // fixes from Paul Irish and Tino Zijdel
  22. ( function () {
  23. var lastTime = 0;
  24. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  25. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  26. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  27. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  28. }
  29. if ( window.requestAnimationFrame === undefined ) {
  30. window.requestAnimationFrame = function ( callback, element ) {
  31. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  32. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  33. lastTime = currTime + timeToCall;
  34. return id;
  35. };
  36. }
  37. if ( window.cancelAnimationFrame === undefined ) {
  38. window.cancelAnimationFrame = function ( id ) { clearTimeout( id ); };
  39. }
  40. }() );
  41. // MATERIAL CONSTANTS
  42. // side
  43. THREE.FrontSide = 0;
  44. THREE.BackSide = 1;
  45. THREE.DoubleSide = 2;
  46. // shading
  47. THREE.NoShading = 0;
  48. THREE.FlatShading = 1;
  49. THREE.SmoothShading = 2;
  50. // colors
  51. THREE.NoColors = 0;
  52. THREE.FaceColors = 1;
  53. THREE.VertexColors = 2;
  54. // blending modes
  55. THREE.NoBlending = 0;
  56. THREE.NormalBlending = 1;
  57. THREE.AdditiveBlending = 2;
  58. THREE.SubtractiveBlending = 3;
  59. THREE.MultiplyBlending = 4;
  60. THREE.CustomBlending = 5;
  61. // custom blending equations
  62. // (numbers start from 100 not to clash with other
  63. // mappings to OpenGL constants defined in Texture.js)
  64. THREE.AddEquation = 100;
  65. THREE.SubtractEquation = 101;
  66. THREE.ReverseSubtractEquation = 102;
  67. // custom blending destination factors
  68. THREE.ZeroFactor = 200;
  69. THREE.OneFactor = 201;
  70. THREE.SrcColorFactor = 202;
  71. THREE.OneMinusSrcColorFactor = 203;
  72. THREE.SrcAlphaFactor = 204;
  73. THREE.OneMinusSrcAlphaFactor = 205;
  74. THREE.DstAlphaFactor = 206;
  75. THREE.OneMinusDstAlphaFactor = 207;
  76. // custom blending source factors
  77. //THREE.ZeroFactor = 200;
  78. //THREE.OneFactor = 201;
  79. //THREE.SrcAlphaFactor = 204;
  80. //THREE.OneMinusSrcAlphaFactor = 205;
  81. //THREE.DstAlphaFactor = 206;
  82. //THREE.OneMinusDstAlphaFactor = 207;
  83. THREE.DstColorFactor = 208;
  84. THREE.OneMinusDstColorFactor = 209;
  85. THREE.SrcAlphaSaturateFactor = 210;
  86. // TEXTURE CONSTANTS
  87. THREE.MultiplyOperation = 0;
  88. THREE.MixOperation = 1;
  89. // Mapping modes
  90. THREE.UVMapping = function () {};
  91. THREE.CubeReflectionMapping = function () {};
  92. THREE.CubeRefractionMapping = function () {};
  93. THREE.SphericalReflectionMapping = function () {};
  94. THREE.SphericalRefractionMapping = function () {};
  95. // Wrapping modes
  96. THREE.RepeatWrapping = 1000;
  97. THREE.ClampToEdgeWrapping = 1001;
  98. THREE.MirroredRepeatWrapping = 1002;
  99. // Filters
  100. THREE.NearestFilter = 1003;
  101. THREE.NearestMipMapNearestFilter = 1004;
  102. THREE.NearestMipMapLinearFilter = 1005;
  103. THREE.LinearFilter = 1006;
  104. THREE.LinearMipMapNearestFilter = 1007;
  105. THREE.LinearMipMapLinearFilter = 1008;
  106. // Data types
  107. THREE.UnsignedByteType = 1009;
  108. THREE.ByteType = 1010;
  109. THREE.ShortType = 1011;
  110. THREE.UnsignedShortType = 1012;
  111. THREE.IntType = 1013;
  112. THREE.UnsignedIntType = 1014;
  113. THREE.FloatType = 1015;
  114. // Pixel types
  115. //THREE.UnsignedByteType = 1009;
  116. THREE.UnsignedShort4444Type = 1016;
  117. THREE.UnsignedShort5551Type = 1017;
  118. THREE.UnsignedShort565Type = 1018;
  119. // Pixel formats
  120. THREE.AlphaFormat = 1019;
  121. THREE.RGBFormat = 1020;
  122. THREE.RGBAFormat = 1021;
  123. THREE.LuminanceFormat = 1022;
  124. THREE.LuminanceAlphaFormat = 1023;
  125. /**
  126. * @author alteredq / http://alteredqualia.com/
  127. */
  128. THREE.Clock = function ( autoStart ) {
  129. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  130. this.startTime = 0;
  131. this.oldTime = 0;
  132. this.elapsedTime = 0;
  133. this.running = false;
  134. };
  135. THREE.Clock.prototype.start = function () {
  136. this.startTime = Date.now();
  137. this.oldTime = this.startTime;
  138. this.running = true;
  139. };
  140. THREE.Clock.prototype.stop = function () {
  141. this.getElapsedTime();
  142. this.running = false;
  143. };
  144. THREE.Clock.prototype.getElapsedTime = function () {
  145. this.elapsedTime += this.getDelta();
  146. return this.elapsedTime;
  147. };
  148. THREE.Clock.prototype.getDelta = function () {
  149. var diff = 0;
  150. if ( this.autoStart && ! this.running ) {
  151. this.start();
  152. }
  153. if ( this.running ) {
  154. var newTime = Date.now();
  155. diff = 0.001 * ( newTime - this.oldTime );
  156. this.oldTime = newTime;
  157. this.elapsedTime += diff;
  158. }
  159. return diff;
  160. };/**
  161. * @author mrdoob / http://mrdoob.com/
  162. */
  163. THREE.Color = function ( hex ) {
  164. if ( hex !== undefined ) this.setHex( hex );
  165. return this;
  166. };
  167. THREE.Color.prototype = {
  168. constructor: THREE.Color,
  169. r: 1, g: 1, b: 1,
  170. copy: function ( color ) {
  171. this.r = color.r;
  172. this.g = color.g;
  173. this.b = color.b;
  174. return this;
  175. },
  176. copyGammaToLinear: function ( color ) {
  177. this.r = color.r * color.r;
  178. this.g = color.g * color.g;
  179. this.b = color.b * color.b;
  180. return this;
  181. },
  182. copyLinearToGamma: function ( color ) {
  183. this.r = Math.sqrt( color.r );
  184. this.g = Math.sqrt( color.g );
  185. this.b = Math.sqrt( color.b );
  186. return this;
  187. },
  188. convertGammaToLinear: function () {
  189. var r = this.r, g = this.g, b = this.b;
  190. this.r = r * r;
  191. this.g = g * g;
  192. this.b = b * b;
  193. return this;
  194. },
  195. convertLinearToGamma: function () {
  196. this.r = Math.sqrt( this.r );
  197. this.g = Math.sqrt( this.g );
  198. this.b = Math.sqrt( this.b );
  199. return this;
  200. },
  201. setRGB: function ( r, g, b ) {
  202. this.r = r;
  203. this.g = g;
  204. this.b = b;
  205. return this;
  206. },
  207. setHSV: function ( h, s, v ) {
  208. // based on MochiKit implementation by Bob Ippolito
  209. // h,s,v ranges are < 0.0 - 1.0 >
  210. var i, f, p, q, t;
  211. if ( v === 0 ) {
  212. this.r = this.g = this.b = 0;
  213. } else {
  214. i = Math.floor( h * 6 );
  215. f = ( h * 6 ) - i;
  216. p = v * ( 1 - s );
  217. q = v * ( 1 - ( s * f ) );
  218. t = v * ( 1 - ( s * ( 1 - f ) ) );
  219. if ( i === 0 ) {
  220. this.r = v;
  221. this.g = t;
  222. this.b = p;
  223. } else if ( i === 1 ) {
  224. this.r = q;
  225. this.g = v;
  226. this.b = p;
  227. } else if ( i === 2 ) {
  228. this.r = p;
  229. this.g = v;
  230. this.b = t;
  231. } else if ( i === 3 ) {
  232. this.r = p;
  233. this.g = q;
  234. this.b = v;
  235. } else if ( i === 4 ) {
  236. this.r = t;
  237. this.g = p;
  238. this.b = v;
  239. } else if ( i === 5 ) {
  240. this.r = v;
  241. this.g = p;
  242. this.b = q;
  243. }
  244. }
  245. return this;
  246. },
  247. setHex: function ( hex ) {
  248. hex = Math.floor( hex );
  249. this.r = ( hex >> 16 & 255 ) / 255;
  250. this.g = ( hex >> 8 & 255 ) / 255;
  251. this.b = ( hex & 255 ) / 255;
  252. return this;
  253. },
  254. lerpSelf: function ( color, alpha ) {
  255. this.r += ( color.r - this.r ) * alpha;
  256. this.g += ( color.g - this.g ) * alpha;
  257. this.b += ( color.b - this.b ) * alpha;
  258. return this;
  259. },
  260. getHex: function () {
  261. return Math.floor( this.r * 255 ) << 16 ^ Math.floor( this.g * 255 ) << 8 ^ Math.floor( this.b * 255 );
  262. },
  263. getContextStyle: function () {
  264. return 'rgb(' + Math.floor( this.r * 255 ) + ',' + Math.floor( this.g * 255 ) + ',' + Math.floor( this.b * 255 ) + ')';
  265. },
  266. clone: function () {
  267. return new THREE.Color().setRGB( this.r, this.g, this.b );
  268. }
  269. };
  270. /**
  271. * @author mrdoob / http://mrdoob.com/
  272. * @author philogb / http://blog.thejit.org/
  273. * @author egraether / http://egraether.com/
  274. * @author zz85 / http://www.lab4games.net/zz85/blog
  275. */
  276. THREE.Vector2 = function ( x, y ) {
  277. this.x = x || 0;
  278. this.y = y || 0;
  279. };
  280. THREE.Vector2.prototype = {
  281. constructor: THREE.Vector2,
  282. set: function ( x, y ) {
  283. this.x = x;
  284. this.y = y;
  285. return this;
  286. },
  287. copy: function ( v ) {
  288. this.x = v.x;
  289. this.y = v.y;
  290. return this;
  291. },
  292. add: function ( a, b ) {
  293. this.x = a.x + b.x;
  294. this.y = a.y + b.y;
  295. return this;
  296. },
  297. addSelf: function ( v ) {
  298. this.x += v.x;
  299. this.y += v.y;
  300. return this;
  301. },
  302. sub: function ( a, b ) {
  303. this.x = a.x - b.x;
  304. this.y = a.y - b.y;
  305. return this;
  306. },
  307. subSelf: function ( v ) {
  308. this.x -= v.x;
  309. this.y -= v.y;
  310. return this;
  311. },
  312. multiplyScalar: function ( s ) {
  313. this.x *= s;
  314. this.y *= s;
  315. return this;
  316. },
  317. divideScalar: function ( s ) {
  318. if ( s ) {
  319. this.x /= s;
  320. this.y /= s;
  321. } else {
  322. this.set( 0, 0 );
  323. }
  324. return this;
  325. },
  326. negate: function() {
  327. return this.multiplyScalar( - 1 );
  328. },
  329. dot: function ( v ) {
  330. return this.x * v.x + this.y * v.y;
  331. },
  332. lengthSq: function () {
  333. return this.x * this.x + this.y * this.y;
  334. },
  335. length: function () {
  336. return Math.sqrt( this.lengthSq() );
  337. },
  338. normalize: function () {
  339. return this.divideScalar( this.length() );
  340. },
  341. distanceTo: function ( v ) {
  342. return Math.sqrt( this.distanceToSquared( v ) );
  343. },
  344. distanceToSquared: function ( v ) {
  345. var dx = this.x - v.x, dy = this.y - v.y;
  346. return dx * dx + dy * dy;
  347. },
  348. setLength: function ( l ) {
  349. return this.normalize().multiplyScalar( l );
  350. },
  351. lerpSelf: function ( v, alpha ) {
  352. this.x += ( v.x - this.x ) * alpha;
  353. this.y += ( v.y - this.y ) * alpha;
  354. return this;
  355. },
  356. equals: function( v ) {
  357. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  358. },
  359. isZero: function () {
  360. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  361. },
  362. clone: function () {
  363. return new THREE.Vector2( this.x, this.y );
  364. }
  365. };
  366. /**
  367. * @author mrdoob / http://mrdoob.com/
  368. * @author kile / http://kile.stravaganza.org/
  369. * @author philogb / http://blog.thejit.org/
  370. * @author mikael emtinger / http://gomo.se/
  371. * @author egraether / http://egraether.com/
  372. * @author WestLangley / http://github.com/WestLangley
  373. */
  374. THREE.Vector3 = function ( x, y, z ) {
  375. this.x = x || 0;
  376. this.y = y || 0;
  377. this.z = z || 0;
  378. };
  379. THREE.Vector3.prototype = {
  380. constructor: THREE.Vector3,
  381. set: function ( x, y, z ) {
  382. this.x = x;
  383. this.y = y;
  384. this.z = z;
  385. return this;
  386. },
  387. setX: function ( x ) {
  388. this.x = x;
  389. return this;
  390. },
  391. setY: function ( y ) {
  392. this.y = y;
  393. return this;
  394. },
  395. setZ: function ( z ) {
  396. this.z = z;
  397. return this;
  398. },
  399. copy: function ( v ) {
  400. this.x = v.x;
  401. this.y = v.y;
  402. this.z = v.z;
  403. return this;
  404. },
  405. add: function ( a, b ) {
  406. this.x = a.x + b.x;
  407. this.y = a.y + b.y;
  408. this.z = a.z + b.z;
  409. return this;
  410. },
  411. addSelf: function ( v ) {
  412. this.x += v.x;
  413. this.y += v.y;
  414. this.z += v.z;
  415. return this;
  416. },
  417. addScalar: function ( s ) {
  418. this.x += s;
  419. this.y += s;
  420. this.z += s;
  421. return this;
  422. },
  423. sub: function ( a, b ) {
  424. this.x = a.x - b.x;
  425. this.y = a.y - b.y;
  426. this.z = a.z - b.z;
  427. return this;
  428. },
  429. subSelf: function ( v ) {
  430. this.x -= v.x;
  431. this.y -= v.y;
  432. this.z -= v.z;
  433. return this;
  434. },
  435. multiply: function ( a, b ) {
  436. this.x = a.x * b.x;
  437. this.y = a.y * b.y;
  438. this.z = a.z * b.z;
  439. return this;
  440. },
  441. multiplySelf: function ( v ) {
  442. this.x *= v.x;
  443. this.y *= v.y;
  444. this.z *= v.z;
  445. return this;
  446. },
  447. multiplyScalar: function ( s ) {
  448. this.x *= s;
  449. this.y *= s;
  450. this.z *= s;
  451. return this;
  452. },
  453. divideSelf: function ( v ) {
  454. this.x /= v.x;
  455. this.y /= v.y;
  456. this.z /= v.z;
  457. return this;
  458. },
  459. divideScalar: function ( s ) {
  460. if ( s ) {
  461. this.x /= s;
  462. this.y /= s;
  463. this.z /= s;
  464. } else {
  465. this.x = 0;
  466. this.y = 0;
  467. this.z = 0;
  468. }
  469. return this;
  470. },
  471. negate: function() {
  472. return this.multiplyScalar( - 1 );
  473. },
  474. dot: function ( v ) {
  475. return this.x * v.x + this.y * v.y + this.z * v.z;
  476. },
  477. lengthSq: function () {
  478. return this.x * this.x + this.y * this.y + this.z * this.z;
  479. },
  480. length: function () {
  481. return Math.sqrt( this.lengthSq() );
  482. },
  483. lengthManhattan: function () {
  484. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  485. },
  486. normalize: function () {
  487. return this.divideScalar( this.length() );
  488. },
  489. setLength: function ( l ) {
  490. return this.normalize().multiplyScalar( l );
  491. },
  492. lerpSelf: function ( v, alpha ) {
  493. this.x += ( v.x - this.x ) * alpha;
  494. this.y += ( v.y - this.y ) * alpha;
  495. this.z += ( v.z - this.z ) * alpha;
  496. return this;
  497. },
  498. cross: function ( a, b ) {
  499. this.x = a.y * b.z - a.z * b.y;
  500. this.y = a.z * b.x - a.x * b.z;
  501. this.z = a.x * b.y - a.y * b.x;
  502. return this;
  503. },
  504. crossSelf: function ( v ) {
  505. var x = this.x, y = this.y, z = this.z;
  506. this.x = y * v.z - z * v.y;
  507. this.y = z * v.x - x * v.z;
  508. this.z = x * v.y - y * v.x;
  509. return this;
  510. },
  511. distanceTo: function ( v ) {
  512. return Math.sqrt( this.distanceToSquared( v ) );
  513. },
  514. distanceToSquared: function ( v ) {
  515. return new THREE.Vector3().sub( this, v ).lengthSq();
  516. },
  517. getPositionFromMatrix: function ( m ) {
  518. this.x = m.elements[12];
  519. this.y = m.elements[13];
  520. this.z = m.elements[14];
  521. return this;
  522. },
  523. setEulerFromRotationMatrix: function ( m, order ) {
  524. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  525. // clamp, to handle numerical problems
  526. function clamp( x ) {
  527. return Math.min( Math.max( x, -1 ), 1 );
  528. }
  529. var te = m.elements;
  530. var m11 = te[0], m12 = te[4], m13 = te[8];
  531. var m21 = te[1], m22 = te[5], m23 = te[9];
  532. var m31 = te[2], m32 = te[6], m33 = te[10];
  533. if ( order === undefined || order === 'XYZ' ) {
  534. this.y = Math.asin( clamp( m13 ) );
  535. if ( Math.abs( m13 ) < 0.99999 ) {
  536. this.x = Math.atan2( - m23, m33 );
  537. this.z = Math.atan2( - m12, m11 );
  538. } else {
  539. this.x = Math.atan2( m21, m22 );
  540. this.z = 0;
  541. }
  542. } else if ( order === 'YXZ' ) {
  543. this.x = Math.asin( - clamp( m23 ) );
  544. if ( Math.abs( m23 ) < 0.99999 ) {
  545. this.y = Math.atan2( m13, m33 );
  546. this.z = Math.atan2( m21, m22 );
  547. } else {
  548. this.y = Math.atan2( - m31, m11 );
  549. this.z = 0;
  550. }
  551. } else if ( order === 'ZXY' ) {
  552. this.x = Math.asin( clamp( m32 ) );
  553. if ( Math.abs( m32 ) < 0.99999 ) {
  554. this.y = Math.atan2( - m31, m33 );
  555. this.z = Math.atan2( - m12, m22 );
  556. } else {
  557. this.y = 0;
  558. this.z = Math.atan2( m13, m11 );
  559. }
  560. } else if ( order === 'ZYX' ) {
  561. this.y = Math.asin( - clamp( m31 ) );
  562. if ( Math.abs( m31 ) < 0.99999 ) {
  563. this.x = Math.atan2( m32, m33 );
  564. this.z = Math.atan2( m21, m11 );
  565. } else {
  566. this.x = 0;
  567. this.z = Math.atan2( - m12, m22 );
  568. }
  569. } else if ( order === 'YZX' ) {
  570. this.z = Math.asin( clamp( m21 ) );
  571. if ( Math.abs( m21 ) < 0.99999 ) {
  572. this.x = Math.atan2( - m23, m22 );
  573. this.y = Math.atan2( - m31, m11 );
  574. } else {
  575. this.x = 0;
  576. this.y = Math.atan2( m31, m33 );
  577. }
  578. } else if ( order === 'XZY' ) {
  579. this.z = Math.asin( - clamp( m12 ) );
  580. if ( Math.abs( m12 ) < 0.99999 ) {
  581. this.x = Math.atan2( m32, m22 );
  582. this.y = Math.atan2( m13, m11 );
  583. } else {
  584. this.x = Math.atan2( - m13, m33 );
  585. this.y = 0;
  586. }
  587. }
  588. return this;
  589. },
  590. setEulerFromQuaternion: function ( q, order ) {
  591. // q is assumed to be normalized
  592. // clamp, to handle numerical problems
  593. function clamp( x ) {
  594. return Math.min( Math.max( x, -1 ), 1 );
  595. }
  596. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  597. var sqx = q.x * q.x;
  598. var sqy = q.y * q.y;
  599. var sqz = q.z * q.z;
  600. var sqw = q.w * q.w;
  601. if ( order === undefined || order === 'XYZ' ) {
  602. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  603. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  604. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  605. } else if ( order === 'YXZ' ) {
  606. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  607. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  608. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  609. } else if ( order === 'ZXY' ) {
  610. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  611. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  612. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  613. } else if ( order === 'ZYX' ) {
  614. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  615. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  616. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  617. } else if ( order === 'YZX' ) {
  618. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  619. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  620. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  621. } else if ( order === 'XZY' ) {
  622. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  623. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  624. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  625. }
  626. return this;
  627. },
  628. getScaleFromMatrix: function ( m ) {
  629. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  630. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  631. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  632. this.x = sx;
  633. this.y = sy;
  634. this.z = sz;
  635. return this;
  636. },
  637. equals: function ( v ) {
  638. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  639. },
  640. isZero: function () {
  641. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  642. },
  643. clone: function () {
  644. return new THREE.Vector3( this.x, this.y, this.z );
  645. }
  646. };
  647. /**
  648. * @author supereggbert / http://www.paulbrunt.co.uk/
  649. * @author philogb / http://blog.thejit.org/
  650. * @author mikael emtinger / http://gomo.se/
  651. * @author egraether / http://egraether.com/
  652. * @author WestLangley / http://github.com/WestLangley
  653. */
  654. THREE.Vector4 = function ( x, y, z, w ) {
  655. this.x = x || 0;
  656. this.y = y || 0;
  657. this.z = z || 0;
  658. this.w = ( w !== undefined ) ? w : 1;
  659. };
  660. THREE.Vector4.prototype = {
  661. constructor: THREE.Vector4,
  662. set: function ( x, y, z, w ) {
  663. this.x = x;
  664. this.y = y;
  665. this.z = z;
  666. this.w = w;
  667. return this;
  668. },
  669. copy: function ( v ) {
  670. this.x = v.x;
  671. this.y = v.y;
  672. this.z = v.z;
  673. this.w = ( v.w !== undefined ) ? v.w : 1;
  674. return this;
  675. },
  676. add: function ( a, b ) {
  677. this.x = a.x + b.x;
  678. this.y = a.y + b.y;
  679. this.z = a.z + b.z;
  680. this.w = a.w + b.w;
  681. return this;
  682. },
  683. addSelf: function ( v ) {
  684. this.x += v.x;
  685. this.y += v.y;
  686. this.z += v.z;
  687. this.w += v.w;
  688. return this;
  689. },
  690. sub: function ( a, b ) {
  691. this.x = a.x - b.x;
  692. this.y = a.y - b.y;
  693. this.z = a.z - b.z;
  694. this.w = a.w - b.w;
  695. return this;
  696. },
  697. subSelf: function ( v ) {
  698. this.x -= v.x;
  699. this.y -= v.y;
  700. this.z -= v.z;
  701. this.w -= v.w;
  702. return this;
  703. },
  704. multiplyScalar: function ( s ) {
  705. this.x *= s;
  706. this.y *= s;
  707. this.z *= s;
  708. this.w *= s;
  709. return this;
  710. },
  711. divideScalar: function ( s ) {
  712. if ( s ) {
  713. this.x /= s;
  714. this.y /= s;
  715. this.z /= s;
  716. this.w /= s;
  717. } else {
  718. this.x = 0;
  719. this.y = 0;
  720. this.z = 0;
  721. this.w = 1;
  722. }
  723. return this;
  724. },
  725. negate: function() {
  726. return this.multiplyScalar( -1 );
  727. },
  728. dot: function ( v ) {
  729. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  730. },
  731. lengthSq: function () {
  732. return this.dot( this );
  733. },
  734. length: function () {
  735. return Math.sqrt( this.lengthSq() );
  736. },
  737. lengthManhattan: function () {
  738. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  739. },
  740. normalize: function () {
  741. return this.divideScalar( this.length() );
  742. },
  743. setLength: function ( l ) {
  744. return this.normalize().multiplyScalar( l );
  745. },
  746. lerpSelf: function ( v, alpha ) {
  747. this.x += ( v.x - this.x ) * alpha;
  748. this.y += ( v.y - this.y ) * alpha;
  749. this.z += ( v.z - this.z ) * alpha;
  750. this.w += ( v.w - this.w ) * alpha;
  751. return this;
  752. },
  753. clone: function () {
  754. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  755. },
  756. setAxisAngleFromQuaternion: function ( q ) {
  757. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  758. // q is assumed to be normalized
  759. this.w = 2 * Math.acos( q.w );
  760. var s = Math.sqrt( 1 - q.w * q.w );
  761. if ( s < 0.0001 ) {
  762. this.x = 1;
  763. this.y = 0;
  764. this.z = 0;
  765. } else {
  766. this.x = q.x / s;
  767. this.y = q.y / s;
  768. this.z = q.z / s;
  769. }
  770. return this;
  771. },
  772. setAxisAngleFromRotationMatrix: function ( m ) {
  773. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  774. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  775. var angle, x, y, z, // variables for result
  776. epsilon = 0.01, // margin to allow for rounding errors
  777. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  778. te = m.elements,
  779. m11 = te[0], m12 = te[4], m13 = te[8],
  780. m21 = te[1], m22 = te[5], m23 = te[9],
  781. m31 = te[2], m32 = te[6], m33 = te[10];
  782. if ( ( Math.abs( m12 - m21 ) < epsilon )
  783. && ( Math.abs( m13 - m31 ) < epsilon )
  784. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  785. // singularity found
  786. // first check for identity matrix which must have +1 for all terms
  787. // in leading diagonal and zero in other terms
  788. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  789. && ( Math.abs( m13 + m31 ) < epsilon2 )
  790. && ( Math.abs( m23 + m32 ) < epsilon2 )
  791. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  792. // this singularity is identity matrix so angle = 0
  793. this.set( 1, 0, 0, 0 );
  794. return this; // zero angle, arbitrary axis
  795. }
  796. // otherwise this singularity is angle = 180
  797. angle = Math.PI;
  798. var xx = ( m11 + 1 ) / 2;
  799. var yy = ( m22 + 1 ) / 2;
  800. var zz = ( m33 + 1 ) / 2;
  801. var xy = ( m12 + m21 ) / 4;
  802. var xz = ( m13 + m31 ) / 4;
  803. var yz = ( m23 + m32 ) / 4;
  804. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  805. if ( xx < epsilon ) {
  806. x = 0;
  807. y = 0.707106781;
  808. z = 0.707106781;
  809. } else {
  810. x = Math.sqrt( xx );
  811. y = xy / x;
  812. z = xz / x;
  813. }
  814. } else if ( yy > zz ) { // m22 is the largest diagonal term
  815. if ( yy < epsilon ) {
  816. x = 0.707106781;
  817. y = 0;
  818. z = 0.707106781;
  819. } else {
  820. y = Math.sqrt( yy );
  821. x = xy / y;
  822. z = yz / y;
  823. }
  824. } else { // m33 is the largest diagonal term so base result on this
  825. if ( zz < epsilon ) {
  826. x = 0.707106781;
  827. y = 0.707106781;
  828. z = 0;
  829. } else {
  830. z = Math.sqrt( zz );
  831. x = xz / z;
  832. y = yz / z;
  833. }
  834. }
  835. this.set( x, y, z, angle );
  836. return this; // return 180 deg rotation
  837. }
  838. // as we have reached here there are no singularities so we can handle normally
  839. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  840. + ( m13 - m31 ) * ( m13 - m31 )
  841. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  842. if ( Math.abs( s ) < 0.001 ) s = 1;
  843. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  844. // caught by singularity test above, but I've left it in just in case
  845. this.x = ( m32 - m23 ) / s;
  846. this.y = ( m13 - m31 ) / s;
  847. this.z = ( m21 - m12 ) / s;
  848. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  849. return this;
  850. }
  851. };
  852. /**
  853. * @author alteredq / http://alteredqualia.com/
  854. */
  855. THREE.Matrix3 = function () {
  856. this.elements = new Float32Array(9);
  857. };
  858. THREE.Matrix3.prototype = {
  859. constructor: THREE.Matrix3,
  860. getInverse: function ( matrix ) {
  861. // input: THREE.Matrix4
  862. // ( based on http://code.google.com/p/webgl-mjs/ )
  863. var me = matrix.elements;
  864. var a11 = me[10] * me[5] - me[6] * me[9];
  865. var a21 = - me[10] * me[1] + me[2] * me[9];
  866. var a31 = me[6] * me[1] - me[2] * me[5];
  867. var a12 = - me[10] * me[4] + me[6] * me[8];
  868. var a22 = me[10] * me[0] - me[2] * me[8];
  869. var a32 = - me[6] * me[0] + me[2] * me[4];
  870. var a13 = me[9] * me[4] - me[5] * me[8];
  871. var a23 = - me[9] * me[0] + me[1] * me[8];
  872. var a33 = me[5] * me[0] - me[1] * me[4];
  873. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  874. // no inverse
  875. if ( det === 0 ) {
  876. console.warn( "Matrix3.getInverse(): determinant == 0" );
  877. }
  878. var idet = 1.0 / det;
  879. var m = this.elements;
  880. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  881. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  882. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  883. return this;
  884. },
  885. transpose: function () {
  886. var tmp, m = this.elements;
  887. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  888. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  889. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  890. return this;
  891. },
  892. transposeIntoArray: function ( r ) {
  893. var m = this.m;
  894. r[ 0 ] = m[ 0 ];
  895. r[ 1 ] = m[ 3 ];
  896. r[ 2 ] = m[ 6 ];
  897. r[ 3 ] = m[ 1 ];
  898. r[ 4 ] = m[ 4 ];
  899. r[ 5 ] = m[ 7 ];
  900. r[ 6 ] = m[ 2 ];
  901. r[ 7 ] = m[ 5 ];
  902. r[ 8 ] = m[ 8 ];
  903. return this;
  904. }
  905. };
  906. /**
  907. * @author mrdoob / http://mrdoob.com/
  908. * @author supereggbert / http://www.paulbrunt.co.uk/
  909. * @author philogb / http://blog.thejit.org/
  910. * @author jordi_ros / http://plattsoft.com
  911. * @author D1plo1d / http://github.com/D1plo1d
  912. * @author alteredq / http://alteredqualia.com/
  913. * @author mikael emtinger / http://gomo.se/
  914. * @author timknip / http://www.floorplanner.com/
  915. */
  916. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  917. this.elements = new Float32Array( 16 );
  918. this.set(
  919. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  920. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  921. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  922. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  923. );
  924. };
  925. THREE.Matrix4.prototype = {
  926. constructor: THREE.Matrix4,
  927. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  928. var te = this.elements;
  929. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  930. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  931. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  932. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  933. return this;
  934. },
  935. identity: function () {
  936. this.set(
  937. 1, 0, 0, 0,
  938. 0, 1, 0, 0,
  939. 0, 0, 1, 0,
  940. 0, 0, 0, 1
  941. );
  942. return this;
  943. },
  944. copy: function ( m ) {
  945. var me = m.elements;
  946. this.set(
  947. me[0], me[4], me[8], me[12],
  948. me[1], me[5], me[9], me[13],
  949. me[2], me[6], me[10], me[14],
  950. me[3], me[7], me[11], me[15]
  951. );
  952. return this;
  953. },
  954. lookAt: function ( eye, target, up ) {
  955. var te = this.elements;
  956. var x = THREE.Matrix4.__v1;
  957. var y = THREE.Matrix4.__v2;
  958. var z = THREE.Matrix4.__v3;
  959. z.sub( eye, target ).normalize();
  960. if ( z.length() === 0 ) {
  961. z.z = 1;
  962. }
  963. x.cross( up, z ).normalize();
  964. if ( x.length() === 0 ) {
  965. z.x += 0.0001;
  966. x.cross( up, z ).normalize();
  967. }
  968. y.cross( z, x );
  969. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  970. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  971. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  972. return this;
  973. },
  974. multiply: function ( a, b ) {
  975. var ae = a.elements;
  976. var be = b.elements;
  977. var te = this.elements;
  978. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  979. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  980. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  981. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  982. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  983. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  984. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  985. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  986. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  987. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  988. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  989. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  990. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  991. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  992. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  993. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  994. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  995. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  996. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  997. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  998. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  999. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1000. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1001. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1002. return this;
  1003. },
  1004. multiplySelf: function ( m ) {
  1005. return this.multiply( this, m );
  1006. },
  1007. multiplyToArray: function ( a, b, r ) {
  1008. var te = this.elements;
  1009. this.multiply( a, b );
  1010. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1011. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1012. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1013. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1014. return this;
  1015. },
  1016. multiplyScalar: function ( s ) {
  1017. var te = this.elements;
  1018. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1019. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1020. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1021. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1022. return this;
  1023. },
  1024. multiplyVector3: function ( v ) {
  1025. var te = this.elements;
  1026. var vx = v.x, vy = v.y, vz = v.z;
  1027. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1028. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1029. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1030. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1031. return v;
  1032. },
  1033. multiplyVector4: function ( v ) {
  1034. var te = this.elements;
  1035. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1036. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1037. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1038. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1039. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1040. return v;
  1041. },
  1042. multiplyVector3Array: function ( a ) {
  1043. var tmp = THREE.Matrix4.__v1;
  1044. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1045. tmp.x = a[ i ];
  1046. tmp.y = a[ i + 1 ];
  1047. tmp.z = a[ i + 2 ];
  1048. this.multiplyVector3( tmp );
  1049. a[ i ] = tmp.x;
  1050. a[ i + 1 ] = tmp.y;
  1051. a[ i + 2 ] = tmp.z;
  1052. }
  1053. return a;
  1054. },
  1055. rotateAxis: function ( v ) {
  1056. var te = this.elements;
  1057. var vx = v.x, vy = v.y, vz = v.z;
  1058. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1059. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1060. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1061. v.normalize();
  1062. return v;
  1063. },
  1064. crossVector: function ( a ) {
  1065. var te = this.elements;
  1066. var v = new THREE.Vector4();
  1067. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1068. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1069. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1070. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1071. return v;
  1072. },
  1073. determinant: function () {
  1074. var te = this.elements;
  1075. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1076. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1077. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1078. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1079. //TODO: make this more efficient
  1080. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1081. return (
  1082. n14 * n23 * n32 * n41-
  1083. n13 * n24 * n32 * n41-
  1084. n14 * n22 * n33 * n41+
  1085. n12 * n24 * n33 * n41+
  1086. n13 * n22 * n34 * n41-
  1087. n12 * n23 * n34 * n41-
  1088. n14 * n23 * n31 * n42+
  1089. n13 * n24 * n31 * n42+
  1090. n14 * n21 * n33 * n42-
  1091. n11 * n24 * n33 * n42-
  1092. n13 * n21 * n34 * n42+
  1093. n11 * n23 * n34 * n42+
  1094. n14 * n22 * n31 * n43-
  1095. n12 * n24 * n31 * n43-
  1096. n14 * n21 * n32 * n43+
  1097. n11 * n24 * n32 * n43+
  1098. n12 * n21 * n34 * n43-
  1099. n11 * n22 * n34 * n43-
  1100. n13 * n22 * n31 * n44+
  1101. n12 * n23 * n31 * n44+
  1102. n13 * n21 * n32 * n44-
  1103. n11 * n23 * n32 * n44-
  1104. n12 * n21 * n33 * n44+
  1105. n11 * n22 * n33 * n44
  1106. );
  1107. },
  1108. transpose: function () {
  1109. var te = this.elements;
  1110. var tmp;
  1111. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1112. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1113. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1114. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1115. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1116. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1117. return this;
  1118. },
  1119. flattenToArray: function ( flat ) {
  1120. var te = this.elements;
  1121. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1122. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1123. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1124. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1125. return flat;
  1126. },
  1127. flattenToArrayOffset: function( flat, offset ) {
  1128. var te = this.elements;
  1129. flat[ offset ] = te[0];
  1130. flat[ offset + 1 ] = te[1];
  1131. flat[ offset + 2 ] = te[2];
  1132. flat[ offset + 3 ] = te[3];
  1133. flat[ offset + 4 ] = te[4];
  1134. flat[ offset + 5 ] = te[5];
  1135. flat[ offset + 6 ] = te[6];
  1136. flat[ offset + 7 ] = te[7];
  1137. flat[ offset + 8 ] = te[8];
  1138. flat[ offset + 9 ] = te[9];
  1139. flat[ offset + 10 ] = te[10];
  1140. flat[ offset + 11 ] = te[11];
  1141. flat[ offset + 12 ] = te[12];
  1142. flat[ offset + 13 ] = te[13];
  1143. flat[ offset + 14 ] = te[14];
  1144. flat[ offset + 15 ] = te[15];
  1145. return flat;
  1146. },
  1147. getPosition: function () {
  1148. var te = this.elements;
  1149. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1150. },
  1151. setPosition: function ( v ) {
  1152. var te = this.elements;
  1153. te[12] = v.x;
  1154. te[13] = v.y;
  1155. te[14] = v.z;
  1156. return this;
  1157. },
  1158. getColumnX: function () {
  1159. var te = this.elements;
  1160. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1161. },
  1162. getColumnY: function () {
  1163. var te = this.elements;
  1164. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1165. },
  1166. getColumnZ: function() {
  1167. var te = this.elements;
  1168. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1169. },
  1170. getInverse: function ( m ) {
  1171. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1172. var te = this.elements;
  1173. var me = m.elements;
  1174. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1175. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1176. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1177. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1178. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1179. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1180. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1181. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1182. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1183. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1184. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1185. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1186. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1187. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1188. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1189. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1190. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1191. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1192. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1193. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1194. this.multiplyScalar( 1 / m.determinant() );
  1195. return this;
  1196. },
  1197. setRotationFromEuler: function ( v, order ) {
  1198. var te = this.elements;
  1199. var x = v.x, y = v.y, z = v.z;
  1200. var a = Math.cos( x ), b = Math.sin( x );
  1201. var c = Math.cos( y ), d = Math.sin( y );
  1202. var e = Math.cos( z ), f = Math.sin( z );
  1203. if ( order === undefined || order === 'XYZ' ) {
  1204. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1205. te[0] = c * e;
  1206. te[4] = - c * f;
  1207. te[8] = d;
  1208. te[1] = af + be * d;
  1209. te[5] = ae - bf * d;
  1210. te[9] = - b * c;
  1211. te[2] = bf - ae * d;
  1212. te[6] = be + af * d;
  1213. te[10] = a * c;
  1214. } else if ( order === 'YXZ' ) {
  1215. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1216. te[0] = ce + df * b;
  1217. te[4] = de * b - cf;
  1218. te[8] = a * d;
  1219. te[1] = a * f;
  1220. te[5] = a * e;
  1221. te[9] = - b;
  1222. te[2] = cf * b - de;
  1223. te[6] = df + ce * b;
  1224. te[10] = a * c;
  1225. } else if ( order === 'ZXY' ) {
  1226. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1227. te[0] = ce - df * b;
  1228. te[4] = - a * f;
  1229. te[8] = de + cf * b;
  1230. te[1] = cf + de * b;
  1231. te[5] = a * e;
  1232. te[9] = df - ce * b;
  1233. te[2] = - a * d;
  1234. te[6] = b;
  1235. te[10] = a * c;
  1236. } else if ( order === 'ZYX' ) {
  1237. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1238. te[0] = c * e;
  1239. te[4] = be * d - af;
  1240. te[8] = ae * d + bf;
  1241. te[1] = c * f;
  1242. te[5] = bf * d + ae;
  1243. te[9] = af * d - be;
  1244. te[2] = - d;
  1245. te[6] = b * c;
  1246. te[10] = a * c;
  1247. } else if ( order === 'YZX' ) {
  1248. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1249. te[0] = c * e;
  1250. te[4] = bd - ac * f;
  1251. te[8] = bc * f + ad;
  1252. te[1] = f;
  1253. te[5] = a * e;
  1254. te[9] = - b * e;
  1255. te[2] = - d * e;
  1256. te[6] = ad * f + bc;
  1257. te[10] = ac - bd * f;
  1258. } else if ( order === 'XZY' ) {
  1259. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1260. te[0] = c * e;
  1261. te[4] = - f;
  1262. te[8] = d * e;
  1263. te[1] = ac * f + bd;
  1264. te[5] = a * e;
  1265. te[9] = ad * f - bc;
  1266. te[2] = bc * f - ad;
  1267. te[6] = b * e;
  1268. te[10] = bd * f + ac;
  1269. }
  1270. return this;
  1271. },
  1272. setRotationFromQuaternion: function ( q ) {
  1273. var te = this.elements;
  1274. var x = q.x, y = q.y, z = q.z, w = q.w;
  1275. var x2 = x + x, y2 = y + y, z2 = z + z;
  1276. var xx = x * x2, xy = x * y2, xz = x * z2;
  1277. var yy = y * y2, yz = y * z2, zz = z * z2;
  1278. var wx = w * x2, wy = w * y2, wz = w * z2;
  1279. te[0] = 1 - ( yy + zz );
  1280. te[4] = xy - wz;
  1281. te[8] = xz + wy;
  1282. te[1] = xy + wz;
  1283. te[5] = 1 - ( xx + zz );
  1284. te[9] = yz - wx;
  1285. te[2] = xz - wy;
  1286. te[6] = yz + wx;
  1287. te[10] = 1 - ( xx + yy );
  1288. return this;
  1289. },
  1290. compose: function ( translation, rotation, scale ) {
  1291. var te = this.elements;
  1292. var mRotation = THREE.Matrix4.__m1;
  1293. var mScale = THREE.Matrix4.__m2;
  1294. mRotation.identity();
  1295. mRotation.setRotationFromQuaternion( rotation );
  1296. mScale.makeScale( scale.x, scale.y, scale.z );
  1297. this.multiply( mRotation, mScale );
  1298. te[12] = translation.x;
  1299. te[13] = translation.y;
  1300. te[14] = translation.z;
  1301. return this;
  1302. },
  1303. decompose: function ( translation, rotation, scale ) {
  1304. var te = this.elements;
  1305. // grab the axis vectors
  1306. var x = THREE.Matrix4.__v1;
  1307. var y = THREE.Matrix4.__v2;
  1308. var z = THREE.Matrix4.__v3;
  1309. x.set( te[0], te[1], te[2] );
  1310. y.set( te[4], te[5], te[6] );
  1311. z.set( te[8], te[9], te[10] );
  1312. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1313. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1314. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1315. scale.x = x.length();
  1316. scale.y = y.length();
  1317. scale.z = z.length();
  1318. translation.x = te[12];
  1319. translation.y = te[13];
  1320. translation.z = te[14];
  1321. // scale the rotation part
  1322. var matrix = THREE.Matrix4.__m1;
  1323. matrix.copy( this );
  1324. matrix.elements[0] /= scale.x;
  1325. matrix.elements[1] /= scale.x;
  1326. matrix.elements[2] /= scale.x;
  1327. matrix.elements[4] /= scale.y;
  1328. matrix.elements[5] /= scale.y;
  1329. matrix.elements[6] /= scale.y;
  1330. matrix.elements[8] /= scale.z;
  1331. matrix.elements[9] /= scale.z;
  1332. matrix.elements[10] /= scale.z;
  1333. rotation.setFromRotationMatrix( matrix );
  1334. return [ translation, rotation, scale ];
  1335. },
  1336. extractPosition: function ( m ) {
  1337. var te = this.elements;
  1338. var me = m.elements;
  1339. te[12] = me[12];
  1340. te[13] = me[13];
  1341. te[14] = me[14];
  1342. return this;
  1343. },
  1344. extractRotation: function ( m ) {
  1345. var te = this.elements;
  1346. var me = m.elements;
  1347. var vector = THREE.Matrix4.__v1;
  1348. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1349. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1350. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1351. te[0] = me[0] * scaleX;
  1352. te[1] = me[1] * scaleX;
  1353. te[2] = me[2] * scaleX;
  1354. te[4] = me[4] * scaleY;
  1355. te[5] = me[5] * scaleY;
  1356. te[6] = me[6] * scaleY;
  1357. te[8] = me[8] * scaleZ;
  1358. te[9] = me[9] * scaleZ;
  1359. te[10] = me[10] * scaleZ;
  1360. return this;
  1361. },
  1362. //
  1363. translate: function ( v ) {
  1364. var te = this.elements;
  1365. var x = v.x, y = v.y, z = v.z;
  1366. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1367. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1368. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1369. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1370. return this;
  1371. },
  1372. rotateX: function ( angle ) {
  1373. var te = this.elements;
  1374. var m12 = te[4];
  1375. var m22 = te[5];
  1376. var m32 = te[6];
  1377. var m42 = te[7];
  1378. var m13 = te[8];
  1379. var m23 = te[9];
  1380. var m33 = te[10];
  1381. var m43 = te[11];
  1382. var c = Math.cos( angle );
  1383. var s = Math.sin( angle );
  1384. te[4] = c * m12 + s * m13;
  1385. te[5] = c * m22 + s * m23;
  1386. te[6] = c * m32 + s * m33;
  1387. te[7] = c * m42 + s * m43;
  1388. te[8] = c * m13 - s * m12;
  1389. te[9] = c * m23 - s * m22;
  1390. te[10] = c * m33 - s * m32;
  1391. te[11] = c * m43 - s * m42;
  1392. return this;
  1393. },
  1394. rotateY: function ( angle ) {
  1395. var te = this.elements;
  1396. var m11 = te[0];
  1397. var m21 = te[1];
  1398. var m31 = te[2];
  1399. var m41 = te[3];
  1400. var m13 = te[8];
  1401. var m23 = te[9];
  1402. var m33 = te[10];
  1403. var m43 = te[11];
  1404. var c = Math.cos( angle );
  1405. var s = Math.sin( angle );
  1406. te[0] = c * m11 - s * m13;
  1407. te[1] = c * m21 - s * m23;
  1408. te[2] = c * m31 - s * m33;
  1409. te[3] = c * m41 - s * m43;
  1410. te[8] = c * m13 + s * m11;
  1411. te[9] = c * m23 + s * m21;
  1412. te[10] = c * m33 + s * m31;
  1413. te[11] = c * m43 + s * m41;
  1414. return this;
  1415. },
  1416. rotateZ: function ( angle ) {
  1417. var te = this.elements;
  1418. var m11 = te[0];
  1419. var m21 = te[1];
  1420. var m31 = te[2];
  1421. var m41 = te[3];
  1422. var m12 = te[4];
  1423. var m22 = te[5];
  1424. var m32 = te[6];
  1425. var m42 = te[7];
  1426. var c = Math.cos( angle );
  1427. var s = Math.sin( angle );
  1428. te[0] = c * m11 + s * m12;
  1429. te[1] = c * m21 + s * m22;
  1430. te[2] = c * m31 + s * m32;
  1431. te[3] = c * m41 + s * m42;
  1432. te[4] = c * m12 - s * m11;
  1433. te[5] = c * m22 - s * m21;
  1434. te[6] = c * m32 - s * m31;
  1435. te[7] = c * m42 - s * m41;
  1436. return this;
  1437. },
  1438. rotateByAxis: function ( axis, angle ) {
  1439. var te = this.elements;
  1440. // optimize by checking axis
  1441. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1442. return this.rotateX( angle );
  1443. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1444. return this.rotateY( angle );
  1445. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1446. return this.rotateZ( angle );
  1447. }
  1448. var x = axis.x, y = axis.y, z = axis.z;
  1449. var n = Math.sqrt(x * x + y * y + z * z);
  1450. x /= n;
  1451. y /= n;
  1452. z /= n;
  1453. var xx = x * x, yy = y * y, zz = z * z;
  1454. var c = Math.cos( angle );
  1455. var s = Math.sin( angle );
  1456. var oneMinusCosine = 1 - c;
  1457. var xy = x * y * oneMinusCosine;
  1458. var xz = x * z * oneMinusCosine;
  1459. var yz = y * z * oneMinusCosine;
  1460. var xs = x * s;
  1461. var ys = y * s;
  1462. var zs = z * s;
  1463. var r11 = xx + (1 - xx) * c;
  1464. var r21 = xy + zs;
  1465. var r31 = xz - ys;
  1466. var r12 = xy - zs;
  1467. var r22 = yy + (1 - yy) * c;
  1468. var r32 = yz + xs;
  1469. var r13 = xz + ys;
  1470. var r23 = yz - xs;
  1471. var r33 = zz + (1 - zz) * c;
  1472. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1473. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1474. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1475. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1476. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1477. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1478. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1479. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1480. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1481. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1482. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1483. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1484. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1485. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1486. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1487. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1488. return this;
  1489. },
  1490. scale: function ( v ) {
  1491. var te = this.elements;
  1492. var x = v.x, y = v.y, z = v.z;
  1493. te[0] *= x; te[4] *= y; te[8] *= z;
  1494. te[1] *= x; te[5] *= y; te[9] *= z;
  1495. te[2] *= x; te[6] *= y; te[10] *= z;
  1496. te[3] *= x; te[7] *= y; te[11] *= z;
  1497. return this;
  1498. },
  1499. getMaxScaleOnAxis: function () {
  1500. var te = this.elements;
  1501. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  1502. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  1503. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  1504. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  1505. },
  1506. //
  1507. makeTranslation: function ( x, y, z ) {
  1508. this.set(
  1509. 1, 0, 0, x,
  1510. 0, 1, 0, y,
  1511. 0, 0, 1, z,
  1512. 0, 0, 0, 1
  1513. );
  1514. return this;
  1515. },
  1516. makeRotationX: function ( theta ) {
  1517. var c = Math.cos( theta ), s = Math.sin( theta );
  1518. this.set(
  1519. 1, 0, 0, 0,
  1520. 0, c, -s, 0,
  1521. 0, s, c, 0,
  1522. 0, 0, 0, 1
  1523. );
  1524. return this;
  1525. },
  1526. makeRotationY: function ( theta ) {
  1527. var c = Math.cos( theta ), s = Math.sin( theta );
  1528. this.set(
  1529. c, 0, s, 0,
  1530. 0, 1, 0, 0,
  1531. -s, 0, c, 0,
  1532. 0, 0, 0, 1
  1533. );
  1534. return this;
  1535. },
  1536. makeRotationZ: function ( theta ) {
  1537. var c = Math.cos( theta ), s = Math.sin( theta );
  1538. this.set(
  1539. c, -s, 0, 0,
  1540. s, c, 0, 0,
  1541. 0, 0, 1, 0,
  1542. 0, 0, 0, 1
  1543. );
  1544. return this;
  1545. },
  1546. makeRotationAxis: function ( axis, angle ) {
  1547. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1548. var c = Math.cos( angle );
  1549. var s = Math.sin( angle );
  1550. var t = 1 - c;
  1551. var x = axis.x, y = axis.y, z = axis.z;
  1552. var tx = t * x, ty = t * y;
  1553. this.set(
  1554. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1555. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1556. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1557. 0, 0, 0, 1
  1558. );
  1559. return this;
  1560. },
  1561. makeScale: function ( x, y, z ) {
  1562. this.set(
  1563. x, 0, 0, 0,
  1564. 0, y, 0, 0,
  1565. 0, 0, z, 0,
  1566. 0, 0, 0, 1
  1567. );
  1568. return this;
  1569. },
  1570. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1571. var te = this.elements;
  1572. var x = 2 * near / ( right - left );
  1573. var y = 2 * near / ( top - bottom );
  1574. var a = ( right + left ) / ( right - left );
  1575. var b = ( top + bottom ) / ( top - bottom );
  1576. var c = - ( far + near ) / ( far - near );
  1577. var d = - 2 * far * near / ( far - near );
  1578. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1579. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1580. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1581. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1582. return this;
  1583. },
  1584. makePerspective: function ( fov, aspect, near, far ) {
  1585. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1586. var ymin = - ymax;
  1587. var xmin = ymin * aspect;
  1588. var xmax = ymax * aspect;
  1589. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1590. },
  1591. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1592. var te = this.elements;
  1593. var w = right - left;
  1594. var h = top - bottom;
  1595. var p = far - near;
  1596. var x = ( right + left ) / w;
  1597. var y = ( top + bottom ) / h;
  1598. var z = ( far + near ) / p;
  1599. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1600. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1601. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1602. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1603. return this;
  1604. },
  1605. clone: function () {
  1606. var te = this.elements;
  1607. return new THREE.Matrix4(
  1608. te[0], te[4], te[8], te[12],
  1609. te[1], te[5], te[9], te[13],
  1610. te[2], te[6], te[10], te[14],
  1611. te[3], te[7], te[11], te[15]
  1612. );
  1613. }
  1614. };
  1615. THREE.Matrix4.__v1 = new THREE.Vector3();
  1616. THREE.Matrix4.__v2 = new THREE.Vector3();
  1617. THREE.Matrix4.__v3 = new THREE.Vector3();
  1618. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1619. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1620. /**
  1621. * https://github.com/mrdoob/eventtarget.js/
  1622. */
  1623. THREE.EventTarget = function () {
  1624. var listeners = {};
  1625. this.addEventListener = function ( type, listener ) {
  1626. if ( listeners[ type ] === undefined ) {
  1627. listeners[ type ] = [];
  1628. }
  1629. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1630. listeners[ type ].push( listener );
  1631. }
  1632. };
  1633. this.dispatchEvent = function ( event ) {
  1634. for ( var listener in listeners[ event.type ] ) {
  1635. listeners[ event.type ][ listener ]( event );
  1636. }
  1637. };
  1638. this.removeEventListener = function ( type, listener ) {
  1639. var index = listeners[ type ].indexOf( listener );
  1640. if ( index !== - 1 ) {
  1641. listeners[ type ].splice( index, 1 );
  1642. }
  1643. };
  1644. };
  1645. /**
  1646. * @author mrdoob / http://mrdoob.com/
  1647. * @author alteredq / http://alteredqualia.com/
  1648. */
  1649. THREE.Frustum = function ( ) {
  1650. this.planes = [
  1651. new THREE.Vector4(),
  1652. new THREE.Vector4(),
  1653. new THREE.Vector4(),
  1654. new THREE.Vector4(),
  1655. new THREE.Vector4(),
  1656. new THREE.Vector4()
  1657. ];
  1658. };
  1659. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  1660. var plane;
  1661. var planes = this.planes;
  1662. var me = m.elements;
  1663. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  1664. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  1665. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  1666. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  1667. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  1668. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  1669. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  1670. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  1671. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  1672. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  1673. for ( var i = 0; i < 6; i ++ ) {
  1674. plane = planes[ i ];
  1675. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  1676. }
  1677. };
  1678. THREE.Frustum.prototype.contains = function ( object ) {
  1679. var distance = 0.0;
  1680. var planes = this.planes;
  1681. var matrix = object.matrixWorld;
  1682. var me = matrix.elements;
  1683. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  1684. for ( var i = 0; i < 6; i ++ ) {
  1685. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  1686. if ( distance <= radius ) return false;
  1687. }
  1688. return true;
  1689. };
  1690. THREE.Frustum.__v1 = new THREE.Vector3();
  1691. /**
  1692. * @author mrdoob / http://mrdoob.com/
  1693. */
  1694. ( function ( THREE ) {
  1695. THREE.Ray = function ( origin, direction, near, far ) {
  1696. this.origin = origin || new THREE.Vector3();
  1697. this.direction = direction || new THREE.Vector3();
  1698. this.near = near || 0;
  1699. this.far = far || Infinity;
  1700. };
  1701. var originCopy = new THREE.Vector3();
  1702. var localOriginCopy = new THREE.Vector3();
  1703. var localDirectionCopy = new THREE.Vector3();
  1704. var vector = new THREE.Vector3();
  1705. var normal = new THREE.Vector3();
  1706. var intersectPoint = new THREE.Vector3();
  1707. var inverseMatrix = new THREE.Matrix4();
  1708. var descSort = function ( a, b ) {
  1709. return a.distance - b.distance;
  1710. };
  1711. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  1712. var distanceFromIntersection = function ( origin, direction, position ) {
  1713. v0.sub( position, origin );
  1714. var dot = v0.dot( direction );
  1715. var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  1716. var distance = position.distanceTo( intersect );
  1717. return distance;
  1718. };
  1719. // http://www.blackpawn.com/texts/pointinpoly/default.html
  1720. var pointInFace3 = function ( p, a, b, c ) {
  1721. v0.sub( c, a );
  1722. v1.sub( b, a );
  1723. v2.sub( p, a );
  1724. var dot00 = v0.dot( v0 );
  1725. var dot01 = v0.dot( v1 );
  1726. var dot02 = v0.dot( v2 );
  1727. var dot11 = v1.dot( v1 );
  1728. var dot12 = v1.dot( v2 );
  1729. var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  1730. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  1731. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  1732. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  1733. };
  1734. var intersectObject = function ( object, ray, intersects ) {
  1735. var distance,intersect;
  1736. if ( object instanceof THREE.Particle ) {
  1737. distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1738. if ( distance > object.scale.x ) {
  1739. return intersects;
  1740. }
  1741. intersect = {
  1742. distance: distance,
  1743. point: object.position,
  1744. face: null,
  1745. object: object
  1746. };
  1747. intersects.push( intersect );
  1748. } else if ( object instanceof THREE.Mesh ) {
  1749. // Checking boundingSphere
  1750. var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
  1751. // Checking distance to ray
  1752. distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1753. if ( distance > scaledRadius) {
  1754. return intersects;
  1755. }
  1756. // Checking faces
  1757. var f, fl, face, dot, scalar,
  1758. geometry = object.geometry,
  1759. vertices = geometry.vertices,
  1760. objMatrix, geometryMaterials,
  1761. isFaceMaterial, material, side, point;
  1762. geometryMaterials = object.geometry.materials;
  1763. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  1764. side = object.material.side;
  1765. var a, b, c, d;
  1766. var precision = ray.precision;
  1767. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  1768. originCopy.copy( ray.origin );
  1769. objMatrix = object.matrixWorld;
  1770. inverseMatrix.getInverse( objMatrix );
  1771. localOriginCopy.copy( originCopy );
  1772. inverseMatrix.multiplyVector3( localOriginCopy );
  1773. localDirectionCopy.copy( ray.direction );
  1774. inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
  1775. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  1776. face = geometry.faces[ f ];
  1777. material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  1778. if ( material === undefined ) continue;
  1779. side = material.side;
  1780. vector.sub( face.centroid, localOriginCopy );
  1781. normal = face.normal;
  1782. dot = localDirectionCopy.dot( normal );
  1783. // bail if ray and plane are parallel
  1784. if ( Math.abs( dot ) < precision ) continue;
  1785. // calc distance to plane
  1786. scalar = normal.dot( vector ) / dot;
  1787. // if negative distance, then plane is behind ray
  1788. if ( scalar < 0 ) continue;
  1789. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  1790. intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
  1791. if ( face instanceof THREE.Face3 ) {
  1792. a = vertices[ face.a ];
  1793. b = vertices[ face.b ];
  1794. c = vertices[ face.c ];
  1795. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  1796. point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1797. distance = originCopy.distanceTo( point );
  1798. if ( distance < ray.near || distance > ray.far ) continue;
  1799. intersect = {
  1800. distance: distance,
  1801. point: point,
  1802. face: face,
  1803. faceIndex: f,
  1804. object: object
  1805. };
  1806. intersects.push( intersect );
  1807. }
  1808. } else if ( face instanceof THREE.Face4 ) {
  1809. a = vertices[ face.a ];
  1810. b = vertices[ face.b ];
  1811. c = vertices[ face.c ];
  1812. d = vertices[ face.d ];
  1813. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  1814. point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1815. distance = originCopy.distanceTo( point );
  1816. if ( distance < ray.near || distance > ray.far ) continue;
  1817. intersect = {
  1818. distance: distance,
  1819. point: point,
  1820. face: face,
  1821. faceIndex: f,
  1822. object: object
  1823. };
  1824. intersects.push( intersect );
  1825. }
  1826. }
  1827. }
  1828. }
  1829. }
  1830. };
  1831. var intersectDescendants= function ( object, ray, intersects ) {
  1832. var descendants = object.getDescendants();
  1833. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  1834. intersectObject( descendants[ i ], this, intersects );
  1835. }
  1836. };
  1837. //
  1838. THREE.Ray.prototype.precision = 0.0001;
  1839. THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
  1840. var intersects = [];
  1841. if ( recursive === true ) {
  1842. intersectDescendants( object, this, intersects );
  1843. }
  1844. intersectObject(object,this,intersects);
  1845. intersects.sort( descSort );
  1846. return intersects;
  1847. };
  1848. THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
  1849. var intersects = [];
  1850. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  1851. intersectObject( objects[ i ], this, intersects );
  1852. if ( recursive === true ) {
  1853. intersectDescendants( objects[ i ], this, intersects );
  1854. }
  1855. }
  1856. intersects.sort( descSort );
  1857. return intersects;
  1858. };
  1859. }( THREE ) );
  1860. /**
  1861. * @author mrdoob / http://mrdoob.com/
  1862. */
  1863. THREE.Rectangle = function () {
  1864. var _left = 0;
  1865. var _top = 0;
  1866. var _right = 0;
  1867. var _bottom = 0;
  1868. var _width = 0;
  1869. var _height = 0;
  1870. var _isEmpty = true;
  1871. function resize() {
  1872. _width = _right - _left;
  1873. _height = _bottom - _top;
  1874. }
  1875. this.getX = function () {
  1876. return _left;
  1877. };
  1878. this.getY = function () {
  1879. return _top;
  1880. };
  1881. this.getWidth = function () {
  1882. return _width;
  1883. };
  1884. this.getHeight = function () {
  1885. return _height;
  1886. };
  1887. this.getLeft = function() {
  1888. return _left;
  1889. };
  1890. this.getTop = function() {
  1891. return _top;
  1892. };
  1893. this.getRight = function() {
  1894. return _right;
  1895. };
  1896. this.getBottom = function() {
  1897. return _bottom;
  1898. };
  1899. this.set = function ( left, top, right, bottom ) {
  1900. _isEmpty = false;
  1901. _left = left; _top = top;
  1902. _right = right; _bottom = bottom;
  1903. resize();
  1904. };
  1905. this.addPoint = function ( x, y ) {
  1906. if ( _isEmpty === true ) {
  1907. _isEmpty = false;
  1908. _left = x; _top = y;
  1909. _right = x; _bottom = y;
  1910. resize();
  1911. } else {
  1912. _left = _left < x ? _left : x; // Math.min( _left, x );
  1913. _top = _top < y ? _top : y; // Math.min( _top, y );
  1914. _right = _right > x ? _right : x; // Math.max( _right, x );
  1915. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  1916. resize();
  1917. }
  1918. };
  1919. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  1920. if ( _isEmpty === true ) {
  1921. _isEmpty = false;
  1922. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  1923. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  1924. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  1925. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  1926. resize();
  1927. } else {
  1928. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  1929. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  1930. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  1931. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  1932. resize();
  1933. };
  1934. };
  1935. this.addRectangle = function ( r ) {
  1936. if ( _isEmpty === true ) {
  1937. _isEmpty = false;
  1938. _left = r.getLeft(); _top = r.getTop();
  1939. _right = r.getRight(); _bottom = r.getBottom();
  1940. resize();
  1941. } else {
  1942. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  1943. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  1944. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  1945. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  1946. resize();
  1947. }
  1948. };
  1949. this.inflate = function ( v ) {
  1950. _left -= v; _top -= v;
  1951. _right += v; _bottom += v;
  1952. resize();
  1953. };
  1954. this.minSelf = function ( r ) {
  1955. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  1956. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  1957. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  1958. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  1959. resize();
  1960. };
  1961. this.intersects = function ( r ) {
  1962. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  1963. if ( _right < r.getLeft() ) return false;
  1964. if ( _left > r.getRight() ) return false;
  1965. if ( _bottom < r.getTop() ) return false;
  1966. if ( _top > r.getBottom() ) return false;
  1967. return true;
  1968. };
  1969. this.empty = function () {
  1970. _isEmpty = true;
  1971. _left = 0; _top = 0;
  1972. _right = 0; _bottom = 0;
  1973. resize();
  1974. };
  1975. this.isEmpty = function () {
  1976. return _isEmpty;
  1977. };
  1978. };
  1979. /**
  1980. * @author alteredq / http://alteredqualia.com/
  1981. */
  1982. THREE.Math = {
  1983. // Clamp value to range <a, b>
  1984. clamp: function ( x, a, b ) {
  1985. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  1986. },
  1987. // Clamp value to range <a, inf)
  1988. clampBottom: function ( x, a ) {
  1989. return x < a ? a : x;
  1990. },
  1991. // Linear mapping from range <a1, a2> to range <b1, b2>
  1992. mapLinear: function ( x, a1, a2, b1, b2 ) {
  1993. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1994. },
  1995. // Random float from <0, 1> with 16 bits of randomness
  1996. // (standard Math.random() creates repetitive patterns when applied over larger space)
  1997. random16: function () {
  1998. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  1999. },
  2000. // Random integer from <low, high> interval
  2001. randInt: function ( low, high ) {
  2002. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2003. },
  2004. // Random float from <low, high> interval
  2005. randFloat: function ( low, high ) {
  2006. return low + Math.random() * ( high - low );
  2007. },
  2008. // Random float from <-range/2, range/2> interval
  2009. randFloatSpread: function ( range ) {
  2010. return range * ( 0.5 - Math.random() );
  2011. },
  2012. sign: function ( x ) {
  2013. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2014. }
  2015. };
  2016. /**
  2017. * @author mrdoob / http://mrdoob.com/
  2018. * @author mikael emtinger / http://gomo.se/
  2019. * @author alteredq / http://alteredqualia.com/
  2020. */
  2021. THREE.Object3D = function () {
  2022. this.id = THREE.Object3DCount ++;
  2023. this.name = '';
  2024. this.properties = {};
  2025. this.parent = undefined;
  2026. this.children = [];
  2027. this.up = new THREE.Vector3( 0, 1, 0 );
  2028. this.position = new THREE.Vector3();
  2029. this.rotation = new THREE.Vector3();
  2030. this.eulerOrder = 'XYZ';
  2031. this.scale = new THREE.Vector3( 1, 1, 1 );
  2032. this.renderDepth = null;
  2033. this.rotationAutoUpdate = true;
  2034. this.matrix = new THREE.Matrix4();
  2035. this.matrixWorld = new THREE.Matrix4();
  2036. this.matrixRotationWorld = new THREE.Matrix4();
  2037. this.matrixAutoUpdate = true;
  2038. this.matrixWorldNeedsUpdate = true;
  2039. this.quaternion = new THREE.Quaternion();
  2040. this.useQuaternion = false;
  2041. this.boundRadius = 0.0;
  2042. this.boundRadiusScale = 1.0;
  2043. this.visible = true;
  2044. this.castShadow = false;
  2045. this.receiveShadow = false;
  2046. this.frustumCulled = true;
  2047. this._vector = new THREE.Vector3();
  2048. };
  2049. THREE.Object3D.prototype = {
  2050. constructor: THREE.Object3D,
  2051. applyMatrix: function ( matrix ) {
  2052. this.matrix.multiply( matrix, this.matrix );
  2053. this.scale.getScaleFromMatrix( this.matrix );
  2054. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2055. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2056. this.position.getPositionFromMatrix( this.matrix );
  2057. },
  2058. translate: function ( distance, axis ) {
  2059. this.matrix.rotateAxis( axis );
  2060. this.position.addSelf( axis.multiplyScalar( distance ) );
  2061. },
  2062. translateX: function ( distance ) {
  2063. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2064. },
  2065. translateY: function ( distance ) {
  2066. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2067. },
  2068. translateZ: function ( distance ) {
  2069. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2070. },
  2071. lookAt: function ( vector ) {
  2072. // TODO: Add hierarchy support.
  2073. this.matrix.lookAt( vector, this.position, this.up );
  2074. if ( this.rotationAutoUpdate ) {
  2075. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2076. }
  2077. },
  2078. add: function ( object ) {
  2079. if ( object === this ) {
  2080. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2081. return;
  2082. }
  2083. if ( object instanceof THREE.Object3D ) {
  2084. if ( object.parent !== undefined ) {
  2085. object.parent.remove( object );
  2086. }
  2087. object.parent = this;
  2088. this.children.push( object );
  2089. // add to scene
  2090. var scene = this;
  2091. while ( scene.parent !== undefined ) {
  2092. scene = scene.parent;
  2093. }
  2094. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2095. scene.__addObject( object );
  2096. }
  2097. }
  2098. },
  2099. remove: function ( object ) {
  2100. var index = this.children.indexOf( object );
  2101. if ( index !== - 1 ) {
  2102. object.parent = undefined;
  2103. this.children.splice( index, 1 );
  2104. // remove from scene
  2105. var scene = this;
  2106. while ( scene.parent !== undefined ) {
  2107. scene = scene.parent;
  2108. }
  2109. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2110. scene.__removeObject( object );
  2111. }
  2112. }
  2113. },
  2114. getChildByName: function ( name, recursive ) {
  2115. var c, cl, child;
  2116. for ( c = 0, cl = this.children.length; c < cl; c ++ ) {
  2117. child = this.children[ c ];
  2118. if ( child.name === name ) {
  2119. return child;
  2120. }
  2121. if ( recursive ) {
  2122. child = child.getChildByName( name, recursive );
  2123. if ( child !== undefined ) {
  2124. return child;
  2125. }
  2126. }
  2127. }
  2128. return undefined;
  2129. },
  2130. getDescendants: function ( array ) {
  2131. if ( array === undefined ) array = [];
  2132. Array.prototype.push.apply( array, this.children );
  2133. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2134. this.children[ i ].getDescendants( array );
  2135. };
  2136. return array;
  2137. },
  2138. updateMatrix: function () {
  2139. this.matrix.setPosition( this.position );
  2140. if ( this.useQuaternion === true ) {
  2141. this.matrix.setRotationFromQuaternion( this.quaternion );
  2142. } else {
  2143. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2144. }
  2145. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2146. this.matrix.scale( this.scale );
  2147. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2148. }
  2149. this.matrixWorldNeedsUpdate = true;
  2150. },
  2151. updateMatrixWorld: function ( force ) {
  2152. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2153. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2154. if ( this.parent !== undefined ) {
  2155. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2156. } else {
  2157. this.matrixWorld.copy( this.matrix );
  2158. }
  2159. this.matrixWorldNeedsUpdate = false;
  2160. force = true;
  2161. }
  2162. // update children
  2163. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2164. this.children[ i ].updateMatrixWorld( force );
  2165. }
  2166. },
  2167. worldToLocal: function ( vector ) {
  2168. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2169. },
  2170. localToWorld: function ( vector ) {
  2171. return this.matrixWorld.multiplyVector3( vector );
  2172. },
  2173. clone: function () {
  2174. // TODO
  2175. }
  2176. };
  2177. THREE.Object3D.__m1 = new THREE.Matrix4();
  2178. THREE.Object3DCount = 0;
  2179. /**
  2180. * @author mrdoob / http://mrdoob.com/
  2181. * @author supereggbert / http://www.paulbrunt.co.uk/
  2182. * @author julianwa / https://github.com/julianwa
  2183. */
  2184. THREE.Projector = function() {
  2185. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  2186. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  2187. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  2188. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  2189. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  2190. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  2191. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  2192. _vector3 = new THREE.Vector3(),
  2193. _vector4 = new THREE.Vector4(),
  2194. _viewProjectionMatrix = new THREE.Matrix4(),
  2195. _modelViewProjectionMatrix = new THREE.Matrix4(),
  2196. _frustum = new THREE.Frustum(),
  2197. _clippedVertex1PositionScreen = new THREE.Vector4(),
  2198. _clippedVertex2PositionScreen = new THREE.Vector4(),
  2199. _face3VertexNormals;
  2200. this.projectVector = function ( vector, camera ) {
  2201. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2202. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2203. _viewProjectionMatrix.multiplyVector3( vector );
  2204. return vector;
  2205. };
  2206. this.unprojectVector = function ( vector, camera ) {
  2207. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  2208. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  2209. _viewProjectionMatrix.multiplyVector3( vector );
  2210. return vector;
  2211. };
  2212. this.pickingRay = function ( vector, camera ) {
  2213. var end, ray, t;
  2214. // set two vectors with opposing z values
  2215. vector.z = -1.0;
  2216. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  2217. this.unprojectVector( vector, camera );
  2218. this.unprojectVector( end, camera );
  2219. // find direction from vector to end
  2220. end.subSelf( vector ).normalize();
  2221. return new THREE.Ray( vector, end );
  2222. };
  2223. var projectGraph = function ( root, sort ) {
  2224. _objectCount = 0;
  2225. _renderData.objects.length = 0;
  2226. _renderData.sprites.length = 0;
  2227. _renderData.lights.length = 0;
  2228. var projectObject = function ( object ) {
  2229. if ( object.visible === false ) return;
  2230. if ( ( object instanceof THREE.Mesh || object instanceof THREE.Line ) &&
  2231. ( object.frustumCulled === false || _frustum.contains( object ) === true ) ) {
  2232. _vector3.copy( object.matrixWorld.getPosition() );
  2233. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2234. _object = getNextObjectInPool();
  2235. _object.object = object;
  2236. _object.z = _vector3.z;
  2237. _renderData.objects.push( _object );
  2238. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  2239. _vector3.copy( object.matrixWorld.getPosition() );
  2240. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2241. _object = getNextObjectInPool();
  2242. _object.object = object;
  2243. _object.z = _vector3.z;
  2244. _renderData.sprites.push( _object );
  2245. } else if ( object instanceof THREE.Light ) {
  2246. _renderData.lights.push( object );
  2247. }
  2248. for ( var c = 0, cl = object.children.length; c < cl; c ++ ) {
  2249. projectObject( object.children[ c ] );
  2250. }
  2251. };
  2252. projectObject( root );
  2253. if ( sort === true ) _renderData.objects.sort( painterSort );
  2254. return _renderData;
  2255. };
  2256. this.projectScene = function ( scene, camera, sort ) {
  2257. var near = camera.near, far = camera.far, visible = false,
  2258. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  2259. modelMatrix, rotationMatrix,
  2260. geometry, geometryMaterials, vertices, vertex, vertexPositionScreen,
  2261. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  2262. v1, v2, v3, v4, isFaceMaterial, material, side;
  2263. _face3Count = 0;
  2264. _face4Count = 0;
  2265. _lineCount = 0;
  2266. _particleCount = 0;
  2267. _renderData.elements.length = 0;
  2268. scene.updateMatrixWorld();
  2269. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2270. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2271. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2272. _frustum.setFromMatrix( _viewProjectionMatrix );
  2273. _renderData = projectGraph( scene, false );
  2274. for ( o = 0, ol = _renderData.objects.length; o < ol; o++ ) {
  2275. object = _renderData.objects[ o ].object;
  2276. modelMatrix = object.matrixWorld;
  2277. _vertexCount = 0;
  2278. if ( object instanceof THREE.Mesh ) {
  2279. geometry = object.geometry;
  2280. geometryMaterials = object.geometry.materials;
  2281. vertices = geometry.vertices;
  2282. faces = geometry.faces;
  2283. faceVertexUvs = geometry.faceVertexUvs;
  2284. rotationMatrix = object.matrixRotationWorld.extractRotation( modelMatrix );
  2285. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2286. side = object.material.side;
  2287. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  2288. _vertex = getNextVertexInPool();
  2289. _vertex.positionWorld.copy( vertices[ v ] );
  2290. modelMatrix.multiplyVector3( _vertex.positionWorld );
  2291. _vertex.positionScreen.copy( _vertex.positionWorld );
  2292. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  2293. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  2294. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  2295. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  2296. }
  2297. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  2298. face = faces[ f ];
  2299. material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  2300. if ( material === undefined ) continue;
  2301. side = material.side;
  2302. if ( face instanceof THREE.Face3 ) {
  2303. v1 = _vertexPool[ face.a ];
  2304. v2 = _vertexPool[ face.b ];
  2305. v3 = _vertexPool[ face.c ];
  2306. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  2307. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2308. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  2309. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2310. _face = getNextFace3InPool();
  2311. _face.v1.copy( v1 );
  2312. _face.v2.copy( v2 );
  2313. _face.v3.copy( v3 );
  2314. } else {
  2315. continue;
  2316. }
  2317. } else {
  2318. continue;
  2319. }
  2320. } else if ( face instanceof THREE.Face4 ) {
  2321. v1 = _vertexPool[ face.a ];
  2322. v2 = _vertexPool[ face.b ];
  2323. v3 = _vertexPool[ face.c ];
  2324. v4 = _vertexPool[ face.d ];
  2325. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  2326. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2327. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  2328. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  2329. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  2330. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2331. _face = getNextFace4InPool();
  2332. _face.v1.copy( v1 );
  2333. _face.v2.copy( v2 );
  2334. _face.v3.copy( v3 );
  2335. _face.v4.copy( v4 );
  2336. } else {
  2337. continue;
  2338. }
  2339. } else {
  2340. continue;
  2341. }
  2342. }
  2343. _face.normalWorld.copy( face.normal );
  2344. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  2345. rotationMatrix.multiplyVector3( _face.normalWorld );
  2346. _face.centroidWorld.copy( face.centroid );
  2347. modelMatrix.multiplyVector3( _face.centroidWorld );
  2348. _face.centroidScreen.copy( _face.centroidWorld );
  2349. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  2350. faceVertexNormals = face.vertexNormals;
  2351. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  2352. normal = _face.vertexNormalsWorld[ n ];
  2353. normal.copy( faceVertexNormals[ n ] );
  2354. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  2355. rotationMatrix.multiplyVector3( normal );
  2356. }
  2357. _face.vertexNormalsLength = faceVertexNormals.length;
  2358. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  2359. uvs = faceVertexUvs[ c ][ f ];
  2360. if ( uvs === undefined ) continue;
  2361. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2362. _face.uvs[ c ][ u ] = uvs[ u ];
  2363. }
  2364. }
  2365. _face.material = material;
  2366. _face.z = _face.centroidScreen.z;
  2367. _renderData.elements.push( _face );
  2368. }
  2369. } else if ( object instanceof THREE.Line ) {
  2370. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  2371. vertices = object.geometry.vertices;
  2372. v1 = getNextVertexInPool();
  2373. v1.positionScreen.copy( vertices[ 0 ] );
  2374. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2375. // Handle LineStrip and LinePieces
  2376. var step = object.type === THREE.LinePieces ? 2 : 1;
  2377. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2378. v1 = getNextVertexInPool();
  2379. v1.positionScreen.copy( vertices[ v ] );
  2380. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2381. if ( ( v + 1 ) % step > 0 ) continue;
  2382. v2 = _vertexPool[ _vertexCount - 2 ];
  2383. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2384. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2385. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  2386. // Perform the perspective divide
  2387. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2388. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2389. _line = getNextLineInPool();
  2390. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2391. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2392. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2393. _line.material = object.material;
  2394. _renderData.elements.push( _line );
  2395. }
  2396. }
  2397. }
  2398. }
  2399. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2400. object = _renderData.sprites[ o ].object;
  2401. modelMatrix = object.matrixWorld;
  2402. if ( object instanceof THREE.Particle ) {
  2403. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  2404. _viewProjectionMatrix.multiplyVector4( _vector4 );
  2405. _vector4.z /= _vector4.w;
  2406. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2407. _particle = getNextParticleInPool();
  2408. _particle.object = object;
  2409. _particle.x = _vector4.x / _vector4.w;
  2410. _particle.y = _vector4.y / _vector4.w;
  2411. _particle.z = _vector4.z;
  2412. _particle.rotation = object.rotation.z;
  2413. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2414. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2415. _particle.material = object.material;
  2416. _renderData.elements.push( _particle );
  2417. }
  2418. }
  2419. }
  2420. sort && _renderData.elements.sort( painterSort );
  2421. return _renderData;
  2422. };
  2423. // Pools
  2424. function getNextObjectInPool() {
  2425. if ( _objectCount === _objectPoolLength ) {
  2426. var object = new THREE.RenderableObject();
  2427. _objectPool.push( object );
  2428. _objectPoolLength ++;
  2429. _objectCount ++;
  2430. return object;
  2431. }
  2432. return _objectPool[ _objectCount ++ ];
  2433. }
  2434. function getNextVertexInPool() {
  2435. if ( _vertexCount === _vertexPoolLength ) {
  2436. var vertex = new THREE.RenderableVertex();
  2437. _vertexPool.push( vertex );
  2438. _vertexPoolLength ++;
  2439. _vertexCount ++;
  2440. return vertex;
  2441. }
  2442. return _vertexPool[ _vertexCount ++ ];
  2443. }
  2444. function getNextFace3InPool() {
  2445. if ( _face3Count === _face3PoolLength ) {
  2446. var face = new THREE.RenderableFace3();
  2447. _face3Pool.push( face );
  2448. _face3PoolLength ++;
  2449. _face3Count ++;
  2450. return face;
  2451. }
  2452. return _face3Pool[ _face3Count ++ ];
  2453. }
  2454. function getNextFace4InPool() {
  2455. if ( _face4Count === _face4PoolLength ) {
  2456. var face = new THREE.RenderableFace4();
  2457. _face4Pool.push( face );
  2458. _face4PoolLength ++;
  2459. _face4Count ++;
  2460. return face;
  2461. }
  2462. return _face4Pool[ _face4Count ++ ];
  2463. }
  2464. function getNextLineInPool() {
  2465. if ( _lineCount === _linePoolLength ) {
  2466. var line = new THREE.RenderableLine();
  2467. _linePool.push( line );
  2468. _linePoolLength ++;
  2469. _lineCount ++
  2470. return line;
  2471. }
  2472. return _linePool[ _lineCount ++ ];
  2473. }
  2474. function getNextParticleInPool() {
  2475. if ( _particleCount === _particlePoolLength ) {
  2476. var particle = new THREE.RenderableParticle();
  2477. _particlePool.push( particle );
  2478. _particlePoolLength ++;
  2479. _particleCount ++
  2480. return particle;
  2481. }
  2482. return _particlePool[ _particleCount ++ ];
  2483. }
  2484. //
  2485. function painterSort( a, b ) {
  2486. return b.z - a.z;
  2487. }
  2488. function clipLine( s1, s2 ) {
  2489. var alpha1 = 0, alpha2 = 1,
  2490. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2491. // Z = -1 and Z = +1, respectively.
  2492. bc1near = s1.z + s1.w,
  2493. bc2near = s2.z + s2.w,
  2494. bc1far = - s1.z + s1.w,
  2495. bc2far = - s2.z + s2.w;
  2496. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2497. // Both vertices lie entirely within all clip planes.
  2498. return true;
  2499. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2500. // Both vertices lie entirely outside one of the clip planes.
  2501. return false;
  2502. } else {
  2503. // The line segment spans at least one clip plane.
  2504. if ( bc1near < 0 ) {
  2505. // v1 lies outside the near plane, v2 inside
  2506. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2507. } else if ( bc2near < 0 ) {
  2508. // v2 lies outside the near plane, v1 inside
  2509. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2510. }
  2511. if ( bc1far < 0 ) {
  2512. // v1 lies outside the far plane, v2 inside
  2513. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2514. } else if ( bc2far < 0 ) {
  2515. // v2 lies outside the far plane, v2 inside
  2516. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2517. }
  2518. if ( alpha2 < alpha1 ) {
  2519. // The line segment spans two boundaries, but is outside both of them.
  2520. // (This can't happen when we're only clipping against just near/far but good
  2521. // to leave the check here for future usage if other clip planes are added.)
  2522. return false;
  2523. } else {
  2524. // Update the s1 and s2 vertices to match the clipped line segment.
  2525. s1.lerpSelf( s2, alpha1 );
  2526. s2.lerpSelf( s1, 1 - alpha2 );
  2527. return true;
  2528. }
  2529. }
  2530. }
  2531. };
  2532. /**
  2533. * @author mikael emtinger / http://gomo.se/
  2534. * @author alteredq / http://alteredqualia.com/
  2535. * @author WestLangley / http://github.com/WestLangley
  2536. */
  2537. THREE.Quaternion = function( x, y, z, w ) {
  2538. this.x = x || 0;
  2539. this.y = y || 0;
  2540. this.z = z || 0;
  2541. this.w = ( w !== undefined ) ? w : 1;
  2542. };
  2543. THREE.Quaternion.prototype = {
  2544. constructor: THREE.Quaternion,
  2545. set: function ( x, y, z, w ) {
  2546. this.x = x;
  2547. this.y = y;
  2548. this.z = z;
  2549. this.w = w;
  2550. return this;
  2551. },
  2552. copy: function ( q ) {
  2553. this.x = q.x;
  2554. this.y = q.y;
  2555. this.z = q.z;
  2556. this.w = q.w;
  2557. return this;
  2558. },
  2559. setFromEuler: function ( v, order ) {
  2560. // http://www.mathworks.com/matlabcentral/fileexchange/
  2561. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2562. // content/SpinCalc.m
  2563. var c1 = Math.cos( v.x / 2 );
  2564. var c2 = Math.cos( v.y / 2 );
  2565. var c3 = Math.cos( v.z / 2 );
  2566. var s1 = Math.sin( v.x / 2 );
  2567. var s2 = Math.sin( v.y / 2 );
  2568. var s3 = Math.sin( v.z / 2 );
  2569. if ( order === undefined || order === 'XYZ' ) {
  2570. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2571. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2572. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2573. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2574. } else if ( order === 'YXZ' ) {
  2575. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2576. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2577. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2578. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2579. } else if ( order === 'ZXY' ) {
  2580. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2581. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2582. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2583. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2584. } else if ( order === 'ZYX' ) {
  2585. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2586. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2587. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2588. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2589. } else if ( order === 'YZX' ) {
  2590. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2591. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2592. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2593. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2594. } else if ( order === 'XZY' ) {
  2595. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2596. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2597. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2598. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2599. }
  2600. return this;
  2601. },
  2602. setFromAxisAngle: function ( axis, angle ) {
  2603. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2604. // axis have to be normalized
  2605. var halfAngle = angle / 2,
  2606. s = Math.sin( halfAngle );
  2607. this.x = axis.x * s;
  2608. this.y = axis.y * s;
  2609. this.z = axis.z * s;
  2610. this.w = Math.cos( halfAngle );
  2611. return this;
  2612. },
  2613. setFromRotationMatrix: function ( m ) {
  2614. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2615. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2616. var te = m.elements,
  2617. m11 = te[0], m12 = te[4], m13 = te[8],
  2618. m21 = te[1], m22 = te[5], m23 = te[9],
  2619. m31 = te[2], m32 = te[6], m33 = te[10],
  2620. trace = m11 + m22 + m33,
  2621. s;
  2622. if( trace > 0 ) {
  2623. s = 0.5 / Math.sqrt( trace + 1.0 );
  2624. this.w = 0.25 / s;
  2625. this.x = ( m32 - m23 ) * s;
  2626. this.y = ( m13 - m31 ) * s;
  2627. this.z = ( m21 - m12 ) * s;
  2628. } else if ( m11 > m22 && m11 > m33 ) {
  2629. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2630. this.w = (m32 - m23 ) / s;
  2631. this.x = 0.25 * s;
  2632. this.y = (m12 + m21 ) / s;
  2633. this.z = (m13 + m31 ) / s;
  2634. } else if (m22 > m33) {
  2635. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2636. this.w = (m13 - m31 ) / s;
  2637. this.x = (m12 + m21 ) / s;
  2638. this.y = 0.25 * s;
  2639. this.z = (m23 + m32 ) / s;
  2640. } else {
  2641. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2642. this.w = ( m21 - m12 ) / s;
  2643. this.x = ( m13 + m31 ) / s;
  2644. this.y = ( m23 + m32 ) / s;
  2645. this.z = 0.25 * s;
  2646. }
  2647. return this;
  2648. },
  2649. calculateW : function () {
  2650. this.w = - Math.sqrt( Math.abs( 1.0 - this.x * this.x - this.y * this.y - this.z * this.z ) );
  2651. return this;
  2652. },
  2653. inverse: function () {
  2654. this.x *= -1;
  2655. this.y *= -1;
  2656. this.z *= -1;
  2657. return this;
  2658. },
  2659. length: function () {
  2660. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2661. },
  2662. normalize: function () {
  2663. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2664. if ( l === 0 ) {
  2665. this.x = 0;
  2666. this.y = 0;
  2667. this.z = 0;
  2668. this.w = 0;
  2669. } else {
  2670. l = 1 / l;
  2671. this.x = this.x * l;
  2672. this.y = this.y * l;
  2673. this.z = this.z * l;
  2674. this.w = this.w * l;
  2675. }
  2676. return this;
  2677. },
  2678. multiply: function ( a, b ) {
  2679. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2680. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2681. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2682. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2683. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2684. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2685. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2686. return this;
  2687. },
  2688. multiplySelf: function ( b ) {
  2689. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2690. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2691. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2692. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2693. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2694. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2695. return this;
  2696. },
  2697. multiplyVector3: function ( vector, dest ) {
  2698. if ( !dest ) { dest = vector; }
  2699. var x = vector.x, y = vector.y, z = vector.z,
  2700. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2701. // calculate quat * vector
  2702. var ix = qw * x + qy * z - qz * y,
  2703. iy = qw * y + qz * x - qx * z,
  2704. iz = qw * z + qx * y - qy * x,
  2705. iw = -qx * x - qy * y - qz * z;
  2706. // calculate result * inverse quat
  2707. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2708. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2709. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2710. return dest;
  2711. },
  2712. slerpSelf: function ( qb, t ) {
  2713. var x = this.x, y = this.y, z = this.z, w = this.w;
  2714. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2715. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2716. if ( cosHalfTheta < 0 ) {
  2717. this.w = -qb.w;
  2718. this.x = -qb.x;
  2719. this.y = -qb.y;
  2720. this.z = -qb.z;
  2721. cosHalfTheta = -cosHalfTheta;
  2722. } else {
  2723. this.copy( qb );
  2724. }
  2725. if ( cosHalfTheta >= 1.0 ) {
  2726. this.w = w;
  2727. this.x = x;
  2728. this.y = y;
  2729. this.z = z;
  2730. return this;
  2731. }
  2732. var halfTheta = Math.acos( cosHalfTheta );
  2733. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2734. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2735. this.w = 0.5 * ( w + this.w );
  2736. this.x = 0.5 * ( x + this.x );
  2737. this.y = 0.5 * ( y + this.y );
  2738. this.z = 0.5 * ( z + this.z );
  2739. return this;
  2740. }
  2741. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2742. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2743. this.w = ( w * ratioA + this.w * ratioB );
  2744. this.x = ( x * ratioA + this.x * ratioB );
  2745. this.y = ( y * ratioA + this.y * ratioB );
  2746. this.z = ( z * ratioA + this.z * ratioB );
  2747. return this;
  2748. },
  2749. clone: function () {
  2750. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2751. }
  2752. }
  2753. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2754. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2755. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2756. if ( cosHalfTheta < 0 ) {
  2757. qm.w = -qb.w;
  2758. qm.x = -qb.x;
  2759. qm.y = -qb.y;
  2760. qm.z = -qb.z;
  2761. cosHalfTheta = -cosHalfTheta;
  2762. } else {
  2763. qm.copy( qb );
  2764. }
  2765. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2766. qm.w = qa.w;
  2767. qm.x = qa.x;
  2768. qm.y = qa.y;
  2769. qm.z = qa.z;
  2770. return qm;
  2771. }
  2772. var halfTheta = Math.acos( cosHalfTheta );
  2773. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2774. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2775. qm.w = 0.5 * ( qa.w + qm.w );
  2776. qm.x = 0.5 * ( qa.x + qm.x );
  2777. qm.y = 0.5 * ( qa.y + qm.y );
  2778. qm.z = 0.5 * ( qa.z + qm.z );
  2779. return qm;
  2780. }
  2781. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2782. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2783. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2784. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2785. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2786. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2787. return qm;
  2788. }
  2789. /**
  2790. * @author mrdoob / http://mrdoob.com/
  2791. */
  2792. THREE.Vertex = function ( v ) {
  2793. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  2794. return v;
  2795. };
  2796. /**
  2797. * @author mrdoob / http://mrdoob.com/
  2798. * @author alteredq / http://alteredqualia.com/
  2799. */
  2800. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2801. this.a = a;
  2802. this.b = b;
  2803. this.c = c;
  2804. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2805. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2806. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2807. this.vertexColors = color instanceof Array ? color : [];
  2808. this.vertexTangents = [];
  2809. this.materialIndex = materialIndex;
  2810. this.centroid = new THREE.Vector3();
  2811. };
  2812. THREE.Face3.prototype = {
  2813. constructor: THREE.Face3,
  2814. clone: function () {
  2815. var face = new THREE.Face3( this.a, this.b, this.c );
  2816. face.normal.copy( this.normal );
  2817. face.color.copy( this.color );
  2818. face.centroid.copy( this.centroid );
  2819. face.materialIndex = this.materialIndex;
  2820. var i, il;
  2821. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2822. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2823. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2824. return face;
  2825. }
  2826. };
  2827. /**
  2828. * @author mrdoob / http://mrdoob.com/
  2829. * @author alteredq / http://alteredqualia.com/
  2830. */
  2831. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2832. this.a = a;
  2833. this.b = b;
  2834. this.c = c;
  2835. this.d = d;
  2836. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2837. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2838. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2839. this.vertexColors = color instanceof Array ? color : [];
  2840. this.vertexTangents = [];
  2841. this.materialIndex = materialIndex;
  2842. this.centroid = new THREE.Vector3();
  2843. };
  2844. THREE.Face4.prototype = {
  2845. constructor: THREE.Face4,
  2846. clone: function () {
  2847. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  2848. face.normal.copy( this.normal );
  2849. face.color.copy( this.color );
  2850. face.centroid.copy( this.centroid );
  2851. face.materialIndex = this.materialIndex;
  2852. var i, il;
  2853. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2854. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2855. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2856. return face;
  2857. }
  2858. };
  2859. /**
  2860. * @author mrdoob / http://mrdoob.com/
  2861. */
  2862. THREE.UV = function ( u, v ) {
  2863. this.u = u || 0;
  2864. this.v = v || 0;
  2865. };
  2866. THREE.UV.prototype = {
  2867. constructor: THREE.UV,
  2868. set: function ( u, v ) {
  2869. this.u = u;
  2870. this.v = v;
  2871. return this;
  2872. },
  2873. copy: function ( uv ) {
  2874. this.u = uv.u;
  2875. this.v = uv.v;
  2876. return this;
  2877. },
  2878. lerpSelf: function ( uv, alpha ) {
  2879. this.u += ( uv.u - this.u ) * alpha;
  2880. this.v += ( uv.v - this.v ) * alpha;
  2881. return this;
  2882. },
  2883. clone: function () {
  2884. return new THREE.UV( this.u, this.v );
  2885. }
  2886. };
  2887. /**
  2888. * @author mrdoob / http://mrdoob.com/
  2889. * @author kile / http://kile.stravaganza.org/
  2890. * @author alteredq / http://alteredqualia.com/
  2891. * @author mikael emtinger / http://gomo.se/
  2892. * @author zz85 / http://www.lab4games.net/zz85/blog
  2893. */
  2894. THREE.Geometry = function () {
  2895. this.id = THREE.GeometryCount ++;
  2896. this.name = '';
  2897. this.vertices = [];
  2898. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  2899. this.materials = [];
  2900. this.faces = [];
  2901. this.faceUvs = [[]];
  2902. this.faceVertexUvs = [[]];
  2903. this.morphTargets = [];
  2904. this.morphColors = [];
  2905. this.morphNormals = [];
  2906. this.skinWeights = [];
  2907. this.skinIndices = [];
  2908. this.boundingBox = null;
  2909. this.boundingSphere = null;
  2910. this.hasTangents = false;
  2911. this.dynamic = true; // the intermediate typearrays will be deleted when set to false
  2912. };
  2913. THREE.Geometry.prototype = {
  2914. constructor : THREE.Geometry,
  2915. applyMatrix: function ( matrix ) {
  2916. var matrixRotation = new THREE.Matrix4();
  2917. matrixRotation.extractRotation( matrix );
  2918. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  2919. var vertex = this.vertices[ i ];
  2920. matrix.multiplyVector3( vertex );
  2921. }
  2922. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  2923. var face = this.faces[ i ];
  2924. matrixRotation.multiplyVector3( face.normal );
  2925. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  2926. matrixRotation.multiplyVector3( face.vertexNormals[ j ] );
  2927. }
  2928. matrix.multiplyVector3( face.centroid );
  2929. }
  2930. },
  2931. computeCentroids: function () {
  2932. var f, fl, face;
  2933. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2934. face = this.faces[ f ];
  2935. face.centroid.set( 0, 0, 0 );
  2936. if ( face instanceof THREE.Face3 ) {
  2937. face.centroid.addSelf( this.vertices[ face.a ] );
  2938. face.centroid.addSelf( this.vertices[ face.b ] );
  2939. face.centroid.addSelf( this.vertices[ face.c ] );
  2940. face.centroid.divideScalar( 3 );
  2941. } else if ( face instanceof THREE.Face4 ) {
  2942. face.centroid.addSelf( this.vertices[ face.a ] );
  2943. face.centroid.addSelf( this.vertices[ face.b ] );
  2944. face.centroid.addSelf( this.vertices[ face.c ] );
  2945. face.centroid.addSelf( this.vertices[ face.d ] );
  2946. face.centroid.divideScalar( 4 );
  2947. }
  2948. }
  2949. },
  2950. computeFaceNormals: function () {
  2951. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  2952. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  2953. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2954. face = this.faces[ f ];
  2955. vA = this.vertices[ face.a ];
  2956. vB = this.vertices[ face.b ];
  2957. vC = this.vertices[ face.c ];
  2958. cb.sub( vC, vB );
  2959. ab.sub( vA, vB );
  2960. cb.crossSelf( ab );
  2961. if ( !cb.isZero() ) {
  2962. cb.normalize();
  2963. }
  2964. face.normal.copy( cb );
  2965. }
  2966. },
  2967. computeVertexNormals: function () {
  2968. var v, vl, f, fl, face, vertices;
  2969. // create internal buffers for reuse when calling this method repeatedly
  2970. // (otherwise memory allocation / deallocation every frame is big resource hog)
  2971. if ( this.__tmpVertices === undefined ) {
  2972. this.__tmpVertices = new Array( this.vertices.length );
  2973. vertices = this.__tmpVertices;
  2974. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2975. vertices[ v ] = new THREE.Vector3();
  2976. }
  2977. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2978. face = this.faces[ f ];
  2979. if ( face instanceof THREE.Face3 ) {
  2980. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2981. } else if ( face instanceof THREE.Face4 ) {
  2982. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2983. }
  2984. }
  2985. } else {
  2986. vertices = this.__tmpVertices;
  2987. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2988. vertices[ v ].set( 0, 0, 0 );
  2989. }
  2990. }
  2991. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2992. face = this.faces[ f ];
  2993. if ( face instanceof THREE.Face3 ) {
  2994. vertices[ face.a ].addSelf( face.normal );
  2995. vertices[ face.b ].addSelf( face.normal );
  2996. vertices[ face.c ].addSelf( face.normal );
  2997. } else if ( face instanceof THREE.Face4 ) {
  2998. vertices[ face.a ].addSelf( face.normal );
  2999. vertices[ face.b ].addSelf( face.normal );
  3000. vertices[ face.c ].addSelf( face.normal );
  3001. vertices[ face.d ].addSelf( face.normal );
  3002. }
  3003. }
  3004. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3005. vertices[ v ].normalize();
  3006. }
  3007. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3008. face = this.faces[ f ];
  3009. if ( face instanceof THREE.Face3 ) {
  3010. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3011. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3012. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3013. } else if ( face instanceof THREE.Face4 ) {
  3014. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3015. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3016. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3017. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3018. }
  3019. }
  3020. },
  3021. computeMorphNormals: function () {
  3022. var i, il, f, fl, face;
  3023. // save original normals
  3024. // - create temp variables on first access
  3025. // otherwise just copy (for faster repeated calls)
  3026. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3027. face = this.faces[ f ];
  3028. if ( ! face.__originalFaceNormal ) {
  3029. face.__originalFaceNormal = face.normal.clone();
  3030. } else {
  3031. face.__originalFaceNormal.copy( face.normal );
  3032. }
  3033. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3034. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3035. if ( ! face.__originalVertexNormals[ i ] ) {
  3036. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3037. } else {
  3038. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3039. }
  3040. }
  3041. }
  3042. // use temp geometry to compute face and vertex normals for each morph
  3043. var tmpGeo = new THREE.Geometry();
  3044. tmpGeo.faces = this.faces;
  3045. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3046. // create on first access
  3047. if ( ! this.morphNormals[ i ] ) {
  3048. this.morphNormals[ i ] = {};
  3049. this.morphNormals[ i ].faceNormals = [];
  3050. this.morphNormals[ i ].vertexNormals = [];
  3051. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3052. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3053. var faceNormal, vertexNormals;
  3054. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3055. face = this.faces[ f ];
  3056. faceNormal = new THREE.Vector3();
  3057. if ( face instanceof THREE.Face3 ) {
  3058. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3059. } else {
  3060. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3061. }
  3062. dstNormalsFace.push( faceNormal );
  3063. dstNormalsVertex.push( vertexNormals );
  3064. }
  3065. }
  3066. var morphNormals = this.morphNormals[ i ];
  3067. // set vertices to morph target
  3068. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3069. // compute morph normals
  3070. tmpGeo.computeFaceNormals();
  3071. tmpGeo.computeVertexNormals();
  3072. // store morph normals
  3073. var faceNormal, vertexNormals;
  3074. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3075. face = this.faces[ f ];
  3076. faceNormal = morphNormals.faceNormals[ f ];
  3077. vertexNormals = morphNormals.vertexNormals[ f ];
  3078. faceNormal.copy( face.normal );
  3079. if ( face instanceof THREE.Face3 ) {
  3080. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3081. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3082. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3083. } else {
  3084. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3085. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3086. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3087. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3088. }
  3089. }
  3090. }
  3091. // restore original normals
  3092. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3093. face = this.faces[ f ];
  3094. face.normal = face.__originalFaceNormal;
  3095. face.vertexNormals = face.__originalVertexNormals;
  3096. }
  3097. },
  3098. computeTangents: function () {
  3099. // based on http://www.terathon.com/code/tangent.html
  3100. // tangents go to vertices
  3101. var f, fl, v, vl, i, il, vertexIndex,
  3102. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3103. x1, x2, y1, y2, z1, z2,
  3104. s1, s2, t1, t2, r, t, test,
  3105. tan1 = [], tan2 = [],
  3106. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3107. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3108. n = new THREE.Vector3(), w;
  3109. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3110. tan1[ v ] = new THREE.Vector3();
  3111. tan2[ v ] = new THREE.Vector3();
  3112. }
  3113. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  3114. vA = context.vertices[ a ];
  3115. vB = context.vertices[ b ];
  3116. vC = context.vertices[ c ];
  3117. uvA = uv[ ua ];
  3118. uvB = uv[ ub ];
  3119. uvC = uv[ uc ];
  3120. x1 = vB.x - vA.x;
  3121. x2 = vC.x - vA.x;
  3122. y1 = vB.y - vA.y;
  3123. y2 = vC.y - vA.y;
  3124. z1 = vB.z - vA.z;
  3125. z2 = vC.z - vA.z;
  3126. s1 = uvB.u - uvA.u;
  3127. s2 = uvC.u - uvA.u;
  3128. t1 = uvB.v - uvA.v;
  3129. t2 = uvC.v - uvA.v;
  3130. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3131. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  3132. ( t2 * y1 - t1 * y2 ) * r,
  3133. ( t2 * z1 - t1 * z2 ) * r );
  3134. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  3135. ( s1 * y2 - s2 * y1 ) * r,
  3136. ( s1 * z2 - s2 * z1 ) * r );
  3137. tan1[ a ].addSelf( sdir );
  3138. tan1[ b ].addSelf( sdir );
  3139. tan1[ c ].addSelf( sdir );
  3140. tan2[ a ].addSelf( tdir );
  3141. tan2[ b ].addSelf( tdir );
  3142. tan2[ c ].addSelf( tdir );
  3143. }
  3144. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3145. face = this.faces[ f ];
  3146. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  3147. if ( face instanceof THREE.Face3 ) {
  3148. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  3149. } else if ( face instanceof THREE.Face4 ) {
  3150. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  3151. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  3152. }
  3153. }
  3154. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  3155. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3156. face = this.faces[ f ];
  3157. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  3158. n.copy( face.vertexNormals[ i ] );
  3159. vertexIndex = face[ faceIndex[ i ] ];
  3160. t = tan1[ vertexIndex ];
  3161. // Gram-Schmidt orthogonalize
  3162. tmp.copy( t );
  3163. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3164. // Calculate handedness
  3165. tmp2.cross( face.vertexNormals[ i ], t );
  3166. test = tmp2.dot( tan2[ vertexIndex ] );
  3167. w = (test < 0.0) ? -1.0 : 1.0;
  3168. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  3169. }
  3170. }
  3171. this.hasTangents = true;
  3172. },
  3173. computeBoundingBox: function () {
  3174. if ( ! this.boundingBox ) {
  3175. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  3176. }
  3177. if ( this.vertices.length > 0 ) {
  3178. var position, firstPosition = this.vertices[ 0 ];
  3179. this.boundingBox.min.copy( firstPosition );
  3180. this.boundingBox.max.copy( firstPosition );
  3181. var min = this.boundingBox.min,
  3182. max = this.boundingBox.max;
  3183. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  3184. position = this.vertices[ v ];
  3185. if ( position.x < min.x ) {
  3186. min.x = position.x;
  3187. } else if ( position.x > max.x ) {
  3188. max.x = position.x;
  3189. }
  3190. if ( position.y < min.y ) {
  3191. min.y = position.y;
  3192. } else if ( position.y > max.y ) {
  3193. max.y = position.y;
  3194. }
  3195. if ( position.z < min.z ) {
  3196. min.z = position.z;
  3197. } else if ( position.z > max.z ) {
  3198. max.z = position.z;
  3199. }
  3200. }
  3201. } else {
  3202. this.boundingBox.min.set( 0, 0, 0 );
  3203. this.boundingBox.max.set( 0, 0, 0 );
  3204. }
  3205. },
  3206. computeBoundingSphere: function () {
  3207. var maxRadiusSq = 0;
  3208. if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
  3209. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  3210. var radiusSq = this.vertices[ i ].lengthSq();
  3211. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3212. }
  3213. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3214. },
  3215. /*
  3216. * Checks for duplicate vertices with hashmap.
  3217. * Duplicated vertices are removed
  3218. * and faces' vertices are updated.
  3219. */
  3220. mergeVertices: function () {
  3221. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  3222. var unique = [], changes = [];
  3223. var v, key;
  3224. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  3225. var precision = Math.pow( 10, precisionPoints );
  3226. var i,il, face;
  3227. var abcd = 'abcd', o, k, j, jl, u;
  3228. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  3229. v = this.vertices[ i ];
  3230. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  3231. if ( verticesMap[ key ] === undefined ) {
  3232. verticesMap[ key ] = i;
  3233. unique.push( this.vertices[ i ] );
  3234. changes[ i ] = unique.length - 1;
  3235. } else {
  3236. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3237. changes[ i ] = changes[ verticesMap[ key ] ];
  3238. }
  3239. };
  3240. // Start to patch face indices
  3241. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  3242. face = this.faces[ i ];
  3243. if ( face instanceof THREE.Face3 ) {
  3244. face.a = changes[ face.a ];
  3245. face.b = changes[ face.b ];
  3246. face.c = changes[ face.c ];
  3247. } else if ( face instanceof THREE.Face4 ) {
  3248. face.a = changes[ face.a ];
  3249. face.b = changes[ face.b ];
  3250. face.c = changes[ face.c ];
  3251. face.d = changes[ face.d ];
  3252. // check dups in (a, b, c, d) and convert to -> face3
  3253. o = [ face.a, face.b, face.c, face.d ];
  3254. for ( k = 3; k > 0; k -- ) {
  3255. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  3256. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  3257. o.splice( k, 1 );
  3258. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  3259. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  3260. u = this.faceVertexUvs[ j ][ i ];
  3261. if ( u ) u.splice( k, 1 );
  3262. }
  3263. this.faces[ i ].vertexColors = face.vertexColors;
  3264. break;
  3265. }
  3266. }
  3267. }
  3268. }
  3269. // Use unique set of vertices
  3270. var diff = this.vertices.length - unique.length;
  3271. this.vertices = unique;
  3272. return diff;
  3273. },
  3274. clone: function () {
  3275. // TODO
  3276. }
  3277. };
  3278. THREE.GeometryCount = 0;
  3279. /**
  3280. * @author alteredq / http://alteredqualia.com/
  3281. */
  3282. THREE.BufferGeometry = function () {
  3283. this.id = THREE.GeometryCount ++;
  3284. // attributes
  3285. this.attributes = {};
  3286. // attributes typed arrays are kept only if dynamic flag is set
  3287. this.dynamic = false;
  3288. // boundings
  3289. this.boundingBox = null;
  3290. this.boundingSphere = null;
  3291. this.hasTangents = false;
  3292. // for compatibility
  3293. this.morphTargets = [];
  3294. };
  3295. THREE.BufferGeometry.prototype = {
  3296. constructor : THREE.BufferGeometry,
  3297. applyMatrix: function ( matrix ) {
  3298. var positionArray;
  3299. var normalArray;
  3300. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  3301. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  3302. if ( positionArray !== undefined ) {
  3303. matrix.multiplyVector3Array( positionArray );
  3304. this.verticesNeedUpdate = true;
  3305. }
  3306. if ( normalArray !== undefined ) {
  3307. var matrixRotation = new THREE.Matrix4();
  3308. matrixRotation.extractRotation( matrix );
  3309. matrixRotation.multiplyVector3Array( normalArray );
  3310. this.normalsNeedUpdate = true;
  3311. }
  3312. },
  3313. computeBoundingBox: function () {
  3314. if ( ! this.boundingBox ) {
  3315. this.boundingBox = {
  3316. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  3317. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  3318. };
  3319. }
  3320. var positions = this.attributes[ "position" ].array;
  3321. if ( positions ) {
  3322. var bb = this.boundingBox;
  3323. var x, y, z;
  3324. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3325. x = positions[ i ];
  3326. y = positions[ i + 1 ];
  3327. z = positions[ i + 2 ];
  3328. // bounding box
  3329. if ( x < bb.min.x ) {
  3330. bb.min.x = x;
  3331. } else if ( x > bb.max.x ) {
  3332. bb.max.x = x;
  3333. }
  3334. if ( y < bb.min.y ) {
  3335. bb.min.y = y;
  3336. } else if ( y > bb.max.y ) {
  3337. bb.max.y = y;
  3338. }
  3339. if ( z < bb.min.z ) {
  3340. bb.min.z = z;
  3341. } else if ( z > bb.max.z ) {
  3342. bb.max.z = z;
  3343. }
  3344. }
  3345. }
  3346. if ( positions === undefined || positions.length === 0 ) {
  3347. this.boundingBox.min.set( 0, 0, 0 );
  3348. this.boundingBox.max.set( 0, 0, 0 );
  3349. }
  3350. },
  3351. computeBoundingSphere: function () {
  3352. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  3353. var positions = this.attributes[ "position" ].array;
  3354. if ( positions ) {
  3355. var radiusSq, maxRadiusSq = 0;
  3356. var x, y, z;
  3357. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3358. x = positions[ i ];
  3359. y = positions[ i + 1 ];
  3360. z = positions[ i + 2 ];
  3361. radiusSq = x * x + y * y + z * z;
  3362. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3363. }
  3364. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3365. }
  3366. },
  3367. computeVertexNormals: function () {
  3368. if ( this.attributes[ "position" ] && this.attributes[ "index" ] ) {
  3369. var i, il;
  3370. var j, jl;
  3371. var nVertexElements = this.attributes[ "position" ].array.length;
  3372. if ( this.attributes[ "normal" ] === undefined ) {
  3373. this.attributes[ "normal" ] = {
  3374. itemSize: 3,
  3375. array: new Float32Array( nVertexElements ),
  3376. numItems: nVertexElements
  3377. };
  3378. } else {
  3379. // reset existing normals to zero
  3380. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  3381. this.attributes[ "normal" ].array[ i ] = 0;
  3382. }
  3383. }
  3384. var offsets = this.offsets;
  3385. var indices = this.attributes[ "index" ].array;
  3386. var positions = this.attributes[ "position" ].array;
  3387. var normals = this.attributes[ "normal" ].array;
  3388. var vA, vB, vC, x, y, z,
  3389. pA = new THREE.Vector3(),
  3390. pB = new THREE.Vector3(),
  3391. pC = new THREE.Vector3(),
  3392. cb = new THREE.Vector3(),
  3393. ab = new THREE.Vector3();
  3394. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3395. var start = offsets[ j ].start;
  3396. var count = offsets[ j ].count;
  3397. var index = offsets[ j ].index;
  3398. for ( i = start, il = start + count; i < il; i += 3 ) {
  3399. vA = index + indices[ i ];
  3400. vB = index + indices[ i + 1 ];
  3401. vC = index + indices[ i + 2 ];
  3402. x = positions[ vA * 3 ];
  3403. y = positions[ vA * 3 + 1 ];
  3404. z = positions[ vA * 3 + 2 ];
  3405. pA.set( x, y, z );
  3406. x = positions[ vB * 3 ];
  3407. y = positions[ vB * 3 + 1 ];
  3408. z = positions[ vB * 3 + 2 ];
  3409. pB.set( x, y, z );
  3410. x = positions[ vC * 3 ];
  3411. y = positions[ vC * 3 + 1 ];
  3412. z = positions[ vC * 3 + 2 ];
  3413. pC.set( x, y, z );
  3414. cb.sub( pC, pB );
  3415. ab.sub( pA, pB );
  3416. cb.crossSelf( ab );
  3417. normals[ vA * 3 ] += cb.x;
  3418. normals[ vA * 3 + 1 ] += cb.y;
  3419. normals[ vA * 3 + 2 ] += cb.z;
  3420. normals[ vB * 3 ] += cb.x;
  3421. normals[ vB * 3 + 1 ] += cb.y;
  3422. normals[ vB * 3 + 2 ] += cb.z;
  3423. normals[ vC * 3 ] += cb.x;
  3424. normals[ vC * 3 + 1 ] += cb.y;
  3425. normals[ vC * 3 + 2 ] += cb.z;
  3426. }
  3427. }
  3428. // normalize normals
  3429. for ( i = 0, il = normals.length; i < il; i += 3 ) {
  3430. x = normals[ i ];
  3431. y = normals[ i + 1 ];
  3432. z = normals[ i + 2 ];
  3433. var n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  3434. normals[ i ] *= n;
  3435. normals[ i + 1 ] *= n;
  3436. normals[ i + 2 ] *= n;
  3437. }
  3438. this.normalsNeedUpdate = true;
  3439. }
  3440. },
  3441. computeTangents: function () {
  3442. // based on http://www.terathon.com/code/tangent.html
  3443. // (per vertex tangents)
  3444. if ( this.attributes[ "index" ] === undefined ||
  3445. this.attributes[ "position" ] === undefined ||
  3446. this.attributes[ "normal" ] === undefined ||
  3447. this.attributes[ "uv" ] === undefined ) {
  3448. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  3449. return;
  3450. }
  3451. var indices = this.attributes[ "index" ].array;
  3452. var positions = this.attributes[ "position" ].array;
  3453. var normals = this.attributes[ "normal" ].array;
  3454. var uvs = this.attributes[ "uv" ].array;
  3455. var nVertices = positions.length / 3;
  3456. if ( this.attributes[ "tangent" ] === undefined ) {
  3457. var nTangentElements = 4 * nVertices;
  3458. this.attributes[ "tangent" ] = {
  3459. itemSize: 4,
  3460. array: new Float32Array( nTangentElements ),
  3461. numItems: nTangentElements
  3462. };
  3463. }
  3464. var tangents = this.attributes[ "tangent" ].array;
  3465. var tan1 = [], tan2 = [];
  3466. for ( var k = 0; k < nVertices; k ++ ) {
  3467. tan1[ k ] = new THREE.Vector3();
  3468. tan2[ k ] = new THREE.Vector3();
  3469. }
  3470. var xA, yA, zA,
  3471. xB, yB, zB,
  3472. xC, yC, zC,
  3473. uA, vA,
  3474. uB, vB,
  3475. uC, vC,
  3476. x1, x2, y1, y2, z1, z2,
  3477. s1, s2, t1, t2, r;
  3478. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  3479. function handleTriangle( a, b, c ) {
  3480. xA = positions[ a * 3 ];
  3481. yA = positions[ a * 3 + 1 ];
  3482. zA = positions[ a * 3 + 2 ];
  3483. xB = positions[ b * 3 ];
  3484. yB = positions[ b * 3 + 1 ];
  3485. zB = positions[ b * 3 + 2 ];
  3486. xC = positions[ c * 3 ];
  3487. yC = positions[ c * 3 + 1 ];
  3488. zC = positions[ c * 3 + 2 ];
  3489. uA = uvs[ a * 2 ];
  3490. vA = uvs[ a * 2 + 1 ];
  3491. uB = uvs[ b * 2 ];
  3492. vB = uvs[ b * 2 + 1 ];
  3493. uC = uvs[ c * 2 ];
  3494. vC = uvs[ c * 2 + 1 ];
  3495. x1 = xB - xA;
  3496. x2 = xC - xA;
  3497. y1 = yB - yA;
  3498. y2 = yC - yA;
  3499. z1 = zB - zA;
  3500. z2 = zC - zA;
  3501. s1 = uB - uA;
  3502. s2 = uC - uA;
  3503. t1 = vB - vA;
  3504. t2 = vC - vA;
  3505. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3506. sdir.set(
  3507. ( t2 * x1 - t1 * x2 ) * r,
  3508. ( t2 * y1 - t1 * y2 ) * r,
  3509. ( t2 * z1 - t1 * z2 ) * r
  3510. );
  3511. tdir.set(
  3512. ( s1 * x2 - s2 * x1 ) * r,
  3513. ( s1 * y2 - s2 * y1 ) * r,
  3514. ( s1 * z2 - s2 * z1 ) * r
  3515. );
  3516. tan1[ a ].addSelf( sdir );
  3517. tan1[ b ].addSelf( sdir );
  3518. tan1[ c ].addSelf( sdir );
  3519. tan2[ a ].addSelf( tdir );
  3520. tan2[ b ].addSelf( tdir );
  3521. tan2[ c ].addSelf( tdir );
  3522. }
  3523. var i, il;
  3524. var j, jl;
  3525. var iA, iB, iC;
  3526. var offsets = this.offsets;
  3527. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3528. var start = offsets[ j ].start;
  3529. var count = offsets[ j ].count;
  3530. var index = offsets[ j ].index;
  3531. for ( i = start, il = start + count; i < il; i += 3 ) {
  3532. iA = index + indices[ i ];
  3533. iB = index + indices[ i + 1 ];
  3534. iC = index + indices[ i + 2 ];
  3535. handleTriangle( iA, iB, iC );
  3536. }
  3537. }
  3538. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  3539. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  3540. var w, t, test;
  3541. var nx, ny, nz;
  3542. function handleVertex( v ) {
  3543. n.x = normals[ v * 3 ];
  3544. n.y = normals[ v * 3 + 1 ];
  3545. n.z = normals[ v * 3 + 2 ];
  3546. n2.copy( n );
  3547. t = tan1[ v ];
  3548. // Gram-Schmidt orthogonalize
  3549. tmp.copy( t );
  3550. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3551. // Calculate handedness
  3552. tmp2.cross( n2, t );
  3553. test = tmp2.dot( tan2[ v ] );
  3554. w = ( test < 0.0 ) ? -1.0 : 1.0;
  3555. tangents[ v * 4 ] = tmp.x;
  3556. tangents[ v * 4 + 1 ] = tmp.y;
  3557. tangents[ v * 4 + 2 ] = tmp.z;
  3558. tangents[ v * 4 + 3 ] = w;
  3559. }
  3560. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3561. var start = offsets[ j ].start;
  3562. var count = offsets[ j ].count;
  3563. var index = offsets[ j ].index;
  3564. for ( i = start, il = start + count; i < il; i += 3 ) {
  3565. iA = index + indices[ i ];
  3566. iB = index + indices[ i + 1 ];
  3567. iC = index + indices[ i + 2 ];
  3568. handleVertex( iA );
  3569. handleVertex( iB );
  3570. handleVertex( iC );
  3571. }
  3572. }
  3573. this.hasTangents = true;
  3574. this.tangentsNeedUpdate = true;
  3575. }
  3576. };
  3577. /**
  3578. * Spline from Tween.js, slightly optimized (and trashed)
  3579. * http://sole.github.com/tween.js/examples/05_spline.html
  3580. *
  3581. * @author mrdoob / http://mrdoob.com/
  3582. * @author alteredq / http://alteredqualia.com/
  3583. */
  3584. THREE.Spline = function ( points ) {
  3585. this.points = points;
  3586. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3587. point, intPoint, weight, w2, w3,
  3588. pa, pb, pc, pd;
  3589. this.initFromArray = function( a ) {
  3590. this.points = [];
  3591. for ( var i = 0; i < a.length; i++ ) {
  3592. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3593. }
  3594. };
  3595. this.getPoint = function ( k ) {
  3596. point = ( this.points.length - 1 ) * k;
  3597. intPoint = Math.floor( point );
  3598. weight = point - intPoint;
  3599. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3600. c[ 1 ] = intPoint;
  3601. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3602. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3603. pa = this.points[ c[ 0 ] ];
  3604. pb = this.points[ c[ 1 ] ];
  3605. pc = this.points[ c[ 2 ] ];
  3606. pd = this.points[ c[ 3 ] ];
  3607. w2 = weight * weight;
  3608. w3 = weight * w2;
  3609. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3610. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3611. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3612. return v3;
  3613. };
  3614. this.getControlPointsArray = function () {
  3615. var i, p, l = this.points.length,
  3616. coords = [];
  3617. for ( i = 0; i < l; i ++ ) {
  3618. p = this.points[ i ];
  3619. coords[ i ] = [ p.x, p.y, p.z ];
  3620. }
  3621. return coords;
  3622. };
  3623. // approximate length by summing linear segments
  3624. this.getLength = function ( nSubDivisions ) {
  3625. var i, index, nSamples, position,
  3626. point = 0, intPoint = 0, oldIntPoint = 0,
  3627. oldPosition = new THREE.Vector3(),
  3628. tmpVec = new THREE.Vector3(),
  3629. chunkLengths = [],
  3630. totalLength = 0;
  3631. // first point has 0 length
  3632. chunkLengths[ 0 ] = 0;
  3633. if ( !nSubDivisions ) nSubDivisions = 100;
  3634. nSamples = this.points.length * nSubDivisions;
  3635. oldPosition.copy( this.points[ 0 ] );
  3636. for ( i = 1; i < nSamples; i ++ ) {
  3637. index = i / nSamples;
  3638. position = this.getPoint( index );
  3639. tmpVec.copy( position );
  3640. totalLength += tmpVec.distanceTo( oldPosition );
  3641. oldPosition.copy( position );
  3642. point = ( this.points.length - 1 ) * index;
  3643. intPoint = Math.floor( point );
  3644. if ( intPoint != oldIntPoint ) {
  3645. chunkLengths[ intPoint ] = totalLength;
  3646. oldIntPoint = intPoint;
  3647. }
  3648. }
  3649. // last point ends with total length
  3650. chunkLengths[ chunkLengths.length ] = totalLength;
  3651. return { chunks: chunkLengths, total: totalLength };
  3652. };
  3653. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3654. var i, j,
  3655. index, indexCurrent, indexNext,
  3656. linearDistance, realDistance,
  3657. sampling, position,
  3658. newpoints = [],
  3659. tmpVec = new THREE.Vector3(),
  3660. sl = this.getLength();
  3661. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3662. for ( i = 1; i < this.points.length; i++ ) {
  3663. //tmpVec.copy( this.points[ i - 1 ] );
  3664. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3665. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3666. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3667. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3668. indexNext = i / ( this.points.length - 1 );
  3669. for ( j = 1; j < sampling - 1; j++ ) {
  3670. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3671. position = this.getPoint( index );
  3672. newpoints.push( tmpVec.copy( position ).clone() );
  3673. }
  3674. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3675. }
  3676. this.points = newpoints;
  3677. };
  3678. // Catmull-Rom
  3679. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3680. var v0 = ( p2 - p0 ) * 0.5,
  3681. v1 = ( p3 - p1 ) * 0.5;
  3682. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3683. };
  3684. };
  3685. /**
  3686. * @author mrdoob / http://mrdoob.com/
  3687. * @author mikael emtinger / http://gomo.se/
  3688. */
  3689. THREE.Camera = function () {
  3690. THREE.Object3D.call( this );
  3691. this.matrixWorldInverse = new THREE.Matrix4();
  3692. this.projectionMatrix = new THREE.Matrix4();
  3693. this.projectionMatrixInverse = new THREE.Matrix4();
  3694. };
  3695. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  3696. THREE.Camera.prototype.lookAt = function ( vector ) {
  3697. // TODO: Add hierarchy support.
  3698. this.matrix.lookAt( this.position, vector, this.up );
  3699. if ( this.rotationAutoUpdate === true ) {
  3700. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3701. }
  3702. };
  3703. /**
  3704. * @author alteredq / http://alteredqualia.com/
  3705. */
  3706. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  3707. THREE.Camera.call( this );
  3708. this.left = left;
  3709. this.right = right;
  3710. this.top = top;
  3711. this.bottom = bottom;
  3712. this.near = ( near !== undefined ) ? near : 0.1;
  3713. this.far = ( far !== undefined ) ? far : 2000;
  3714. this.updateProjectionMatrix();
  3715. };
  3716. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  3717. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  3718. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  3719. };
  3720. /**
  3721. * @author mrdoob / http://mrdoob.com/
  3722. * @author greggman / http://games.greggman.com/
  3723. * @author zz85 / http://www.lab4games.net/zz85/blog
  3724. */
  3725. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  3726. THREE.Camera.call( this );
  3727. this.fov = fov !== undefined ? fov : 50;
  3728. this.aspect = aspect !== undefined ? aspect : 1;
  3729. this.near = near !== undefined ? near : 0.1;
  3730. this.far = far !== undefined ? far : 2000;
  3731. this.updateProjectionMatrix();
  3732. };
  3733. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  3734. /**
  3735. * Uses Focal Length (in mm) to estimate and set FOV
  3736. * 35mm (fullframe) camera is used if frame size is not specified;
  3737. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  3738. */
  3739. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  3740. if ( frameHeight === undefined ) frameHeight = 24;
  3741. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  3742. this.updateProjectionMatrix();
  3743. }
  3744. /**
  3745. * Sets an offset in a larger frustum. This is useful for multi-window or
  3746. * multi-monitor/multi-machine setups.
  3747. *
  3748. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  3749. * the monitors are in grid like this
  3750. *
  3751. * +---+---+---+
  3752. * | A | B | C |
  3753. * +---+---+---+
  3754. * | D | E | F |
  3755. * +---+---+---+
  3756. *
  3757. * then for each monitor you would call it like this
  3758. *
  3759. * var w = 1920;
  3760. * var h = 1080;
  3761. * var fullWidth = w * 3;
  3762. * var fullHeight = h * 2;
  3763. *
  3764. * --A--
  3765. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  3766. * --B--
  3767. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  3768. * --C--
  3769. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  3770. * --D--
  3771. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  3772. * --E--
  3773. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  3774. * --F--
  3775. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  3776. *
  3777. * Note there is no reason monitors have to be the same size or in a grid.
  3778. */
  3779. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  3780. this.fullWidth = fullWidth;
  3781. this.fullHeight = fullHeight;
  3782. this.x = x;
  3783. this.y = y;
  3784. this.width = width;
  3785. this.height = height;
  3786. this.updateProjectionMatrix();
  3787. };
  3788. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  3789. if ( this.fullWidth ) {
  3790. var aspect = this.fullWidth / this.fullHeight;
  3791. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  3792. var bottom = -top;
  3793. var left = aspect * bottom;
  3794. var right = aspect * top;
  3795. var width = Math.abs( right - left );
  3796. var height = Math.abs( top - bottom );
  3797. this.projectionMatrix.makeFrustum(
  3798. left + this.x * width / this.fullWidth,
  3799. left + ( this.x + this.width ) * width / this.fullWidth,
  3800. top - ( this.y + this.height ) * height / this.fullHeight,
  3801. top - this.y * height / this.fullHeight,
  3802. this.near,
  3803. this.far
  3804. );
  3805. } else {
  3806. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  3807. }
  3808. };
  3809. /**
  3810. * @author mrdoob / http://mrdoob.com/
  3811. * @author alteredq / http://alteredqualia.com/
  3812. */
  3813. THREE.Light = function ( hex ) {
  3814. THREE.Object3D.call( this );
  3815. this.color = new THREE.Color( hex );
  3816. };
  3817. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  3818. /**
  3819. * @author mrdoob / http://mrdoob.com/
  3820. */
  3821. THREE.AmbientLight = function ( hex ) {
  3822. THREE.Light.call( this, hex );
  3823. };
  3824. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  3825. /**
  3826. * @author mrdoob / http://mrdoob.com/
  3827. * @author alteredq / http://alteredqualia.com/
  3828. */
  3829. THREE.DirectionalLight = function ( hex, intensity, distance ) {
  3830. THREE.Light.call( this, hex );
  3831. this.position = new THREE.Vector3( 0, 1, 0 );
  3832. this.target = new THREE.Object3D();
  3833. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3834. this.distance = ( distance !== undefined ) ? distance : 0;
  3835. this.castShadow = false;
  3836. this.onlyShadow = false;
  3837. //
  3838. this.shadowCameraNear = 50;
  3839. this.shadowCameraFar = 5000;
  3840. this.shadowCameraLeft = -500;
  3841. this.shadowCameraRight = 500;
  3842. this.shadowCameraTop = 500;
  3843. this.shadowCameraBottom = -500;
  3844. this.shadowCameraVisible = false;
  3845. this.shadowBias = 0;
  3846. this.shadowDarkness = 0.5;
  3847. this.shadowMapWidth = 512;
  3848. this.shadowMapHeight = 512;
  3849. //
  3850. this.shadowCascade = false;
  3851. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  3852. this.shadowCascadeCount = 2;
  3853. this.shadowCascadeBias = [ 0, 0, 0 ];
  3854. this.shadowCascadeWidth = [ 512, 512, 512 ];
  3855. this.shadowCascadeHeight = [ 512, 512, 512 ];
  3856. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  3857. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  3858. this.shadowCascadeArray = [];
  3859. //
  3860. this.shadowMap = null;
  3861. this.shadowMapSize = null;
  3862. this.shadowCamera = null;
  3863. this.shadowMatrix = null;
  3864. };
  3865. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  3866. /**
  3867. * @author mrdoob / http://mrdoob.com/
  3868. */
  3869. THREE.PointLight = function ( hex, intensity, distance ) {
  3870. THREE.Light.call( this, hex );
  3871. this.position = new THREE.Vector3( 0, 0, 0 );
  3872. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3873. this.distance = ( distance !== undefined ) ? distance : 0;
  3874. };
  3875. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  3876. /**
  3877. * @author alteredq / http://alteredqualia.com/
  3878. */
  3879. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  3880. THREE.Light.call( this, hex );
  3881. this.position = new THREE.Vector3( 0, 1, 0 );
  3882. this.target = new THREE.Object3D();
  3883. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3884. this.distance = ( distance !== undefined ) ? distance : 0;
  3885. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  3886. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  3887. this.castShadow = false;
  3888. this.onlyShadow = false;
  3889. //
  3890. this.shadowCameraNear = 50;
  3891. this.shadowCameraFar = 5000;
  3892. this.shadowCameraFov = 50;
  3893. this.shadowCameraVisible = false;
  3894. this.shadowBias = 0;
  3895. this.shadowDarkness = 0.5;
  3896. this.shadowMapWidth = 512;
  3897. this.shadowMapHeight = 512;
  3898. //
  3899. this.shadowMap = null;
  3900. this.shadowMapSize = null;
  3901. this.shadowCamera = null;
  3902. this.shadowMatrix = null;
  3903. };
  3904. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  3905. /**
  3906. * @author alteredq / http://alteredqualia.com/
  3907. */
  3908. THREE.Loader = function ( showStatus ) {
  3909. this.showStatus = showStatus;
  3910. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  3911. this.onLoadStart = function () {};
  3912. this.onLoadProgress = function () {};
  3913. this.onLoadComplete = function () {};
  3914. };
  3915. THREE.Loader.prototype = {
  3916. constructor: THREE.Loader,
  3917. crossOrigin: 'anonymous',
  3918. addStatusElement: function () {
  3919. var e = document.createElement( "div" );
  3920. e.style.position = "absolute";
  3921. e.style.right = "0px";
  3922. e.style.top = "0px";
  3923. e.style.fontSize = "0.8em";
  3924. e.style.textAlign = "left";
  3925. e.style.background = "rgba(0,0,0,0.25)";
  3926. e.style.color = "#fff";
  3927. e.style.width = "120px";
  3928. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  3929. e.style.zIndex = 1000;
  3930. e.innerHTML = "Loading ...";
  3931. return e;
  3932. },
  3933. updateProgress: function ( progress ) {
  3934. var message = "Loaded ";
  3935. if ( progress.total ) {
  3936. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  3937. } else {
  3938. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  3939. }
  3940. this.statusDomElement.innerHTML = message;
  3941. },
  3942. extractUrlBase: function ( url ) {
  3943. var parts = url.split( '/' );
  3944. parts.pop();
  3945. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  3946. },
  3947. initMaterials: function ( scope, materials, texturePath ) {
  3948. scope.materials = [];
  3949. for ( var i = 0; i < materials.length; ++ i ) {
  3950. scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  3951. }
  3952. },
  3953. hasNormals: function ( scope ) {
  3954. var m, i, il = scope.materials.length;
  3955. for( i = 0; i < il; i ++ ) {
  3956. m = scope.materials[ i ];
  3957. if ( m instanceof THREE.ShaderMaterial ) return true;
  3958. }
  3959. return false;
  3960. },
  3961. createMaterial: function ( m, texturePath ) {
  3962. var _this = this;
  3963. function is_pow2( n ) {
  3964. var l = Math.log( n ) / Math.LN2;
  3965. return Math.floor( l ) == l;
  3966. }
  3967. function nearest_pow2( n ) {
  3968. var l = Math.log( n ) / Math.LN2;
  3969. return Math.pow( 2, Math.round( l ) );
  3970. }
  3971. function load_image( where, url ) {
  3972. var image = new Image();
  3973. image.onload = function () {
  3974. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  3975. var width = nearest_pow2( this.width );
  3976. var height = nearest_pow2( this.height );
  3977. where.image.width = width;
  3978. where.image.height = height;
  3979. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  3980. } else {
  3981. where.image = this;
  3982. }
  3983. where.needsUpdate = true;
  3984. };
  3985. image.crossOrigin = _this.crossOrigin;
  3986. image.src = url;
  3987. }
  3988. function create_texture( where, name, sourceFile, repeat, offset, wrap ) {
  3989. var texture = document.createElement( 'canvas' );
  3990. where[ name ] = new THREE.Texture( texture );
  3991. where[ name ].sourceFile = sourceFile;
  3992. if( repeat ) {
  3993. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  3994. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  3995. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  3996. }
  3997. if ( offset ) {
  3998. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  3999. }
  4000. if ( wrap ) {
  4001. var wrapMap = {
  4002. "repeat": THREE.RepeatWrapping,
  4003. "mirror": THREE.MirroredRepeatWrapping
  4004. }
  4005. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4006. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4007. }
  4008. load_image( where[ name ], texturePath + "/" + sourceFile );
  4009. }
  4010. function rgb2hex( rgb ) {
  4011. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4012. }
  4013. // defaults
  4014. var mtype = "MeshLambertMaterial";
  4015. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4016. // parameters from model file
  4017. if ( m.shading ) {
  4018. var shading = m.shading.toLowerCase();
  4019. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4020. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4021. }
  4022. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4023. mpars.blending = THREE[ m.blending ];
  4024. }
  4025. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4026. mpars.transparent = m.transparent;
  4027. }
  4028. if ( m.depthTest !== undefined ) {
  4029. mpars.depthTest = m.depthTest;
  4030. }
  4031. if ( m.depthWrite !== undefined ) {
  4032. mpars.depthWrite = m.depthWrite;
  4033. }
  4034. if ( m.visible !== undefined ) {
  4035. mpars.visible = m.visible;
  4036. }
  4037. if ( m.flipSided !== undefined ) {
  4038. mpars.side = THREE.BackSide;
  4039. }
  4040. if ( m.doubleSided !== undefined ) {
  4041. mpars.side = THREE.DoubleSide;
  4042. }
  4043. if ( m.wireframe !== undefined ) {
  4044. mpars.wireframe = m.wireframe;
  4045. }
  4046. if ( m.vertexColors !== undefined ) {
  4047. if ( m.vertexColors == "face" ) {
  4048. mpars.vertexColors = THREE.FaceColors;
  4049. } else if ( m.vertexColors ) {
  4050. mpars.vertexColors = THREE.VertexColors;
  4051. }
  4052. }
  4053. // colors
  4054. if ( m.colorDiffuse ) {
  4055. mpars.color = rgb2hex( m.colorDiffuse );
  4056. } else if ( m.DbgColor ) {
  4057. mpars.color = m.DbgColor;
  4058. }
  4059. if ( m.colorSpecular ) {
  4060. mpars.specular = rgb2hex( m.colorSpecular );
  4061. }
  4062. if ( m.colorAmbient ) {
  4063. mpars.ambient = rgb2hex( m.colorAmbient );
  4064. }
  4065. // modifiers
  4066. if ( m.transparency ) {
  4067. mpars.opacity = m.transparency;
  4068. }
  4069. if ( m.specularCoef ) {
  4070. mpars.shininess = m.specularCoef;
  4071. }
  4072. // textures
  4073. if ( m.mapDiffuse && texturePath ) {
  4074. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  4075. }
  4076. if ( m.mapLight && texturePath ) {
  4077. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  4078. }
  4079. if ( m.mapBump && texturePath ) {
  4080. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap );
  4081. }
  4082. if ( m.mapNormal && texturePath ) {
  4083. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  4084. }
  4085. if ( m.mapSpecular && texturePath ) {
  4086. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  4087. }
  4088. // special case for normal mapped material
  4089. if ( m.mapNormal ) {
  4090. var shader = THREE.ShaderUtils.lib[ "normal" ];
  4091. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  4092. uniforms[ "tNormal" ].value = mpars.normalMap;
  4093. if ( m.mapNormalFactor ) {
  4094. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  4095. }
  4096. if ( mpars.map ) {
  4097. uniforms[ "tDiffuse" ].value = mpars.map;
  4098. uniforms[ "enableDiffuse" ].value = true;
  4099. }
  4100. if ( mpars.specularMap ) {
  4101. uniforms[ "tSpecular" ].value = mpars.specularMap;
  4102. uniforms[ "enableSpecular" ].value = true;
  4103. }
  4104. if ( mpars.lightMap ) {
  4105. uniforms[ "tAO" ].value = mpars.lightMap;
  4106. uniforms[ "enableAO" ].value = true;
  4107. }
  4108. // for the moment don't handle displacement texture
  4109. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  4110. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  4111. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  4112. uniforms[ "uShininess" ].value = mpars.shininess;
  4113. if ( mpars.opacity !== undefined ) {
  4114. uniforms[ "uOpacity" ].value = mpars.opacity;
  4115. }
  4116. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  4117. var material = new THREE.ShaderMaterial( parameters );
  4118. } else {
  4119. var material = new THREE[ mtype ]( mpars );
  4120. }
  4121. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  4122. return material;
  4123. }
  4124. };
  4125. /**
  4126. * @author alteredq / http://alteredqualia.com/
  4127. */
  4128. THREE.BinaryLoader = function ( showStatus ) {
  4129. THREE.Loader.call( this, showStatus );
  4130. };
  4131. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  4132. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  4133. // - binary models consist of two files: JS and BIN
  4134. // - parameters
  4135. // - url (required)
  4136. // - callback (required)
  4137. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  4138. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  4139. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  4140. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4141. binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
  4142. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  4143. this.onLoadStart();
  4144. // #1 load JS part via web worker
  4145. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  4146. };
  4147. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  4148. var xhr = new XMLHttpRequest();
  4149. xhr.onreadystatechange = function () {
  4150. if ( xhr.readyState == 4 ) {
  4151. if ( xhr.status == 200 || xhr.status == 0 ) {
  4152. var json = JSON.parse( xhr.responseText );
  4153. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  4154. } else {
  4155. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4156. }
  4157. }
  4158. };
  4159. xhr.open( "GET", url, true );
  4160. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  4161. xhr.setRequestHeader( "Content-Type", "text/plain" );
  4162. xhr.send( null );
  4163. };
  4164. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  4165. var xhr = new XMLHttpRequest(),
  4166. url = binaryPath + "/" + json.buffers;
  4167. var length = 0;
  4168. xhr.onreadystatechange = function () {
  4169. if ( xhr.readyState == 4 ) {
  4170. if ( xhr.status == 200 || xhr.status == 0 ) {
  4171. var buffer = xhr.response;
  4172. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  4173. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  4174. } else {
  4175. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4176. }
  4177. } else if ( xhr.readyState == 3 ) {
  4178. if ( callbackProgress ) {
  4179. if ( length == 0 ) {
  4180. length = xhr.getResponseHeader( "Content-Length" );
  4181. }
  4182. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4183. }
  4184. } else if ( xhr.readyState == 2 ) {
  4185. length = xhr.getResponseHeader( "Content-Length" );
  4186. }
  4187. };
  4188. xhr.open( "GET", url, true );
  4189. xhr.responseType = "arraybuffer";
  4190. xhr.send( null );
  4191. };
  4192. // Binary AJAX parser
  4193. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
  4194. var Model = function ( texturePath ) {
  4195. var scope = this,
  4196. currentOffset = 0,
  4197. md,
  4198. normals = [],
  4199. uvs = [],
  4200. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  4201. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  4202. tri_size, quad_size,
  4203. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  4204. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  4205. THREE.Geometry.call( this );
  4206. THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
  4207. md = parseMetaData( data, currentOffset );
  4208. currentOffset += md.header_bytes;
  4209. /*
  4210. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4211. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  4212. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4213. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4214. */
  4215. // buffers sizes
  4216. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  4217. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  4218. len_tri_flat = md.ntri_flat * ( tri_size );
  4219. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  4220. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  4221. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  4222. len_quad_flat = md.nquad_flat * ( quad_size );
  4223. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  4224. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  4225. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  4226. // read buffers
  4227. currentOffset += init_vertices( currentOffset );
  4228. currentOffset += init_normals( currentOffset );
  4229. currentOffset += handlePadding( md.nnormals * 3 );
  4230. currentOffset += init_uvs( currentOffset );
  4231. start_tri_flat = currentOffset;
  4232. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  4233. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  4234. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  4235. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  4236. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  4237. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  4238. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  4239. // have to first process faces with uvs
  4240. // so that face and uv indices match
  4241. init_triangles_flat_uv( start_tri_flat_uv );
  4242. init_triangles_smooth_uv( start_tri_smooth_uv );
  4243. init_quads_flat_uv( start_quad_flat_uv );
  4244. init_quads_smooth_uv( start_quad_smooth_uv );
  4245. // now we can process untextured faces
  4246. init_triangles_flat( start_tri_flat );
  4247. init_triangles_smooth( start_tri_smooth );
  4248. init_quads_flat( start_quad_flat );
  4249. init_quads_smooth( start_quad_smooth );
  4250. this.computeCentroids();
  4251. this.computeFaceNormals();
  4252. if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
  4253. function handlePadding( n ) {
  4254. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  4255. };
  4256. function parseMetaData( data, offset ) {
  4257. var metaData = {
  4258. 'signature' :parseString( data, offset, 12 ),
  4259. 'header_bytes' :parseUChar8( data, offset + 12 ),
  4260. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  4261. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  4262. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  4263. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  4264. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  4265. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  4266. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  4267. 'nvertices' :parseUInt32( data, offset + 20 ),
  4268. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  4269. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  4270. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  4271. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  4272. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  4273. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  4274. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  4275. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  4276. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  4277. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  4278. };
  4279. /*
  4280. console.log( "signature: " + metaData.signature );
  4281. console.log( "header_bytes: " + metaData.header_bytes );
  4282. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  4283. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  4284. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  4285. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  4286. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  4287. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  4288. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  4289. console.log( "nvertices: " + metaData.nvertices );
  4290. console.log( "nnormals: " + metaData.nnormals );
  4291. console.log( "nuvs: " + metaData.nuvs );
  4292. console.log( "ntri_flat: " + metaData.ntri_flat );
  4293. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  4294. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  4295. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  4296. console.log( "nquad_flat: " + metaData.nquad_flat );
  4297. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  4298. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  4299. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  4300. var total = metaData.header_bytes
  4301. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  4302. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  4303. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  4304. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  4305. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  4306. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  4307. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  4308. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  4309. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  4310. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  4311. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  4312. console.log( "total bytes: " + total );
  4313. */
  4314. return metaData;
  4315. };
  4316. function parseString( data, offset, length ) {
  4317. var charArray = new Uint8Array( data, offset, length );
  4318. var text = "";
  4319. for ( var i = 0; i < length; i ++ ) {
  4320. text += String.fromCharCode( charArray[ offset + i ] );
  4321. }
  4322. return text;
  4323. };
  4324. function parseUChar8( data, offset ) {
  4325. var charArray = new Uint8Array( data, offset, 1 );
  4326. return charArray[ 0 ];
  4327. };
  4328. function parseUInt32( data, offset ) {
  4329. var intArray = new Uint32Array( data, offset, 1 );
  4330. return intArray[ 0 ];
  4331. };
  4332. function init_vertices( start ) {
  4333. var nElements = md.nvertices;
  4334. var coordArray = new Float32Array( data, start, nElements * 3 );
  4335. var i, x, y, z;
  4336. for( i = 0; i < nElements; i ++ ) {
  4337. x = coordArray[ i * 3 ];
  4338. y = coordArray[ i * 3 + 1 ];
  4339. z = coordArray[ i * 3 + 2 ];
  4340. vertex( scope, x, y, z );
  4341. }
  4342. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  4343. };
  4344. function init_normals( start ) {
  4345. var nElements = md.nnormals;
  4346. if ( nElements ) {
  4347. var normalArray = new Int8Array( data, start, nElements * 3 );
  4348. var i, x, y, z;
  4349. for( i = 0; i < nElements; i ++ ) {
  4350. x = normalArray[ i * 3 ];
  4351. y = normalArray[ i * 3 + 1 ];
  4352. z = normalArray[ i * 3 + 2 ];
  4353. normals.push( x/127, y/127, z/127 );
  4354. }
  4355. }
  4356. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  4357. };
  4358. function init_uvs( start ) {
  4359. var nElements = md.nuvs;
  4360. if ( nElements ) {
  4361. var uvArray = new Float32Array( data, start, nElements * 2 );
  4362. var i, u, v;
  4363. for( i = 0; i < nElements; i ++ ) {
  4364. u = uvArray[ i * 2 ];
  4365. v = uvArray[ i * 2 + 1 ];
  4366. uvs.push( u, v );
  4367. }
  4368. }
  4369. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  4370. };
  4371. function init_uvs3( nElements, offset ) {
  4372. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  4373. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  4374. for( i = 0; i < nElements; i ++ ) {
  4375. uva = uvIndexBuffer[ i * 3 ];
  4376. uvb = uvIndexBuffer[ i * 3 + 1 ];
  4377. uvc = uvIndexBuffer[ i * 3 + 2 ];
  4378. u1 = uvs[ uva*2 ];
  4379. v1 = uvs[ uva*2 + 1 ];
  4380. u2 = uvs[ uvb*2 ];
  4381. v2 = uvs[ uvb*2 + 1 ];
  4382. u3 = uvs[ uvc*2 ];
  4383. v3 = uvs[ uvc*2 + 1 ];
  4384. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  4385. }
  4386. };
  4387. function init_uvs4( nElements, offset ) {
  4388. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  4389. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  4390. for( i = 0; i < nElements; i ++ ) {
  4391. uva = uvIndexBuffer[ i * 4 ];
  4392. uvb = uvIndexBuffer[ i * 4 + 1 ];
  4393. uvc = uvIndexBuffer[ i * 4 + 2 ];
  4394. uvd = uvIndexBuffer[ i * 4 + 3 ];
  4395. u1 = uvs[ uva*2 ];
  4396. v1 = uvs[ uva*2 + 1 ];
  4397. u2 = uvs[ uvb*2 ];
  4398. v2 = uvs[ uvb*2 + 1 ];
  4399. u3 = uvs[ uvc*2 ];
  4400. v3 = uvs[ uvc*2 + 1 ];
  4401. u4 = uvs[ uvd*2 ];
  4402. v4 = uvs[ uvd*2 + 1 ];
  4403. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  4404. }
  4405. };
  4406. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  4407. var i, a, b, c, m;
  4408. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4409. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4410. for( i = 0; i < nElements; i ++ ) {
  4411. a = vertexIndexBuffer[ i * 3 ];
  4412. b = vertexIndexBuffer[ i * 3 + 1 ];
  4413. c = vertexIndexBuffer[ i * 3 + 2 ];
  4414. m = materialIndexBuffer[ i ];
  4415. f3( scope, a, b, c, m );
  4416. }
  4417. };
  4418. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  4419. var i, a, b, c, d, m;
  4420. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4421. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4422. for( i = 0; i < nElements; i ++ ) {
  4423. a = vertexIndexBuffer[ i * 4 ];
  4424. b = vertexIndexBuffer[ i * 4 + 1 ];
  4425. c = vertexIndexBuffer[ i * 4 + 2 ];
  4426. d = vertexIndexBuffer[ i * 4 + 3 ];
  4427. m = materialIndexBuffer[ i ];
  4428. f4( scope, a, b, c, d, m );
  4429. }
  4430. };
  4431. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4432. var i, a, b, c, m;
  4433. var na, nb, nc;
  4434. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4435. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  4436. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4437. for( i = 0; i < nElements; i ++ ) {
  4438. a = vertexIndexBuffer[ i * 3 ];
  4439. b = vertexIndexBuffer[ i * 3 + 1 ];
  4440. c = vertexIndexBuffer[ i * 3 + 2 ];
  4441. na = normalIndexBuffer[ i * 3 ];
  4442. nb = normalIndexBuffer[ i * 3 + 1 ];
  4443. nc = normalIndexBuffer[ i * 3 + 2 ];
  4444. m = materialIndexBuffer[ i ];
  4445. f3n( scope, normals, a, b, c, m, na, nb, nc );
  4446. }
  4447. };
  4448. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4449. var i, a, b, c, d, m;
  4450. var na, nb, nc, nd;
  4451. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4452. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  4453. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4454. for( i = 0; i < nElements; i ++ ) {
  4455. a = vertexIndexBuffer[ i * 4 ];
  4456. b = vertexIndexBuffer[ i * 4 + 1 ];
  4457. c = vertexIndexBuffer[ i * 4 + 2 ];
  4458. d = vertexIndexBuffer[ i * 4 + 3 ];
  4459. na = normalIndexBuffer[ i * 4 ];
  4460. nb = normalIndexBuffer[ i * 4 + 1 ];
  4461. nc = normalIndexBuffer[ i * 4 + 2 ];
  4462. nd = normalIndexBuffer[ i * 4 + 3 ];
  4463. m = materialIndexBuffer[ i ];
  4464. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  4465. }
  4466. };
  4467. function init_triangles_flat( start ) {
  4468. var nElements = md.ntri_flat;
  4469. if ( nElements ) {
  4470. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4471. init_faces3_flat( nElements, start, offsetMaterials );
  4472. }
  4473. };
  4474. function init_triangles_flat_uv( start ) {
  4475. var nElements = md.ntri_flat_uv;
  4476. if ( nElements ) {
  4477. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4478. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4479. init_faces3_flat( nElements, start, offsetMaterials );
  4480. init_uvs3( nElements, offsetUvs );
  4481. }
  4482. };
  4483. function init_triangles_smooth( start ) {
  4484. var nElements = md.ntri_smooth;
  4485. if ( nElements ) {
  4486. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4487. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4488. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4489. }
  4490. };
  4491. function init_triangles_smooth_uv( start ) {
  4492. var nElements = md.ntri_smooth_uv;
  4493. if ( nElements ) {
  4494. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4495. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4496. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4497. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4498. init_uvs3( nElements, offsetUvs );
  4499. }
  4500. };
  4501. function init_quads_flat( start ) {
  4502. var nElements = md.nquad_flat;
  4503. if ( nElements ) {
  4504. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4505. init_faces4_flat( nElements, start, offsetMaterials );
  4506. }
  4507. };
  4508. function init_quads_flat_uv( start ) {
  4509. var nElements = md.nquad_flat_uv;
  4510. if ( nElements ) {
  4511. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4512. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4513. init_faces4_flat( nElements, start, offsetMaterials );
  4514. init_uvs4( nElements, offsetUvs );
  4515. }
  4516. };
  4517. function init_quads_smooth( start ) {
  4518. var nElements = md.nquad_smooth;
  4519. if ( nElements ) {
  4520. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4521. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4522. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4523. }
  4524. };
  4525. function init_quads_smooth_uv( start ) {
  4526. var nElements = md.nquad_smooth_uv;
  4527. if ( nElements ) {
  4528. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4529. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4530. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4531. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4532. init_uvs4( nElements, offsetUvs );
  4533. }
  4534. };
  4535. };
  4536. function vertex ( scope, x, y, z ) {
  4537. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  4538. };
  4539. function f3 ( scope, a, b, c, mi ) {
  4540. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  4541. };
  4542. function f4 ( scope, a, b, c, d, mi ) {
  4543. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  4544. };
  4545. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  4546. var nax = normals[ na*3 ],
  4547. nay = normals[ na*3 + 1 ],
  4548. naz = normals[ na*3 + 2 ],
  4549. nbx = normals[ nb*3 ],
  4550. nby = normals[ nb*3 + 1 ],
  4551. nbz = normals[ nb*3 + 2 ],
  4552. ncx = normals[ nc*3 ],
  4553. ncy = normals[ nc*3 + 1 ],
  4554. ncz = normals[ nc*3 + 2 ];
  4555. scope.faces.push( new THREE.Face3( a, b, c,
  4556. [new THREE.Vector3( nax, nay, naz ),
  4557. new THREE.Vector3( nbx, nby, nbz ),
  4558. new THREE.Vector3( ncx, ncy, ncz )],
  4559. null,
  4560. mi ) );
  4561. };
  4562. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  4563. var nax = normals[ na*3 ],
  4564. nay = normals[ na*3 + 1 ],
  4565. naz = normals[ na*3 + 2 ],
  4566. nbx = normals[ nb*3 ],
  4567. nby = normals[ nb*3 + 1 ],
  4568. nbz = normals[ nb*3 + 2 ],
  4569. ncx = normals[ nc*3 ],
  4570. ncy = normals[ nc*3 + 1 ],
  4571. ncz = normals[ nc*3 + 2 ],
  4572. ndx = normals[ nd*3 ],
  4573. ndy = normals[ nd*3 + 1 ],
  4574. ndz = normals[ nd*3 + 2 ];
  4575. scope.faces.push( new THREE.Face4( a, b, c, d,
  4576. [new THREE.Vector3( nax, nay, naz ),
  4577. new THREE.Vector3( nbx, nby, nbz ),
  4578. new THREE.Vector3( ncx, ncy, ncz ),
  4579. new THREE.Vector3( ndx, ndy, ndz )],
  4580. null,
  4581. mi ) );
  4582. };
  4583. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  4584. var uv = [];
  4585. uv.push( new THREE.UV( u1, v1 ) );
  4586. uv.push( new THREE.UV( u2, v2 ) );
  4587. uv.push( new THREE.UV( u3, v3 ) );
  4588. where.push( uv );
  4589. };
  4590. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  4591. var uv = [];
  4592. uv.push( new THREE.UV( u1, v1 ) );
  4593. uv.push( new THREE.UV( u2, v2 ) );
  4594. uv.push( new THREE.UV( u3, v3 ) );
  4595. uv.push( new THREE.UV( u4, v4 ) );
  4596. where.push( uv );
  4597. };
  4598. Model.prototype = Object.create( THREE.Geometry.prototype );
  4599. callback( new Model( texturePath ) );
  4600. };
  4601. /**
  4602. * @author mrdoob / http://mrdoob.com/
  4603. */
  4604. THREE.ImageLoader = function () {
  4605. THREE.EventTarget.call( this );
  4606. this.crossOrigin = null;
  4607. };
  4608. THREE.ImageLoader.prototype = {
  4609. constructor: THREE.ImageLoader,
  4610. load: function ( url, image ) {
  4611. var scope = this;
  4612. if ( image === undefined ) image = new Image();
  4613. image.addEventListener( 'load', function () {
  4614. scope.dispatchEvent( { type: 'load', content: image } );
  4615. }, false );
  4616. image.addEventListener( 'error', function () {
  4617. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4618. }, false );
  4619. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  4620. image.src = url;
  4621. }
  4622. }
  4623. /**
  4624. * @author mrdoob / http://mrdoob.com/
  4625. * @author alteredq / http://alteredqualia.com/
  4626. */
  4627. THREE.JSONLoader = function ( showStatus ) {
  4628. THREE.Loader.call( this, showStatus );
  4629. };
  4630. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  4631. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  4632. var scope = this;
  4633. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4634. this.onLoadStart();
  4635. this.loadAjaxJSON( this, url, callback, texturePath );
  4636. };
  4637. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  4638. var xhr = new XMLHttpRequest();
  4639. var length = 0;
  4640. xhr.onreadystatechange = function () {
  4641. if ( xhr.readyState === xhr.DONE ) {
  4642. if ( xhr.status === 200 || xhr.status === 0 ) {
  4643. if ( xhr.responseText ) {
  4644. var json = JSON.parse( xhr.responseText );
  4645. context.createModel( json, callback, texturePath );
  4646. } else {
  4647. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  4648. }
  4649. // in context of more complex asset initialization
  4650. // do not block on single failed file
  4651. // maybe should go even one more level up
  4652. context.onLoadComplete();
  4653. } else {
  4654. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4655. }
  4656. } else if ( xhr.readyState === xhr.LOADING ) {
  4657. if ( callbackProgress ) {
  4658. if ( length === 0 ) {
  4659. length = xhr.getResponseHeader( "Content-Length" );
  4660. }
  4661. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4662. }
  4663. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  4664. length = xhr.getResponseHeader( "Content-Length" );
  4665. }
  4666. };
  4667. xhr.open( "GET", url, true );
  4668. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "application/json; charset=x-user-defined" );
  4669. xhr.setRequestHeader( "Content-Type", "application/json" );
  4670. xhr.send( null );
  4671. };
  4672. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  4673. var scope = this,
  4674. geometry = new THREE.Geometry(),
  4675. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  4676. this.initMaterials( geometry, json.materials, texturePath );
  4677. parseModel( scale );
  4678. parseSkin();
  4679. parseMorphing( scale );
  4680. geometry.computeCentroids();
  4681. geometry.computeFaceNormals();
  4682. if ( this.hasNormals( geometry ) ) geometry.computeTangents();
  4683. function parseModel( scale ) {
  4684. function isBitSet( value, position ) {
  4685. return value & ( 1 << position );
  4686. }
  4687. var i, j, fi,
  4688. offset, zLength, nVertices,
  4689. colorIndex, normalIndex, uvIndex, materialIndex,
  4690. type,
  4691. isQuad,
  4692. hasMaterial,
  4693. hasFaceUv, hasFaceVertexUv,
  4694. hasFaceNormal, hasFaceVertexNormal,
  4695. hasFaceColor, hasFaceVertexColor,
  4696. vertex, face, color, normal,
  4697. uvLayer, uvs, u, v,
  4698. faces = json.faces,
  4699. vertices = json.vertices,
  4700. normals = json.normals,
  4701. colors = json.colors,
  4702. nUvLayers = 0;
  4703. // disregard empty arrays
  4704. for ( i = 0; i < json.uvs.length; i++ ) {
  4705. if ( json.uvs[ i ].length ) nUvLayers ++;
  4706. }
  4707. for ( i = 0; i < nUvLayers; i++ ) {
  4708. geometry.faceUvs[ i ] = [];
  4709. geometry.faceVertexUvs[ i ] = [];
  4710. }
  4711. offset = 0;
  4712. zLength = vertices.length;
  4713. while ( offset < zLength ) {
  4714. vertex = new THREE.Vector3();
  4715. vertex.x = vertices[ offset ++ ] * scale;
  4716. vertex.y = vertices[ offset ++ ] * scale;
  4717. vertex.z = vertices[ offset ++ ] * scale;
  4718. geometry.vertices.push( vertex );
  4719. }
  4720. offset = 0;
  4721. zLength = faces.length;
  4722. while ( offset < zLength ) {
  4723. type = faces[ offset ++ ];
  4724. isQuad = isBitSet( type, 0 );
  4725. hasMaterial = isBitSet( type, 1 );
  4726. hasFaceUv = isBitSet( type, 2 );
  4727. hasFaceVertexUv = isBitSet( type, 3 );
  4728. hasFaceNormal = isBitSet( type, 4 );
  4729. hasFaceVertexNormal = isBitSet( type, 5 );
  4730. hasFaceColor = isBitSet( type, 6 );
  4731. hasFaceVertexColor = isBitSet( type, 7 );
  4732. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  4733. if ( isQuad ) {
  4734. face = new THREE.Face4();
  4735. face.a = faces[ offset ++ ];
  4736. face.b = faces[ offset ++ ];
  4737. face.c = faces[ offset ++ ];
  4738. face.d = faces[ offset ++ ];
  4739. nVertices = 4;
  4740. } else {
  4741. face = new THREE.Face3();
  4742. face.a = faces[ offset ++ ];
  4743. face.b = faces[ offset ++ ];
  4744. face.c = faces[ offset ++ ];
  4745. nVertices = 3;
  4746. }
  4747. if ( hasMaterial ) {
  4748. materialIndex = faces[ offset ++ ];
  4749. face.materialIndex = materialIndex;
  4750. }
  4751. // to get face <=> uv index correspondence
  4752. fi = geometry.faces.length;
  4753. if ( hasFaceUv ) {
  4754. for ( i = 0; i < nUvLayers; i++ ) {
  4755. uvLayer = json.uvs[ i ];
  4756. uvIndex = faces[ offset ++ ];
  4757. u = uvLayer[ uvIndex * 2 ];
  4758. v = uvLayer[ uvIndex * 2 + 1 ];
  4759. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  4760. }
  4761. }
  4762. if ( hasFaceVertexUv ) {
  4763. for ( i = 0; i < nUvLayers; i++ ) {
  4764. uvLayer = json.uvs[ i ];
  4765. uvs = [];
  4766. for ( j = 0; j < nVertices; j ++ ) {
  4767. uvIndex = faces[ offset ++ ];
  4768. u = uvLayer[ uvIndex * 2 ];
  4769. v = uvLayer[ uvIndex * 2 + 1 ];
  4770. uvs[ j ] = new THREE.UV( u, v );
  4771. }
  4772. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  4773. }
  4774. }
  4775. if ( hasFaceNormal ) {
  4776. normalIndex = faces[ offset ++ ] * 3;
  4777. normal = new THREE.Vector3();
  4778. normal.x = normals[ normalIndex ++ ];
  4779. normal.y = normals[ normalIndex ++ ];
  4780. normal.z = normals[ normalIndex ];
  4781. face.normal = normal;
  4782. }
  4783. if ( hasFaceVertexNormal ) {
  4784. for ( i = 0; i < nVertices; i++ ) {
  4785. normalIndex = faces[ offset ++ ] * 3;
  4786. normal = new THREE.Vector3();
  4787. normal.x = normals[ normalIndex ++ ];
  4788. normal.y = normals[ normalIndex ++ ];
  4789. normal.z = normals[ normalIndex ];
  4790. face.vertexNormals.push( normal );
  4791. }
  4792. }
  4793. if ( hasFaceColor ) {
  4794. colorIndex = faces[ offset ++ ];
  4795. color = new THREE.Color( colors[ colorIndex ] );
  4796. face.color = color;
  4797. }
  4798. if ( hasFaceVertexColor ) {
  4799. for ( i = 0; i < nVertices; i++ ) {
  4800. colorIndex = faces[ offset ++ ];
  4801. color = new THREE.Color( colors[ colorIndex ] );
  4802. face.vertexColors.push( color );
  4803. }
  4804. }
  4805. geometry.faces.push( face );
  4806. }
  4807. };
  4808. function parseSkin() {
  4809. var i, l, x, y, z, w, a, b, c, d;
  4810. if ( json.skinWeights ) {
  4811. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  4812. x = json.skinWeights[ i ];
  4813. y = json.skinWeights[ i + 1 ];
  4814. z = 0;
  4815. w = 0;
  4816. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  4817. }
  4818. }
  4819. if ( json.skinIndices ) {
  4820. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  4821. a = json.skinIndices[ i ];
  4822. b = json.skinIndices[ i + 1 ];
  4823. c = 0;
  4824. d = 0;
  4825. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  4826. }
  4827. }
  4828. geometry.bones = json.bones;
  4829. geometry.animation = json.animation;
  4830. };
  4831. function parseMorphing( scale ) {
  4832. if ( json.morphTargets !== undefined ) {
  4833. var i, l, v, vl, dstVertices, srcVertices;
  4834. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  4835. geometry.morphTargets[ i ] = {};
  4836. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  4837. geometry.morphTargets[ i ].vertices = [];
  4838. dstVertices = geometry.morphTargets[ i ].vertices;
  4839. srcVertices = json.morphTargets [ i ].vertices;
  4840. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  4841. var vertex = new THREE.Vector3();
  4842. vertex.x = srcVertices[ v ] * scale;
  4843. vertex.y = srcVertices[ v + 1 ] * scale;
  4844. vertex.z = srcVertices[ v + 2 ] * scale;
  4845. dstVertices.push( vertex );
  4846. }
  4847. }
  4848. }
  4849. if ( json.morphColors !== undefined ) {
  4850. var i, l, c, cl, dstColors, srcColors, color;
  4851. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  4852. geometry.morphColors[ i ] = {};
  4853. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  4854. geometry.morphColors[ i ].colors = [];
  4855. dstColors = geometry.morphColors[ i ].colors;
  4856. srcColors = json.morphColors [ i ].colors;
  4857. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  4858. color = new THREE.Color( 0xffaa00 );
  4859. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  4860. dstColors.push( color );
  4861. }
  4862. }
  4863. }
  4864. };
  4865. callback( geometry );
  4866. };
  4867. /**
  4868. * @author mrdoob / http://mrdoob.com/
  4869. * @author alteredq / http://alteredqualia.com/
  4870. */
  4871. THREE.GeometryLoader = function () {
  4872. THREE.EventTarget.call( this );
  4873. this.crossOrigin = null;
  4874. this.path = null;
  4875. };
  4876. THREE.GeometryLoader.prototype = {
  4877. constructor: THREE.GeometryLoader,
  4878. load: function ( url ) {
  4879. var scope = this;
  4880. var geometry = null;
  4881. if ( scope.path === null ) {
  4882. var parts = url.split( '/' ); parts.pop();
  4883. scope.path = ( parts.length < 1 ? '.' : parts.join( '/' ) );
  4884. }
  4885. //
  4886. var xhr = new XMLHttpRequest();
  4887. xhr.addEventListener( 'load', function ( event ) {
  4888. if ( event.target.responseText ) {
  4889. geometry = scope.parse( JSON.parse( event.target.responseText ), monitor );
  4890. } else {
  4891. scope.dispatchEvent( { type: 'error', message: 'Invalid file [' + url + ']' } );
  4892. }
  4893. }, false );
  4894. xhr.addEventListener( 'error', function () {
  4895. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4896. }, false );
  4897. xhr.open( 'GET', url, true );
  4898. xhr.setRequestHeader( "Content-Type", "application/json" );
  4899. xhr.send( null );
  4900. //
  4901. var monitor = new THREE.LoadingMonitor();
  4902. monitor.addEventListener( 'load', function ( event ) {
  4903. scope.dispatchEvent( { type: 'load', content: geometry } );
  4904. } );
  4905. monitor.add( xhr );
  4906. },
  4907. parse: function ( data, monitor ) {
  4908. var scope = this;
  4909. var geometry = new THREE.Geometry();
  4910. var scale = ( data.scale !== undefined ) ? 1 / data.scale : 1;
  4911. // materials
  4912. if ( data.materials ) {
  4913. geometry.materials = [];
  4914. for ( var i = 0; i < data.materials.length; ++ i ) {
  4915. var m = data.materials[ i ];
  4916. function isPow2( n ) {
  4917. var l = Math.log( n ) / Math.LN2;
  4918. return Math.floor( l ) == l;
  4919. }
  4920. function nearestPow2( n ) {
  4921. var l = Math.log( n ) / Math.LN2;
  4922. return Math.pow( 2, Math.round( l ) );
  4923. }
  4924. function createTexture( where, name, sourceFile, repeat, offset, wrap ) {
  4925. where[ name ] = new THREE.Texture();
  4926. where[ name ].sourceFile = sourceFile;
  4927. if ( repeat ) {
  4928. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4929. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4930. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4931. }
  4932. if ( offset ) {
  4933. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4934. }
  4935. if ( wrap ) {
  4936. var wrapMap = {
  4937. "repeat": THREE.RepeatWrapping,
  4938. "mirror": THREE.MirroredRepeatWrapping
  4939. }
  4940. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4941. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4942. }
  4943. // load image
  4944. var texture = where[ name ];
  4945. var loader = new THREE.ImageLoader();
  4946. loader.addEventListener( 'load', function ( event ) {
  4947. var image = event.content;
  4948. if ( !isPow2( image.width ) || !isPow2( image.height ) ) {
  4949. var width = nearestPow2( image.width );
  4950. var height = nearestPow2( image.height );
  4951. texture.image = document.createElement( 'canvas' );
  4952. texture.image.width = width;
  4953. texture.image.height = height;
  4954. texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
  4955. } else {
  4956. texture.image = image;
  4957. }
  4958. texture.needsUpdate = true;
  4959. } );
  4960. loader.crossOrigin = scope.crossOrigin;
  4961. loader.load( scope.path + '/' + sourceFile );
  4962. if ( monitor ) monitor.add( loader );
  4963. }
  4964. function rgb2hex( rgb ) {
  4965. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4966. }
  4967. // defaults
  4968. var mtype = "MeshLambertMaterial";
  4969. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4970. // parameters from model file
  4971. if ( m.shading ) {
  4972. var shading = m.shading.toLowerCase();
  4973. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4974. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4975. }
  4976. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4977. mpars.blending = THREE[ m.blending ];
  4978. }
  4979. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4980. mpars.transparent = m.transparent;
  4981. }
  4982. if ( m.depthTest !== undefined ) {
  4983. mpars.depthTest = m.depthTest;
  4984. }
  4985. if ( m.depthWrite !== undefined ) {
  4986. mpars.depthWrite = m.depthWrite;
  4987. }
  4988. if ( m.vertexColors !== undefined ) {
  4989. if ( m.vertexColors == "face" ) {
  4990. mpars.vertexColors = THREE.FaceColors;
  4991. } else if ( m.vertexColors ) {
  4992. mpars.vertexColors = THREE.VertexColors;
  4993. }
  4994. }
  4995. // colors
  4996. if ( m.colorDiffuse ) {
  4997. mpars.color = rgb2hex( m.colorDiffuse );
  4998. } else if ( m.DbgColor ) {
  4999. mpars.color = m.DbgColor;
  5000. }
  5001. if ( m.colorSpecular ) {
  5002. mpars.specular = rgb2hex( m.colorSpecular );
  5003. }
  5004. if ( m.colorAmbient ) {
  5005. mpars.ambient = rgb2hex( m.colorAmbient );
  5006. }
  5007. // modifiers
  5008. if ( m.transparency ) {
  5009. mpars.opacity = m.transparency;
  5010. }
  5011. if ( m.specularCoef ) {
  5012. mpars.shininess = m.specularCoef;
  5013. }
  5014. if ( m.visible !== undefined ) {
  5015. mpars.visible = m.visible;
  5016. }
  5017. if ( m.flipSided !== undefined ) {
  5018. mpars.side = THREE.BackSide;
  5019. }
  5020. if ( m.doubleSided !== undefined ) {
  5021. mpars.side = THREE.DoubleSide;
  5022. }
  5023. if ( m.wireframe !== undefined ) {
  5024. mpars.wireframe = m.wireframe;
  5025. }
  5026. // textures
  5027. if ( m.mapDiffuse ) {
  5028. createTexture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  5029. }
  5030. if ( m.mapLight ) {
  5031. createTexture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  5032. }
  5033. if ( m.mapBump ) {
  5034. createTexture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap );
  5035. }
  5036. if ( m.mapNormal ) {
  5037. createTexture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  5038. }
  5039. if ( m.mapSpecular ) {
  5040. createTexture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  5041. }
  5042. // special case for normal mapped material
  5043. if ( m.mapNormal ) {
  5044. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5045. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5046. uniforms[ "tNormal" ].value = mpars.normalMap;
  5047. if ( m.mapNormalFactor ) {
  5048. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  5049. }
  5050. if ( mpars.map ) {
  5051. uniforms[ "tDiffuse" ].value = mpars.map;
  5052. uniforms[ "enableDiffuse" ].value = true;
  5053. }
  5054. if ( mpars.specularMap ) {
  5055. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5056. uniforms[ "enableSpecular" ].value = true;
  5057. }
  5058. if ( mpars.lightMap ) {
  5059. uniforms[ "tAO" ].value = mpars.lightMap;
  5060. uniforms[ "enableAO" ].value = true;
  5061. }
  5062. // for the moment don't handle displacement texture
  5063. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5064. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5065. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5066. uniforms[ "uShininess" ].value = mpars.shininess;
  5067. if ( mpars.opacity !== undefined ) {
  5068. uniforms[ "uOpacity" ].value = mpars.opacity;
  5069. }
  5070. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5071. var material = new THREE.ShaderMaterial( parameters );
  5072. } else {
  5073. var material = new THREE[ mtype ]( mpars );
  5074. }
  5075. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5076. geometry.materials[ i ] = material;
  5077. }
  5078. }
  5079. // geometry
  5080. function isBitSet( value, position ) {
  5081. return value & ( 1 << position );
  5082. }
  5083. var faces = data.faces;
  5084. var vertices = data.vertices;
  5085. var normals = data.normals;
  5086. var colors = data.colors;
  5087. var nUvLayers = 0;
  5088. // disregard empty arrays
  5089. if ( data.uvs ) {
  5090. for ( var i = 0; i < data.uvs.length; i ++ ) {
  5091. if ( data.uvs[ i ].length ) nUvLayers ++;
  5092. }
  5093. }
  5094. for ( var i = 0; i < nUvLayers; i ++ ) {
  5095. geometry.faceUvs[ i ] = [];
  5096. geometry.faceVertexUvs[ i ] = [];
  5097. }
  5098. var offset = 0;
  5099. var zLength = vertices.length;
  5100. while ( offset < zLength ) {
  5101. var vertex = new THREE.Vector3();
  5102. vertex.x = vertices[ offset ++ ] * scale;
  5103. vertex.y = vertices[ offset ++ ] * scale;
  5104. vertex.z = vertices[ offset ++ ] * scale;
  5105. geometry.vertices.push( vertex );
  5106. }
  5107. offset = 0;
  5108. zLength = faces.length;
  5109. while ( offset < zLength ) {
  5110. var type = faces[ offset ++ ];
  5111. var isQuad = isBitSet( type, 0 );
  5112. var hasMaterial = isBitSet( type, 1 );
  5113. var hasFaceUv = isBitSet( type, 2 );
  5114. var hasFaceVertexUv = isBitSet( type, 3 );
  5115. var hasFaceNormal = isBitSet( type, 4 );
  5116. var hasFaceVertexNormal = isBitSet( type, 5 );
  5117. var hasFaceColor = isBitSet( type, 6 );
  5118. var hasFaceVertexColor = isBitSet( type, 7 );
  5119. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5120. if ( isQuad ) {
  5121. var face = new THREE.Face4();
  5122. face.a = faces[ offset ++ ];
  5123. face.b = faces[ offset ++ ];
  5124. face.c = faces[ offset ++ ];
  5125. face.d = faces[ offset ++ ];
  5126. var nVertices = 4;
  5127. } else {
  5128. var face = new THREE.Face3();
  5129. face.a = faces[ offset ++ ];
  5130. face.b = faces[ offset ++ ];
  5131. face.c = faces[ offset ++ ];
  5132. var nVertices = 3;
  5133. }
  5134. if ( hasMaterial ) {
  5135. var materialIndex = faces[ offset ++ ];
  5136. face.materialIndex = materialIndex;
  5137. }
  5138. // to get face <=> uv index correspondence
  5139. var fi = geometry.faces.length;
  5140. if ( hasFaceUv ) {
  5141. for ( var i = 0; i < nUvLayers; i ++ ) {
  5142. var uvLayer = data.uvs[ i ];
  5143. var uvIndex = faces[ offset ++ ];
  5144. var u = uvLayer[ uvIndex * 2 ];
  5145. var v = uvLayer[ uvIndex * 2 + 1 ];
  5146. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5147. }
  5148. }
  5149. if ( hasFaceVertexUv ) {
  5150. for ( var i = 0; i < nUvLayers; i ++ ) {
  5151. var uvLayer = data.uvs[ i ];
  5152. var uvs = [];
  5153. for ( var j = 0; j < nVertices; j ++ ) {
  5154. var uvIndex = faces[ offset ++ ];
  5155. var u = uvLayer[ uvIndex * 2 ];
  5156. var v = uvLayer[ uvIndex * 2 + 1 ];
  5157. uvs[ j ] = new THREE.UV( u, v );
  5158. }
  5159. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5160. }
  5161. }
  5162. if ( hasFaceNormal ) {
  5163. var normalIndex = faces[ offset ++ ] * 3;
  5164. var normal = new THREE.Vector3();
  5165. normal.x = normals[ normalIndex ++ ];
  5166. normal.y = normals[ normalIndex ++ ];
  5167. normal.z = normals[ normalIndex ];
  5168. face.normal = normal;
  5169. }
  5170. if ( hasFaceVertexNormal ) {
  5171. for ( i = 0; i < nVertices; i ++ ) {
  5172. var normalIndex = faces[ offset ++ ] * 3;
  5173. var normal = new THREE.Vector3();
  5174. normal.x = normals[ normalIndex ++ ];
  5175. normal.y = normals[ normalIndex ++ ];
  5176. normal.z = normals[ normalIndex ];
  5177. face.vertexNormals.push( normal );
  5178. }
  5179. }
  5180. if ( hasFaceColor ) {
  5181. var colorIndex = faces[ offset ++ ];
  5182. face.color = new THREE.Color( colors[ colorIndex ] );
  5183. }
  5184. if ( hasFaceVertexColor ) {
  5185. for ( var i = 0; i < nVertices; i ++ ) {
  5186. var colorIndex = faces[ offset ++ ];
  5187. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  5188. }
  5189. }
  5190. geometry.faces.push( face );
  5191. }
  5192. // skin
  5193. if ( data.skinWeights ) {
  5194. for ( var i = 0, l = data.skinWeights.length; i < l; i += 2 ) {
  5195. var x = data.skinWeights[ i ];
  5196. var y = data.skinWeights[ i + 1 ];
  5197. var z = 0;
  5198. var w = 0;
  5199. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5200. }
  5201. }
  5202. if ( data.skinIndices ) {
  5203. for ( var i = 0, l = data.skinIndices.length; i < l; i += 2 ) {
  5204. var a = data.skinIndices[ i ];
  5205. var b = data.skinIndices[ i + 1 ];
  5206. var c = 0;
  5207. var d = 0;
  5208. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5209. }
  5210. }
  5211. geometry.bones = data.bones;
  5212. geometry.animation = data.animation;
  5213. // morphing
  5214. if ( data.morphTargets ) {
  5215. for ( var i = 0, l = data.morphTargets.length; i < l; i ++ ) {
  5216. geometry.morphTargets[ i ] = {};
  5217. geometry.morphTargets[ i ].name = data.morphTargets[ i ].name;
  5218. geometry.morphTargets[ i ].vertices = [];
  5219. var dstVertices = geometry.morphTargets[ i ].vertices;
  5220. var srcVertices = data.morphTargets [ i ].vertices;
  5221. for( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5222. var vertex = new THREE.Vector3();
  5223. vertex.x = srcVertices[ v ] * scale;
  5224. vertex.y = srcVertices[ v + 1 ] * scale;
  5225. vertex.z = srcVertices[ v + 2 ] * scale;
  5226. dstVertices.push( vertex );
  5227. }
  5228. }
  5229. }
  5230. if ( data.morphColors ) {
  5231. for ( var i = 0, l = data.morphColors.length; i < l; i++ ) {
  5232. geometry.morphColors[ i ] = {};
  5233. geometry.morphColors[ i ].name = data.morphColors[ i ].name;
  5234. geometry.morphColors[ i ].colors = [];
  5235. var dstColors = geometry.morphColors[ i ].colors;
  5236. var srcColors = data.morphColors [ i ].colors;
  5237. for ( var c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5238. var color = new THREE.Color( 0xffaa00 );
  5239. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5240. dstColors.push( color );
  5241. }
  5242. }
  5243. }
  5244. geometry.computeCentroids();
  5245. geometry.computeFaceNormals();
  5246. return geometry;
  5247. }
  5248. };
  5249. /**
  5250. * @author alteredq / http://alteredqualia.com/
  5251. */
  5252. THREE.SceneLoader = function () {
  5253. this.onLoadStart = function () {};
  5254. this.onLoadProgress = function() {};
  5255. this.onLoadComplete = function () {};
  5256. this.callbackSync = function () {};
  5257. this.callbackProgress = function () {};
  5258. };
  5259. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5260. THREE.SceneLoader.prototype.load = function( url, callbackFinished ) {
  5261. var context = this;
  5262. var xhr = new XMLHttpRequest();
  5263. xhr.onreadystatechange = function () {
  5264. if ( xhr.readyState === 4 ) {
  5265. if ( xhr.status === 200 || xhr.status === 0 ) {
  5266. var json = JSON.parse( xhr.responseText );
  5267. context.createScene( json, callbackFinished, url );
  5268. } else {
  5269. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5270. }
  5271. }
  5272. };
  5273. xhr.open( "GET", url, true );
  5274. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "application/json; charset=x-user-defined" );
  5275. xhr.setRequestHeader( "Content-Type", "application/json" );
  5276. xhr.send( null );
  5277. };
  5278. THREE.SceneLoader.prototype.createScene = function ( json, callbackFinished, url ) {
  5279. var scope = this;
  5280. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5281. var dg, dm, dd, dl, dc, df, dt,
  5282. g, o, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  5283. geometry, material, camera, fog,
  5284. texture, images,
  5285. light,
  5286. data, binLoader, jsonLoader,
  5287. counter_models, counter_textures,
  5288. total_models, total_textures,
  5289. result;
  5290. data = json;
  5291. binLoader = new THREE.BinaryLoader();
  5292. jsonLoader = new THREE.JSONLoader();
  5293. counter_models = 0;
  5294. counter_textures = 0;
  5295. result = {
  5296. scene: new THREE.Scene(),
  5297. geometries: {},
  5298. materials: {},
  5299. textures: {},
  5300. objects: {},
  5301. cameras: {},
  5302. lights: {},
  5303. fogs: {},
  5304. empties: {}
  5305. };
  5306. if ( data.transform ) {
  5307. var position = data.transform.position,
  5308. rotation = data.transform.rotation,
  5309. scale = data.transform.scale;
  5310. if ( position )
  5311. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5312. if ( rotation )
  5313. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5314. if ( scale )
  5315. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5316. if ( position || rotation || scale ) {
  5317. result.scene.updateMatrix();
  5318. result.scene.updateMatrixWorld();
  5319. }
  5320. }
  5321. function get_url( source_url, url_type ) {
  5322. if ( url_type == "relativeToHTML" ) {
  5323. return source_url;
  5324. } else {
  5325. return urlBase + "/" + source_url;
  5326. }
  5327. };
  5328. // the toplevel loader function, delegates to handle_children
  5329. function handle_objects() {
  5330. handle_children( result.scene, data.objects );
  5331. }
  5332. // handle all the children from the loaded json and attach them to given parent
  5333. function handle_children( parent, children ) {
  5334. var object;
  5335. for ( dd in children ) {
  5336. // check by id if child has already been handled,
  5337. // if not, create new object
  5338. if ( result.objects[ dd ] === undefined ) {
  5339. o = children[ dd ];
  5340. if ( o.geometry !== undefined ) {
  5341. geometry = result.geometries[ o.geometry ];
  5342. // geometry already loaded
  5343. if ( geometry ) {
  5344. var hasNormals = false;
  5345. // not anymore support for multiple materials
  5346. // shouldn't really be array
  5347. material = result.materials[ o.materials[ 0 ] ];
  5348. hasNormals = material instanceof THREE.ShaderMaterial;
  5349. if ( hasNormals ) {
  5350. geometry.computeTangents();
  5351. }
  5352. p = o.position;
  5353. r = o.rotation;
  5354. q = o.quaternion;
  5355. s = o.scale;
  5356. m = o.matrix;
  5357. // turn off quaternions, for the moment
  5358. q = 0;
  5359. if ( o.materials.length == 0 ) {
  5360. material = new THREE.MeshFaceMaterial();
  5361. }
  5362. // dirty hack to handle meshes with multiple materials
  5363. // just use face materials defined in model
  5364. if ( o.materials.length > 1 ) {
  5365. material = new THREE.MeshFaceMaterial();
  5366. }
  5367. object = new THREE.Mesh( geometry, material );
  5368. object.name = dd;
  5369. if ( m ) {
  5370. object.matrixAutoUpdate = false;
  5371. object.matrix.set(
  5372. m[0], m[1], m[2], m[3],
  5373. m[4], m[5], m[6], m[7],
  5374. m[8], m[9], m[10], m[11],
  5375. m[12], m[13], m[14], m[15]
  5376. );
  5377. } else {
  5378. object.position.set( p[0], p[1], p[2] );
  5379. if ( q ) {
  5380. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5381. object.useQuaternion = true;
  5382. } else {
  5383. object.rotation.set( r[0], r[1], r[2] );
  5384. }
  5385. object.scale.set( s[0], s[1], s[2] );
  5386. }
  5387. object.visible = o.visible;
  5388. object.castShadow = o.castShadow;
  5389. object.receiveShadow = o.receiveShadow;
  5390. parent.add( object );
  5391. result.objects[ dd ] = object;
  5392. }
  5393. // pure Object3D
  5394. } else {
  5395. p = o.position;
  5396. r = o.rotation;
  5397. q = o.quaternion;
  5398. s = o.scale;
  5399. // turn off quaternions, for the moment
  5400. q = 0;
  5401. object = new THREE.Object3D();
  5402. object.name = dd;
  5403. object.position.set( p[0], p[1], p[2] );
  5404. if ( q ) {
  5405. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5406. object.useQuaternion = true;
  5407. } else {
  5408. object.rotation.set( r[0], r[1], r[2] );
  5409. }
  5410. object.scale.set( s[0], s[1], s[2] );
  5411. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  5412. parent.add( object );
  5413. result.objects[ dd ] = object;
  5414. result.empties[ dd ] = object;
  5415. }
  5416. if ( o.properties !== undefined) {
  5417. for ( var key in o.properties ) {
  5418. var value = o.properties[ key ];
  5419. object.properties[ key ] = value;
  5420. }
  5421. }
  5422. if ( o.children !== undefined ) {
  5423. handle_children( object, o.children );
  5424. }
  5425. }
  5426. }
  5427. };
  5428. function handle_mesh( geo, id ) {
  5429. result.geometries[ id ] = geo;
  5430. handle_objects();
  5431. };
  5432. function create_callback( id ) {
  5433. return function( geo ) {
  5434. handle_mesh( geo, id );
  5435. counter_models -= 1;
  5436. scope.onLoadComplete();
  5437. async_callback_gate();
  5438. }
  5439. };
  5440. function create_callback_embed( id ) {
  5441. return function( geo ) {
  5442. result.geometries[ id ] = geo;
  5443. }
  5444. };
  5445. function async_callback_gate() {
  5446. var progress = {
  5447. totalModels : total_models,
  5448. totalTextures : total_textures,
  5449. loadedModels : total_models - counter_models,
  5450. loadedTextures : total_textures - counter_textures
  5451. };
  5452. scope.callbackProgress( progress, result );
  5453. scope.onLoadProgress();
  5454. if ( counter_models === 0 && counter_textures === 0 ) {
  5455. callbackFinished( result );
  5456. }
  5457. };
  5458. var callbackTexture = function ( count ) {
  5459. counter_textures -= count;
  5460. async_callback_gate();
  5461. scope.onLoadComplete();
  5462. };
  5463. // must use this instead of just directly calling callbackTexture
  5464. // because of closure in the calling context loop
  5465. var generateTextureCallback = function ( count ) {
  5466. return function() {
  5467. callbackTexture( count );
  5468. };
  5469. };
  5470. // first go synchronous elements
  5471. // cameras
  5472. for( dc in data.cameras ) {
  5473. c = data.cameras[ dc ];
  5474. if ( c.type === "perspective" ) {
  5475. camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );
  5476. } else if ( c.type === "ortho" ) {
  5477. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  5478. }
  5479. p = c.position;
  5480. t = c.target;
  5481. u = c.up;
  5482. camera.position.set( p[0], p[1], p[2] );
  5483. camera.target = new THREE.Vector3( t[0], t[1], t[2] );
  5484. if ( u ) camera.up.set( u[0], u[1], u[2] );
  5485. result.cameras[ dc ] = camera;
  5486. }
  5487. // lights
  5488. var hex, intensity;
  5489. for ( dl in data.lights ) {
  5490. l = data.lights[ dl ];
  5491. hex = ( l.color !== undefined ) ? l.color : 0xffffff;
  5492. intensity = ( l.intensity !== undefined ) ? l.intensity : 1;
  5493. if ( l.type === "directional" ) {
  5494. p = l.direction;
  5495. light = new THREE.DirectionalLight( hex, intensity );
  5496. light.position.set( p[0], p[1], p[2] );
  5497. light.position.normalize();
  5498. } else if ( l.type === "point" ) {
  5499. p = l.position;
  5500. d = l.distance;
  5501. light = new THREE.PointLight( hex, intensity, d );
  5502. light.position.set( p[0], p[1], p[2] );
  5503. } else if ( l.type === "ambient" ) {
  5504. light = new THREE.AmbientLight( hex );
  5505. }
  5506. result.scene.add( light );
  5507. result.lights[ dl ] = light;
  5508. }
  5509. // fogs
  5510. for( df in data.fogs ) {
  5511. f = data.fogs[ df ];
  5512. if ( f.type === "linear" ) {
  5513. fog = new THREE.Fog( 0x000000, f.near, f.far );
  5514. } else if ( f.type === "exp2" ) {
  5515. fog = new THREE.FogExp2( 0x000000, f.density );
  5516. }
  5517. c = f.color;
  5518. fog.color.setRGB( c[0], c[1], c[2] );
  5519. result.fogs[ df ] = fog;
  5520. }
  5521. // defaults
  5522. if ( result.cameras && data.defaults.camera ) {
  5523. result.currentCamera = result.cameras[ data.defaults.camera ];
  5524. }
  5525. if ( result.fogs && data.defaults.fog ) {
  5526. result.scene.fog = result.fogs[ data.defaults.fog ];
  5527. }
  5528. c = data.defaults.bgcolor;
  5529. result.bgColor = new THREE.Color();
  5530. result.bgColor.setRGB( c[0], c[1], c[2] );
  5531. result.bgColorAlpha = data.defaults.bgalpha;
  5532. // now come potentially asynchronous elements
  5533. // geometries
  5534. // count how many models will be loaded asynchronously
  5535. for( dg in data.geometries ) {
  5536. g = data.geometries[ dg ];
  5537. if ( g.type == "bin_mesh" || g.type == "ascii_mesh" ) {
  5538. counter_models += 1;
  5539. scope.onLoadStart();
  5540. }
  5541. }
  5542. total_models = counter_models;
  5543. for ( dg in data.geometries ) {
  5544. g = data.geometries[ dg ];
  5545. if ( g.type === "cube" ) {
  5546. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.segmentsWidth, g.segmentsHeight, g.segmentsDepth, null, g.flipped, g.sides );
  5547. result.geometries[ dg ] = geometry;
  5548. } else if ( g.type === "plane" ) {
  5549. geometry = new THREE.PlaneGeometry( g.width, g.height, g.segmentsWidth, g.segmentsHeight );
  5550. result.geometries[ dg ] = geometry;
  5551. } else if ( g.type === "sphere" ) {
  5552. geometry = new THREE.SphereGeometry( g.radius, g.segmentsWidth, g.segmentsHeight );
  5553. result.geometries[ dg ] = geometry;
  5554. } else if ( g.type === "cylinder" ) {
  5555. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  5556. result.geometries[ dg ] = geometry;
  5557. } else if ( g.type === "torus" ) {
  5558. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  5559. result.geometries[ dg ] = geometry;
  5560. } else if ( g.type === "icosahedron" ) {
  5561. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  5562. result.geometries[ dg ] = geometry;
  5563. } else if ( g.type === "bin_mesh" ) {
  5564. binLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  5565. } else if ( g.type === "ascii_mesh" ) {
  5566. jsonLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  5567. } else if ( g.type === "embedded_mesh" ) {
  5568. var modelJson = data.embeds[ g.id ],
  5569. texture_path = "";
  5570. // pass metadata along to jsonLoader so it knows the format version
  5571. modelJson.metadata = data.metadata;
  5572. if ( modelJson ) {
  5573. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  5574. }
  5575. }
  5576. }
  5577. // textures
  5578. // count how many textures will be loaded asynchronously
  5579. for( dt in data.textures ) {
  5580. tt = data.textures[ dt ];
  5581. if( tt.url instanceof Array ) {
  5582. counter_textures += tt.url.length;
  5583. for( var n = 0; n < tt.url.length; n ++ ) {
  5584. scope.onLoadStart();
  5585. }
  5586. } else {
  5587. counter_textures += 1;
  5588. scope.onLoadStart();
  5589. }
  5590. }
  5591. total_textures = counter_textures;
  5592. for( dt in data.textures ) {
  5593. tt = data.textures[ dt ];
  5594. if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined ) {
  5595. tt.mapping = new THREE[ tt.mapping ]();
  5596. }
  5597. if( tt.url instanceof Array ) {
  5598. var count = tt.url.length;
  5599. var url_array = [];
  5600. for( var i = 0; i < count; i ++ ) {
  5601. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  5602. }
  5603. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5604. } else {
  5605. texture = THREE.ImageUtils.loadTexture( get_url( tt.url, data.urlBaseType ), tt.mapping, generateTextureCallback( 1 ) );
  5606. if ( THREE[ tt.minFilter ] !== undefined )
  5607. texture.minFilter = THREE[ tt.minFilter ];
  5608. if ( THREE[ tt.magFilter ] !== undefined )
  5609. texture.magFilter = THREE[ tt.magFilter ];
  5610. if ( tt.repeat ) {
  5611. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  5612. if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  5613. if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  5614. }
  5615. if ( tt.offset ) {
  5616. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  5617. }
  5618. // handle wrap after repeat so that default repeat can be overriden
  5619. if ( tt.wrap ) {
  5620. var wrapMap = {
  5621. "repeat" : THREE.RepeatWrapping,
  5622. "mirror" : THREE.MirroredRepeatWrapping
  5623. }
  5624. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  5625. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  5626. }
  5627. }
  5628. result.textures[ dt ] = texture;
  5629. }
  5630. // materials
  5631. for ( dm in data.materials ) {
  5632. m = data.materials[ dm ];
  5633. for ( pp in m.parameters ) {
  5634. if ( pp === "envMap" || pp === "map" || pp === "lightMap" ) {
  5635. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  5636. } else if ( pp === "shading" ) {
  5637. m.parameters[ pp ] = ( m.parameters[ pp ] == "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  5638. } else if ( pp === "blending" ) {
  5639. m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  5640. } else if ( pp === "combine" ) {
  5641. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  5642. } else if ( pp === "vertexColors" ) {
  5643. if ( m.parameters[ pp ] == "face" ) {
  5644. m.parameters[ pp ] = THREE.FaceColors;
  5645. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  5646. } else if ( m.parameters[ pp ] ) {
  5647. m.parameters[ pp ] = THREE.VertexColors;
  5648. }
  5649. }
  5650. }
  5651. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  5652. m.parameters.transparent = true;
  5653. }
  5654. if ( m.parameters.normalMap ) {
  5655. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5656. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5657. var diffuse = m.parameters.color;
  5658. var specular = m.parameters.specular;
  5659. var ambient = m.parameters.ambient;
  5660. var shininess = m.parameters.shininess;
  5661. uniforms[ "tNormal" ].value = result.textures[ m.parameters.normalMap ];
  5662. if ( m.parameters.normalMapFactor ) {
  5663. uniforms[ "uNormalScale" ].value = m.parameters.normalMapFactor;
  5664. }
  5665. if ( m.parameters.map ) {
  5666. uniforms[ "tDiffuse" ].value = m.parameters.map;
  5667. uniforms[ "enableDiffuse" ].value = true;
  5668. }
  5669. if ( m.parameters.lightMap ) {
  5670. uniforms[ "tAO" ].value = m.parameters.lightMap;
  5671. uniforms[ "enableAO" ].value = true;
  5672. }
  5673. if ( m.parameters.specularMap ) {
  5674. uniforms[ "tSpecular" ].value = result.textures[ m.parameters.specularMap ];
  5675. uniforms[ "enableSpecular" ].value = true;
  5676. }
  5677. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  5678. uniforms[ "uSpecularColor" ].value.setHex( specular );
  5679. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  5680. uniforms[ "uShininess" ].value = shininess;
  5681. if ( m.parameters.opacity ) {
  5682. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  5683. }
  5684. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5685. material = new THREE.ShaderMaterial( parameters );
  5686. } else {
  5687. material = new THREE[ m.type ]( m.parameters );
  5688. }
  5689. result.materials[ dm ] = material;
  5690. }
  5691. // objects ( synchronous init of procedural primitives )
  5692. handle_objects();
  5693. // synchronous callback
  5694. scope.callbackSync( result );
  5695. // just in case there are no async elements
  5696. async_callback_gate();
  5697. };
  5698. /**
  5699. * @author mrdoob / http://mrdoob.com/
  5700. */
  5701. THREE.TextureLoader = function () {
  5702. THREE.EventTarget.call( this );
  5703. this.crossOrigin = null;
  5704. };
  5705. THREE.TextureLoader.prototype = {
  5706. constructor: THREE.TextureLoader,
  5707. load: function ( url ) {
  5708. var scope = this;
  5709. var image = new Image();
  5710. image.addEventListener( 'load', function () {
  5711. var texture = new THREE.Texture( image );
  5712. texture.needsUpdate = true;
  5713. scope.dispatchEvent( { type: 'load', content: texture } );
  5714. }, false );
  5715. image.addEventListener( 'error', function () {
  5716. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5717. }, false );
  5718. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5719. image.src = url;
  5720. }
  5721. }
  5722. /**
  5723. * @author mrdoob / http://mrdoob.com/
  5724. * @author alteredq / http://alteredqualia.com/
  5725. */
  5726. THREE.Material = function () {
  5727. this.id = THREE.MaterialCount ++;
  5728. this.name = '';
  5729. this.side = THREE.FrontSide;
  5730. this.opacity = 1;
  5731. this.transparent = false;
  5732. this.blending = THREE.NormalBlending;
  5733. this.blendSrc = THREE.SrcAlphaFactor;
  5734. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  5735. this.blendEquation = THREE.AddEquation;
  5736. this.depthTest = true;
  5737. this.depthWrite = true;
  5738. this.polygonOffset = false;
  5739. this.polygonOffsetFactor = 0;
  5740. this.polygonOffsetUnits = 0;
  5741. this.alphaTest = 0;
  5742. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  5743. this.visible = true;
  5744. this.needsUpdate = true;
  5745. };
  5746. THREE.Material.prototype.setValues = function ( values ) {
  5747. if ( values === undefined ) return;
  5748. for ( var key in values ) {
  5749. var newValue = values[ key ];
  5750. if ( newValue === undefined ) {
  5751. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5752. continue;
  5753. }
  5754. if ( key in this ) {
  5755. var currentValue = this[ key ];
  5756. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  5757. currentValue.copy( newValue );
  5758. } else if ( currentValue instanceof THREE.Color && typeof( newValue ) === "number" ) {
  5759. currentValue.setHex( newValue );
  5760. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  5761. currentValue.copy( newValue );
  5762. } else {
  5763. this[ key ] = newValue;
  5764. }
  5765. }
  5766. }
  5767. };
  5768. THREE.Material.prototype.clone = function ( material ) {
  5769. if ( material === undefined ) material = new THREE.Material();
  5770. material.name = this.name;
  5771. material.side = this.side;
  5772. material.opacity = this.opacity;
  5773. material.transparent = this.transparent;
  5774. material.blending = this.blending;
  5775. material.blendSrc = this.blendSrc;
  5776. material.blendDst = this.blendDst;
  5777. material.blendEquation = this.blendEquation;
  5778. material.depthTest = this.depthTest;
  5779. material.depthWrite = this.depthWrite;
  5780. material.polygonOffset = this.polygonOffset;
  5781. material.polygonOffsetFactor = this.polygonOffsetFactor;
  5782. material.polygonOffsetUnits = this.polygonOffsetUnits;
  5783. material.alphaTest = this.alphaTest;
  5784. material.overdraw = this.overdraw;
  5785. material.visible = this.visible;
  5786. return material;
  5787. };
  5788. THREE.MaterialCount = 0;
  5789. /**
  5790. * @author mrdoob / http://mrdoob.com/
  5791. * @author alteredq / http://alteredqualia.com/
  5792. *
  5793. * parameters = {
  5794. * color: <hex>,
  5795. * opacity: <float>,
  5796. *
  5797. * blending: THREE.NormalBlending,
  5798. * depthTest: <bool>,
  5799. *
  5800. * linewidth: <float>,
  5801. * linecap: "round",
  5802. * linejoin: "round",
  5803. *
  5804. * vertexColors: <bool>
  5805. *
  5806. * fog: <bool>
  5807. * }
  5808. */
  5809. THREE.LineBasicMaterial = function ( parameters ) {
  5810. THREE.Material.call( this );
  5811. this.color = new THREE.Color( 0xffffff );
  5812. this.linewidth = 1;
  5813. this.linecap = 'round';
  5814. this.linejoin = 'round';
  5815. this.vertexColors = false;
  5816. this.fog = true;
  5817. this.setValues( parameters );
  5818. };
  5819. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  5820. THREE.LineBasicMaterial.prototype.clone = function () {
  5821. var material = new THREE.LineBasicMaterial();
  5822. THREE.Material.prototype.clone.call( this, material );
  5823. material.color.copy( this.color );
  5824. material.linewidth = this.linewidth;
  5825. material.linecap = this.linecap;
  5826. material.linejoin = this.linejoin;
  5827. material.vertexColors = this.vertexColors;
  5828. material.fog = this.fog;
  5829. return material;
  5830. };
  5831. /**
  5832. * @author mrdoob / http://mrdoob.com/
  5833. * @author alteredq / http://alteredqualia.com/
  5834. *
  5835. * parameters = {
  5836. * color: <hex>,
  5837. * opacity: <float>,
  5838. * map: new THREE.Texture( <Image> ),
  5839. *
  5840. * lightMap: new THREE.Texture( <Image> ),
  5841. *
  5842. * specularMap: new THREE.Texture( <Image> ),
  5843. *
  5844. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  5845. * combine: THREE.Multiply,
  5846. * reflectivity: <float>,
  5847. * refractionRatio: <float>,
  5848. *
  5849. * shading: THREE.SmoothShading,
  5850. * blending: THREE.NormalBlending,
  5851. * depthTest: <bool>,
  5852. *
  5853. * wireframe: <boolean>,
  5854. * wireframeLinewidth: <float>,
  5855. *
  5856. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  5857. *
  5858. * skinning: <bool>,
  5859. * morphTargets: <bool>,
  5860. *
  5861. * fog: <bool>
  5862. * }
  5863. */
  5864. THREE.MeshBasicMaterial = function ( parameters ) {
  5865. THREE.Material.call( this );
  5866. this.color = new THREE.Color( 0xffffff ); // emissive
  5867. this.map = null;
  5868. this.lightMap = null;
  5869. this.specularMap = null;
  5870. this.envMap = null;
  5871. this.combine = THREE.MultiplyOperation;
  5872. this.reflectivity = 1;
  5873. this.refractionRatio = 0.98;
  5874. this.fog = true;
  5875. this.shading = THREE.SmoothShading;
  5876. this.wireframe = false;
  5877. this.wireframeLinewidth = 1;
  5878. this.wireframeLinecap = 'round';
  5879. this.wireframeLinejoin = 'round';
  5880. this.vertexColors = THREE.NoColors;
  5881. this.skinning = false;
  5882. this.morphTargets = false;
  5883. this.setValues( parameters );
  5884. };
  5885. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  5886. THREE.MeshBasicMaterial.prototype.clone = function () {
  5887. var material = new THREE.MeshBasicMaterial();
  5888. THREE.Material.prototype.clone.call( this, material );
  5889. material.color.copy( this.color );
  5890. material.map = this.map;
  5891. material.lightMap = this.lightMap;
  5892. material.specularMap = this.specularMap;
  5893. material.envMap = this.envMap;
  5894. material.combine = this.combine;
  5895. material.reflectivity = this.reflectivity;
  5896. material.refractionRatio = this.refractionRatio;
  5897. material.fog = this.fog;
  5898. material.shading = this.shading;
  5899. material.wireframe = this.wireframe;
  5900. material.wireframeLinewidth = this.wireframeLinewidth;
  5901. material.wireframeLinecap = this.wireframeLinecap;
  5902. material.wireframeLinejoin = this.wireframeLinejoin;
  5903. material.vertexColors = this.vertexColors;
  5904. material.skinning = this.skinning;
  5905. material.morphTargets = this.morphTargets;
  5906. return material;
  5907. };
  5908. /**
  5909. * @author mrdoob / http://mrdoob.com/
  5910. * @author alteredq / http://alteredqualia.com/
  5911. *
  5912. * parameters = {
  5913. * color: <hex>,
  5914. * ambient: <hex>,
  5915. * emissive: <hex>,
  5916. * opacity: <float>,
  5917. *
  5918. * map: new THREE.Texture( <Image> ),
  5919. *
  5920. * lightMap: new THREE.Texture( <Image> ),
  5921. *
  5922. * specularMap: new THREE.Texture( <Image> ),
  5923. *
  5924. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  5925. * combine: THREE.Multiply,
  5926. * reflectivity: <float>,
  5927. * refractionRatio: <float>,
  5928. *
  5929. * shading: THREE.SmoothShading,
  5930. * blending: THREE.NormalBlending,
  5931. * depthTest: <bool>,
  5932. *
  5933. * wireframe: <boolean>,
  5934. * wireframeLinewidth: <float>,
  5935. *
  5936. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  5937. *
  5938. * skinning: <bool>,
  5939. * morphTargets: <bool>,
  5940. * morphNormals: <bool>,
  5941. *
  5942. * fog: <bool>
  5943. * }
  5944. */
  5945. THREE.MeshLambertMaterial = function ( parameters ) {
  5946. THREE.Material.call( this );
  5947. this.color = new THREE.Color( 0xffffff ); // diffuse
  5948. this.ambient = new THREE.Color( 0xffffff );
  5949. this.emissive = new THREE.Color( 0x000000 );
  5950. this.wrapAround = false;
  5951. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  5952. this.map = null;
  5953. this.lightMap = null;
  5954. this.specularMap = null;
  5955. this.envMap = null;
  5956. this.combine = THREE.MultiplyOperation;
  5957. this.reflectivity = 1;
  5958. this.refractionRatio = 0.98;
  5959. this.fog = true;
  5960. this.shading = THREE.SmoothShading;
  5961. this.wireframe = false;
  5962. this.wireframeLinewidth = 1;
  5963. this.wireframeLinecap = 'round';
  5964. this.wireframeLinejoin = 'round';
  5965. this.vertexColors = THREE.NoColors;
  5966. this.skinning = false;
  5967. this.morphTargets = false;
  5968. this.morphNormals = false;
  5969. this.setValues( parameters );
  5970. };
  5971. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  5972. THREE.MeshLambertMaterial.prototype.clone = function () {
  5973. var material = new THREE.MeshLambertMaterial();
  5974. THREE.Material.prototype.clone.call( this, material );
  5975. material.color.copy( this.color );
  5976. material.ambient.copy( this.ambient );
  5977. material.emissive.copy( this.emissive );
  5978. material.wrapAround = this.wrapAround;
  5979. material.wrapRGB.copy( this.wrapRGB );
  5980. material.map = this.map;
  5981. material.lightMap = this.lightMap;
  5982. material.specularMap = this.specularMap;
  5983. material.envMap = this.envMap;
  5984. material.combine = this.combine;
  5985. material.reflectivity = this.reflectivity;
  5986. material.refractionRatio = this.refractionRatio;
  5987. material.fog = this.fog;
  5988. material.shading = this.shading;
  5989. material.wireframe = this.wireframe;
  5990. material.wireframeLinewidth = this.wireframeLinewidth;
  5991. material.wireframeLinecap = this.wireframeLinecap;
  5992. material.wireframeLinejoin = this.wireframeLinejoin;
  5993. material.vertexColors = this.vertexColors;
  5994. material.skinning = this.skinning;
  5995. material.morphTargets = this.morphTargets;
  5996. material.morphNormals = this.morphNormals;
  5997. return material;
  5998. };
  5999. /**
  6000. * @author mrdoob / http://mrdoob.com/
  6001. * @author alteredq / http://alteredqualia.com/
  6002. *
  6003. * parameters = {
  6004. * color: <hex>,
  6005. * ambient: <hex>,
  6006. * emissive: <hex>,
  6007. * specular: <hex>,
  6008. * shininess: <float>,
  6009. * opacity: <float>,
  6010. *
  6011. * map: new THREE.Texture( <Image> ),
  6012. *
  6013. * lightMap: new THREE.Texture( <Image> ),
  6014. *
  6015. * bumpMap: new THREE.Texture( <Image> ),
  6016. * bumpScale: <float>,
  6017. *
  6018. * specularMap: new THREE.Texture( <Image> ),
  6019. *
  6020. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6021. * combine: THREE.Multiply,
  6022. * reflectivity: <float>,
  6023. * refractionRatio: <float>,
  6024. *
  6025. * shading: THREE.SmoothShading,
  6026. * blending: THREE.NormalBlending,
  6027. * depthTest: <bool>,
  6028. *
  6029. * wireframe: <boolean>,
  6030. * wireframeLinewidth: <float>,
  6031. *
  6032. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6033. *
  6034. * skinning: <bool>,
  6035. * morphTargets: <bool>,
  6036. * morphNormals: <bool>,
  6037. *
  6038. * fog: <bool>
  6039. * }
  6040. */
  6041. THREE.MeshPhongMaterial = function ( parameters ) {
  6042. THREE.Material.call( this );
  6043. this.color = new THREE.Color( 0xffffff ); // diffuse
  6044. this.ambient = new THREE.Color( 0xffffff );
  6045. this.emissive = new THREE.Color( 0x000000 );
  6046. this.specular = new THREE.Color( 0x111111 );
  6047. this.shininess = 30;
  6048. this.metal = false;
  6049. this.perPixel = false;
  6050. this.wrapAround = false;
  6051. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6052. this.map = null;
  6053. this.lightMap = null;
  6054. this.bumpMap = null;
  6055. this.bumpScale = 1;
  6056. this.specularMap = null;
  6057. this.envMap = null;
  6058. this.combine = THREE.MultiplyOperation;
  6059. this.reflectivity = 1;
  6060. this.refractionRatio = 0.98;
  6061. this.fog = true;
  6062. this.shading = THREE.SmoothShading;
  6063. this.wireframe = false;
  6064. this.wireframeLinewidth = 1;
  6065. this.wireframeLinecap = 'round';
  6066. this.wireframeLinejoin = 'round';
  6067. this.vertexColors = THREE.NoColors;
  6068. this.skinning = false;
  6069. this.morphTargets = false;
  6070. this.morphNormals = false;
  6071. this.setValues( parameters );
  6072. };
  6073. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6074. THREE.MeshPhongMaterial.prototype.clone = function () {
  6075. var material = new THREE.MeshPhongMaterial();
  6076. THREE.Material.prototype.clone.call( this, material );
  6077. material.color.copy( this.color );
  6078. material.ambient.copy( this.ambient );
  6079. material.emissive.copy( this.emissive );
  6080. material.specular.copy( this.specular );
  6081. material.shininess = this.shininess;
  6082. material.metal = this.metal;
  6083. material.perPixel = this.perPixel;
  6084. material.wrapAround = this.wrapAround;
  6085. material.wrapRGB.copy( this.wrapRGB );
  6086. material.map = this.map;
  6087. material.lightMap = this.lightMap;
  6088. material.bumpMap = this.bumpMap;
  6089. material.bumpScale= this.bumpScale;
  6090. material.specularMap = this.specularMap;
  6091. material.envMap = this.envMap;
  6092. material.combine = this.combine;
  6093. material.reflectivity = this.reflectivity;
  6094. material.refractionRatio = this.refractionRatio;
  6095. material.fog = this.fog;
  6096. material.shading = this.shading;
  6097. material.wireframe = this.wireframe;
  6098. material.wireframeLinewidth = this.wireframeLinewidth;
  6099. material.wireframeLinecap = this.wireframeLinecap;
  6100. material.wireframeLinejoin = this.wireframeLinejoin;
  6101. material.vertexColors = this.vertexColors;
  6102. material.skinning = this.skinning;
  6103. material.morphTargets = this.morphTargets;
  6104. material.morphNormals = this.morphNormals;
  6105. return material;
  6106. };
  6107. /**
  6108. * @author mrdoob / http://mrdoob.com/
  6109. * @author alteredq / http://alteredqualia.com/
  6110. *
  6111. * parameters = {
  6112. * opacity: <float>,
  6113. * blending: THREE.NormalBlending,
  6114. * depthTest: <bool>,
  6115. * wireframe: <boolean>,
  6116. * wireframeLinewidth: <float>
  6117. * }
  6118. */
  6119. THREE.MeshDepthMaterial = function ( parameters ) {
  6120. THREE.Material.call( this );
  6121. this.wireframe = false;
  6122. this.wireframeLinewidth = 1;
  6123. this.setValues( parameters );
  6124. };
  6125. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6126. THREE.MeshDepthMaterial.prototype.clone = function () {
  6127. var material = new THREE.LineBasicMaterial();
  6128. THREE.Material.prototype.clone.call( this, material );
  6129. material.wireframe = this.wireframe;
  6130. material.wireframeLinewidth = this.wireframeLinewidth;
  6131. return material;
  6132. };
  6133. /**
  6134. * @author mrdoob / http://mrdoob.com/
  6135. *
  6136. * parameters = {
  6137. * opacity: <float>,
  6138. * shading: THREE.FlatShading,
  6139. * blending: THREE.NormalBlending,
  6140. * depthTest: <bool>,
  6141. * wireframe: <boolean>,
  6142. * wireframeLinewidth: <float>
  6143. * }
  6144. */
  6145. THREE.MeshNormalMaterial = function ( parameters ) {
  6146. THREE.Material.call( this, parameters );
  6147. this.shading = THREE.FlatShading;
  6148. this.wireframe = false;
  6149. this.wireframeLinewidth = 1;
  6150. this.setValues( parameters );
  6151. };
  6152. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6153. THREE.MeshNormalMaterial.prototype.clone = function () {
  6154. var material = new THREE.MeshNormalMaterial();
  6155. THREE.Material.prototype.clone.call( this, material );
  6156. material.shading = this.shading;
  6157. material.wireframe = this.wireframe;
  6158. material.wireframeLinewidth = this.wireframeLinewidth;
  6159. return material;
  6160. };
  6161. /**
  6162. * @author mrdoob / http://mrdoob.com/
  6163. */
  6164. THREE.MeshFaceMaterial = function () {};
  6165. THREE.MeshFaceMaterial.prototype.clone = function () {
  6166. return new THREE.MeshFaceMaterial();
  6167. };
  6168. /**
  6169. * @author mrdoob / http://mrdoob.com/
  6170. * @author alteredq / http://alteredqualia.com/
  6171. *
  6172. * parameters = {
  6173. * color: <hex>,
  6174. * opacity: <float>,
  6175. * map: new THREE.Texture( <Image> ),
  6176. *
  6177. * size: <float>,
  6178. *
  6179. * blending: THREE.NormalBlending,
  6180. * depthTest: <bool>,
  6181. *
  6182. * vertexColors: <bool>,
  6183. *
  6184. * fog: <bool>
  6185. * }
  6186. */
  6187. THREE.ParticleBasicMaterial = function ( parameters ) {
  6188. THREE.Material.call( this );
  6189. this.color = new THREE.Color( 0xffffff );
  6190. this.map = null;
  6191. this.size = 1;
  6192. this.sizeAttenuation = true;
  6193. this.vertexColors = false;
  6194. this.fog = true;
  6195. this.setValues( parameters );
  6196. };
  6197. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6198. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6199. var material = new THREE.ParticleBasicMaterial();
  6200. THREE.Material.prototype.clone.call( this, material );
  6201. material.color.copy( this.color );
  6202. material.map = this.map;
  6203. material.size = this.size;
  6204. material.sizeAttenuation = this.sizeAttenuation;
  6205. material.vertexColors = this.vertexColors;
  6206. material.fog = this.fog;
  6207. return material;
  6208. };
  6209. /**
  6210. * @author mrdoob / http://mrdoob.com/
  6211. *
  6212. * parameters = {
  6213. * color: <hex>,
  6214. * program: <function>,
  6215. * opacity: <float>,
  6216. * blending: THREE.NormalBlending
  6217. * }
  6218. */
  6219. THREE.ParticleCanvasMaterial = function ( parameters ) {
  6220. THREE.Material.call( this );
  6221. this.color = new THREE.Color( 0xffffff );
  6222. this.program = function ( context, color ) {};
  6223. this.setValues( parameters );
  6224. };
  6225. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  6226. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  6227. var material = new THREE.ParticleCanvasMaterial();
  6228. THREE.Material.prototype.clone.call( this, material );
  6229. material.color.copy( this.color );
  6230. material.program = this.program;
  6231. return material;
  6232. };
  6233. /**
  6234. * @author mrdoob / http://mrdoob.com/
  6235. */
  6236. THREE.ParticleDOMMaterial = function ( domElement ) {
  6237. this.domElement = domElement;
  6238. };
  6239. THREE.ParticleDOMMaterial.prototype.clone = function(){
  6240. return new THREE.ParticleDOMMaterial( this.domElement );
  6241. };
  6242. /**
  6243. * @author alteredq / http://alteredqualia.com/
  6244. *
  6245. * parameters = {
  6246. * fragmentShader: <string>,
  6247. * vertexShader: <string>,
  6248. *
  6249. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  6250. *
  6251. * shading: THREE.SmoothShading,
  6252. * blending: THREE.NormalBlending,
  6253. * depthTest: <bool>,
  6254. *
  6255. * wireframe: <boolean>,
  6256. * wireframeLinewidth: <float>,
  6257. *
  6258. * lights: <bool>,
  6259. *
  6260. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6261. *
  6262. * skinning: <bool>,
  6263. * morphTargets: <bool>,
  6264. * morphNormals: <bool>,
  6265. *
  6266. * fog: <bool>
  6267. * }
  6268. */
  6269. THREE.ShaderMaterial = function ( parameters ) {
  6270. THREE.Material.call( this );
  6271. this.fragmentShader = "void main() {}";
  6272. this.vertexShader = "void main() {}";
  6273. this.uniforms = {};
  6274. this.attributes = null;
  6275. this.shading = THREE.SmoothShading;
  6276. this.wireframe = false;
  6277. this.wireframeLinewidth = 1;
  6278. this.fog = false; // set to use scene fog
  6279. this.lights = false; // set to use scene lights
  6280. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  6281. this.skinning = false; // set to use skinning attribute streams
  6282. this.morphTargets = false; // set to use morph targets
  6283. this.morphNormals = false; // set to use morph normals
  6284. this.setValues( parameters );
  6285. };
  6286. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  6287. THREE.ShaderMaterial.prototype.clone = function () {
  6288. var material = new THREE.ShaderMaterial();
  6289. THREE.Material.prototype.clone.call( this, material );
  6290. material.fragmentShader = this.fragmentShader;
  6291. material.vertexShader = this.vertexShader;
  6292. material.uniforms = this.uniforms;
  6293. material.attributes = this.attributes;
  6294. material.shading = this.shading;
  6295. material.wireframe = this.wireframe;
  6296. material.wireframeLinewidth = this.wireframeLinewidth;
  6297. material.fog = this.fog;
  6298. material.lights = this.lights;
  6299. material.vertexColors = this.vertexColors;
  6300. material.skinning = this.skinning;
  6301. material.morphTargets = this.morphTargets;
  6302. material.morphNormals = this.morphNormals;
  6303. return material;
  6304. };
  6305. /**
  6306. * @author mrdoob / http://mrdoob.com/
  6307. * @author alteredq / http://alteredqualia.com/
  6308. * @author szimek / https://github.com/szimek/
  6309. */
  6310. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  6311. this.id = THREE.TextureCount ++;
  6312. this.image = image;
  6313. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  6314. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  6315. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  6316. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  6317. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  6318. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6319. this.format = format !== undefined ? format : THREE.RGBAFormat;
  6320. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  6321. this.offset = new THREE.Vector2( 0, 0 );
  6322. this.repeat = new THREE.Vector2( 1, 1 );
  6323. this.generateMipmaps = true;
  6324. this.premultiplyAlpha = false;
  6325. this.flipY = true;
  6326. this.needsUpdate = false;
  6327. this.onUpdate = null;
  6328. };
  6329. THREE.Texture.prototype = {
  6330. constructor: THREE.Texture,
  6331. clone: function () {
  6332. var clonedTexture = new THREE.Texture( this.image, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter, this.format, this.type, this.anisotropy );
  6333. clonedTexture.offset.copy( this.offset );
  6334. clonedTexture.repeat.copy( this.repeat );
  6335. clonedTexture.generateMipmaps = this.generateMipmaps;
  6336. clonedTexture.premultiplyAlpha = this.premultiplyAlpha;
  6337. clonedTexture.flipY = this.flipY;
  6338. return clonedTexture;
  6339. }
  6340. };
  6341. THREE.TextureCount = 0;
  6342. /**
  6343. * @author alteredq / http://alteredqualia.com/
  6344. */
  6345. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6346. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6347. this.image = { data: data, width: width, height: height };
  6348. };
  6349. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  6350. THREE.DataTexture.prototype.clone = function () {
  6351. 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 );
  6352. clonedTexture.offset.copy( this.offset );
  6353. clonedTexture.repeat.copy( this.repeat );
  6354. return clonedTexture;
  6355. };
  6356. /**
  6357. * @author mrdoob / http://mrdoob.com/
  6358. */
  6359. THREE.Particle = function ( material ) {
  6360. THREE.Object3D.call( this );
  6361. this.material = material;
  6362. };
  6363. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  6364. /**
  6365. * @author alteredq / http://alteredqualia.com/
  6366. */
  6367. THREE.ParticleSystem = function ( geometry, material ) {
  6368. THREE.Object3D.call( this );
  6369. this.geometry = geometry;
  6370. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  6371. this.sortParticles = false;
  6372. if ( this.geometry ) {
  6373. // calc bound radius
  6374. if( !this.geometry.boundingSphere ) {
  6375. this.geometry.computeBoundingSphere();
  6376. }
  6377. this.boundRadius = geometry.boundingSphere.radius;
  6378. }
  6379. this.frustumCulled = false;
  6380. };
  6381. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  6382. /**
  6383. * @author mrdoob / http://mrdoob.com/
  6384. */
  6385. THREE.Line = function ( geometry, material, type ) {
  6386. THREE.Object3D.call( this );
  6387. this.geometry = geometry;
  6388. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6389. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  6390. if ( this.geometry ) {
  6391. if ( ! this.geometry.boundingSphere ) {
  6392. this.geometry.computeBoundingSphere();
  6393. }
  6394. }
  6395. };
  6396. THREE.LineStrip = 0;
  6397. THREE.LinePieces = 1;
  6398. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  6399. /**
  6400. * @author mrdoob / http://mrdoob.com/
  6401. * @author alteredq / http://alteredqualia.com/
  6402. * @author mikael emtinger / http://gomo.se/
  6403. */
  6404. THREE.Mesh = function ( geometry, material ) {
  6405. THREE.Object3D.call( this );
  6406. this.geometry = geometry;
  6407. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  6408. if ( this.geometry ) {
  6409. // calc bound radius
  6410. if ( ! this.geometry.boundingSphere ) {
  6411. this.geometry.computeBoundingSphere();
  6412. }
  6413. this.boundRadius = geometry.boundingSphere.radius;
  6414. // setup morph targets
  6415. if( this.geometry.morphTargets.length ) {
  6416. this.morphTargetBase = -1;
  6417. this.morphTargetForcedOrder = [];
  6418. this.morphTargetInfluences = [];
  6419. this.morphTargetDictionary = {};
  6420. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  6421. this.morphTargetInfluences.push( 0 );
  6422. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  6423. }
  6424. }
  6425. }
  6426. }
  6427. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  6428. /*
  6429. * Get Morph Target Index by Name
  6430. */
  6431. THREE.Mesh.prototype.getMorphTargetIndexByName = function( name ) {
  6432. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  6433. return this.morphTargetDictionary[ name ];
  6434. }
  6435. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  6436. return 0;
  6437. }
  6438. /**
  6439. * @author mikael emtinger / http://gomo.se/
  6440. * @author alteredq / http://alteredqualia.com/
  6441. */
  6442. THREE.Bone = function( belongsToSkin ) {
  6443. THREE.Object3D.call( this );
  6444. this.skin = belongsToSkin;
  6445. this.skinMatrix = new THREE.Matrix4();
  6446. };
  6447. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  6448. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  6449. // update local
  6450. if ( this.matrixAutoUpdate ) {
  6451. forceUpdate |= this.updateMatrix();
  6452. }
  6453. // update skin matrix
  6454. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  6455. if( parentSkinMatrix ) {
  6456. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  6457. } else {
  6458. this.skinMatrix.copy( this.matrix );
  6459. }
  6460. this.matrixWorldNeedsUpdate = false;
  6461. forceUpdate = true;
  6462. }
  6463. // update children
  6464. var child, i, l = this.children.length;
  6465. for ( i = 0; i < l; i ++ ) {
  6466. this.children[ i ].update( this.skinMatrix, forceUpdate );
  6467. }
  6468. };
  6469. /**
  6470. * @author mikael emtinger / http://gomo.se/
  6471. * @author alteredq / http://alteredqualia.com/
  6472. */
  6473. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  6474. THREE.Mesh.call( this, geometry, material );
  6475. //
  6476. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  6477. // init bones
  6478. this.identityMatrix = new THREE.Matrix4();
  6479. this.bones = [];
  6480. this.boneMatrices = [];
  6481. var b, bone, gbone, p, q, s;
  6482. if ( this.geometry.bones !== undefined ) {
  6483. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  6484. gbone = this.geometry.bones[ b ];
  6485. p = gbone.pos;
  6486. q = gbone.rotq;
  6487. s = gbone.scl;
  6488. bone = this.addBone();
  6489. bone.name = gbone.name;
  6490. bone.position.set( p[0], p[1], p[2] );
  6491. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  6492. bone.useQuaternion = true;
  6493. if ( s !== undefined ) {
  6494. bone.scale.set( s[0], s[1], s[2] );
  6495. } else {
  6496. bone.scale.set( 1, 1, 1 );
  6497. }
  6498. }
  6499. for ( b = 0; b < this.bones.length; b ++ ) {
  6500. gbone = this.geometry.bones[ b ];
  6501. bone = this.bones[ b ];
  6502. if ( gbone.parent === -1 ) {
  6503. this.add( bone );
  6504. } else {
  6505. this.bones[ gbone.parent ].add( bone );
  6506. }
  6507. }
  6508. //
  6509. var nBones = this.bones.length;
  6510. if ( this.useVertexTexture ) {
  6511. // layout (1 matrix = 4 pixels)
  6512. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  6513. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  6514. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  6515. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  6516. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  6517. var size;
  6518. if ( nBones > 256 )
  6519. size = 64;
  6520. else if ( nBones > 64 )
  6521. size = 32;
  6522. else if ( nBones > 16 )
  6523. size = 16;
  6524. else
  6525. size = 8;
  6526. this.boneTextureWidth = size;
  6527. this.boneTextureHeight = size;
  6528. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  6529. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  6530. this.boneTexture.minFilter = THREE.NearestFilter;
  6531. this.boneTexture.magFilter = THREE.NearestFilter;
  6532. this.boneTexture.generateMipmaps = false;
  6533. this.boneTexture.flipY = false;
  6534. } else {
  6535. this.boneMatrices = new Float32Array( 16 * nBones );
  6536. }
  6537. this.pose();
  6538. }
  6539. };
  6540. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  6541. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  6542. if ( bone === undefined ) {
  6543. bone = new THREE.Bone( this );
  6544. }
  6545. this.bones.push( bone );
  6546. return bone;
  6547. };
  6548. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  6549. this.matrixAutoUpdate && this.updateMatrix();
  6550. // update matrixWorld
  6551. if ( this.matrixWorldNeedsUpdate || force ) {
  6552. if ( this.parent ) {
  6553. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  6554. } else {
  6555. this.matrixWorld.copy( this.matrix );
  6556. }
  6557. this.matrixWorldNeedsUpdate = false;
  6558. force = true;
  6559. }
  6560. // update children
  6561. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6562. var child = this.children[ i ];
  6563. if ( child instanceof THREE.Bone ) {
  6564. child.update( this.identityMatrix, false );
  6565. } else {
  6566. child.updateMatrixWorld( true );
  6567. }
  6568. }
  6569. // make a snapshot of the bones' rest position
  6570. if ( this.boneInverses == undefined ) {
  6571. this.boneInverses = [];
  6572. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6573. var inverse = new THREE.Matrix4();
  6574. inverse.getInverse( this.bones[ b ].skinMatrix );
  6575. this.boneInverses.push( inverse );
  6576. }
  6577. }
  6578. // flatten bone matrices to array
  6579. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6580. // compute the offset between the current and the original transform;
  6581. //TODO: we could get rid of this multiplication step if the skinMatrix
  6582. // was already representing the offset; however, this requires some
  6583. // major changes to the animation system
  6584. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  6585. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  6586. }
  6587. if ( this.useVertexTexture ) {
  6588. this.boneTexture.needsUpdate = true;
  6589. }
  6590. };
  6591. /*
  6592. * Pose
  6593. */
  6594. THREE.SkinnedMesh.prototype.pose = function() {
  6595. this.updateMatrixWorld( true );
  6596. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  6597. // normalize weights
  6598. var sw = this.geometry.skinWeights[ i ];
  6599. var scale = 1.0 / sw.lengthManhattan();
  6600. if ( scale !== Infinity ) {
  6601. sw.multiplyScalar( scale );
  6602. } else {
  6603. sw.set( 1 ); // this will be normalized by the shader anyway
  6604. }
  6605. }
  6606. };
  6607. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  6608. /**
  6609. * @author alteredq / http://alteredqualia.com/
  6610. */
  6611. THREE.MorphAnimMesh = function ( geometry, material ) {
  6612. THREE.Mesh.call( this, geometry, material );
  6613. // API
  6614. this.duration = 1000; // milliseconds
  6615. this.mirroredLoop = false;
  6616. this.time = 0;
  6617. // internals
  6618. this.lastKeyframe = 0;
  6619. this.currentKeyframe = 0;
  6620. this.direction = 1;
  6621. this.directionBackwards = false;
  6622. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  6623. };
  6624. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  6625. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  6626. this.startKeyframe = start;
  6627. this.endKeyframe = end;
  6628. this.length = this.endKeyframe - this.startKeyframe + 1;
  6629. };
  6630. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  6631. this.direction = 1;
  6632. this.directionBackwards = false;
  6633. };
  6634. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  6635. this.direction = -1;
  6636. this.directionBackwards = true;
  6637. };
  6638. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  6639. var geometry = this.geometry;
  6640. if ( ! geometry.animations ) geometry.animations = {};
  6641. var firstAnimation, animations = geometry.animations;
  6642. var pattern = /([a-z]+)(\d+)/;
  6643. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  6644. var morph = geometry.morphTargets[ i ];
  6645. var parts = morph.name.match( pattern );
  6646. if ( parts && parts.length > 1 ) {
  6647. var label = parts[ 1 ];
  6648. var num = parts[ 2 ];
  6649. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  6650. var animation = animations[ label ];
  6651. if ( i < animation.start ) animation.start = i;
  6652. if ( i > animation.end ) animation.end = i;
  6653. if ( ! firstAnimation ) firstAnimation = label;
  6654. }
  6655. }
  6656. geometry.firstAnimation = firstAnimation;
  6657. };
  6658. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  6659. if ( ! this.geometry.animations ) this.geometry.animations = {};
  6660. this.geometry.animations[ label ] = { start: start, end: end };
  6661. };
  6662. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  6663. var animation = this.geometry.animations[ label ];
  6664. if ( animation ) {
  6665. this.setFrameRange( animation.start, animation.end );
  6666. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  6667. this.time = 0;
  6668. } else {
  6669. console.warn( "animation[" + label + "] undefined" );
  6670. }
  6671. };
  6672. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  6673. var frameTime = this.duration / this.length;
  6674. this.time += this.direction * delta;
  6675. if ( this.mirroredLoop ) {
  6676. if ( this.time > this.duration || this.time < 0 ) {
  6677. this.direction *= -1;
  6678. if ( this.time > this.duration ) {
  6679. this.time = this.duration;
  6680. this.directionBackwards = true;
  6681. }
  6682. if ( this.time < 0 ) {
  6683. this.time = 0;
  6684. this.directionBackwards = false;
  6685. }
  6686. }
  6687. } else {
  6688. this.time = this.time % this.duration;
  6689. if ( this.time < 0 ) this.time += this.duration;
  6690. }
  6691. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  6692. if ( keyframe !== this.currentKeyframe ) {
  6693. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  6694. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  6695. this.morphTargetInfluences[ keyframe ] = 0;
  6696. this.lastKeyframe = this.currentKeyframe;
  6697. this.currentKeyframe = keyframe;
  6698. }
  6699. var mix = ( this.time % frameTime ) / frameTime;
  6700. if ( this.directionBackwards ) {
  6701. mix = 1 - mix;
  6702. }
  6703. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  6704. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  6705. };
  6706. /**
  6707. * @author alteredq / http://alteredqualia.com/
  6708. */
  6709. THREE.Ribbon = function ( geometry, material ) {
  6710. THREE.Object3D.call( this );
  6711. this.geometry = geometry;
  6712. this.material = material;
  6713. };
  6714. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  6715. /**
  6716. * @author mikael emtinger / http://gomo.se/
  6717. * @author alteredq / http://alteredqualia.com/
  6718. * @author mrdoob / http://mrdoob.com/
  6719. */
  6720. THREE.LOD = function () {
  6721. THREE.Object3D.call( this );
  6722. this.LODs = [];
  6723. };
  6724. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  6725. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  6726. if ( visibleAtDistance === undefined ) {
  6727. visibleAtDistance = 0;
  6728. }
  6729. visibleAtDistance = Math.abs( visibleAtDistance );
  6730. for ( var l = 0; l < this.LODs.length; l ++ ) {
  6731. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  6732. break;
  6733. }
  6734. }
  6735. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  6736. this.add( object3D );
  6737. };
  6738. THREE.LOD.prototype.update = function ( camera ) {
  6739. if ( this.LODs.length > 1 ) {
  6740. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  6741. var inverse = camera.matrixWorldInverse;
  6742. 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] );
  6743. this.LODs[ 0 ].object3D.visible = true;
  6744. for ( var l = 1; l < this.LODs.length; l ++ ) {
  6745. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  6746. this.LODs[ l - 1 ].object3D.visible = false;
  6747. this.LODs[ l ].object3D.visible = true;
  6748. } else {
  6749. break;
  6750. }
  6751. }
  6752. for( ; l < this.LODs.length; l ++ ) {
  6753. this.LODs[ l ].object3D.visible = false;
  6754. }
  6755. }
  6756. };
  6757. /**
  6758. * @author mikael emtinger / http://gomo.se/
  6759. */
  6760. THREE.Sprite = function ( parameters ) {
  6761. THREE.Object3D.call( this );
  6762. this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  6763. this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();
  6764. this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;
  6765. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  6766. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  6767. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  6768. this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
  6769. this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
  6770. this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
  6771. this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
  6772. this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center;
  6773. this.rotation3d = this.rotation;
  6774. this.rotation = 0;
  6775. this.opacity = 1;
  6776. this.uvOffset = new THREE.Vector2( 0, 0 );
  6777. this.uvScale = new THREE.Vector2( 1, 1 );
  6778. };
  6779. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  6780. /*
  6781. * Custom update matrix
  6782. */
  6783. THREE.Sprite.prototype.updateMatrix = function () {
  6784. this.matrix.setPosition( this.position );
  6785. this.rotation3d.set( 0, 0, this.rotation );
  6786. this.matrix.setRotationFromEuler( this.rotation3d );
  6787. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  6788. this.matrix.scale( this.scale );
  6789. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  6790. }
  6791. this.matrixWorldNeedsUpdate = true;
  6792. };
  6793. /*
  6794. * Alignment
  6795. */
  6796. THREE.SpriteAlignment = {};
  6797. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  6798. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  6799. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  6800. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  6801. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  6802. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  6803. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  6804. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  6805. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  6806. /**
  6807. * @author mrdoob / http://mrdoob.com/
  6808. */
  6809. THREE.Scene = function () {
  6810. THREE.Object3D.call( this );
  6811. this.fog = null;
  6812. this.overrideMaterial = null;
  6813. this.matrixAutoUpdate = false;
  6814. this.__objects = [];
  6815. this.__lights = [];
  6816. this.__objectsAdded = [];
  6817. this.__objectsRemoved = [];
  6818. };
  6819. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  6820. THREE.Scene.prototype.__addObject = function ( object ) {
  6821. if ( object instanceof THREE.Light ) {
  6822. if ( this.__lights.indexOf( object ) === - 1 ) {
  6823. this.__lights.push( object );
  6824. }
  6825. if ( object.target && object.target.parent === undefined ) {
  6826. this.add( object.target );
  6827. }
  6828. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  6829. if ( this.__objects.indexOf( object ) === - 1 ) {
  6830. this.__objects.push( object );
  6831. this.__objectsAdded.push( object );
  6832. // check if previously removed
  6833. var i = this.__objectsRemoved.indexOf( object );
  6834. if ( i !== -1 ) {
  6835. this.__objectsRemoved.splice( i, 1 );
  6836. }
  6837. }
  6838. }
  6839. for ( var c = 0; c < object.children.length; c ++ ) {
  6840. this.__addObject( object.children[ c ] );
  6841. }
  6842. };
  6843. THREE.Scene.prototype.__removeObject = function ( object ) {
  6844. if ( object instanceof THREE.Light ) {
  6845. var i = this.__lights.indexOf( object );
  6846. if ( i !== -1 ) {
  6847. this.__lights.splice( i, 1 );
  6848. }
  6849. } else if ( !( object instanceof THREE.Camera ) ) {
  6850. var i = this.__objects.indexOf( object );
  6851. if( i !== -1 ) {
  6852. this.__objects.splice( i, 1 );
  6853. this.__objectsRemoved.push( object );
  6854. // check if previously added
  6855. var ai = this.__objectsAdded.indexOf( object );
  6856. if ( ai !== -1 ) {
  6857. this.__objectsAdded.splice( ai, 1 );
  6858. }
  6859. }
  6860. }
  6861. for ( var c = 0; c < object.children.length; c ++ ) {
  6862. this.__removeObject( object.children[ c ] );
  6863. }
  6864. };
  6865. /**
  6866. * @author mrdoob / http://mrdoob.com/
  6867. * @author alteredq / http://alteredqualia.com/
  6868. */
  6869. THREE.Fog = function ( hex, near, far ) {
  6870. this.color = new THREE.Color( hex );
  6871. this.near = ( near !== undefined ) ? near : 1;
  6872. this.far = ( far !== undefined ) ? far : 1000;
  6873. };
  6874. /**
  6875. * @author mrdoob / http://mrdoob.com/
  6876. * @author alteredq / http://alteredqualia.com/
  6877. */
  6878. THREE.FogExp2 = function ( hex, density ) {
  6879. this.color = new THREE.Color( hex );
  6880. this.density = ( density !== undefined ) ? density : 0.00025;
  6881. };
  6882. /**
  6883. * @author mrdoob / http://mrdoob.com/
  6884. */
  6885. THREE.CanvasRenderer = function ( parameters ) {
  6886. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  6887. parameters = parameters || {};
  6888. var _this = this,
  6889. _renderData, _elements, _lights,
  6890. _projector = new THREE.Projector(),
  6891. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  6892. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  6893. _context = _canvas.getContext( '2d' ),
  6894. _clearColor = new THREE.Color( 0x000000 ),
  6895. _clearOpacity = 0,
  6896. _contextGlobalAlpha = 1,
  6897. _contextGlobalCompositeOperation = 0,
  6898. _contextStrokeStyle = null,
  6899. _contextFillStyle = null,
  6900. _contextLineWidth = null,
  6901. _contextLineCap = null,
  6902. _contextLineJoin = null,
  6903. _v1, _v2, _v3, _v4,
  6904. _v5 = new THREE.RenderableVertex(),
  6905. _v6 = new THREE.RenderableVertex(),
  6906. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  6907. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  6908. _color = new THREE.Color(),
  6909. _color1 = new THREE.Color(),
  6910. _color2 = new THREE.Color(),
  6911. _color3 = new THREE.Color(),
  6912. _color4 = new THREE.Color(),
  6913. _patterns = [], _imagedatas = [],
  6914. _near, _far,
  6915. _image, _uvs,
  6916. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  6917. _clipRect = new THREE.Rectangle(),
  6918. _clearRect = new THREE.Rectangle(),
  6919. _bboxRect = new THREE.Rectangle(),
  6920. _enableLighting = false,
  6921. _ambientLight = new THREE.Color(),
  6922. _directionalLights = new THREE.Color(),
  6923. _pointLights = new THREE.Color(),
  6924. _pi2 = Math.PI * 2,
  6925. _vector3 = new THREE.Vector3(), // Needed for PointLight
  6926. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  6927. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  6928. _pixelMap = document.createElement( 'canvas' );
  6929. _pixelMap.width = _pixelMap.height = 2;
  6930. _pixelMapContext = _pixelMap.getContext( '2d' );
  6931. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  6932. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  6933. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  6934. _pixelMapData = _pixelMapImage.data;
  6935. _gradientMap = document.createElement( 'canvas' );
  6936. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  6937. _gradientMapContext = _gradientMap.getContext( '2d' );
  6938. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  6939. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  6940. _gradientMapQuality --; // Fix UVs
  6941. this.domElement = _canvas;
  6942. this.autoClear = true;
  6943. this.sortObjects = true;
  6944. this.sortElements = true;
  6945. this.info = {
  6946. render: {
  6947. vertices: 0,
  6948. faces: 0
  6949. }
  6950. }
  6951. this.setSize = function ( width, height ) {
  6952. _canvasWidth = width;
  6953. _canvasHeight = height;
  6954. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  6955. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  6956. _canvas.width = _canvasWidth;
  6957. _canvas.height = _canvasHeight;
  6958. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6959. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6960. _contextGlobalAlpha = 1;
  6961. _contextGlobalCompositeOperation = 0;
  6962. _contextStrokeStyle = null;
  6963. _contextFillStyle = null;
  6964. _contextLineWidth = null;
  6965. _contextLineCap = null;
  6966. _contextLineJoin = null;
  6967. };
  6968. this.setClearColor = function ( color, opacity ) {
  6969. _clearColor.copy( color );
  6970. _clearOpacity = opacity !== undefined ? opacity : 1;
  6971. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6972. };
  6973. this.setClearColorHex = function ( hex, opacity ) {
  6974. _clearColor.setHex( hex );
  6975. _clearOpacity = opacity !== undefined ? opacity : 1;
  6976. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6977. };
  6978. this.clear = function () {
  6979. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  6980. if ( _clearRect.isEmpty() === false ) {
  6981. _clearRect.minSelf( _clipRect );
  6982. _clearRect.inflate( 2 );
  6983. if ( _clearOpacity < 1 ) {
  6984. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  6985. }
  6986. if ( _clearOpacity > 0 ) {
  6987. setBlending( THREE.NormalBlending );
  6988. setOpacity( 1 );
  6989. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  6990. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  6991. }
  6992. _clearRect.empty();
  6993. }
  6994. };
  6995. this.render = function ( scene, camera ) {
  6996. if ( camera instanceof THREE.Camera === false ) {
  6997. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  6998. return;
  6999. }
  7000. var e, el, element, material;
  7001. this.autoClear === true ? this.clear() : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7002. _this.info.render.vertices = 0;
  7003. _this.info.render.faces = 0;
  7004. _renderData = _projector.projectScene( scene, camera, this.sortElements );
  7005. _elements = _renderData.elements;
  7006. _lights = _renderData.lights;
  7007. /* DEBUG
  7008. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7009. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  7010. */
  7011. _enableLighting = _lights.length > 0;
  7012. if ( _enableLighting === true ) {
  7013. calculateLights();
  7014. }
  7015. for ( e = 0, el = _elements.length; e < el; e++ ) {
  7016. element = _elements[ e ];
  7017. material = element.material;
  7018. if ( material === undefined || material.visible === false ) continue;
  7019. _bboxRect.empty();
  7020. if ( element instanceof THREE.RenderableParticle ) {
  7021. _v1 = element;
  7022. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7023. renderParticle( _v1, element, material, scene );
  7024. } else if ( element instanceof THREE.RenderableLine ) {
  7025. _v1 = element.v1; _v2 = element.v2;
  7026. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7027. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7028. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7029. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7030. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7031. renderLine( _v1, _v2, element, material, scene );
  7032. }
  7033. } else if ( element instanceof THREE.RenderableFace3 ) {
  7034. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7035. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7036. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7037. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7038. if ( material.overdraw === true ) {
  7039. expand( _v1.positionScreen, _v2.positionScreen );
  7040. expand( _v2.positionScreen, _v3.positionScreen );
  7041. expand( _v3.positionScreen, _v1.positionScreen );
  7042. }
  7043. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  7044. _v2.positionScreen.x, _v2.positionScreen.y,
  7045. _v3.positionScreen.x, _v3.positionScreen.y );
  7046. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7047. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7048. }
  7049. } else if ( element instanceof THREE.RenderableFace4 ) {
  7050. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7051. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7052. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7053. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7054. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7055. _v5.positionScreen.copy( _v2.positionScreen );
  7056. _v6.positionScreen.copy( _v4.positionScreen );
  7057. if ( material.overdraw === true ) {
  7058. expand( _v1.positionScreen, _v2.positionScreen );
  7059. expand( _v2.positionScreen, _v4.positionScreen );
  7060. expand( _v4.positionScreen, _v1.positionScreen );
  7061. expand( _v3.positionScreen, _v5.positionScreen );
  7062. expand( _v3.positionScreen, _v6.positionScreen );
  7063. }
  7064. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7065. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7066. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  7067. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  7068. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7069. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  7070. }
  7071. }
  7072. /* DEBUG
  7073. _context.lineWidth = 1;
  7074. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  7075. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  7076. */
  7077. _clearRect.addRectangle( _bboxRect );
  7078. }
  7079. /* DEBUG
  7080. _context.lineWidth = 1;
  7081. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  7082. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  7083. */
  7084. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  7085. //
  7086. function calculateLights() {
  7087. _ambientLight.setRGB( 0, 0, 0 );
  7088. _directionalLights.setRGB( 0, 0, 0 );
  7089. _pointLights.setRGB( 0, 0, 0 );
  7090. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7091. var light = _lights[ l ];
  7092. var lightColor = light.color;
  7093. if ( light instanceof THREE.AmbientLight ) {
  7094. _ambientLight.r += lightColor.r;
  7095. _ambientLight.g += lightColor.g;
  7096. _ambientLight.b += lightColor.b;
  7097. } else if ( light instanceof THREE.DirectionalLight ) {
  7098. // for particles
  7099. _directionalLights.r += lightColor.r;
  7100. _directionalLights.g += lightColor.g;
  7101. _directionalLights.b += lightColor.b;
  7102. } else if ( light instanceof THREE.PointLight ) {
  7103. // for particles
  7104. _pointLights.r += lightColor.r;
  7105. _pointLights.g += lightColor.g;
  7106. _pointLights.b += lightColor.b;
  7107. }
  7108. }
  7109. }
  7110. function calculateLight( position, normal, color ) {
  7111. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7112. var light = _lights[ l ];
  7113. var lightColor = light.color;
  7114. if ( light instanceof THREE.DirectionalLight ) {
  7115. var lightPosition = light.matrixWorld.getPosition().normalize();
  7116. var amount = normal.dot( lightPosition );
  7117. if ( amount <= 0 ) continue;
  7118. amount *= light.intensity;
  7119. color.r += lightColor.r * amount;
  7120. color.g += lightColor.g * amount;
  7121. color.b += lightColor.b * amount;
  7122. } else if ( light instanceof THREE.PointLight ) {
  7123. var lightPosition = light.matrixWorld.getPosition();
  7124. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  7125. if ( amount <= 0 ) continue;
  7126. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  7127. if ( amount == 0 ) continue;
  7128. amount *= light.intensity;
  7129. color.r += lightColor.r * amount;
  7130. color.g += lightColor.g * amount;
  7131. color.b += lightColor.b * amount;
  7132. }
  7133. }
  7134. }
  7135. function renderParticle( v1, element, material, scene ) {
  7136. setOpacity( material.opacity );
  7137. setBlending( material.blending );
  7138. var width, height, scaleX, scaleY,
  7139. bitmap, bitmapWidth, bitmapHeight;
  7140. if ( material instanceof THREE.ParticleBasicMaterial ) {
  7141. if ( material.map === null ) {
  7142. scaleX = element.object.scale.x;
  7143. scaleY = element.object.scale.y;
  7144. // TODO: Be able to disable this
  7145. scaleX *= element.scale.x * _canvasWidthHalf;
  7146. scaleY *= element.scale.y * _canvasHeightHalf;
  7147. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  7148. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7149. return;
  7150. }
  7151. setFillStyle( material.color.getContextStyle() );
  7152. _context.save();
  7153. _context.translate( v1.x, v1.y );
  7154. _context.rotate( - element.rotation );
  7155. _context.scale( scaleX, scaleY );
  7156. _context.fillRect( -1, -1, 2, 2 );
  7157. _context.restore();
  7158. } else {
  7159. bitmap = material.map.image;
  7160. bitmapWidth = bitmap.width >> 1;
  7161. bitmapHeight = bitmap.height >> 1;
  7162. scaleX = element.scale.x * _canvasWidthHalf;
  7163. scaleY = element.scale.y * _canvasHeightHalf;
  7164. width = scaleX * bitmapWidth;
  7165. height = scaleY * bitmapHeight;
  7166. // TODO: Rotations break this...
  7167. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7168. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7169. return;
  7170. }
  7171. _context.save();
  7172. _context.translate( v1.x, v1.y );
  7173. _context.rotate( - element.rotation );
  7174. _context.scale( scaleX, - scaleY );
  7175. _context.translate( - bitmapWidth, - bitmapHeight );
  7176. _context.drawImage( bitmap, 0, 0 );
  7177. _context.restore();
  7178. }
  7179. /* DEBUG
  7180. setStrokeStyle( 'rgb(255,255,0)' );
  7181. _context.beginPath();
  7182. _context.moveTo( v1.x - 10, v1.y );
  7183. _context.lineTo( v1.x + 10, v1.y );
  7184. _context.moveTo( v1.x, v1.y - 10 );
  7185. _context.lineTo( v1.x, v1.y + 10 );
  7186. _context.stroke();
  7187. */
  7188. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  7189. width = element.scale.x * _canvasWidthHalf;
  7190. height = element.scale.y * _canvasHeightHalf;
  7191. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7192. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7193. return;
  7194. }
  7195. setStrokeStyle( material.color.getContextStyle() );
  7196. setFillStyle( material.color.getContextStyle() );
  7197. _context.save();
  7198. _context.translate( v1.x, v1.y );
  7199. _context.rotate( - element.rotation );
  7200. _context.scale( width, height );
  7201. material.program( _context );
  7202. _context.restore();
  7203. }
  7204. }
  7205. function renderLine( v1, v2, element, material, scene ) {
  7206. setOpacity( material.opacity );
  7207. setBlending( material.blending );
  7208. _context.beginPath();
  7209. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  7210. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  7211. if ( material instanceof THREE.LineBasicMaterial ) {
  7212. setLineWidth( material.linewidth );
  7213. setLineCap( material.linecap );
  7214. setLineJoin( material.linejoin );
  7215. setStrokeStyle( material.color.getContextStyle() );
  7216. _context.stroke();
  7217. _bboxRect.inflate( material.linewidth * 2 );
  7218. }
  7219. }
  7220. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  7221. _this.info.render.vertices += 3;
  7222. _this.info.render.faces ++;
  7223. setOpacity( material.opacity );
  7224. setBlending( material.blending );
  7225. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7226. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7227. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7228. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  7229. if ( material instanceof THREE.MeshBasicMaterial ) {
  7230. if ( material.map !== null ) {
  7231. if ( material.map.mapping instanceof THREE.UVMapping ) {
  7232. _uvs = element.uvs[ 0 ];
  7233. 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 );
  7234. }
  7235. } else if ( material.envMap !== null ) {
  7236. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  7237. var cameraMatrix = camera.matrixWorldInverse;
  7238. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  7239. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7240. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7241. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  7242. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7243. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7244. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  7245. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7246. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7247. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  7248. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  7249. }*/
  7250. } else {
  7251. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7252. }
  7253. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  7254. if ( _enableLighting === true ) {
  7255. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  7256. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  7257. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  7258. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  7259. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7260. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7261. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  7262. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  7263. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  7264. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  7265. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  7266. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  7267. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  7268. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  7269. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  7270. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  7271. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7272. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7273. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7274. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7275. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7276. } else {
  7277. _color.r = _ambientLight.r;
  7278. _color.g = _ambientLight.g;
  7279. _color.b = _ambientLight.b;
  7280. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7281. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  7282. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  7283. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  7284. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7285. }
  7286. } else {
  7287. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7288. }
  7289. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7290. _near = camera.near;
  7291. _far = camera.far;
  7292. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7293. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7294. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7295. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7296. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7297. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7298. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7299. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7300. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7301. _color.r = normalToComponent( element.normalWorld.x );
  7302. _color.g = normalToComponent( element.normalWorld.y );
  7303. _color.b = normalToComponent( element.normalWorld.z );
  7304. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7305. }
  7306. }
  7307. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  7308. _this.info.render.vertices += 4;
  7309. _this.info.render.faces ++;
  7310. setOpacity( material.opacity );
  7311. setBlending( material.blending );
  7312. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  7313. // Let renderFace3() handle this
  7314. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  7315. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  7316. return;
  7317. }
  7318. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7319. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7320. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7321. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  7322. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  7323. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  7324. if ( material instanceof THREE.MeshBasicMaterial ) {
  7325. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7326. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7327. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  7328. if ( _enableLighting === true ) {
  7329. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  7330. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  7331. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  7332. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  7333. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7334. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7335. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  7336. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  7337. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  7338. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  7339. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  7340. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  7341. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  7342. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  7343. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  7344. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  7345. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  7346. _color4.r = Math.max( 0, Math.min( material.color.r * _color4.r, 1 ) );
  7347. _color4.g = Math.max( 0, Math.min( material.color.g * _color4.g, 1 ) );
  7348. _color4.b = Math.max( 0, Math.min( material.color.b * _color4.b, 1 ) );
  7349. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7350. // TODO: UVs are incorrect, v4->v3?
  7351. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7352. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7353. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7354. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7355. } else {
  7356. _color.r = _ambientLight.r;
  7357. _color.g = _ambientLight.g;
  7358. _color.b = _ambientLight.b;
  7359. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7360. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  7361. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  7362. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  7363. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7364. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7365. }
  7366. } else {
  7367. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7368. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7369. }
  7370. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7371. _color.r = normalToComponent( element.normalWorld.x );
  7372. _color.g = normalToComponent( element.normalWorld.y );
  7373. _color.b = normalToComponent( element.normalWorld.z );
  7374. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7375. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7376. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7377. _near = camera.near;
  7378. _far = camera.far;
  7379. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7380. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7381. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  7382. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7383. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7384. // TODO: UVs are incorrect, v4->v3?
  7385. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7386. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7387. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7388. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7389. }
  7390. }
  7391. //
  7392. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  7393. _context.beginPath();
  7394. _context.moveTo( x0, y0 );
  7395. _context.lineTo( x1, y1 );
  7396. _context.lineTo( x2, y2 );
  7397. _context.closePath();
  7398. }
  7399. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  7400. _context.beginPath();
  7401. _context.moveTo( x0, y0 );
  7402. _context.lineTo( x1, y1 );
  7403. _context.lineTo( x2, y2 );
  7404. _context.lineTo( x3, y3 );
  7405. _context.closePath();
  7406. }
  7407. function strokePath( color, linewidth, linecap, linejoin ) {
  7408. setLineWidth( linewidth );
  7409. setLineCap( linecap );
  7410. setLineJoin( linejoin );
  7411. setStrokeStyle( color.getContextStyle() );
  7412. _context.stroke();
  7413. _bboxRect.inflate( linewidth * 2 );
  7414. }
  7415. function fillPath( color ) {
  7416. setFillStyle( color.getContextStyle() );
  7417. _context.fill();
  7418. }
  7419. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  7420. if ( texture.image === undefined || texture.image.width === 0 ) return;
  7421. if ( texture.needsUpdate === true || _patterns[ texture.id ] === undefined ) {
  7422. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  7423. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  7424. _patterns[ texture.id ] = _context.createPattern( texture.image, repeatX === true && repeatY === true ? 'repeat' : repeatX === true && repeatY === false ? 'repeat-x' : repeatX === false && repeatY === true ? 'repeat-y' : 'no-repeat' );
  7425. texture.needsUpdate = false;
  7426. }
  7427. setFillStyle( _patterns[ texture.id ] );
  7428. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7429. var a, b, c, d, e, f, det, idet,
  7430. offsetX = texture.offset.x / texture.repeat.x,
  7431. offsetY = texture.offset.y / texture.repeat.y,
  7432. width = texture.image.width * texture.repeat.x,
  7433. height = texture.image.height * texture.repeat.y;
  7434. u0 = ( u0 + offsetX ) * width;
  7435. v0 = ( 1.0 - v0 + offsetY ) * height;
  7436. u1 = ( u1 + offsetX ) * width;
  7437. v1 = ( 1.0 - v1 + offsetY ) * height;
  7438. u2 = ( u2 + offsetX ) * width;
  7439. v2 = ( 1.0 - v2 + offsetY ) * height;
  7440. x1 -= x0; y1 -= y0;
  7441. x2 -= x0; y2 -= y0;
  7442. u1 -= u0; v1 -= v0;
  7443. u2 -= u0; v2 -= v0;
  7444. det = u1 * v2 - u2 * v1;
  7445. if ( det === 0 ) {
  7446. if ( _imagedatas[ texture.id ] === undefined ) {
  7447. var canvas = document.createElement( 'canvas' )
  7448. canvas.width = texture.image.width;
  7449. canvas.height = texture.image.height;
  7450. var context = canvas.getContext( '2d' );
  7451. context.drawImage( texture.image, 0, 0 );
  7452. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  7453. }
  7454. var data = _imagedatas[ texture.id ];
  7455. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  7456. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  7457. fillPath( _color );
  7458. return;
  7459. }
  7460. idet = 1 / det;
  7461. a = ( v2 * x1 - v1 * x2 ) * idet;
  7462. b = ( v2 * y1 - v1 * y2 ) * idet;
  7463. c = ( u1 * x2 - u2 * x1 ) * idet;
  7464. d = ( u1 * y2 - u2 * y1 ) * idet;
  7465. e = x0 - a * u0 - c * v0;
  7466. f = y0 - b * u0 - d * v0;
  7467. _context.save();
  7468. _context.transform( a, b, c, d, e, f );
  7469. _context.fill();
  7470. _context.restore();
  7471. }
  7472. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  7473. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7474. var a, b, c, d, e, f, det, idet,
  7475. width = image.width - 1,
  7476. height = image.height - 1;
  7477. u0 *= width; v0 *= height;
  7478. u1 *= width; v1 *= height;
  7479. u2 *= width; v2 *= height;
  7480. x1 -= x0; y1 -= y0;
  7481. x2 -= x0; y2 -= y0;
  7482. u1 -= u0; v1 -= v0;
  7483. u2 -= u0; v2 -= v0;
  7484. det = u1 * v2 - u2 * v1;
  7485. idet = 1 / det;
  7486. a = ( v2 * x1 - v1 * x2 ) * idet;
  7487. b = ( v2 * y1 - v1 * y2 ) * idet;
  7488. c = ( u1 * x2 - u2 * x1 ) * idet;
  7489. d = ( u1 * y2 - u2 * y1 ) * idet;
  7490. e = x0 - a * u0 - c * v0;
  7491. f = y0 - b * u0 - d * v0;
  7492. _context.save();
  7493. _context.transform( a, b, c, d, e, f );
  7494. _context.clip();
  7495. _context.drawImage( image, 0, 0 );
  7496. _context.restore();
  7497. }
  7498. function getGradientTexture( color1, color2, color3, color4 ) {
  7499. // http://mrdoob.com/blog/post/710
  7500. var c1r = ( color1.r * 255 ) | 0, c1g = ( color1.g * 255 ) | 0, c1b = ( color1.b * 255 ) | 0;
  7501. var c2r = ( color2.r * 255 ) | 0, c2g = ( color2.g * 255 ) | 0, c2b = ( color2.b * 255 ) | 0;
  7502. var c3r = ( color3.r * 255 ) | 0, c3g = ( color3.g * 255 ) | 0, c3b = ( color3.b * 255 ) | 0;
  7503. var c4r = ( color4.r * 255 ) | 0, c4g = ( color4.g * 255 ) | 0, c4b = ( color4.b * 255 ) | 0;
  7504. _pixelMapData[ 0 ] = c1r < 0 ? 0 : c1r > 255 ? 255 : c1r;
  7505. _pixelMapData[ 1 ] = c1g < 0 ? 0 : c1g > 255 ? 255 : c1g;
  7506. _pixelMapData[ 2 ] = c1b < 0 ? 0 : c1b > 255 ? 255 : c1b;
  7507. _pixelMapData[ 4 ] = c2r < 0 ? 0 : c2r > 255 ? 255 : c2r;
  7508. _pixelMapData[ 5 ] = c2g < 0 ? 0 : c2g > 255 ? 255 : c2g;
  7509. _pixelMapData[ 6 ] = c2b < 0 ? 0 : c2b > 255 ? 255 : c2b;
  7510. _pixelMapData[ 8 ] = c3r < 0 ? 0 : c3r > 255 ? 255 : c3r;
  7511. _pixelMapData[ 9 ] = c3g < 0 ? 0 : c3g > 255 ? 255 : c3g;
  7512. _pixelMapData[ 10 ] = c3b < 0 ? 0 : c3b > 255 ? 255 : c3b;
  7513. _pixelMapData[ 12 ] = c4r < 0 ? 0 : c4r > 255 ? 255 : c4r;
  7514. _pixelMapData[ 13 ] = c4g < 0 ? 0 : c4g > 255 ? 255 : c4g;
  7515. _pixelMapData[ 14 ] = c4b < 0 ? 0 : c4b > 255 ? 255 : c4b;
  7516. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  7517. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  7518. return _gradientMap;
  7519. }
  7520. function smoothstep( value, min, max ) {
  7521. var x = ( value - min ) / ( max - min );
  7522. return x * x * ( 3 - 2 * x );
  7523. }
  7524. function normalToComponent( normal ) {
  7525. var component = ( normal + 1 ) * 0.5;
  7526. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  7527. }
  7528. // Hide anti-alias gaps
  7529. function expand( v1, v2 ) {
  7530. var x = v2.x - v1.x, y = v2.y - v1.y,
  7531. det = x * x + y * y, idet;
  7532. if ( det === 0 ) return;
  7533. idet = 1 / Math.sqrt( det );
  7534. x *= idet; y *= idet;
  7535. v2.x += x; v2.y += y;
  7536. v1.x -= x; v1.y -= y;
  7537. }
  7538. };
  7539. // Context cached methods.
  7540. function setOpacity( value ) {
  7541. if ( _contextGlobalAlpha !== value ) {
  7542. _context.globalAlpha = value;
  7543. _contextGlobalAlpha = value;
  7544. }
  7545. }
  7546. function setBlending( value ) {
  7547. if ( _contextGlobalCompositeOperation !== value ) {
  7548. if ( value === THREE.NormalBlending ) {
  7549. _context.globalCompositeOperation = 'source-over';
  7550. } else if ( value === THREE.AdditiveBlending ) {
  7551. _context.globalCompositeOperation = 'lighter';
  7552. } else if ( value === THREE.SubtractiveBlending ) {
  7553. _context.globalCompositeOperation = 'darker';
  7554. }
  7555. _contextGlobalCompositeOperation = value;
  7556. }
  7557. }
  7558. function setLineWidth( value ) {
  7559. if ( _contextLineWidth !== value ) {
  7560. _context.lineWidth = value;
  7561. _contextLineWidth = value;
  7562. }
  7563. }
  7564. function setLineCap( value ) {
  7565. // "butt", "round", "square"
  7566. if ( _contextLineCap !== value ) {
  7567. _context.lineCap = value;
  7568. _contextLineCap = value;
  7569. }
  7570. }
  7571. function setLineJoin( value ) {
  7572. // "round", "bevel", "miter"
  7573. if ( _contextLineJoin !== value ) {
  7574. _context.lineJoin = value;
  7575. _contextLineJoin = value;
  7576. }
  7577. }
  7578. function setStrokeStyle( value ) {
  7579. if ( _contextStrokeStyle !== value ) {
  7580. _context.strokeStyle = value;
  7581. _contextStrokeStyle = value;
  7582. }
  7583. }
  7584. function setFillStyle( value ) {
  7585. if ( _contextFillStyle !== value ) {
  7586. _context.fillStyle = value;
  7587. _contextFillStyle = value;
  7588. }
  7589. }
  7590. };
  7591. /**
  7592. * @author alteredq / http://alteredqualia.com/
  7593. * @author mrdoob / http://mrdoob.com/
  7594. * @author mikael emtinger / http://gomo.se/
  7595. */
  7596. THREE.ShaderChunk = {
  7597. // FOG
  7598. fog_pars_fragment: [
  7599. "#ifdef USE_FOG",
  7600. "uniform vec3 fogColor;",
  7601. "#ifdef FOG_EXP2",
  7602. "uniform float fogDensity;",
  7603. "#else",
  7604. "uniform float fogNear;",
  7605. "uniform float fogFar;",
  7606. "#endif",
  7607. "#endif"
  7608. ].join("\n"),
  7609. fog_fragment: [
  7610. "#ifdef USE_FOG",
  7611. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  7612. "#ifdef FOG_EXP2",
  7613. "const float LOG2 = 1.442695;",
  7614. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  7615. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  7616. "#else",
  7617. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  7618. "#endif",
  7619. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  7620. "#endif"
  7621. ].join("\n"),
  7622. // ENVIRONMENT MAP
  7623. envmap_pars_fragment: [
  7624. "#ifdef USE_ENVMAP",
  7625. "uniform float reflectivity;",
  7626. "uniform samplerCube envMap;",
  7627. "uniform float flipEnvMap;",
  7628. "uniform int combine;",
  7629. "#ifdef USE_BUMPMAP",
  7630. "uniform bool useRefract;",
  7631. "uniform float refractionRatio;",
  7632. "#else",
  7633. "varying vec3 vReflect;",
  7634. "#endif",
  7635. "#endif"
  7636. ].join("\n"),
  7637. envmap_fragment: [
  7638. "#ifdef USE_ENVMAP",
  7639. "vec3 reflectVec;",
  7640. "#ifdef USE_BUMPMAP",
  7641. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  7642. "if ( useRefract ) {",
  7643. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  7644. "} else { ",
  7645. "reflectVec = reflect( cameraToVertex, normal );",
  7646. "}",
  7647. "#else",
  7648. "reflectVec = vReflect;",
  7649. "#endif",
  7650. "#ifdef DOUBLE_SIDED",
  7651. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  7652. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  7653. "#else",
  7654. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  7655. "#endif",
  7656. "#ifdef GAMMA_INPUT",
  7657. "cubeColor.xyz *= cubeColor.xyz;",
  7658. "#endif",
  7659. "if ( combine == 1 ) {",
  7660. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  7661. "} else {",
  7662. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  7663. "}",
  7664. "#endif"
  7665. ].join("\n"),
  7666. envmap_pars_vertex: [
  7667. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP )",
  7668. "varying vec3 vReflect;",
  7669. "uniform float refractionRatio;",
  7670. "uniform bool useRefract;",
  7671. "#endif"
  7672. ].join("\n"),
  7673. worldpos_vertex : [
  7674. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  7675. "#ifdef USE_SKINNING",
  7676. "vec4 mPosition = modelMatrix * skinned;",
  7677. "#endif",
  7678. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  7679. "vec4 mPosition = modelMatrix * vec4( morphed, 1.0 );",
  7680. "#endif",
  7681. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  7682. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  7683. "#endif",
  7684. "#endif"
  7685. ].join("\n"),
  7686. envmap_vertex : [
  7687. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP )",
  7688. "vec3 nWorld = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  7689. "if ( useRefract ) {",
  7690. "vReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refractionRatio );",
  7691. "} else {",
  7692. "vReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );",
  7693. "}",
  7694. "#endif"
  7695. ].join("\n"),
  7696. // COLOR MAP (particles)
  7697. map_particle_pars_fragment: [
  7698. "#ifdef USE_MAP",
  7699. "uniform sampler2D map;",
  7700. "#endif"
  7701. ].join("\n"),
  7702. map_particle_fragment: [
  7703. "#ifdef USE_MAP",
  7704. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  7705. "#endif"
  7706. ].join("\n"),
  7707. // COLOR MAP (triangles)
  7708. map_pars_vertex: [
  7709. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_SPECULARMAP )",
  7710. "varying vec2 vUv;",
  7711. "uniform vec4 offsetRepeat;",
  7712. "#endif"
  7713. ].join("\n"),
  7714. map_pars_fragment: [
  7715. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_SPECULARMAP )",
  7716. "varying vec2 vUv;",
  7717. "#endif",
  7718. "#ifdef USE_MAP",
  7719. "uniform sampler2D map;",
  7720. "#endif",
  7721. ].join("\n"),
  7722. map_vertex: [
  7723. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_SPECULARMAP )",
  7724. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  7725. "#endif"
  7726. ].join("\n"),
  7727. map_fragment: [
  7728. "#ifdef USE_MAP",
  7729. "#ifdef GAMMA_INPUT",
  7730. "vec4 texelColor = texture2D( map, vUv );",
  7731. "texelColor.xyz *= texelColor.xyz;",
  7732. "gl_FragColor = gl_FragColor * texelColor;",
  7733. "#else",
  7734. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  7735. "#endif",
  7736. "#endif"
  7737. ].join("\n"),
  7738. // LIGHT MAP
  7739. lightmap_pars_fragment: [
  7740. "#ifdef USE_LIGHTMAP",
  7741. "varying vec2 vUv2;",
  7742. "uniform sampler2D lightMap;",
  7743. "#endif"
  7744. ].join("\n"),
  7745. lightmap_pars_vertex: [
  7746. "#ifdef USE_LIGHTMAP",
  7747. "varying vec2 vUv2;",
  7748. "#endif"
  7749. ].join("\n"),
  7750. lightmap_fragment: [
  7751. "#ifdef USE_LIGHTMAP",
  7752. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  7753. "#endif"
  7754. ].join("\n"),
  7755. lightmap_vertex: [
  7756. "#ifdef USE_LIGHTMAP",
  7757. "vUv2 = uv2;",
  7758. "#endif"
  7759. ].join("\n"),
  7760. // BUMP MAP
  7761. bumpmap_pars_fragment: [
  7762. "#ifdef USE_BUMPMAP",
  7763. "uniform sampler2D bumpMap;",
  7764. "uniform float bumpScale;",
  7765. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  7766. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  7767. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  7768. "vec2 dHdxy_fwd() {",
  7769. "vec2 dSTdx = dFdx( vUv );",
  7770. "vec2 dSTdy = dFdy( vUv );",
  7771. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  7772. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  7773. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  7774. "return vec2( dBx, dBy );",
  7775. "}",
  7776. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  7777. "vec3 vSigmaX = dFdx( surf_pos );",
  7778. "vec3 vSigmaY = dFdy( surf_pos );",
  7779. "vec3 vN = surf_norm;", // normalized
  7780. "vec3 R1 = cross( vSigmaY, vN );",
  7781. "vec3 R2 = cross( vN, vSigmaX );",
  7782. "float fDet = dot( vSigmaX, R1 );",
  7783. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  7784. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  7785. "}",
  7786. "#endif"
  7787. ].join("\n"),
  7788. // SPECULAR MAP
  7789. specularmap_pars_fragment: [
  7790. "#ifdef USE_SPECULARMAP",
  7791. "uniform sampler2D specularMap;",
  7792. "#endif"
  7793. ].join("\n"),
  7794. specularmap_fragment: [
  7795. "float specularStrength;",
  7796. "#ifdef USE_SPECULARMAP",
  7797. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  7798. "specularStrength = texelSpecular.r;",
  7799. "#else",
  7800. "specularStrength = 1.0;",
  7801. "#endif"
  7802. ].join("\n"),
  7803. // LIGHTS LAMBERT
  7804. lights_lambert_pars_vertex: [
  7805. "uniform vec3 ambient;",
  7806. "uniform vec3 diffuse;",
  7807. "uniform vec3 emissive;",
  7808. "uniform vec3 ambientLightColor;",
  7809. "#if MAX_DIR_LIGHTS > 0",
  7810. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  7811. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  7812. "#endif",
  7813. "#if MAX_POINT_LIGHTS > 0",
  7814. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  7815. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  7816. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  7817. "#endif",
  7818. "#if MAX_SPOT_LIGHTS > 0",
  7819. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  7820. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  7821. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  7822. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  7823. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  7824. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  7825. "#endif",
  7826. "#ifdef WRAP_AROUND",
  7827. "uniform vec3 wrapRGB;",
  7828. "#endif"
  7829. ].join("\n"),
  7830. lights_lambert_vertex: [
  7831. "vLightFront = vec3( 0.0 );",
  7832. "#ifdef DOUBLE_SIDED",
  7833. "vLightBack = vec3( 0.0 );",
  7834. "#endif",
  7835. "transformedNormal = normalize( transformedNormal );",
  7836. "#if MAX_DIR_LIGHTS > 0",
  7837. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  7838. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  7839. "vec3 dirVector = normalize( lDirection.xyz );",
  7840. "float dotProduct = dot( transformedNormal, dirVector );",
  7841. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  7842. "#ifdef DOUBLE_SIDED",
  7843. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  7844. "#ifdef WRAP_AROUND",
  7845. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  7846. "#endif",
  7847. "#endif",
  7848. "#ifdef WRAP_AROUND",
  7849. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  7850. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  7851. "#ifdef DOUBLE_SIDED",
  7852. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  7853. "#endif",
  7854. "#endif",
  7855. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  7856. "#ifdef DOUBLE_SIDED",
  7857. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  7858. "#endif",
  7859. "}",
  7860. "#endif",
  7861. "#if MAX_POINT_LIGHTS > 0",
  7862. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  7863. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  7864. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7865. "float lDistance = 1.0;",
  7866. "if ( pointLightDistance[ i ] > 0.0 )",
  7867. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  7868. "lVector = normalize( lVector );",
  7869. "float dotProduct = dot( transformedNormal, lVector );",
  7870. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  7871. "#ifdef DOUBLE_SIDED",
  7872. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  7873. "#ifdef WRAP_AROUND",
  7874. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  7875. "#endif",
  7876. "#endif",
  7877. "#ifdef WRAP_AROUND",
  7878. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  7879. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  7880. "#ifdef DOUBLE_SIDED",
  7881. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  7882. "#endif",
  7883. "#endif",
  7884. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  7885. "#ifdef DOUBLE_SIDED",
  7886. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  7887. "#endif",
  7888. "}",
  7889. "#endif",
  7890. "#if MAX_SPOT_LIGHTS > 0",
  7891. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  7892. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  7893. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7894. "lVector = normalize( lVector );",
  7895. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - mPosition.xyz ) );",
  7896. "if ( spotEffect > spotLightAngle[ i ] ) {",
  7897. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  7898. "float lDistance = 1.0;",
  7899. "if ( spotLightDistance[ i ] > 0.0 )",
  7900. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  7901. "float dotProduct = dot( transformedNormal, lVector );",
  7902. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  7903. "#ifdef DOUBLE_SIDED",
  7904. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  7905. "#ifdef WRAP_AROUND",
  7906. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  7907. "#endif",
  7908. "#endif",
  7909. "#ifdef WRAP_AROUND",
  7910. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  7911. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  7912. "#ifdef DOUBLE_SIDED",
  7913. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  7914. "#endif",
  7915. "#endif",
  7916. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  7917. "#ifdef DOUBLE_SIDED",
  7918. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  7919. "#endif",
  7920. "}",
  7921. "}",
  7922. "#endif",
  7923. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  7924. "#ifdef DOUBLE_SIDED",
  7925. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  7926. "#endif"
  7927. ].join("\n"),
  7928. // LIGHTS PHONG
  7929. lights_phong_pars_vertex: [
  7930. "#ifndef PHONG_PER_PIXEL",
  7931. "#if MAX_POINT_LIGHTS > 0",
  7932. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  7933. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  7934. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  7935. "#endif",
  7936. "#if MAX_SPOT_LIGHTS > 0",
  7937. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  7938. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  7939. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  7940. "#endif",
  7941. "#endif",
  7942. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  7943. "varying vec3 vWorldPosition;",
  7944. "#endif"
  7945. ].join("\n"),
  7946. lights_phong_vertex: [
  7947. "#ifndef PHONG_PER_PIXEL",
  7948. "#if MAX_POINT_LIGHTS > 0",
  7949. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  7950. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  7951. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7952. "float lDistance = 1.0;",
  7953. "if ( pointLightDistance[ i ] > 0.0 )",
  7954. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  7955. "vPointLight[ i ] = vec4( lVector, lDistance );",
  7956. "}",
  7957. "#endif",
  7958. "#if MAX_SPOT_LIGHTS > 0",
  7959. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  7960. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  7961. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7962. "float lDistance = 1.0;",
  7963. "if ( spotLightDistance[ i ] > 0.0 )",
  7964. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  7965. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  7966. "}",
  7967. "#endif",
  7968. "#endif",
  7969. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  7970. "vWorldPosition = mPosition.xyz;",
  7971. "#endif"
  7972. ].join("\n"),
  7973. lights_phong_pars_fragment: [
  7974. "uniform vec3 ambientLightColor;",
  7975. "#if MAX_DIR_LIGHTS > 0",
  7976. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  7977. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  7978. "#endif",
  7979. "#if MAX_POINT_LIGHTS > 0",
  7980. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  7981. "#ifdef PHONG_PER_PIXEL",
  7982. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  7983. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  7984. "#else",
  7985. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  7986. "#endif",
  7987. "#endif",
  7988. "#if MAX_SPOT_LIGHTS > 0",
  7989. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  7990. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  7991. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  7992. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  7993. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  7994. "#ifdef PHONG_PER_PIXEL",
  7995. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  7996. "#else",
  7997. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  7998. "#endif",
  7999. "#endif",
  8000. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8001. "varying vec3 vWorldPosition;",
  8002. "#endif",
  8003. "#ifdef WRAP_AROUND",
  8004. "uniform vec3 wrapRGB;",
  8005. "#endif",
  8006. "varying vec3 vViewPosition;",
  8007. "varying vec3 vNormal;"
  8008. ].join("\n"),
  8009. lights_phong_fragment: [
  8010. "vec3 normal = normalize( vNormal );",
  8011. "vec3 viewPosition = normalize( vViewPosition );",
  8012. "#ifdef DOUBLE_SIDED",
  8013. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8014. "#endif",
  8015. "#ifdef USE_BUMPMAP",
  8016. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  8017. "#endif",
  8018. "#if MAX_POINT_LIGHTS > 0",
  8019. "vec3 pointDiffuse = vec3( 0.0 );",
  8020. "vec3 pointSpecular = vec3( 0.0 );",
  8021. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8022. "#ifdef PHONG_PER_PIXEL",
  8023. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8024. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8025. "float lDistance = 1.0;",
  8026. "if ( pointLightDistance[ i ] > 0.0 )",
  8027. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8028. "lVector = normalize( lVector );",
  8029. "#else",
  8030. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  8031. "float lDistance = vPointLight[ i ].w;",
  8032. "#endif",
  8033. // diffuse
  8034. "float dotProduct = dot( normal, lVector );",
  8035. "#ifdef WRAP_AROUND",
  8036. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  8037. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8038. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  8039. "#else",
  8040. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  8041. "#endif",
  8042. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  8043. // specular
  8044. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  8045. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  8046. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  8047. "#ifdef PHYSICALLY_BASED_SHADING",
  8048. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8049. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8050. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  8051. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  8052. "#else",
  8053. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  8054. "#endif",
  8055. "}",
  8056. "#endif",
  8057. "#if MAX_SPOT_LIGHTS > 0",
  8058. "vec3 spotDiffuse = vec3( 0.0 );",
  8059. "vec3 spotSpecular = vec3( 0.0 );",
  8060. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8061. "#ifdef PHONG_PER_PIXEL",
  8062. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8063. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8064. "float lDistance = 1.0;",
  8065. "if ( spotLightDistance[ i ] > 0.0 )",
  8066. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8067. "lVector = normalize( lVector );",
  8068. "#else",
  8069. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  8070. "float lDistance = vSpotLight[ i ].w;",
  8071. "#endif",
  8072. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  8073. "if ( spotEffect > spotLightAngle[ i ] ) {",
  8074. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  8075. // diffuse
  8076. "float dotProduct = dot( normal, lVector );",
  8077. "#ifdef WRAP_AROUND",
  8078. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  8079. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8080. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  8081. "#else",
  8082. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  8083. "#endif",
  8084. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  8085. // specular
  8086. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  8087. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  8088. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  8089. "#ifdef PHYSICALLY_BASED_SHADING",
  8090. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8091. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8092. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  8093. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  8094. "#else",
  8095. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  8096. "#endif",
  8097. "}",
  8098. "}",
  8099. "#endif",
  8100. "#if MAX_DIR_LIGHTS > 0",
  8101. "vec3 dirDiffuse = vec3( 0.0 );",
  8102. "vec3 dirSpecular = vec3( 0.0 );" ,
  8103. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8104. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8105. "vec3 dirVector = normalize( lDirection.xyz );",
  8106. // diffuse
  8107. "float dotProduct = dot( normal, dirVector );",
  8108. "#ifdef WRAP_AROUND",
  8109. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  8110. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8111. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  8112. "#else",
  8113. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  8114. "#endif",
  8115. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  8116. // specular
  8117. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  8118. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  8119. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  8120. "#ifdef PHYSICALLY_BASED_SHADING",
  8121. /*
  8122. // fresnel term from skin shader
  8123. "const float F0 = 0.128;",
  8124. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  8125. "float exponential = pow( base, 5.0 );",
  8126. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  8127. */
  8128. /*
  8129. // fresnel term from fresnel shader
  8130. "const float mFresnelBias = 0.08;",
  8131. "const float mFresnelScale = 0.3;",
  8132. "const float mFresnelPower = 5.0;",
  8133. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  8134. */
  8135. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8136. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8137. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  8138. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  8139. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  8140. "#else",
  8141. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  8142. "#endif",
  8143. "}",
  8144. "#endif",
  8145. "vec3 totalDiffuse = vec3( 0.0 );",
  8146. "vec3 totalSpecular = vec3( 0.0 );",
  8147. "#if MAX_DIR_LIGHTS > 0",
  8148. "totalDiffuse += dirDiffuse;",
  8149. "totalSpecular += dirSpecular;",
  8150. "#endif",
  8151. "#if MAX_POINT_LIGHTS > 0",
  8152. "totalDiffuse += pointDiffuse;",
  8153. "totalSpecular += pointSpecular;",
  8154. "#endif",
  8155. "#if MAX_SPOT_LIGHTS > 0",
  8156. "totalDiffuse += spotDiffuse;",
  8157. "totalSpecular += spotSpecular;",
  8158. "#endif",
  8159. "#ifdef METAL",
  8160. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  8161. "#else",
  8162. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  8163. "#endif"
  8164. ].join("\n"),
  8165. // VERTEX COLORS
  8166. color_pars_fragment: [
  8167. "#ifdef USE_COLOR",
  8168. "varying vec3 vColor;",
  8169. "#endif"
  8170. ].join("\n"),
  8171. color_fragment: [
  8172. "#ifdef USE_COLOR",
  8173. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  8174. "#endif"
  8175. ].join("\n"),
  8176. color_pars_vertex: [
  8177. "#ifdef USE_COLOR",
  8178. "varying vec3 vColor;",
  8179. "#endif"
  8180. ].join("\n"),
  8181. color_vertex: [
  8182. "#ifdef USE_COLOR",
  8183. "#ifdef GAMMA_INPUT",
  8184. "vColor = color * color;",
  8185. "#else",
  8186. "vColor = color;",
  8187. "#endif",
  8188. "#endif"
  8189. ].join("\n"),
  8190. // SKINNING
  8191. skinning_pars_vertex: [
  8192. "#ifdef USE_SKINNING",
  8193. "#ifdef BONE_TEXTURE",
  8194. "uniform sampler2D boneTexture;",
  8195. "mat4 getBoneMatrix( const in float i ) {",
  8196. "float j = i * 4.0;",
  8197. "float x = mod( j, N_BONE_PIXEL_X );",
  8198. "float y = floor( j / N_BONE_PIXEL_X );",
  8199. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  8200. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  8201. "y = dy * ( y + 0.5 );",
  8202. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  8203. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  8204. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  8205. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  8206. "mat4 bone = mat4( v1, v2, v3, v4 );",
  8207. "return bone;",
  8208. "}",
  8209. "#else",
  8210. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  8211. "mat4 getBoneMatrix( const in float i ) {",
  8212. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  8213. "return bone;",
  8214. "}",
  8215. "#endif",
  8216. "#endif"
  8217. ].join("\n"),
  8218. skinbase_vertex: [
  8219. "#ifdef USE_SKINNING",
  8220. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  8221. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  8222. "#endif"
  8223. ].join("\n"),
  8224. skinning_vertex: [
  8225. "#ifdef USE_SKINNING",
  8226. "#ifdef USE_MORPHTARGETS",
  8227. "vec4 skinVertex = vec4( morphed, 1.0 );",
  8228. "#else",
  8229. "vec4 skinVertex = vec4( position, 1.0 );",
  8230. "#endif",
  8231. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  8232. "skinned += boneMatY * skinVertex * skinWeight.y;",
  8233. "#endif"
  8234. ].join("\n"),
  8235. // MORPHING
  8236. morphtarget_pars_vertex: [
  8237. "#ifdef USE_MORPHTARGETS",
  8238. "#ifndef USE_MORPHNORMALS",
  8239. "uniform float morphTargetInfluences[ 8 ];",
  8240. "#else",
  8241. "uniform float morphTargetInfluences[ 4 ];",
  8242. "#endif",
  8243. "#endif"
  8244. ].join("\n"),
  8245. morphtarget_vertex: [
  8246. "#ifdef USE_MORPHTARGETS",
  8247. "vec3 morphed = vec3( 0.0 );",
  8248. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  8249. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  8250. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  8251. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  8252. "#ifndef USE_MORPHNORMALS",
  8253. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  8254. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  8255. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  8256. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  8257. "#endif",
  8258. "morphed += position;",
  8259. "#endif"
  8260. ].join("\n"),
  8261. default_vertex : [
  8262. "vec4 mvPosition;",
  8263. "#ifdef USE_SKINNING",
  8264. "mvPosition = modelViewMatrix * skinned;",
  8265. "#endif",
  8266. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  8267. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  8268. "#endif",
  8269. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  8270. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8271. "#endif",
  8272. "gl_Position = projectionMatrix * mvPosition;",
  8273. ].join("\n"),
  8274. morphnormal_vertex: [
  8275. "#ifdef USE_MORPHNORMALS",
  8276. "vec3 morphedNormal = vec3( 0.0 );",
  8277. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  8278. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  8279. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  8280. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  8281. "morphedNormal += normal;",
  8282. "#endif"
  8283. ].join("\n"),
  8284. skinnormal_vertex: [
  8285. "#ifdef USE_SKINNING",
  8286. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  8287. "skinMatrix += skinWeight.y * boneMatY;",
  8288. "#ifdef USE_MORPHNORMALS",
  8289. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  8290. "#else",
  8291. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  8292. "#endif",
  8293. "#endif"
  8294. ].join("\n"),
  8295. defaultnormal_vertex: [
  8296. "vec3 objectNormal;",
  8297. "#ifdef USE_SKINNING",
  8298. "objectNormal = skinnedNormal.xyz;",
  8299. "#endif",
  8300. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  8301. "objectNormal = morphedNormal;",
  8302. "#endif",
  8303. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  8304. "objectNormal = normal;",
  8305. "#endif",
  8306. "vec3 transformedNormal = normalMatrix * objectNormal;",
  8307. ].join("\n"),
  8308. // SHADOW MAP
  8309. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  8310. // http://spidergl.org/example.php?id=6
  8311. // http://fabiensanglard.net/shadowmapping
  8312. shadowmap_pars_fragment: [
  8313. "#ifdef USE_SHADOWMAP",
  8314. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  8315. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  8316. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  8317. "uniform float shadowBias[ MAX_SHADOWS ];",
  8318. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8319. "float unpackDepth( const in vec4 rgba_depth ) {",
  8320. "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 );",
  8321. "float depth = dot( rgba_depth, bit_shift );",
  8322. "return depth;",
  8323. "}",
  8324. "#endif"
  8325. ].join("\n"),
  8326. shadowmap_fragment: [
  8327. "#ifdef USE_SHADOWMAP",
  8328. "#ifdef SHADOWMAP_DEBUG",
  8329. "vec3 frustumColors[3];",
  8330. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  8331. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  8332. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  8333. "#endif",
  8334. "#ifdef SHADOWMAP_CASCADE",
  8335. "int inFrustumCount = 0;",
  8336. "#endif",
  8337. "float fDepth;",
  8338. "vec3 shadowColor = vec3( 1.0 );",
  8339. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8340. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  8341. // "if ( something && something )" breaks ATI OpenGL shader compiler
  8342. // "if ( all( something, something ) )" using this instead
  8343. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  8344. "bool inFrustum = all( inFrustumVec );",
  8345. // don't shadow pixels outside of light frustum
  8346. // use just first frustum (for cascades)
  8347. // don't shadow pixels behind far plane of light frustum
  8348. "#ifdef SHADOWMAP_CASCADE",
  8349. "inFrustumCount += int( inFrustum );",
  8350. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  8351. "#else",
  8352. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  8353. "#endif",
  8354. "bool frustumTest = all( frustumTestVec );",
  8355. "if ( frustumTest ) {",
  8356. "shadowCoord.z += shadowBias[ i ];",
  8357. "#ifdef SHADOWMAP_SOFT",
  8358. // Percentage-close filtering
  8359. // (9 pixel kernel)
  8360. // http://fabiensanglard.net/shadowmappingPCF/
  8361. "float shadow = 0.0;",
  8362. /*
  8363. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  8364. // must enroll loop manually
  8365. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  8366. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  8367. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  8368. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  8369. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  8370. "float fDepth = unpackDepth( rgbaDepth );",
  8371. "if ( fDepth < shadowCoord.z )",
  8372. "shadow += 1.0;",
  8373. "}",
  8374. "shadow /= 9.0;",
  8375. */
  8376. "const float shadowDelta = 1.0 / 9.0;",
  8377. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  8378. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  8379. "float dx0 = -1.25 * xPixelOffset;",
  8380. "float dy0 = -1.25 * yPixelOffset;",
  8381. "float dx1 = 1.25 * xPixelOffset;",
  8382. "float dy1 = 1.25 * yPixelOffset;",
  8383. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  8384. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8385. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  8386. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8387. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  8388. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8389. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  8390. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8391. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  8392. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8393. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  8394. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8395. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  8396. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8397. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  8398. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8399. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  8400. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8401. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  8402. "#else",
  8403. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  8404. "float fDepth = unpackDepth( rgbaDepth );",
  8405. "if ( fDepth < shadowCoord.z )",
  8406. // spot with multiple shadows is darker
  8407. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  8408. // spot with multiple shadows has the same color as single shadow spot
  8409. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  8410. "#endif",
  8411. "}",
  8412. "#ifdef SHADOWMAP_DEBUG",
  8413. "#ifdef SHADOWMAP_CASCADE",
  8414. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  8415. "#else",
  8416. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  8417. "#endif",
  8418. "#endif",
  8419. "}",
  8420. "#ifdef GAMMA_OUTPUT",
  8421. "shadowColor *= shadowColor;",
  8422. "#endif",
  8423. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  8424. "#endif"
  8425. ].join("\n"),
  8426. shadowmap_pars_vertex: [
  8427. "#ifdef USE_SHADOWMAP",
  8428. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8429. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  8430. "#endif"
  8431. ].join("\n"),
  8432. shadowmap_vertex: [
  8433. "#ifdef USE_SHADOWMAP",
  8434. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8435. "vShadowCoord[ i ] = shadowMatrix[ i ] * mPosition;",
  8436. "}",
  8437. "#endif"
  8438. ].join("\n"),
  8439. // ALPHATEST
  8440. alphatest_fragment: [
  8441. "#ifdef ALPHATEST",
  8442. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  8443. "#endif"
  8444. ].join("\n"),
  8445. // LINEAR SPACE
  8446. linear_to_gamma_fragment: [
  8447. "#ifdef GAMMA_OUTPUT",
  8448. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  8449. "#endif"
  8450. ].join("\n"),
  8451. };
  8452. THREE.UniformsUtils = {
  8453. merge: function ( uniforms ) {
  8454. var u, p, tmp, merged = {};
  8455. for ( u = 0; u < uniforms.length; u ++ ) {
  8456. tmp = this.clone( uniforms[ u ] );
  8457. for ( p in tmp ) {
  8458. merged[ p ] = tmp[ p ];
  8459. }
  8460. }
  8461. return merged;
  8462. },
  8463. clone: function ( uniforms_src ) {
  8464. var u, p, parameter, parameter_src, uniforms_dst = {};
  8465. for ( u in uniforms_src ) {
  8466. uniforms_dst[ u ] = {};
  8467. for ( p in uniforms_src[ u ] ) {
  8468. parameter_src = uniforms_src[ u ][ p ];
  8469. if ( parameter_src instanceof THREE.Color ||
  8470. parameter_src instanceof THREE.Vector2 ||
  8471. parameter_src instanceof THREE.Vector3 ||
  8472. parameter_src instanceof THREE.Vector4 ||
  8473. parameter_src instanceof THREE.Matrix4 ||
  8474. parameter_src instanceof THREE.Texture ) {
  8475. uniforms_dst[ u ][ p ] = parameter_src.clone();
  8476. } else if ( parameter_src instanceof Array ) {
  8477. uniforms_dst[ u ][ p ] = parameter_src.slice();
  8478. } else {
  8479. uniforms_dst[ u ][ p ] = parameter_src;
  8480. }
  8481. }
  8482. }
  8483. return uniforms_dst;
  8484. }
  8485. };
  8486. THREE.UniformsLib = {
  8487. common: {
  8488. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8489. "opacity" : { type: "f", value: 1.0 },
  8490. "map" : { type: "t", value: null },
  8491. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  8492. "lightMap" : { type: "t", value: null },
  8493. "specularMap" : { type: "t", value: null },
  8494. "envMap" : { type: "t", value: null },
  8495. "flipEnvMap" : { type: "f", value: -1 },
  8496. "useRefract" : { type: "i", value: 0 },
  8497. "reflectivity" : { type: "f", value: 1.0 },
  8498. "refractionRatio" : { type: "f", value: 0.98 },
  8499. "combine" : { type: "i", value: 0 },
  8500. "morphTargetInfluences" : { type: "f", value: 0 }
  8501. },
  8502. bump: {
  8503. "bumpMap" : { type: "t", value: null },
  8504. "bumpScale" : { type: "f", value: 1 }
  8505. },
  8506. fog : {
  8507. "fogDensity" : { type: "f", value: 0.00025 },
  8508. "fogNear" : { type: "f", value: 1 },
  8509. "fogFar" : { type: "f", value: 2000 },
  8510. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8511. },
  8512. lights: {
  8513. "ambientLightColor" : { type: "fv", value: [] },
  8514. "directionalLightDirection" : { type: "fv", value: [] },
  8515. "directionalLightColor" : { type: "fv", value: [] },
  8516. "pointLightColor" : { type: "fv", value: [] },
  8517. "pointLightPosition" : { type: "fv", value: [] },
  8518. "pointLightDistance" : { type: "fv1", value: [] },
  8519. "spotLightColor" : { type: "fv", value: [] },
  8520. "spotLightPosition" : { type: "fv", value: [] },
  8521. "spotLightDirection" : { type: "fv", value: [] },
  8522. "spotLightDistance" : { type: "fv1", value: [] },
  8523. "spotLightAngle" : { type: "fv1", value: [] },
  8524. "spotLightExponent" : { type: "fv1", value: [] }
  8525. },
  8526. particle: {
  8527. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8528. "opacity" : { type: "f", value: 1.0 },
  8529. "size" : { type: "f", value: 1.0 },
  8530. "scale" : { type: "f", value: 1.0 },
  8531. "map" : { type: "t", value: null },
  8532. "fogDensity" : { type: "f", value: 0.00025 },
  8533. "fogNear" : { type: "f", value: 1 },
  8534. "fogFar" : { type: "f", value: 2000 },
  8535. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8536. },
  8537. shadowmap: {
  8538. "shadowMap": { type: "tv", value: [] },
  8539. "shadowMapSize": { type: "v2v", value: [] },
  8540. "shadowBias" : { type: "fv1", value: [] },
  8541. "shadowDarkness": { type: "fv1", value: [] },
  8542. "shadowMatrix" : { type: "m4v", value: [] },
  8543. }
  8544. };
  8545. THREE.ShaderLib = {
  8546. 'depth': {
  8547. uniforms: {
  8548. "mNear": { type: "f", value: 1.0 },
  8549. "mFar" : { type: "f", value: 2000.0 },
  8550. "opacity" : { type: "f", value: 1.0 }
  8551. },
  8552. vertexShader: [
  8553. "void main() {",
  8554. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  8555. "}"
  8556. ].join("\n"),
  8557. fragmentShader: [
  8558. "uniform float mNear;",
  8559. "uniform float mFar;",
  8560. "uniform float opacity;",
  8561. "void main() {",
  8562. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8563. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  8564. "gl_FragColor = vec4( vec3( color ), opacity );",
  8565. "}"
  8566. ].join("\n")
  8567. },
  8568. 'normal': {
  8569. uniforms: {
  8570. "opacity" : { type: "f", value: 1.0 }
  8571. },
  8572. vertexShader: [
  8573. "varying vec3 vNormal;",
  8574. "void main() {",
  8575. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8576. "vNormal = normalMatrix * normal;",
  8577. "gl_Position = projectionMatrix * mvPosition;",
  8578. "}"
  8579. ].join("\n"),
  8580. fragmentShader: [
  8581. "uniform float opacity;",
  8582. "varying vec3 vNormal;",
  8583. "void main() {",
  8584. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  8585. "}"
  8586. ].join("\n")
  8587. },
  8588. 'basic': {
  8589. uniforms: THREE.UniformsUtils.merge( [
  8590. THREE.UniformsLib[ "common" ],
  8591. THREE.UniformsLib[ "fog" ],
  8592. THREE.UniformsLib[ "shadowmap" ]
  8593. ] ),
  8594. vertexShader: [
  8595. THREE.ShaderChunk[ "map_pars_vertex" ],
  8596. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  8597. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  8598. THREE.ShaderChunk[ "color_pars_vertex" ],
  8599. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8600. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8601. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8602. "void main() {",
  8603. THREE.ShaderChunk[ "map_vertex" ],
  8604. THREE.ShaderChunk[ "lightmap_vertex" ],
  8605. THREE.ShaderChunk[ "color_vertex" ],
  8606. "#ifdef USE_ENVMAP",
  8607. THREE.ShaderChunk[ "morphnormal_vertex" ],
  8608. THREE.ShaderChunk[ "skinbase_vertex" ],
  8609. THREE.ShaderChunk[ "skinnormal_vertex" ],
  8610. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  8611. "#endif",
  8612. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8613. THREE.ShaderChunk[ "skinning_vertex" ],
  8614. THREE.ShaderChunk[ "default_vertex" ],
  8615. THREE.ShaderChunk[ "worldpos_vertex" ],
  8616. THREE.ShaderChunk[ "envmap_vertex" ],
  8617. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8618. "}"
  8619. ].join("\n"),
  8620. fragmentShader: [
  8621. "uniform vec3 diffuse;",
  8622. "uniform float opacity;",
  8623. THREE.ShaderChunk[ "color_pars_fragment" ],
  8624. THREE.ShaderChunk[ "map_pars_fragment" ],
  8625. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  8626. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  8627. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8628. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8629. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  8630. "void main() {",
  8631. "gl_FragColor = vec4( diffuse, opacity );",
  8632. THREE.ShaderChunk[ "map_fragment" ],
  8633. THREE.ShaderChunk[ "alphatest_fragment" ],
  8634. THREE.ShaderChunk[ "specularmap_fragment" ],
  8635. THREE.ShaderChunk[ "lightmap_fragment" ],
  8636. THREE.ShaderChunk[ "color_fragment" ],
  8637. THREE.ShaderChunk[ "envmap_fragment" ],
  8638. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8639. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  8640. THREE.ShaderChunk[ "fog_fragment" ],
  8641. "}"
  8642. ].join("\n")
  8643. },
  8644. 'lambert': {
  8645. uniforms: THREE.UniformsUtils.merge( [
  8646. THREE.UniformsLib[ "common" ],
  8647. THREE.UniformsLib[ "fog" ],
  8648. THREE.UniformsLib[ "lights" ],
  8649. THREE.UniformsLib[ "shadowmap" ],
  8650. {
  8651. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  8652. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  8653. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  8654. }
  8655. ] ),
  8656. vertexShader: [
  8657. "#define LAMBERT",
  8658. "varying vec3 vLightFront;",
  8659. "#ifdef DOUBLE_SIDED",
  8660. "varying vec3 vLightBack;",
  8661. "#endif",
  8662. THREE.ShaderChunk[ "map_pars_vertex" ],
  8663. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  8664. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  8665. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  8666. THREE.ShaderChunk[ "color_pars_vertex" ],
  8667. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8668. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8669. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8670. "void main() {",
  8671. THREE.ShaderChunk[ "map_vertex" ],
  8672. THREE.ShaderChunk[ "lightmap_vertex" ],
  8673. THREE.ShaderChunk[ "color_vertex" ],
  8674. THREE.ShaderChunk[ "morphnormal_vertex" ],
  8675. THREE.ShaderChunk[ "skinbase_vertex" ],
  8676. THREE.ShaderChunk[ "skinnormal_vertex" ],
  8677. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  8678. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8679. THREE.ShaderChunk[ "skinning_vertex" ],
  8680. THREE.ShaderChunk[ "default_vertex" ],
  8681. THREE.ShaderChunk[ "worldpos_vertex" ],
  8682. THREE.ShaderChunk[ "envmap_vertex" ],
  8683. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  8684. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8685. "}"
  8686. ].join("\n"),
  8687. fragmentShader: [
  8688. "uniform float opacity;",
  8689. "varying vec3 vLightFront;",
  8690. "#ifdef DOUBLE_SIDED",
  8691. "varying vec3 vLightBack;",
  8692. "#endif",
  8693. THREE.ShaderChunk[ "color_pars_fragment" ],
  8694. THREE.ShaderChunk[ "map_pars_fragment" ],
  8695. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  8696. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  8697. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8698. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8699. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  8700. "void main() {",
  8701. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  8702. THREE.ShaderChunk[ "map_fragment" ],
  8703. THREE.ShaderChunk[ "alphatest_fragment" ],
  8704. THREE.ShaderChunk[ "specularmap_fragment" ],
  8705. "#ifdef DOUBLE_SIDED",
  8706. //"float isFront = float( gl_FrontFacing );",
  8707. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  8708. "if ( gl_FrontFacing )",
  8709. "gl_FragColor.xyz *= vLightFront;",
  8710. "else",
  8711. "gl_FragColor.xyz *= vLightBack;",
  8712. "#else",
  8713. "gl_FragColor.xyz *= vLightFront;",
  8714. "#endif",
  8715. THREE.ShaderChunk[ "lightmap_fragment" ],
  8716. THREE.ShaderChunk[ "color_fragment" ],
  8717. THREE.ShaderChunk[ "envmap_fragment" ],
  8718. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8719. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  8720. THREE.ShaderChunk[ "fog_fragment" ],
  8721. "}"
  8722. ].join("\n")
  8723. },
  8724. 'phong': {
  8725. uniforms: THREE.UniformsUtils.merge( [
  8726. THREE.UniformsLib[ "common" ],
  8727. THREE.UniformsLib[ "bump" ],
  8728. THREE.UniformsLib[ "fog" ],
  8729. THREE.UniformsLib[ "lights" ],
  8730. THREE.UniformsLib[ "shadowmap" ],
  8731. {
  8732. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  8733. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  8734. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  8735. "shininess": { type: "f", value: 30 },
  8736. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  8737. }
  8738. ] ),
  8739. vertexShader: [
  8740. "#define PHONG",
  8741. "varying vec3 vViewPosition;",
  8742. "varying vec3 vNormal;",
  8743. THREE.ShaderChunk[ "map_pars_vertex" ],
  8744. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  8745. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  8746. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  8747. THREE.ShaderChunk[ "color_pars_vertex" ],
  8748. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8749. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8750. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8751. "void main() {",
  8752. THREE.ShaderChunk[ "map_vertex" ],
  8753. THREE.ShaderChunk[ "lightmap_vertex" ],
  8754. THREE.ShaderChunk[ "color_vertex" ],
  8755. THREE.ShaderChunk[ "morphnormal_vertex" ],
  8756. THREE.ShaderChunk[ "skinbase_vertex" ],
  8757. THREE.ShaderChunk[ "skinnormal_vertex" ],
  8758. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  8759. "vNormal = transformedNormal;",
  8760. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8761. THREE.ShaderChunk[ "skinning_vertex" ],
  8762. THREE.ShaderChunk[ "default_vertex" ],
  8763. "vViewPosition = -mvPosition.xyz;",
  8764. THREE.ShaderChunk[ "worldpos_vertex" ],
  8765. THREE.ShaderChunk[ "envmap_vertex" ],
  8766. THREE.ShaderChunk[ "lights_phong_vertex" ],
  8767. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8768. "}"
  8769. ].join("\n"),
  8770. fragmentShader: [
  8771. "uniform vec3 diffuse;",
  8772. "uniform float opacity;",
  8773. "uniform vec3 ambient;",
  8774. "uniform vec3 emissive;",
  8775. "uniform vec3 specular;",
  8776. "uniform float shininess;",
  8777. THREE.ShaderChunk[ "color_pars_fragment" ],
  8778. THREE.ShaderChunk[ "map_pars_fragment" ],
  8779. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  8780. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  8781. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8782. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  8783. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8784. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  8785. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  8786. "void main() {",
  8787. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  8788. THREE.ShaderChunk[ "map_fragment" ],
  8789. THREE.ShaderChunk[ "alphatest_fragment" ],
  8790. THREE.ShaderChunk[ "specularmap_fragment" ],
  8791. THREE.ShaderChunk[ "lights_phong_fragment" ],
  8792. THREE.ShaderChunk[ "lightmap_fragment" ],
  8793. THREE.ShaderChunk[ "color_fragment" ],
  8794. THREE.ShaderChunk[ "envmap_fragment" ],
  8795. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8796. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  8797. THREE.ShaderChunk[ "fog_fragment" ],
  8798. "}"
  8799. ].join("\n")
  8800. },
  8801. 'particle_basic': {
  8802. uniforms: THREE.UniformsUtils.merge( [
  8803. THREE.UniformsLib[ "particle" ],
  8804. THREE.UniformsLib[ "shadowmap" ]
  8805. ] ),
  8806. vertexShader: [
  8807. "uniform float size;",
  8808. "uniform float scale;",
  8809. THREE.ShaderChunk[ "color_pars_vertex" ],
  8810. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8811. "void main() {",
  8812. THREE.ShaderChunk[ "color_vertex" ],
  8813. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8814. "#ifdef USE_SIZEATTENUATION",
  8815. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  8816. "#else",
  8817. "gl_PointSize = size;",
  8818. "#endif",
  8819. "gl_Position = projectionMatrix * mvPosition;",
  8820. THREE.ShaderChunk[ "worldpos_vertex" ],
  8821. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8822. "}"
  8823. ].join("\n"),
  8824. fragmentShader: [
  8825. "uniform vec3 psColor;",
  8826. "uniform float opacity;",
  8827. THREE.ShaderChunk[ "color_pars_fragment" ],
  8828. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  8829. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8830. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8831. "void main() {",
  8832. "gl_FragColor = vec4( psColor, opacity );",
  8833. THREE.ShaderChunk[ "map_particle_fragment" ],
  8834. THREE.ShaderChunk[ "alphatest_fragment" ],
  8835. THREE.ShaderChunk[ "color_fragment" ],
  8836. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8837. THREE.ShaderChunk[ "fog_fragment" ],
  8838. "}"
  8839. ].join("\n")
  8840. },
  8841. // Depth encoding into RGBA texture
  8842. // based on SpiderGL shadow map example
  8843. // http://spidergl.org/example.php?id=6
  8844. // originally from
  8845. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  8846. // see also here:
  8847. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  8848. 'depthRGBA': {
  8849. uniforms: {},
  8850. vertexShader: [
  8851. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8852. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8853. "void main() {",
  8854. THREE.ShaderChunk[ "skinbase_vertex" ],
  8855. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8856. THREE.ShaderChunk[ "skinning_vertex" ],
  8857. THREE.ShaderChunk[ "default_vertex" ],
  8858. "}"
  8859. ].join("\n"),
  8860. fragmentShader: [
  8861. "vec4 pack_depth( const in float depth ) {",
  8862. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  8863. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  8864. "vec4 res = fract( depth * bit_shift );",
  8865. "res -= res.xxyz * bit_mask;",
  8866. "return res;",
  8867. "}",
  8868. "void main() {",
  8869. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  8870. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  8871. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  8872. //"gl_FragData[ 0 ] = pack_depth( z );",
  8873. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  8874. "}"
  8875. ].join("\n")
  8876. }
  8877. };
  8878. /**
  8879. * @author supereggbert / http://www.paulbrunt.co.uk/
  8880. * @author mrdoob / http://mrdoob.com/
  8881. * @author alteredq / http://alteredqualia.com/
  8882. * @author szimek / https://github.com/szimek/
  8883. */
  8884. THREE.WebGLRenderer = function ( parameters ) {
  8885. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  8886. parameters = parameters || {};
  8887. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  8888. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  8889. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  8890. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  8891. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  8892. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  8893. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  8894. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  8895. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,
  8896. _maxLights = parameters.maxLights !== undefined ? parameters.maxLights : 4;
  8897. // public properties
  8898. this.domElement = _canvas;
  8899. this.context = null;
  8900. // clearing
  8901. this.autoClear = true;
  8902. this.autoClearColor = true;
  8903. this.autoClearDepth = true;
  8904. this.autoClearStencil = true;
  8905. // scene graph
  8906. this.sortObjects = true;
  8907. this.autoUpdateObjects = true;
  8908. this.autoUpdateScene = true;
  8909. // physically based shading
  8910. this.gammaInput = false;
  8911. this.gammaOutput = false;
  8912. this.physicallyBasedShading = false;
  8913. // shadow map
  8914. this.shadowMapEnabled = false;
  8915. this.shadowMapAutoUpdate = true;
  8916. this.shadowMapSoft = true;
  8917. this.shadowMapCullFrontFaces = true;
  8918. this.shadowMapDebug = false;
  8919. this.shadowMapCascade = false;
  8920. // morphs
  8921. this.maxMorphTargets = 8;
  8922. this.maxMorphNormals = 4;
  8923. // flags
  8924. this.autoScaleCubemaps = true;
  8925. // custom render plugins
  8926. this.renderPluginsPre = [];
  8927. this.renderPluginsPost = [];
  8928. // info
  8929. this.info = {
  8930. memory: {
  8931. programs: 0,
  8932. geometries: 0,
  8933. textures: 0
  8934. },
  8935. render: {
  8936. calls: 0,
  8937. vertices: 0,
  8938. faces: 0,
  8939. points: 0
  8940. }
  8941. };
  8942. // internal properties
  8943. var _this = this,
  8944. _programs = [],
  8945. _programs_counter = 0,
  8946. // internal state cache
  8947. _currentProgram = null,
  8948. _currentFramebuffer = null,
  8949. _currentMaterialId = -1,
  8950. _currentGeometryGroupHash = null,
  8951. _currentCamera = null,
  8952. _geometryGroupCounter = 0,
  8953. _usedTextureUnits = 0,
  8954. // GL state cache
  8955. _oldDoubleSided = -1,
  8956. _oldFlipSided = -1,
  8957. _oldBlending = -1,
  8958. _oldBlendEquation = -1,
  8959. _oldBlendSrc = -1,
  8960. _oldBlendDst = -1,
  8961. _oldDepthTest = -1,
  8962. _oldDepthWrite = -1,
  8963. _oldPolygonOffset = null,
  8964. _oldPolygonOffsetFactor = null,
  8965. _oldPolygonOffsetUnits = null,
  8966. _oldLineWidth = null,
  8967. _viewportX = 0,
  8968. _viewportY = 0,
  8969. _viewportWidth = 0,
  8970. _viewportHeight = 0,
  8971. _currentWidth = 0,
  8972. _currentHeight = 0,
  8973. // frustum
  8974. _frustum = new THREE.Frustum(),
  8975. // camera matrices cache
  8976. _projScreenMatrix = new THREE.Matrix4(),
  8977. _projScreenMatrixPS = new THREE.Matrix4(),
  8978. _vector3 = new THREE.Vector4(),
  8979. // light arrays cache
  8980. _direction = new THREE.Vector3(),
  8981. _lightsNeedUpdate = true,
  8982. _lights = {
  8983. ambient: [ 0, 0, 0 ],
  8984. directional: { length: 0, colors: new Array(), positions: new Array() },
  8985. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  8986. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), angles: new Array(), exponents: new Array() }
  8987. };
  8988. // initialize
  8989. var _gl;
  8990. var _glExtensionTextureFloat;
  8991. var _glExtensionStandardDerivatives;
  8992. var _glExtensionTextureFilterAnisotropic;
  8993. initGL();
  8994. setDefaultGLState();
  8995. this.context = _gl;
  8996. // GPU capabilities
  8997. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  8998. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  8999. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  9000. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9001. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  9002. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  9003. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  9004. // API
  9005. this.getContext = function () {
  9006. return _gl;
  9007. };
  9008. this.supportsVertexTextures = function () {
  9009. return _supportsVertexTextures;
  9010. };
  9011. this.getMaxAnisotropy = function () {
  9012. return _maxAnisotropy;
  9013. };
  9014. this.setSize = function ( width, height ) {
  9015. _canvas.width = width;
  9016. _canvas.height = height;
  9017. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  9018. };
  9019. this.setViewport = function ( x, y, width, height ) {
  9020. _viewportX = x !== undefined ? x : 0;
  9021. _viewportY = y !== undefined ? y : 0;
  9022. _viewportWidth = width !== undefined ? width : _canvas.width;
  9023. _viewportHeight = height !== undefined ? height : _canvas.height;
  9024. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  9025. };
  9026. this.setScissor = function ( x, y, width, height ) {
  9027. _gl.scissor( x, y, width, height );
  9028. };
  9029. this.enableScissorTest = function ( enable ) {
  9030. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  9031. };
  9032. // Clearing
  9033. this.setClearColorHex = function ( hex, alpha ) {
  9034. _clearColor.setHex( hex );
  9035. _clearAlpha = alpha;
  9036. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9037. };
  9038. this.setClearColor = function ( color, alpha ) {
  9039. _clearColor.copy( color );
  9040. _clearAlpha = alpha;
  9041. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9042. };
  9043. this.getClearColor = function () {
  9044. return _clearColor;
  9045. };
  9046. this.getClearAlpha = function () {
  9047. return _clearAlpha;
  9048. };
  9049. this.clear = function ( color, depth, stencil ) {
  9050. var bits = 0;
  9051. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  9052. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  9053. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  9054. _gl.clear( bits );
  9055. };
  9056. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  9057. this.setRenderTarget( renderTarget );
  9058. this.clear( color, depth, stencil );
  9059. };
  9060. // Plugins
  9061. this.addPostPlugin = function ( plugin ) {
  9062. plugin.init( this );
  9063. this.renderPluginsPost.push( plugin );
  9064. };
  9065. this.addPrePlugin = function ( plugin ) {
  9066. plugin.init( this );
  9067. this.renderPluginsPre.push( plugin );
  9068. };
  9069. // Deallocation
  9070. this.deallocateObject = function ( object ) {
  9071. if ( ! object.__webglInit ) return;
  9072. object.__webglInit = false;
  9073. delete object._modelViewMatrix;
  9074. delete object._normalMatrix;
  9075. delete object._normalMatrixArray;
  9076. delete object._modelViewMatrixArray;
  9077. delete object._modelMatrixArray;
  9078. if ( object instanceof THREE.Mesh ) {
  9079. for ( var g in object.geometry.geometryGroups ) {
  9080. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  9081. }
  9082. } else if ( object instanceof THREE.Ribbon ) {
  9083. deleteRibbonBuffers( object.geometry );
  9084. } else if ( object instanceof THREE.Line ) {
  9085. deleteLineBuffers( object.geometry );
  9086. } else if ( object instanceof THREE.ParticleSystem ) {
  9087. deleteParticleBuffers( object.geometry );
  9088. }
  9089. };
  9090. this.deallocateTexture = function ( texture ) {
  9091. if ( ! texture.__webglInit ) return;
  9092. texture.__webglInit = false;
  9093. _gl.deleteTexture( texture.__webglTexture );
  9094. _this.info.memory.textures --;
  9095. };
  9096. this.deallocateRenderTarget = function ( renderTarget ) {
  9097. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  9098. _gl.deleteTexture( renderTarget.__webglTexture );
  9099. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9100. for ( var i = 0; i < 6; i ++ ) {
  9101. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  9102. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  9103. }
  9104. } else {
  9105. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  9106. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  9107. }
  9108. };
  9109. this.deallocateMaterial = function ( material ) {
  9110. var program = material.program;
  9111. if ( ! program ) return;
  9112. material.program = undefined;
  9113. // only deallocate GL program if this was the last use of shared program
  9114. // assumed there is only single copy of any program in the _programs list
  9115. // (that's how it's constructed)
  9116. var i, il, programInfo;
  9117. var deleteProgram = false;
  9118. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9119. programInfo = _programs[ i ];
  9120. if ( programInfo.program === program ) {
  9121. programInfo.usedTimes --;
  9122. if ( programInfo.usedTimes === 0 ) {
  9123. deleteProgram = true;
  9124. }
  9125. break;
  9126. }
  9127. }
  9128. if ( deleteProgram ) {
  9129. // avoid using array.splice, this is costlier than creating new array from scratch
  9130. var newPrograms = [];
  9131. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9132. programInfo = _programs[ i ];
  9133. if ( programInfo.program !== program ) {
  9134. newPrograms.push( programInfo );
  9135. }
  9136. }
  9137. _programs = newPrograms;
  9138. _gl.deleteProgram( program );
  9139. _this.info.memory.programs --;
  9140. }
  9141. };
  9142. // Rendering
  9143. this.updateShadowMap = function ( scene, camera ) {
  9144. _currentProgram = null;
  9145. _oldBlending = -1;
  9146. _oldDepthTest = -1;
  9147. _oldDepthWrite = -1;
  9148. _currentGeometryGroupHash = -1;
  9149. _currentMaterialId = -1;
  9150. _lightsNeedUpdate = true;
  9151. _oldDoubleSided = -1;
  9152. _oldFlipSided = -1;
  9153. this.shadowMapPlugin.update( scene, camera );
  9154. };
  9155. // Internal functions
  9156. // Buffer allocation
  9157. function createParticleBuffers ( geometry ) {
  9158. geometry.__webglVertexBuffer = _gl.createBuffer();
  9159. geometry.__webglColorBuffer = _gl.createBuffer();
  9160. _this.info.geometries ++;
  9161. };
  9162. function createLineBuffers ( geometry ) {
  9163. geometry.__webglVertexBuffer = _gl.createBuffer();
  9164. geometry.__webglColorBuffer = _gl.createBuffer();
  9165. _this.info.memory.geometries ++;
  9166. };
  9167. function createRibbonBuffers ( geometry ) {
  9168. geometry.__webglVertexBuffer = _gl.createBuffer();
  9169. geometry.__webglColorBuffer = _gl.createBuffer();
  9170. _this.info.memory.geometries ++;
  9171. };
  9172. function createMeshBuffers ( geometryGroup ) {
  9173. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  9174. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  9175. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  9176. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  9177. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  9178. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  9179. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  9180. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  9181. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  9182. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  9183. var m, ml;
  9184. if ( geometryGroup.numMorphTargets ) {
  9185. geometryGroup.__webglMorphTargetsBuffers = [];
  9186. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9187. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  9188. }
  9189. }
  9190. if ( geometryGroup.numMorphNormals ) {
  9191. geometryGroup.__webglMorphNormalsBuffers = [];
  9192. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9193. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  9194. }
  9195. }
  9196. _this.info.memory.geometries ++;
  9197. };
  9198. // Buffer deallocation
  9199. function deleteParticleBuffers ( geometry ) {
  9200. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9201. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9202. _this.info.memory.geometries --;
  9203. };
  9204. function deleteLineBuffers ( geometry ) {
  9205. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9206. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9207. _this.info.memory.geometries --;
  9208. };
  9209. function deleteRibbonBuffers ( geometry ) {
  9210. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9211. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9212. _this.info.memory.geometries --;
  9213. };
  9214. function deleteMeshBuffers ( geometryGroup ) {
  9215. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  9216. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  9217. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  9218. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  9219. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  9220. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  9221. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  9222. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  9223. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  9224. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  9225. var m, ml;
  9226. if ( geometryGroup.numMorphTargets ) {
  9227. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9228. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  9229. }
  9230. }
  9231. if ( geometryGroup.numMorphNormals ) {
  9232. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9233. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  9234. }
  9235. }
  9236. if ( geometryGroup.__webglCustomAttributesList ) {
  9237. for ( var id in geometryGroup.__webglCustomAttributesList ) {
  9238. _gl.deleteBuffer( geometryGroup.__webglCustomAttributesList[ id ].buffer );
  9239. }
  9240. }
  9241. _this.info.memory.geometries --;
  9242. };
  9243. // Buffer initialization
  9244. function initCustomAttributes ( geometry, object ) {
  9245. var nvertices = geometry.vertices.length;
  9246. var material = object.material;
  9247. if ( material.attributes ) {
  9248. if ( geometry.__webglCustomAttributesList === undefined ) {
  9249. geometry.__webglCustomAttributesList = [];
  9250. }
  9251. for ( var a in material.attributes ) {
  9252. var attribute = material.attributes[ a ];
  9253. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9254. attribute.__webglInitialized = true;
  9255. var size = 1; // "f" and "i"
  9256. if ( attribute.type === "v2" ) size = 2;
  9257. else if ( attribute.type === "v3" ) size = 3;
  9258. else if ( attribute.type === "v4" ) size = 4;
  9259. else if ( attribute.type === "c" ) size = 3;
  9260. attribute.size = size;
  9261. attribute.array = new Float32Array( nvertices * size );
  9262. attribute.buffer = _gl.createBuffer();
  9263. attribute.buffer.belongsToAttribute = a;
  9264. attribute.needsUpdate = true;
  9265. }
  9266. geometry.__webglCustomAttributesList.push( attribute );
  9267. }
  9268. }
  9269. };
  9270. function initParticleBuffers ( geometry, object ) {
  9271. var nvertices = geometry.vertices.length;
  9272. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9273. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9274. geometry.__sortArray = [];
  9275. geometry.__webglParticleCount = nvertices;
  9276. initCustomAttributes ( geometry, object );
  9277. };
  9278. function initLineBuffers ( geometry, object ) {
  9279. var nvertices = geometry.vertices.length;
  9280. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9281. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9282. geometry.__webglLineCount = nvertices;
  9283. initCustomAttributes ( geometry, object );
  9284. };
  9285. function initRibbonBuffers ( geometry ) {
  9286. var nvertices = geometry.vertices.length;
  9287. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9288. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9289. geometry.__webglVertexCount = nvertices;
  9290. };
  9291. function initMeshBuffers ( geometryGroup, object ) {
  9292. var geometry = object.geometry,
  9293. faces3 = geometryGroup.faces3,
  9294. faces4 = geometryGroup.faces4,
  9295. nvertices = faces3.length * 3 + faces4.length * 4,
  9296. ntris = faces3.length * 1 + faces4.length * 2,
  9297. nlines = faces3.length * 3 + faces4.length * 4,
  9298. material = getBufferMaterial( object, geometryGroup ),
  9299. uvType = bufferGuessUVType( material ),
  9300. normalType = bufferGuessNormalType( material ),
  9301. vertexColorType = bufferGuessVertexColorType( material );
  9302. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  9303. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  9304. if ( normalType ) {
  9305. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  9306. }
  9307. if ( geometry.hasTangents ) {
  9308. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  9309. }
  9310. if ( vertexColorType ) {
  9311. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  9312. }
  9313. if ( uvType ) {
  9314. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  9315. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  9316. }
  9317. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  9318. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  9319. }
  9320. }
  9321. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  9322. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  9323. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  9324. }
  9325. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  9326. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  9327. var m, ml;
  9328. if ( geometryGroup.numMorphTargets ) {
  9329. geometryGroup.__morphTargetsArrays = [];
  9330. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9331. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  9332. }
  9333. }
  9334. if ( geometryGroup.numMorphNormals ) {
  9335. geometryGroup.__morphNormalsArrays = [];
  9336. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9337. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  9338. }
  9339. }
  9340. geometryGroup.__webglFaceCount = ntris * 3;
  9341. geometryGroup.__webglLineCount = nlines * 2;
  9342. // custom attributes
  9343. if ( material.attributes ) {
  9344. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  9345. geometryGroup.__webglCustomAttributesList = [];
  9346. }
  9347. for ( var a in material.attributes ) {
  9348. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  9349. // attribute buffers which are correctly indexed in the setMeshBuffers function
  9350. var originalAttribute = material.attributes[ a ];
  9351. var attribute = {};
  9352. for ( var property in originalAttribute ) {
  9353. attribute[ property ] = originalAttribute[ property ];
  9354. }
  9355. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9356. attribute.__webglInitialized = true;
  9357. var size = 1; // "f" and "i"
  9358. if( attribute.type === "v2" ) size = 2;
  9359. else if( attribute.type === "v3" ) size = 3;
  9360. else if( attribute.type === "v4" ) size = 4;
  9361. else if( attribute.type === "c" ) size = 3;
  9362. attribute.size = size;
  9363. attribute.array = new Float32Array( nvertices * size );
  9364. attribute.buffer = _gl.createBuffer();
  9365. attribute.buffer.belongsToAttribute = a;
  9366. originalAttribute.needsUpdate = true;
  9367. attribute.__original = originalAttribute;
  9368. }
  9369. geometryGroup.__webglCustomAttributesList.push( attribute );
  9370. }
  9371. }
  9372. geometryGroup.__inittedArrays = true;
  9373. };
  9374. function getBufferMaterial( object, geometryGroup ) {
  9375. if ( object.material && ! ( object.material instanceof THREE.MeshFaceMaterial ) ) {
  9376. return object.material;
  9377. } else if ( geometryGroup.materialIndex >= 0 ) {
  9378. return object.geometry.materials[ geometryGroup.materialIndex ];
  9379. }
  9380. };
  9381. function materialNeedsSmoothNormals ( material ) {
  9382. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  9383. };
  9384. function bufferGuessNormalType ( material ) {
  9385. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  9386. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  9387. return false;
  9388. }
  9389. if ( materialNeedsSmoothNormals( material ) ) {
  9390. return THREE.SmoothShading;
  9391. } else {
  9392. return THREE.FlatShading;
  9393. }
  9394. };
  9395. function bufferGuessVertexColorType ( material ) {
  9396. if ( material.vertexColors ) {
  9397. return material.vertexColors;
  9398. }
  9399. return false;
  9400. };
  9401. function bufferGuessUVType ( material ) {
  9402. // material must use some texture to require uvs
  9403. if ( material.map || material.lightMap || material.bumpMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  9404. return true;
  9405. }
  9406. return false;
  9407. };
  9408. //
  9409. function initDirectBuffers( geometry ) {
  9410. var a, attribute, type;
  9411. for ( a in geometry.attributes ) {
  9412. if ( a === "index" ) {
  9413. type = _gl.ELEMENT_ARRAY_BUFFER;
  9414. } else {
  9415. type = _gl.ARRAY_BUFFER;
  9416. }
  9417. attribute = geometry.attributes[ a ];
  9418. attribute.buffer = _gl.createBuffer();
  9419. _gl.bindBuffer( type, attribute.buffer );
  9420. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  9421. }
  9422. };
  9423. // Buffer setting
  9424. function setParticleBuffers ( geometry, hint, object ) {
  9425. var v, c, vertex, offset, index, color,
  9426. vertices = geometry.vertices,
  9427. vl = vertices.length,
  9428. colors = geometry.colors,
  9429. cl = colors.length,
  9430. vertexArray = geometry.__vertexArray,
  9431. colorArray = geometry.__colorArray,
  9432. sortArray = geometry.__sortArray,
  9433. dirtyVertices = geometry.verticesNeedUpdate,
  9434. dirtyElements = geometry.elementsNeedUpdate,
  9435. dirtyColors = geometry.colorsNeedUpdate,
  9436. customAttributes = geometry.__webglCustomAttributesList,
  9437. i, il,
  9438. a, ca, cal, value,
  9439. customAttribute;
  9440. if ( object.sortParticles ) {
  9441. _projScreenMatrixPS.copy( _projScreenMatrix );
  9442. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  9443. for ( v = 0; v < vl; v ++ ) {
  9444. vertex = vertices[ v ];
  9445. _vector3.copy( vertex );
  9446. _projScreenMatrixPS.multiplyVector3( _vector3 );
  9447. sortArray[ v ] = [ _vector3.z, v ];
  9448. }
  9449. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  9450. for ( v = 0; v < vl; v ++ ) {
  9451. vertex = vertices[ sortArray[v][1] ];
  9452. offset = v * 3;
  9453. vertexArray[ offset ] = vertex.x;
  9454. vertexArray[ offset + 1 ] = vertex.y;
  9455. vertexArray[ offset + 2 ] = vertex.z;
  9456. }
  9457. for ( c = 0; c < cl; c ++ ) {
  9458. offset = c * 3;
  9459. color = colors[ sortArray[c][1] ];
  9460. colorArray[ offset ] = color.r;
  9461. colorArray[ offset + 1 ] = color.g;
  9462. colorArray[ offset + 2 ] = color.b;
  9463. }
  9464. if ( customAttributes ) {
  9465. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9466. customAttribute = customAttributes[ i ];
  9467. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  9468. offset = 0;
  9469. cal = customAttribute.value.length;
  9470. if ( customAttribute.size === 1 ) {
  9471. for ( ca = 0; ca < cal; ca ++ ) {
  9472. index = sortArray[ ca ][ 1 ];
  9473. customAttribute.array[ ca ] = customAttribute.value[ index ];
  9474. }
  9475. } else if ( customAttribute.size === 2 ) {
  9476. for ( ca = 0; ca < cal; ca ++ ) {
  9477. index = sortArray[ ca ][ 1 ];
  9478. value = customAttribute.value[ index ];
  9479. customAttribute.array[ offset ] = value.x;
  9480. customAttribute.array[ offset + 1 ] = value.y;
  9481. offset += 2;
  9482. }
  9483. } else if ( customAttribute.size === 3 ) {
  9484. if ( customAttribute.type === "c" ) {
  9485. for ( ca = 0; ca < cal; ca ++ ) {
  9486. index = sortArray[ ca ][ 1 ];
  9487. value = customAttribute.value[ index ];
  9488. customAttribute.array[ offset ] = value.r;
  9489. customAttribute.array[ offset + 1 ] = value.g;
  9490. customAttribute.array[ offset + 2 ] = value.b;
  9491. offset += 3;
  9492. }
  9493. } else {
  9494. for ( ca = 0; ca < cal; ca ++ ) {
  9495. index = sortArray[ ca ][ 1 ];
  9496. value = customAttribute.value[ index ];
  9497. customAttribute.array[ offset ] = value.x;
  9498. customAttribute.array[ offset + 1 ] = value.y;
  9499. customAttribute.array[ offset + 2 ] = value.z;
  9500. offset += 3;
  9501. }
  9502. }
  9503. } else if ( customAttribute.size === 4 ) {
  9504. for ( ca = 0; ca < cal; ca ++ ) {
  9505. index = sortArray[ ca ][ 1 ];
  9506. value = customAttribute.value[ index ];
  9507. customAttribute.array[ offset ] = value.x;
  9508. customAttribute.array[ offset + 1 ] = value.y;
  9509. customAttribute.array[ offset + 2 ] = value.z;
  9510. customAttribute.array[ offset + 3 ] = value.w;
  9511. offset += 4;
  9512. }
  9513. }
  9514. }
  9515. }
  9516. } else {
  9517. if ( dirtyVertices ) {
  9518. for ( v = 0; v < vl; v ++ ) {
  9519. vertex = vertices[ v ];
  9520. offset = v * 3;
  9521. vertexArray[ offset ] = vertex.x;
  9522. vertexArray[ offset + 1 ] = vertex.y;
  9523. vertexArray[ offset + 2 ] = vertex.z;
  9524. }
  9525. }
  9526. if ( dirtyColors ) {
  9527. for ( c = 0; c < cl; c ++ ) {
  9528. color = colors[ c ];
  9529. offset = c * 3;
  9530. colorArray[ offset ] = color.r;
  9531. colorArray[ offset + 1 ] = color.g;
  9532. colorArray[ offset + 2 ] = color.b;
  9533. }
  9534. }
  9535. if ( customAttributes ) {
  9536. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9537. customAttribute = customAttributes[ i ];
  9538. if ( customAttribute.needsUpdate &&
  9539. ( customAttribute.boundTo === undefined ||
  9540. customAttribute.boundTo === "vertices") ) {
  9541. cal = customAttribute.value.length;
  9542. offset = 0;
  9543. if ( customAttribute.size === 1 ) {
  9544. for ( ca = 0; ca < cal; ca ++ ) {
  9545. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  9546. }
  9547. } else if ( customAttribute.size === 2 ) {
  9548. for ( ca = 0; ca < cal; ca ++ ) {
  9549. value = customAttribute.value[ ca ];
  9550. customAttribute.array[ offset ] = value.x;
  9551. customAttribute.array[ offset + 1 ] = value.y;
  9552. offset += 2;
  9553. }
  9554. } else if ( customAttribute.size === 3 ) {
  9555. if ( customAttribute.type === "c" ) {
  9556. for ( ca = 0; ca < cal; ca ++ ) {
  9557. value = customAttribute.value[ ca ];
  9558. customAttribute.array[ offset ] = value.r;
  9559. customAttribute.array[ offset + 1 ] = value.g;
  9560. customAttribute.array[ offset + 2 ] = value.b;
  9561. offset += 3;
  9562. }
  9563. } else {
  9564. for ( ca = 0; ca < cal; ca ++ ) {
  9565. value = customAttribute.value[ ca ];
  9566. customAttribute.array[ offset ] = value.x;
  9567. customAttribute.array[ offset + 1 ] = value.y;
  9568. customAttribute.array[ offset + 2 ] = value.z;
  9569. offset += 3;
  9570. }
  9571. }
  9572. } else if ( customAttribute.size === 4 ) {
  9573. for ( ca = 0; ca < cal; ca ++ ) {
  9574. value = customAttribute.value[ ca ];
  9575. customAttribute.array[ offset ] = value.x;
  9576. customAttribute.array[ offset + 1 ] = value.y;
  9577. customAttribute.array[ offset + 2 ] = value.z;
  9578. customAttribute.array[ offset + 3 ] = value.w;
  9579. offset += 4;
  9580. }
  9581. }
  9582. }
  9583. }
  9584. }
  9585. }
  9586. if ( dirtyVertices || object.sortParticles ) {
  9587. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  9588. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9589. }
  9590. if ( dirtyColors || object.sortParticles ) {
  9591. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  9592. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  9593. }
  9594. if ( customAttributes ) {
  9595. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9596. customAttribute = customAttributes[ i ];
  9597. if ( customAttribute.needsUpdate || object.sortParticles ) {
  9598. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  9599. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  9600. }
  9601. }
  9602. }
  9603. };
  9604. function setLineBuffers ( geometry, hint ) {
  9605. var v, c, vertex, offset, color,
  9606. vertices = geometry.vertices,
  9607. colors = geometry.colors,
  9608. vl = vertices.length,
  9609. cl = colors.length,
  9610. vertexArray = geometry.__vertexArray,
  9611. colorArray = geometry.__colorArray,
  9612. dirtyVertices = geometry.verticesNeedUpdate,
  9613. dirtyColors = geometry.colorsNeedUpdate,
  9614. customAttributes = geometry.__webglCustomAttributesList,
  9615. i, il,
  9616. a, ca, cal, value,
  9617. customAttribute;
  9618. if ( dirtyVertices ) {
  9619. for ( v = 0; v < vl; v ++ ) {
  9620. vertex = vertices[ v ];
  9621. offset = v * 3;
  9622. vertexArray[ offset ] = vertex.x;
  9623. vertexArray[ offset + 1 ] = vertex.y;
  9624. vertexArray[ offset + 2 ] = vertex.z;
  9625. }
  9626. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  9627. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9628. }
  9629. if ( dirtyColors ) {
  9630. for ( c = 0; c < cl; c ++ ) {
  9631. color = colors[ c ];
  9632. offset = c * 3;
  9633. colorArray[ offset ] = color.r;
  9634. colorArray[ offset + 1 ] = color.g;
  9635. colorArray[ offset + 2 ] = color.b;
  9636. }
  9637. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  9638. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  9639. }
  9640. if ( customAttributes ) {
  9641. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9642. customAttribute = customAttributes[ i ];
  9643. if ( customAttribute.needsUpdate &&
  9644. ( customAttribute.boundTo === undefined ||
  9645. customAttribute.boundTo === "vertices" ) ) {
  9646. offset = 0;
  9647. cal = customAttribute.value.length;
  9648. if ( customAttribute.size === 1 ) {
  9649. for ( ca = 0; ca < cal; ca ++ ) {
  9650. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  9651. }
  9652. } else if ( customAttribute.size === 2 ) {
  9653. for ( ca = 0; ca < cal; ca ++ ) {
  9654. value = customAttribute.value[ ca ];
  9655. customAttribute.array[ offset ] = value.x;
  9656. customAttribute.array[ offset + 1 ] = value.y;
  9657. offset += 2;
  9658. }
  9659. } else if ( customAttribute.size === 3 ) {
  9660. if ( customAttribute.type === "c" ) {
  9661. for ( ca = 0; ca < cal; ca ++ ) {
  9662. value = customAttribute.value[ ca ];
  9663. customAttribute.array[ offset ] = value.r;
  9664. customAttribute.array[ offset + 1 ] = value.g;
  9665. customAttribute.array[ offset + 2 ] = value.b;
  9666. offset += 3;
  9667. }
  9668. } else {
  9669. for ( ca = 0; ca < cal; ca ++ ) {
  9670. value = customAttribute.value[ ca ];
  9671. customAttribute.array[ offset ] = value.x;
  9672. customAttribute.array[ offset + 1 ] = value.y;
  9673. customAttribute.array[ offset + 2 ] = value.z;
  9674. offset += 3;
  9675. }
  9676. }
  9677. } else if ( customAttribute.size === 4 ) {
  9678. for ( ca = 0; ca < cal; ca ++ ) {
  9679. value = customAttribute.value[ ca ];
  9680. customAttribute.array[ offset ] = value.x;
  9681. customAttribute.array[ offset + 1 ] = value.y;
  9682. customAttribute.array[ offset + 2 ] = value.z;
  9683. customAttribute.array[ offset + 3 ] = value.w;
  9684. offset += 4;
  9685. }
  9686. }
  9687. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  9688. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  9689. }
  9690. }
  9691. }
  9692. };
  9693. function setRibbonBuffers ( geometry, hint ) {
  9694. var v, c, vertex, offset, color,
  9695. vertices = geometry.vertices,
  9696. colors = geometry.colors,
  9697. vl = vertices.length,
  9698. cl = colors.length,
  9699. vertexArray = geometry.__vertexArray,
  9700. colorArray = geometry.__colorArray,
  9701. dirtyVertices = geometry.verticesNeedUpdate,
  9702. dirtyColors = geometry.colorsNeedUpdate;
  9703. if ( dirtyVertices ) {
  9704. for ( v = 0; v < vl; v ++ ) {
  9705. vertex = vertices[ v ];
  9706. offset = v * 3;
  9707. vertexArray[ offset ] = vertex.x;
  9708. vertexArray[ offset + 1 ] = vertex.y;
  9709. vertexArray[ offset + 2 ] = vertex.z;
  9710. }
  9711. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  9712. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9713. }
  9714. if ( dirtyColors ) {
  9715. for ( c = 0; c < cl; c ++ ) {
  9716. color = colors[ c ];
  9717. offset = c * 3;
  9718. colorArray[ offset ] = color.r;
  9719. colorArray[ offset + 1 ] = color.g;
  9720. colorArray[ offset + 2 ] = color.b;
  9721. }
  9722. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  9723. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  9724. }
  9725. };
  9726. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  9727. if ( ! geometryGroup.__inittedArrays ) {
  9728. // console.log( object );
  9729. return;
  9730. }
  9731. var normalType = bufferGuessNormalType( material ),
  9732. vertexColorType = bufferGuessVertexColorType( material ),
  9733. uvType = bufferGuessUVType( material ),
  9734. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  9735. var f, fl, fi, face,
  9736. vertexNormals, faceNormal, normal,
  9737. vertexColors, faceColor,
  9738. vertexTangents,
  9739. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  9740. c1, c2, c3, c4,
  9741. sw1, sw2, sw3, sw4,
  9742. si1, si2, si3, si4,
  9743. sa1, sa2, sa3, sa4,
  9744. sb1, sb2, sb3, sb4,
  9745. m, ml, i, il,
  9746. vn, uvi, uv2i,
  9747. vk, vkl, vka,
  9748. nka, chf, faceVertexNormals,
  9749. a,
  9750. vertexIndex = 0,
  9751. offset = 0,
  9752. offset_uv = 0,
  9753. offset_uv2 = 0,
  9754. offset_face = 0,
  9755. offset_normal = 0,
  9756. offset_tangent = 0,
  9757. offset_line = 0,
  9758. offset_color = 0,
  9759. offset_skin = 0,
  9760. offset_morphTarget = 0,
  9761. offset_custom = 0,
  9762. offset_customSrc = 0,
  9763. value,
  9764. vertexArray = geometryGroup.__vertexArray,
  9765. uvArray = geometryGroup.__uvArray,
  9766. uv2Array = geometryGroup.__uv2Array,
  9767. normalArray = geometryGroup.__normalArray,
  9768. tangentArray = geometryGroup.__tangentArray,
  9769. colorArray = geometryGroup.__colorArray,
  9770. skinIndexArray = geometryGroup.__skinIndexArray,
  9771. skinWeightArray = geometryGroup.__skinWeightArray,
  9772. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  9773. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  9774. customAttributes = geometryGroup.__webglCustomAttributesList,
  9775. customAttribute,
  9776. faceArray = geometryGroup.__faceArray,
  9777. lineArray = geometryGroup.__lineArray,
  9778. geometry = object.geometry, // this is shared for all chunks
  9779. dirtyVertices = geometry.verticesNeedUpdate,
  9780. dirtyElements = geometry.elementsNeedUpdate,
  9781. dirtyUvs = geometry.uvsNeedUpdate,
  9782. dirtyNormals = geometry.normalsNeedUpdate,
  9783. dirtyTangents = geometry.tangentsNeedUpdate,
  9784. dirtyColors = geometry.colorsNeedUpdate,
  9785. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  9786. vertices = geometry.vertices,
  9787. chunk_faces3 = geometryGroup.faces3,
  9788. chunk_faces4 = geometryGroup.faces4,
  9789. obj_faces = geometry.faces,
  9790. obj_uvs = geometry.faceVertexUvs[ 0 ],
  9791. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  9792. obj_colors = geometry.colors,
  9793. obj_skinIndices = geometry.skinIndices,
  9794. obj_skinWeights = geometry.skinWeights,
  9795. morphTargets = geometry.morphTargets,
  9796. morphNormals = geometry.morphNormals;
  9797. if ( dirtyVertices ) {
  9798. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  9799. face = obj_faces[ chunk_faces3[ f ] ];
  9800. v1 = vertices[ face.a ];
  9801. v2 = vertices[ face.b ];
  9802. v3 = vertices[ face.c ];
  9803. vertexArray[ offset ] = v1.x;
  9804. vertexArray[ offset + 1 ] = v1.y;
  9805. vertexArray[ offset + 2 ] = v1.z;
  9806. vertexArray[ offset + 3 ] = v2.x;
  9807. vertexArray[ offset + 4 ] = v2.y;
  9808. vertexArray[ offset + 5 ] = v2.z;
  9809. vertexArray[ offset + 6 ] = v3.x;
  9810. vertexArray[ offset + 7 ] = v3.y;
  9811. vertexArray[ offset + 8 ] = v3.z;
  9812. offset += 9;
  9813. }
  9814. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  9815. face = obj_faces[ chunk_faces4[ f ] ];
  9816. v1 = vertices[ face.a ];
  9817. v2 = vertices[ face.b ];
  9818. v3 = vertices[ face.c ];
  9819. v4 = vertices[ face.d ];
  9820. vertexArray[ offset ] = v1.x;
  9821. vertexArray[ offset + 1 ] = v1.y;
  9822. vertexArray[ offset + 2 ] = v1.z;
  9823. vertexArray[ offset + 3 ] = v2.x;
  9824. vertexArray[ offset + 4 ] = v2.y;
  9825. vertexArray[ offset + 5 ] = v2.z;
  9826. vertexArray[ offset + 6 ] = v3.x;
  9827. vertexArray[ offset + 7 ] = v3.y;
  9828. vertexArray[ offset + 8 ] = v3.z;
  9829. vertexArray[ offset + 9 ] = v4.x;
  9830. vertexArray[ offset + 10 ] = v4.y;
  9831. vertexArray[ offset + 11 ] = v4.z;
  9832. offset += 12;
  9833. }
  9834. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  9835. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9836. }
  9837. if ( dirtyMorphTargets ) {
  9838. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  9839. offset_morphTarget = 0;
  9840. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  9841. chf = chunk_faces3[ f ];
  9842. face = obj_faces[ chf ];
  9843. // morph positions
  9844. v1 = morphTargets[ vk ].vertices[ face.a ];
  9845. v2 = morphTargets[ vk ].vertices[ face.b ];
  9846. v3 = morphTargets[ vk ].vertices[ face.c ];
  9847. vka = morphTargetsArrays[ vk ];
  9848. vka[ offset_morphTarget ] = v1.x;
  9849. vka[ offset_morphTarget + 1 ] = v1.y;
  9850. vka[ offset_morphTarget + 2 ] = v1.z;
  9851. vka[ offset_morphTarget + 3 ] = v2.x;
  9852. vka[ offset_morphTarget + 4 ] = v2.y;
  9853. vka[ offset_morphTarget + 5 ] = v2.z;
  9854. vka[ offset_morphTarget + 6 ] = v3.x;
  9855. vka[ offset_morphTarget + 7 ] = v3.y;
  9856. vka[ offset_morphTarget + 8 ] = v3.z;
  9857. // morph normals
  9858. if ( material.morphNormals ) {
  9859. if ( needsSmoothNormals ) {
  9860. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  9861. n1 = faceVertexNormals.a;
  9862. n2 = faceVertexNormals.b;
  9863. n3 = faceVertexNormals.c;
  9864. } else {
  9865. n1 = morphNormals[ vk ].faceNormals[ chf ];
  9866. n2 = n1;
  9867. n3 = n1;
  9868. }
  9869. nka = morphNormalsArrays[ vk ];
  9870. nka[ offset_morphTarget ] = n1.x;
  9871. nka[ offset_morphTarget + 1 ] = n1.y;
  9872. nka[ offset_morphTarget + 2 ] = n1.z;
  9873. nka[ offset_morphTarget + 3 ] = n2.x;
  9874. nka[ offset_morphTarget + 4 ] = n2.y;
  9875. nka[ offset_morphTarget + 5 ] = n2.z;
  9876. nka[ offset_morphTarget + 6 ] = n3.x;
  9877. nka[ offset_morphTarget + 7 ] = n3.y;
  9878. nka[ offset_morphTarget + 8 ] = n3.z;
  9879. }
  9880. //
  9881. offset_morphTarget += 9;
  9882. }
  9883. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  9884. chf = chunk_faces4[ f ];
  9885. face = obj_faces[ chf ];
  9886. // morph positions
  9887. v1 = morphTargets[ vk ].vertices[ face.a ];
  9888. v2 = morphTargets[ vk ].vertices[ face.b ];
  9889. v3 = morphTargets[ vk ].vertices[ face.c ];
  9890. v4 = morphTargets[ vk ].vertices[ face.d ];
  9891. vka = morphTargetsArrays[ vk ];
  9892. vka[ offset_morphTarget ] = v1.x;
  9893. vka[ offset_morphTarget + 1 ] = v1.y;
  9894. vka[ offset_morphTarget + 2 ] = v1.z;
  9895. vka[ offset_morphTarget + 3 ] = v2.x;
  9896. vka[ offset_morphTarget + 4 ] = v2.y;
  9897. vka[ offset_morphTarget + 5 ] = v2.z;
  9898. vka[ offset_morphTarget + 6 ] = v3.x;
  9899. vka[ offset_morphTarget + 7 ] = v3.y;
  9900. vka[ offset_morphTarget + 8 ] = v3.z;
  9901. vka[ offset_morphTarget + 9 ] = v4.x;
  9902. vka[ offset_morphTarget + 10 ] = v4.y;
  9903. vka[ offset_morphTarget + 11 ] = v4.z;
  9904. // morph normals
  9905. if ( material.morphNormals ) {
  9906. if ( needsSmoothNormals ) {
  9907. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  9908. n1 = faceVertexNormals.a;
  9909. n2 = faceVertexNormals.b;
  9910. n3 = faceVertexNormals.c;
  9911. n4 = faceVertexNormals.d;
  9912. } else {
  9913. n1 = morphNormals[ vk ].faceNormals[ chf ];
  9914. n2 = n1;
  9915. n3 = n1;
  9916. n4 = n1;
  9917. }
  9918. nka = morphNormalsArrays[ vk ];
  9919. nka[ offset_morphTarget ] = n1.x;
  9920. nka[ offset_morphTarget + 1 ] = n1.y;
  9921. nka[ offset_morphTarget + 2 ] = n1.z;
  9922. nka[ offset_morphTarget + 3 ] = n2.x;
  9923. nka[ offset_morphTarget + 4 ] = n2.y;
  9924. nka[ offset_morphTarget + 5 ] = n2.z;
  9925. nka[ offset_morphTarget + 6 ] = n3.x;
  9926. nka[ offset_morphTarget + 7 ] = n3.y;
  9927. nka[ offset_morphTarget + 8 ] = n3.z;
  9928. nka[ offset_morphTarget + 9 ] = n4.x;
  9929. nka[ offset_morphTarget + 10 ] = n4.y;
  9930. nka[ offset_morphTarget + 11 ] = n4.z;
  9931. }
  9932. //
  9933. offset_morphTarget += 12;
  9934. }
  9935. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  9936. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  9937. if ( material.morphNormals ) {
  9938. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  9939. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  9940. }
  9941. }
  9942. }
  9943. if ( obj_skinWeights.length ) {
  9944. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  9945. face = obj_faces[ chunk_faces3[ f ] ];
  9946. // weights
  9947. sw1 = obj_skinWeights[ face.a ];
  9948. sw2 = obj_skinWeights[ face.b ];
  9949. sw3 = obj_skinWeights[ face.c ];
  9950. skinWeightArray[ offset_skin ] = sw1.x;
  9951. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  9952. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  9953. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  9954. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  9955. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  9956. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  9957. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  9958. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  9959. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  9960. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  9961. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  9962. // indices
  9963. si1 = obj_skinIndices[ face.a ];
  9964. si2 = obj_skinIndices[ face.b ];
  9965. si3 = obj_skinIndices[ face.c ];
  9966. skinIndexArray[ offset_skin ] = si1.x;
  9967. skinIndexArray[ offset_skin + 1 ] = si1.y;
  9968. skinIndexArray[ offset_skin + 2 ] = si1.z;
  9969. skinIndexArray[ offset_skin + 3 ] = si1.w;
  9970. skinIndexArray[ offset_skin + 4 ] = si2.x;
  9971. skinIndexArray[ offset_skin + 5 ] = si2.y;
  9972. skinIndexArray[ offset_skin + 6 ] = si2.z;
  9973. skinIndexArray[ offset_skin + 7 ] = si2.w;
  9974. skinIndexArray[ offset_skin + 8 ] = si3.x;
  9975. skinIndexArray[ offset_skin + 9 ] = si3.y;
  9976. skinIndexArray[ offset_skin + 10 ] = si3.z;
  9977. skinIndexArray[ offset_skin + 11 ] = si3.w;
  9978. offset_skin += 12;
  9979. }
  9980. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  9981. face = obj_faces[ chunk_faces4[ f ] ];
  9982. // weights
  9983. sw1 = obj_skinWeights[ face.a ];
  9984. sw2 = obj_skinWeights[ face.b ];
  9985. sw3 = obj_skinWeights[ face.c ];
  9986. sw4 = obj_skinWeights[ face.d ];
  9987. skinWeightArray[ offset_skin ] = sw1.x;
  9988. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  9989. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  9990. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  9991. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  9992. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  9993. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  9994. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  9995. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  9996. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  9997. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  9998. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  9999. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  10000. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  10001. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  10002. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  10003. // indices
  10004. si1 = obj_skinIndices[ face.a ];
  10005. si2 = obj_skinIndices[ face.b ];
  10006. si3 = obj_skinIndices[ face.c ];
  10007. si4 = obj_skinIndices[ face.d ];
  10008. skinIndexArray[ offset_skin ] = si1.x;
  10009. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10010. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10011. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10012. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10013. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10014. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10015. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10016. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10017. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10018. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10019. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10020. skinIndexArray[ offset_skin + 12 ] = si4.x;
  10021. skinIndexArray[ offset_skin + 13 ] = si4.y;
  10022. skinIndexArray[ offset_skin + 14 ] = si4.z;
  10023. skinIndexArray[ offset_skin + 15 ] = si4.w;
  10024. offset_skin += 16;
  10025. }
  10026. if ( offset_skin > 0 ) {
  10027. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10028. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  10029. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10030. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  10031. }
  10032. }
  10033. if ( dirtyColors && vertexColorType ) {
  10034. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10035. face = obj_faces[ chunk_faces3[ f ] ];
  10036. vertexColors = face.vertexColors;
  10037. faceColor = face.color;
  10038. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  10039. c1 = vertexColors[ 0 ];
  10040. c2 = vertexColors[ 1 ];
  10041. c3 = vertexColors[ 2 ];
  10042. } else {
  10043. c1 = faceColor;
  10044. c2 = faceColor;
  10045. c3 = faceColor;
  10046. }
  10047. colorArray[ offset_color ] = c1.r;
  10048. colorArray[ offset_color + 1 ] = c1.g;
  10049. colorArray[ offset_color + 2 ] = c1.b;
  10050. colorArray[ offset_color + 3 ] = c2.r;
  10051. colorArray[ offset_color + 4 ] = c2.g;
  10052. colorArray[ offset_color + 5 ] = c2.b;
  10053. colorArray[ offset_color + 6 ] = c3.r;
  10054. colorArray[ offset_color + 7 ] = c3.g;
  10055. colorArray[ offset_color + 8 ] = c3.b;
  10056. offset_color += 9;
  10057. }
  10058. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10059. face = obj_faces[ chunk_faces4[ f ] ];
  10060. vertexColors = face.vertexColors;
  10061. faceColor = face.color;
  10062. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  10063. c1 = vertexColors[ 0 ];
  10064. c2 = vertexColors[ 1 ];
  10065. c3 = vertexColors[ 2 ];
  10066. c4 = vertexColors[ 3 ];
  10067. } else {
  10068. c1 = faceColor;
  10069. c2 = faceColor;
  10070. c3 = faceColor;
  10071. c4 = faceColor;
  10072. }
  10073. colorArray[ offset_color ] = c1.r;
  10074. colorArray[ offset_color + 1 ] = c1.g;
  10075. colorArray[ offset_color + 2 ] = c1.b;
  10076. colorArray[ offset_color + 3 ] = c2.r;
  10077. colorArray[ offset_color + 4 ] = c2.g;
  10078. colorArray[ offset_color + 5 ] = c2.b;
  10079. colorArray[ offset_color + 6 ] = c3.r;
  10080. colorArray[ offset_color + 7 ] = c3.g;
  10081. colorArray[ offset_color + 8 ] = c3.b;
  10082. colorArray[ offset_color + 9 ] = c4.r;
  10083. colorArray[ offset_color + 10 ] = c4.g;
  10084. colorArray[ offset_color + 11 ] = c4.b;
  10085. offset_color += 12;
  10086. }
  10087. if ( offset_color > 0 ) {
  10088. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10089. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10090. }
  10091. }
  10092. if ( dirtyTangents && geometry.hasTangents ) {
  10093. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10094. face = obj_faces[ chunk_faces3[ f ] ];
  10095. vertexTangents = face.vertexTangents;
  10096. t1 = vertexTangents[ 0 ];
  10097. t2 = vertexTangents[ 1 ];
  10098. t3 = vertexTangents[ 2 ];
  10099. tangentArray[ offset_tangent ] = t1.x;
  10100. tangentArray[ offset_tangent + 1 ] = t1.y;
  10101. tangentArray[ offset_tangent + 2 ] = t1.z;
  10102. tangentArray[ offset_tangent + 3 ] = t1.w;
  10103. tangentArray[ offset_tangent + 4 ] = t2.x;
  10104. tangentArray[ offset_tangent + 5 ] = t2.y;
  10105. tangentArray[ offset_tangent + 6 ] = t2.z;
  10106. tangentArray[ offset_tangent + 7 ] = t2.w;
  10107. tangentArray[ offset_tangent + 8 ] = t3.x;
  10108. tangentArray[ offset_tangent + 9 ] = t3.y;
  10109. tangentArray[ offset_tangent + 10 ] = t3.z;
  10110. tangentArray[ offset_tangent + 11 ] = t3.w;
  10111. offset_tangent += 12;
  10112. }
  10113. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10114. face = obj_faces[ chunk_faces4[ f ] ];
  10115. vertexTangents = face.vertexTangents;
  10116. t1 = vertexTangents[ 0 ];
  10117. t2 = vertexTangents[ 1 ];
  10118. t3 = vertexTangents[ 2 ];
  10119. t4 = vertexTangents[ 3 ];
  10120. tangentArray[ offset_tangent ] = t1.x;
  10121. tangentArray[ offset_tangent + 1 ] = t1.y;
  10122. tangentArray[ offset_tangent + 2 ] = t1.z;
  10123. tangentArray[ offset_tangent + 3 ] = t1.w;
  10124. tangentArray[ offset_tangent + 4 ] = t2.x;
  10125. tangentArray[ offset_tangent + 5 ] = t2.y;
  10126. tangentArray[ offset_tangent + 6 ] = t2.z;
  10127. tangentArray[ offset_tangent + 7 ] = t2.w;
  10128. tangentArray[ offset_tangent + 8 ] = t3.x;
  10129. tangentArray[ offset_tangent + 9 ] = t3.y;
  10130. tangentArray[ offset_tangent + 10 ] = t3.z;
  10131. tangentArray[ offset_tangent + 11 ] = t3.w;
  10132. tangentArray[ offset_tangent + 12 ] = t4.x;
  10133. tangentArray[ offset_tangent + 13 ] = t4.y;
  10134. tangentArray[ offset_tangent + 14 ] = t4.z;
  10135. tangentArray[ offset_tangent + 15 ] = t4.w;
  10136. offset_tangent += 16;
  10137. }
  10138. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10139. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  10140. }
  10141. if ( dirtyNormals && normalType ) {
  10142. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10143. face = obj_faces[ chunk_faces3[ f ] ];
  10144. vertexNormals = face.vertexNormals;
  10145. faceNormal = face.normal;
  10146. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  10147. for ( i = 0; i < 3; i ++ ) {
  10148. vn = vertexNormals[ i ];
  10149. normalArray[ offset_normal ] = vn.x;
  10150. normalArray[ offset_normal + 1 ] = vn.y;
  10151. normalArray[ offset_normal + 2 ] = vn.z;
  10152. offset_normal += 3;
  10153. }
  10154. } else {
  10155. for ( i = 0; i < 3; i ++ ) {
  10156. normalArray[ offset_normal ] = faceNormal.x;
  10157. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10158. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10159. offset_normal += 3;
  10160. }
  10161. }
  10162. }
  10163. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10164. face = obj_faces[ chunk_faces4[ f ] ];
  10165. vertexNormals = face.vertexNormals;
  10166. faceNormal = face.normal;
  10167. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  10168. for ( i = 0; i < 4; i ++ ) {
  10169. vn = vertexNormals[ i ];
  10170. normalArray[ offset_normal ] = vn.x;
  10171. normalArray[ offset_normal + 1 ] = vn.y;
  10172. normalArray[ offset_normal + 2 ] = vn.z;
  10173. offset_normal += 3;
  10174. }
  10175. } else {
  10176. for ( i = 0; i < 4; i ++ ) {
  10177. normalArray[ offset_normal ] = faceNormal.x;
  10178. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10179. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10180. offset_normal += 3;
  10181. }
  10182. }
  10183. }
  10184. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10185. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10186. }
  10187. if ( dirtyUvs && obj_uvs && uvType ) {
  10188. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10189. fi = chunk_faces3[ f ];
  10190. face = obj_faces[ fi ];
  10191. uv = obj_uvs[ fi ];
  10192. if ( uv === undefined ) continue;
  10193. for ( i = 0; i < 3; i ++ ) {
  10194. uvi = uv[ i ];
  10195. uvArray[ offset_uv ] = uvi.u;
  10196. uvArray[ offset_uv + 1 ] = uvi.v;
  10197. offset_uv += 2;
  10198. }
  10199. }
  10200. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10201. fi = chunk_faces4[ f ];
  10202. face = obj_faces[ fi ];
  10203. uv = obj_uvs[ fi ];
  10204. if ( uv === undefined ) continue;
  10205. for ( i = 0; i < 4; i ++ ) {
  10206. uvi = uv[ i ];
  10207. uvArray[ offset_uv ] = uvi.u;
  10208. uvArray[ offset_uv + 1 ] = uvi.v;
  10209. offset_uv += 2;
  10210. }
  10211. }
  10212. if ( offset_uv > 0 ) {
  10213. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10214. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  10215. }
  10216. }
  10217. if ( dirtyUvs && obj_uvs2 && uvType ) {
  10218. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10219. fi = chunk_faces3[ f ];
  10220. face = obj_faces[ fi ];
  10221. uv2 = obj_uvs2[ fi ];
  10222. if ( uv2 === undefined ) continue;
  10223. for ( i = 0; i < 3; i ++ ) {
  10224. uv2i = uv2[ i ];
  10225. uv2Array[ offset_uv2 ] = uv2i.u;
  10226. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10227. offset_uv2 += 2;
  10228. }
  10229. }
  10230. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10231. fi = chunk_faces4[ f ];
  10232. face = obj_faces[ fi ];
  10233. uv2 = obj_uvs2[ fi ];
  10234. if ( uv2 === undefined ) continue;
  10235. for ( i = 0; i < 4; i ++ ) {
  10236. uv2i = uv2[ i ];
  10237. uv2Array[ offset_uv2 ] = uv2i.u;
  10238. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10239. offset_uv2 += 2;
  10240. }
  10241. }
  10242. if ( offset_uv2 > 0 ) {
  10243. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10244. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  10245. }
  10246. }
  10247. if ( dirtyElements ) {
  10248. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10249. face = obj_faces[ chunk_faces3[ f ] ];
  10250. faceArray[ offset_face ] = vertexIndex;
  10251. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10252. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  10253. offset_face += 3;
  10254. lineArray[ offset_line ] = vertexIndex;
  10255. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10256. lineArray[ offset_line + 2 ] = vertexIndex;
  10257. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  10258. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10259. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10260. offset_line += 6;
  10261. vertexIndex += 3;
  10262. }
  10263. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10264. face = obj_faces[ chunk_faces4[ f ] ];
  10265. faceArray[ offset_face ] = vertexIndex;
  10266. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10267. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  10268. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  10269. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  10270. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  10271. offset_face += 6;
  10272. lineArray[ offset_line ] = vertexIndex;
  10273. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10274. lineArray[ offset_line + 2 ] = vertexIndex;
  10275. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  10276. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10277. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10278. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  10279. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  10280. offset_line += 8;
  10281. vertexIndex += 4;
  10282. }
  10283. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10284. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  10285. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10286. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  10287. }
  10288. if ( customAttributes ) {
  10289. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10290. customAttribute = customAttributes[ i ];
  10291. if ( ! customAttribute.__original.needsUpdate ) continue;
  10292. offset_custom = 0;
  10293. offset_customSrc = 0;
  10294. if ( customAttribute.size === 1 ) {
  10295. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10296. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10297. face = obj_faces[ chunk_faces3[ f ] ];
  10298. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10299. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10300. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10301. offset_custom += 3;
  10302. }
  10303. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10304. face = obj_faces[ chunk_faces4[ f ] ];
  10305. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10306. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10307. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10308. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  10309. offset_custom += 4;
  10310. }
  10311. } else if ( customAttribute.boundTo === "faces" ) {
  10312. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10313. value = customAttribute.value[ chunk_faces3[ f ] ];
  10314. customAttribute.array[ offset_custom ] = value;
  10315. customAttribute.array[ offset_custom + 1 ] = value;
  10316. customAttribute.array[ offset_custom + 2 ] = value;
  10317. offset_custom += 3;
  10318. }
  10319. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10320. value = customAttribute.value[ chunk_faces4[ f ] ];
  10321. customAttribute.array[ offset_custom ] = value;
  10322. customAttribute.array[ offset_custom + 1 ] = value;
  10323. customAttribute.array[ offset_custom + 2 ] = value;
  10324. customAttribute.array[ offset_custom + 3 ] = value;
  10325. offset_custom += 4;
  10326. }
  10327. }
  10328. } else if ( customAttribute.size === 2 ) {
  10329. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10330. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10331. face = obj_faces[ chunk_faces3[ f ] ];
  10332. v1 = customAttribute.value[ face.a ];
  10333. v2 = customAttribute.value[ face.b ];
  10334. v3 = customAttribute.value[ face.c ];
  10335. customAttribute.array[ offset_custom ] = v1.x;
  10336. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10337. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10338. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10339. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10340. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10341. offset_custom += 6;
  10342. }
  10343. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10344. face = obj_faces[ chunk_faces4[ f ] ];
  10345. v1 = customAttribute.value[ face.a ];
  10346. v2 = customAttribute.value[ face.b ];
  10347. v3 = customAttribute.value[ face.c ];
  10348. v4 = customAttribute.value[ face.d ];
  10349. customAttribute.array[ offset_custom ] = v1.x;
  10350. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10351. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10352. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10353. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10354. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10355. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10356. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10357. offset_custom += 8;
  10358. }
  10359. } else if ( customAttribute.boundTo === "faces" ) {
  10360. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10361. value = customAttribute.value[ chunk_faces3[ f ] ];
  10362. v1 = value;
  10363. v2 = value;
  10364. v3 = value;
  10365. customAttribute.array[ offset_custom ] = v1.x;
  10366. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10367. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10368. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10369. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10370. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10371. offset_custom += 6;
  10372. }
  10373. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10374. value = customAttribute.value[ chunk_faces4[ f ] ];
  10375. v1 = value;
  10376. v2 = value;
  10377. v3 = value;
  10378. v4 = value;
  10379. customAttribute.array[ offset_custom ] = v1.x;
  10380. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10381. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10382. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10383. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10384. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10385. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10386. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10387. offset_custom += 8;
  10388. }
  10389. }
  10390. } else if ( customAttribute.size === 3 ) {
  10391. var pp;
  10392. if ( customAttribute.type === "c" ) {
  10393. pp = [ "r", "g", "b" ];
  10394. } else {
  10395. pp = [ "x", "y", "z" ];
  10396. }
  10397. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10398. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10399. face = obj_faces[ chunk_faces3[ f ] ];
  10400. v1 = customAttribute.value[ face.a ];
  10401. v2 = customAttribute.value[ face.b ];
  10402. v3 = customAttribute.value[ face.c ];
  10403. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10404. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10405. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10406. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10407. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10408. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10409. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10410. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10411. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10412. offset_custom += 9;
  10413. }
  10414. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10415. face = obj_faces[ chunk_faces4[ f ] ];
  10416. v1 = customAttribute.value[ face.a ];
  10417. v2 = customAttribute.value[ face.b ];
  10418. v3 = customAttribute.value[ face.c ];
  10419. v4 = customAttribute.value[ face.d ];
  10420. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10421. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10422. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10423. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10424. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10425. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10426. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10427. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10428. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10429. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10430. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10431. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10432. offset_custom += 12;
  10433. }
  10434. } else if ( customAttribute.boundTo === "faces" ) {
  10435. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10436. value = customAttribute.value[ chunk_faces3[ f ] ];
  10437. v1 = value;
  10438. v2 = value;
  10439. v3 = value;
  10440. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10441. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10442. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10443. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10444. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10445. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10446. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10447. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10448. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10449. offset_custom += 9;
  10450. }
  10451. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10452. value = customAttribute.value[ chunk_faces4[ f ] ];
  10453. v1 = value;
  10454. v2 = value;
  10455. v3 = value;
  10456. v4 = value;
  10457. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10458. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10459. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10460. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10461. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10462. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10463. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10464. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10465. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10466. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10467. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10468. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10469. offset_custom += 12;
  10470. }
  10471. } else if ( customAttribute.boundTo === "faceVertices" ) {
  10472. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10473. value = customAttribute.value[ chunk_faces3[ f ] ];
  10474. v1 = value[ 0 ];
  10475. v2 = value[ 1 ];
  10476. v3 = value[ 2 ];
  10477. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10478. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10479. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10480. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10481. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10482. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10483. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10484. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10485. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10486. offset_custom += 9;
  10487. }
  10488. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10489. value = customAttribute.value[ chunk_faces4[ f ] ];
  10490. v1 = value[ 0 ];
  10491. v2 = value[ 1 ];
  10492. v3 = value[ 2 ];
  10493. v4 = value[ 3 ];
  10494. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10495. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10496. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10497. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10498. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10499. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10500. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10501. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10502. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10503. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10504. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10505. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10506. offset_custom += 12;
  10507. }
  10508. }
  10509. } else if ( customAttribute.size === 4 ) {
  10510. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10511. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10512. face = obj_faces[ chunk_faces3[ f ] ];
  10513. v1 = customAttribute.value[ face.a ];
  10514. v2 = customAttribute.value[ face.b ];
  10515. v3 = customAttribute.value[ face.c ];
  10516. customAttribute.array[ offset_custom ] = v1.x;
  10517. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10518. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10519. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10520. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10521. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10522. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10523. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10524. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10525. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10526. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10527. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10528. offset_custom += 12;
  10529. }
  10530. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10531. face = obj_faces[ chunk_faces4[ f ] ];
  10532. v1 = customAttribute.value[ face.a ];
  10533. v2 = customAttribute.value[ face.b ];
  10534. v3 = customAttribute.value[ face.c ];
  10535. v4 = customAttribute.value[ face.d ];
  10536. customAttribute.array[ offset_custom ] = v1.x;
  10537. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10538. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10539. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10540. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10541. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10542. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10543. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10544. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10545. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10546. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10547. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10548. customAttribute.array[ offset_custom + 12 ] = v4.x;
  10549. customAttribute.array[ offset_custom + 13 ] = v4.y;
  10550. customAttribute.array[ offset_custom + 14 ] = v4.z;
  10551. customAttribute.array[ offset_custom + 15 ] = v4.w;
  10552. offset_custom += 16;
  10553. }
  10554. } else if ( customAttribute.boundTo === "faces" ) {
  10555. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10556. value = customAttribute.value[ chunk_faces3[ f ] ];
  10557. v1 = value;
  10558. v2 = value;
  10559. v3 = value;
  10560. customAttribute.array[ offset_custom ] = v1.x;
  10561. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10562. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10563. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10564. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10565. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10566. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10567. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10568. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10569. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10570. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10571. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10572. offset_custom += 12;
  10573. }
  10574. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10575. value = customAttribute.value[ chunk_faces4[ f ] ];
  10576. v1 = value;
  10577. v2 = value;
  10578. v3 = value;
  10579. v4 = value;
  10580. customAttribute.array[ offset_custom ] = v1.x;
  10581. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10582. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10583. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10584. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10585. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10586. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10587. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10588. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10589. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10590. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10591. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10592. customAttribute.array[ offset_custom + 12 ] = v4.x;
  10593. customAttribute.array[ offset_custom + 13 ] = v4.y;
  10594. customAttribute.array[ offset_custom + 14 ] = v4.z;
  10595. customAttribute.array[ offset_custom + 15 ] = v4.w;
  10596. offset_custom += 16;
  10597. }
  10598. } else if ( customAttribute.boundTo === "faceVertices" ) {
  10599. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10600. value = customAttribute.value[ chunk_faces3[ f ] ];
  10601. v1 = value[ 0 ];
  10602. v2 = value[ 1 ];
  10603. v3 = value[ 2 ];
  10604. customAttribute.array[ offset_custom ] = v1.x;
  10605. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10606. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10607. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10608. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10609. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10610. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10611. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10612. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10613. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10614. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10615. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10616. offset_custom += 12;
  10617. }
  10618. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10619. value = customAttribute.value[ chunk_faces4[ f ] ];
  10620. v1 = value[ 0 ];
  10621. v2 = value[ 1 ];
  10622. v3 = value[ 2 ];
  10623. v4 = value[ 3 ];
  10624. customAttribute.array[ offset_custom ] = v1.x;
  10625. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10626. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10627. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10628. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10629. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10630. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10631. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10632. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10633. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10634. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10635. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10636. customAttribute.array[ offset_custom + 12 ] = v4.x;
  10637. customAttribute.array[ offset_custom + 13 ] = v4.y;
  10638. customAttribute.array[ offset_custom + 14 ] = v4.z;
  10639. customAttribute.array[ offset_custom + 15 ] = v4.w;
  10640. offset_custom += 16;
  10641. }
  10642. }
  10643. }
  10644. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10645. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10646. }
  10647. }
  10648. if ( dispose ) {
  10649. delete geometryGroup.__inittedArrays;
  10650. delete geometryGroup.__colorArray;
  10651. delete geometryGroup.__normalArray;
  10652. delete geometryGroup.__tangentArray;
  10653. delete geometryGroup.__uvArray;
  10654. delete geometryGroup.__uv2Array;
  10655. delete geometryGroup.__faceArray;
  10656. delete geometryGroup.__vertexArray;
  10657. delete geometryGroup.__lineArray;
  10658. delete geometryGroup.__skinIndexArray;
  10659. delete geometryGroup.__skinWeightArray;
  10660. }
  10661. };
  10662. function setDirectBuffers ( geometry, hint, dispose ) {
  10663. var attributes = geometry.attributes;
  10664. var index = attributes[ "index" ];
  10665. var position = attributes[ "position" ];
  10666. var normal = attributes[ "normal" ];
  10667. var uv = attributes[ "uv" ];
  10668. var color = attributes[ "color" ];
  10669. var tangent = attributes[ "tangent" ];
  10670. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  10671. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  10672. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  10673. }
  10674. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  10675. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  10676. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  10677. }
  10678. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  10679. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  10680. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  10681. }
  10682. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  10683. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  10684. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  10685. }
  10686. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  10687. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  10688. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  10689. }
  10690. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  10691. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  10692. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  10693. }
  10694. if ( dispose ) {
  10695. for ( var i in geometry.attributes ) {
  10696. delete geometry.attributes[ i ].array;
  10697. }
  10698. }
  10699. };
  10700. // Buffer rendering
  10701. this.renderBufferImmediate = function ( object, program, material ) {
  10702. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  10703. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  10704. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  10705. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  10706. if ( object.hasPositions ) {
  10707. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  10708. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  10709. _gl.enableVertexAttribArray( program.attributes.position );
  10710. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  10711. }
  10712. if ( object.hasNormals ) {
  10713. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  10714. if ( material.shading === THREE.FlatShading ) {
  10715. var nx, ny, nz,
  10716. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  10717. normalArray,
  10718. i, il = object.count * 3;
  10719. for( i = 0; i < il; i += 9 ) {
  10720. normalArray = object.normalArray;
  10721. nax = normalArray[ i ];
  10722. nay = normalArray[ i + 1 ];
  10723. naz = normalArray[ i + 2 ];
  10724. nbx = normalArray[ i + 3 ];
  10725. nby = normalArray[ i + 4 ];
  10726. nbz = normalArray[ i + 5 ];
  10727. ncx = normalArray[ i + 6 ];
  10728. ncy = normalArray[ i + 7 ];
  10729. ncz = normalArray[ i + 8 ];
  10730. nx = ( nax + nbx + ncx ) / 3;
  10731. ny = ( nay + nby + ncy ) / 3;
  10732. nz = ( naz + nbz + ncz ) / 3;
  10733. normalArray[ i ] = nx;
  10734. normalArray[ i + 1 ] = ny;
  10735. normalArray[ i + 2 ] = nz;
  10736. normalArray[ i + 3 ] = nx;
  10737. normalArray[ i + 4 ] = ny;
  10738. normalArray[ i + 5 ] = nz;
  10739. normalArray[ i + 6 ] = nx;
  10740. normalArray[ i + 7 ] = ny;
  10741. normalArray[ i + 8 ] = nz;
  10742. }
  10743. }
  10744. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  10745. _gl.enableVertexAttribArray( program.attributes.normal );
  10746. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  10747. }
  10748. if ( object.hasUvs && material.map ) {
  10749. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  10750. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  10751. _gl.enableVertexAttribArray( program.attributes.uv );
  10752. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  10753. }
  10754. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  10755. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  10756. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  10757. _gl.enableVertexAttribArray( program.attributes.color );
  10758. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  10759. }
  10760. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  10761. object.count = 0;
  10762. };
  10763. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  10764. if ( material.visible === false ) return;
  10765. var program, attributes, linewidth, primitives, a, attribute;
  10766. program = setProgram( camera, lights, fog, material, object );
  10767. attributes = program.attributes;
  10768. var updateBuffers = false,
  10769. wireframeBit = material.wireframe ? 1 : 0,
  10770. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  10771. if ( geometryHash !== _currentGeometryGroupHash ) {
  10772. _currentGeometryGroupHash = geometryHash;
  10773. updateBuffers = true;
  10774. }
  10775. // render mesh
  10776. if ( object instanceof THREE.Mesh ) {
  10777. var offsets = geometry.offsets;
  10778. // if there is more than 1 chunk
  10779. // must set attribute pointers to use new offsets for each chunk
  10780. // even if geometry and materials didn't change
  10781. if ( offsets.length > 1 ) updateBuffers = true;
  10782. for ( var i = 0, il = offsets.length; i < il; ++ i ) {
  10783. var startIndex = offsets[ i ].index;
  10784. if ( updateBuffers ) {
  10785. // vertices
  10786. var position = geometry.attributes[ "position" ];
  10787. var positionSize = position.itemSize;
  10788. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  10789. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  10790. // normals
  10791. var normal = geometry.attributes[ "normal" ];
  10792. if ( attributes.normal >= 0 && normal ) {
  10793. var normalSize = normal.itemSize;
  10794. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  10795. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  10796. }
  10797. // uvs
  10798. var uv = geometry.attributes[ "uv" ];
  10799. if ( attributes.uv >= 0 && uv ) {
  10800. if ( uv.buffer ) {
  10801. var uvSize = uv.itemSize;
  10802. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  10803. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  10804. _gl.enableVertexAttribArray( attributes.uv );
  10805. } else {
  10806. _gl.disableVertexAttribArray( attributes.uv );
  10807. }
  10808. }
  10809. // colors
  10810. var color = geometry.attributes[ "color" ];
  10811. if ( attributes.color >= 0 && color ) {
  10812. var colorSize = color.itemSize;
  10813. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  10814. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  10815. }
  10816. // tangents
  10817. var tangent = geometry.attributes[ "tangent" ];
  10818. if ( attributes.tangent >= 0 && tangent ) {
  10819. var tangentSize = tangent.itemSize;
  10820. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  10821. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  10822. }
  10823. // indices
  10824. var index = geometry.attributes[ "index" ];
  10825. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  10826. }
  10827. // render indexed triangles
  10828. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  10829. _this.info.render.calls ++;
  10830. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  10831. _this.info.render.faces += offsets[ i ].count / 3;
  10832. }
  10833. }
  10834. };
  10835. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  10836. if ( material.visible === false ) return;
  10837. var program, attributes, linewidth, primitives, a, attribute, i, il;
  10838. program = setProgram( camera, lights, fog, material, object );
  10839. attributes = program.attributes;
  10840. var updateBuffers = false,
  10841. wireframeBit = material.wireframe ? 1 : 0,
  10842. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  10843. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  10844. _currentGeometryGroupHash = geometryGroupHash;
  10845. updateBuffers = true;
  10846. }
  10847. // vertices
  10848. if ( !material.morphTargets && attributes.position >= 0 ) {
  10849. if ( updateBuffers ) {
  10850. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10851. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  10852. }
  10853. } else {
  10854. if ( object.morphTargetBase ) {
  10855. setupMorphTargets( material, geometryGroup, object );
  10856. }
  10857. }
  10858. if ( updateBuffers ) {
  10859. // custom attributes
  10860. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  10861. if ( geometryGroup.__webglCustomAttributesList ) {
  10862. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  10863. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  10864. if( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  10865. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  10866. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  10867. }
  10868. }
  10869. }
  10870. // colors
  10871. if ( attributes.color >= 0 ) {
  10872. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10873. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  10874. }
  10875. // normals
  10876. if ( attributes.normal >= 0 ) {
  10877. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10878. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  10879. }
  10880. // tangents
  10881. if ( attributes.tangent >= 0 ) {
  10882. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10883. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  10884. }
  10885. // uvs
  10886. if ( attributes.uv >= 0 ) {
  10887. if ( geometryGroup.__webglUVBuffer ) {
  10888. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10889. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  10890. _gl.enableVertexAttribArray( attributes.uv );
  10891. } else {
  10892. _gl.disableVertexAttribArray( attributes.uv );
  10893. }
  10894. }
  10895. if ( attributes.uv2 >= 0 ) {
  10896. if ( geometryGroup.__webglUV2Buffer ) {
  10897. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10898. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  10899. _gl.enableVertexAttribArray( attributes.uv2 );
  10900. } else {
  10901. _gl.disableVertexAttribArray( attributes.uv2 );
  10902. }
  10903. }
  10904. if ( material.skinning &&
  10905. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  10906. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10907. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  10908. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10909. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  10910. }
  10911. }
  10912. // render mesh
  10913. if ( object instanceof THREE.Mesh ) {
  10914. // wireframe
  10915. if ( material.wireframe ) {
  10916. setLineWidth( material.wireframeLinewidth );
  10917. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10918. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  10919. // triangles
  10920. } else {
  10921. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10922. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  10923. }
  10924. _this.info.render.calls ++;
  10925. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  10926. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  10927. // render lines
  10928. } else if ( object instanceof THREE.Line ) {
  10929. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  10930. setLineWidth( material.linewidth );
  10931. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  10932. _this.info.render.calls ++;
  10933. // render particles
  10934. } else if ( object instanceof THREE.ParticleSystem ) {
  10935. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  10936. _this.info.render.calls ++;
  10937. _this.info.render.points += geometryGroup.__webglParticleCount;
  10938. // render ribbon
  10939. } else if ( object instanceof THREE.Ribbon ) {
  10940. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  10941. _this.info.render.calls ++;
  10942. }
  10943. };
  10944. function setupMorphTargets ( material, geometryGroup, object ) {
  10945. // set base
  10946. var attributes = material.program.attributes;
  10947. if ( object.morphTargetBase !== -1 ) {
  10948. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  10949. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  10950. } else if ( attributes.position >= 0 ) {
  10951. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10952. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  10953. }
  10954. if ( object.morphTargetForcedOrder.length ) {
  10955. // set forced order
  10956. var m = 0;
  10957. var order = object.morphTargetForcedOrder;
  10958. var influences = object.morphTargetInfluences;
  10959. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  10960. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  10961. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  10962. if ( material.morphNormals ) {
  10963. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  10964. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  10965. }
  10966. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  10967. m ++;
  10968. }
  10969. } else {
  10970. // find the most influencing
  10971. var influence, activeInfluenceIndices = [];
  10972. var influences = object.morphTargetInfluences;
  10973. var i, il = influences.length;
  10974. for ( i = 0; i < il; i ++ ) {
  10975. influence = influences[ i ];
  10976. if ( influence > 0 ) {
  10977. activeInfluenceIndices.push( [ i, influence ] );
  10978. }
  10979. }
  10980. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  10981. activeInfluenceIndices.sort( numericalSort );
  10982. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  10983. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  10984. activeInfluenceIndices.sort( numericalSort );
  10985. } else if ( activeInfluenceIndices.length === 0 ) {
  10986. activeInfluenceIndices.push( [ 0, 0 ] );
  10987. };
  10988. var influenceIndex, m = 0;
  10989. while ( m < material.numSupportedMorphTargets ) {
  10990. if ( activeInfluenceIndices[ m ] ) {
  10991. influenceIndex = activeInfluenceIndices[ m ][ 0 ];
  10992. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  10993. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  10994. if ( material.morphNormals ) {
  10995. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  10996. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  10997. }
  10998. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  10999. } else {
  11000. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11001. if ( material.morphNormals ) {
  11002. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11003. }
  11004. object.__webglMorphTargetInfluences[ m ] = 0;
  11005. }
  11006. m ++;
  11007. }
  11008. }
  11009. // load updated influences uniform
  11010. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11011. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11012. }
  11013. };
  11014. // Sorting
  11015. function painterSort ( a, b ) {
  11016. return b.z - a.z;
  11017. };
  11018. function numericalSort ( a, b ) {
  11019. return b[ 1 ] - a[ 1 ];
  11020. };
  11021. // Rendering
  11022. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11023. if ( camera instanceof THREE.Camera === false ) {
  11024. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11025. return;
  11026. }
  11027. var i, il,
  11028. webglObject, object,
  11029. renderList,
  11030. lights = scene.__lights,
  11031. fog = scene.fog;
  11032. // reset caching for this frame
  11033. _currentMaterialId = -1;
  11034. _lightsNeedUpdate = true;
  11035. // update scene graph
  11036. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11037. // update camera matrices and frustum
  11038. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11039. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  11040. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  11041. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11042. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  11043. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  11044. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11045. _frustum.setFromMatrix( _projScreenMatrix );
  11046. // update WebGL objects
  11047. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11048. // custom render plugins (pre pass)
  11049. renderPlugins( this.renderPluginsPre, scene, camera );
  11050. //
  11051. _this.info.render.calls = 0;
  11052. _this.info.render.vertices = 0;
  11053. _this.info.render.faces = 0;
  11054. _this.info.render.points = 0;
  11055. this.setRenderTarget( renderTarget );
  11056. if ( this.autoClear || forceClear ) {
  11057. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11058. }
  11059. // set matrices for regular objects (frustum culled)
  11060. renderList = scene.__webglObjects;
  11061. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11062. webglObject = renderList[ i ];
  11063. object = webglObject.object;
  11064. webglObject.render = false;
  11065. if ( object.visible ) {
  11066. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11067. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11068. setupMatrices( object, camera );
  11069. unrollBufferMaterial( webglObject );
  11070. webglObject.render = true;
  11071. if ( this.sortObjects ) {
  11072. if ( object.renderDepth ) {
  11073. webglObject.z = object.renderDepth;
  11074. } else {
  11075. _vector3.copy( object.matrixWorld.getPosition() );
  11076. _projScreenMatrix.multiplyVector3( _vector3 );
  11077. webglObject.z = _vector3.z;
  11078. }
  11079. }
  11080. }
  11081. }
  11082. }
  11083. if ( this.sortObjects ) {
  11084. renderList.sort( painterSort );
  11085. }
  11086. // set matrices for immediate objects
  11087. renderList = scene.__webglObjectsImmediate;
  11088. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11089. webglObject = renderList[ i ];
  11090. object = webglObject.object;
  11091. if ( object.visible ) {
  11092. /*
  11093. if ( object.matrixAutoUpdate ) {
  11094. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11095. }
  11096. */
  11097. setupMatrices( object, camera );
  11098. unrollImmediateBufferMaterial( webglObject );
  11099. }
  11100. }
  11101. if ( scene.overrideMaterial ) {
  11102. var material = scene.overrideMaterial;
  11103. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11104. this.setDepthTest( material.depthTest );
  11105. this.setDepthWrite( material.depthWrite );
  11106. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11107. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11108. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11109. } else {
  11110. // opaque pass (front-to-back order)
  11111. this.setBlending( THREE.NormalBlending );
  11112. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  11113. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  11114. // transparent pass (back-to-front order)
  11115. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  11116. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  11117. }
  11118. // custom render plugins (post pass)
  11119. renderPlugins( this.renderPluginsPost, scene, camera );
  11120. // Generate mipmap if we're using any kind of mipmap filtering
  11121. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11122. updateRenderTargetMipmap( renderTarget );
  11123. }
  11124. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11125. this.setDepthTest( true );
  11126. this.setDepthWrite( true );
  11127. // _gl.finish();
  11128. };
  11129. function renderPlugins( plugins, scene, camera ) {
  11130. if ( ! plugins.length ) return;
  11131. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11132. // reset state for plugin (to start from clean slate)
  11133. _currentProgram = null;
  11134. _currentCamera = null;
  11135. _oldBlending = -1;
  11136. _oldDepthTest = -1;
  11137. _oldDepthWrite = -1;
  11138. _oldDoubleSided = -1;
  11139. _oldFlipSided = -1;
  11140. _currentGeometryGroupHash = -1;
  11141. _currentMaterialId = -1;
  11142. _lightsNeedUpdate = true;
  11143. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  11144. // reset state after plugin (anything could have changed)
  11145. _currentProgram = null;
  11146. _currentCamera = null;
  11147. _oldBlending = -1;
  11148. _oldDepthTest = -1;
  11149. _oldDepthWrite = -1;
  11150. _oldDoubleSided = -1;
  11151. _oldFlipSided = -1;
  11152. _currentGeometryGroupHash = -1;
  11153. _currentMaterialId = -1;
  11154. _lightsNeedUpdate = true;
  11155. }
  11156. };
  11157. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11158. var webglObject, object, buffer, material, start, end, delta;
  11159. if ( reverse ) {
  11160. start = renderList.length - 1;
  11161. end = -1;
  11162. delta = -1;
  11163. } else {
  11164. start = 0;
  11165. end = renderList.length;
  11166. delta = 1;
  11167. }
  11168. for ( var i = start; i !== end; i += delta ) {
  11169. webglObject = renderList[ i ];
  11170. if ( webglObject.render ) {
  11171. object = webglObject.object;
  11172. buffer = webglObject.buffer;
  11173. if ( overrideMaterial ) {
  11174. material = overrideMaterial;
  11175. } else {
  11176. material = webglObject[ materialType ];
  11177. if ( ! material ) continue;
  11178. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11179. _this.setDepthTest( material.depthTest );
  11180. _this.setDepthWrite( material.depthWrite );
  11181. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11182. }
  11183. _this.setMaterialFaces( material );
  11184. if ( buffer instanceof THREE.BufferGeometry ) {
  11185. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11186. } else {
  11187. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11188. }
  11189. }
  11190. }
  11191. };
  11192. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11193. var webglObject, object, material, program;
  11194. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11195. webglObject = renderList[ i ];
  11196. object = webglObject.object;
  11197. if ( object.visible ) {
  11198. if ( overrideMaterial ) {
  11199. material = overrideMaterial;
  11200. } else {
  11201. material = webglObject[ materialType ];
  11202. if ( ! material ) continue;
  11203. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11204. _this.setDepthTest( material.depthTest );
  11205. _this.setDepthWrite( material.depthWrite );
  11206. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11207. }
  11208. _this.renderImmediateObject( camera, lights, fog, material, object );
  11209. }
  11210. }
  11211. };
  11212. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  11213. var program = setProgram( camera, lights, fog, material, object );
  11214. _currentGeometryGroupHash = -1;
  11215. _this.setMaterialFaces( material );
  11216. if ( object.immediateRenderCallback ) {
  11217. object.immediateRenderCallback( program, _gl, _frustum );
  11218. } else {
  11219. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  11220. }
  11221. };
  11222. function unrollImmediateBufferMaterial ( globject ) {
  11223. var object = globject.object,
  11224. material = object.material;
  11225. if ( material.transparent ) {
  11226. globject.transparent = material;
  11227. globject.opaque = null;
  11228. } else {
  11229. globject.opaque = material;
  11230. globject.transparent = null;
  11231. }
  11232. };
  11233. function unrollBufferMaterial ( globject ) {
  11234. var object = globject.object,
  11235. buffer = globject.buffer,
  11236. material, materialIndex, meshMaterial;
  11237. meshMaterial = object.material;
  11238. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  11239. materialIndex = buffer.materialIndex;
  11240. if ( materialIndex >= 0 ) {
  11241. material = object.geometry.materials[ materialIndex ];
  11242. if ( material.transparent ) {
  11243. globject.transparent = material;
  11244. globject.opaque = null;
  11245. } else {
  11246. globject.opaque = material;
  11247. globject.transparent = null;
  11248. }
  11249. }
  11250. } else {
  11251. material = meshMaterial;
  11252. if ( material ) {
  11253. if ( material.transparent ) {
  11254. globject.transparent = material;
  11255. globject.opaque = null;
  11256. } else {
  11257. globject.opaque = material;
  11258. globject.transparent = null;
  11259. }
  11260. }
  11261. }
  11262. };
  11263. // Geometry splitting
  11264. function sortFacesByMaterial ( geometry ) {
  11265. var f, fl, face, materialIndex, vertices,
  11266. materialHash, groupHash,
  11267. hash_map = {};
  11268. var numMorphTargets = geometry.morphTargets.length;
  11269. var numMorphNormals = geometry.morphNormals.length;
  11270. geometry.geometryGroups = {};
  11271. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  11272. face = geometry.faces[ f ];
  11273. materialIndex = face.materialIndex;
  11274. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  11275. if ( hash_map[ materialHash ] === undefined ) {
  11276. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  11277. }
  11278. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11279. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11280. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11281. }
  11282. vertices = face instanceof THREE.Face3 ? 3 : 4;
  11283. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  11284. hash_map[ materialHash ].counter += 1;
  11285. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11286. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11287. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11288. }
  11289. }
  11290. if ( face instanceof THREE.Face3 ) {
  11291. geometry.geometryGroups[ groupHash ].faces3.push( f );
  11292. } else {
  11293. geometry.geometryGroups[ groupHash ].faces4.push( f );
  11294. }
  11295. geometry.geometryGroups[ groupHash ].vertices += vertices;
  11296. }
  11297. geometry.geometryGroupsList = [];
  11298. for ( var g in geometry.geometryGroups ) {
  11299. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  11300. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  11301. }
  11302. };
  11303. // Objects refresh
  11304. this.initWebGLObjects = function ( scene ) {
  11305. if ( !scene.__webglObjects ) {
  11306. scene.__webglObjects = [];
  11307. scene.__webglObjectsImmediate = [];
  11308. scene.__webglSprites = [];
  11309. scene.__webglFlares = [];
  11310. }
  11311. while ( scene.__objectsAdded.length ) {
  11312. addObject( scene.__objectsAdded[ 0 ], scene );
  11313. scene.__objectsAdded.splice( 0, 1 );
  11314. }
  11315. while ( scene.__objectsRemoved.length ) {
  11316. removeObject( scene.__objectsRemoved[ 0 ], scene );
  11317. scene.__objectsRemoved.splice( 0, 1 );
  11318. }
  11319. // update must be called after objects adding / removal
  11320. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  11321. updateObject( scene.__webglObjects[ o ].object );
  11322. }
  11323. };
  11324. // Objects adding
  11325. function addObject ( object, scene ) {
  11326. var g, geometry, geometryGroup;
  11327. if ( ! object.__webglInit ) {
  11328. object.__webglInit = true;
  11329. object._modelViewMatrix = new THREE.Matrix4();
  11330. object._normalMatrix = new THREE.Matrix3();
  11331. if ( object instanceof THREE.Mesh ) {
  11332. geometry = object.geometry;
  11333. if ( geometry instanceof THREE.Geometry ) {
  11334. if ( geometry.geometryGroups === undefined ) {
  11335. sortFacesByMaterial( geometry );
  11336. }
  11337. // create separate VBOs per geometry chunk
  11338. for ( g in geometry.geometryGroups ) {
  11339. geometryGroup = geometry.geometryGroups[ g ];
  11340. // initialise VBO on the first access
  11341. if ( ! geometryGroup.__webglVertexBuffer ) {
  11342. createMeshBuffers( geometryGroup );
  11343. initMeshBuffers( geometryGroup, object );
  11344. geometry.verticesNeedUpdate = true;
  11345. geometry.morphTargetsNeedUpdate = true;
  11346. geometry.elementsNeedUpdate = true;
  11347. geometry.uvsNeedUpdate = true;
  11348. geometry.normalsNeedUpdate = true;
  11349. geometry.tangentsNeedUpdate = true;
  11350. geometry.colorsNeedUpdate = true;
  11351. }
  11352. }
  11353. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11354. initDirectBuffers( geometry );
  11355. }
  11356. } else if ( object instanceof THREE.Ribbon ) {
  11357. geometry = object.geometry;
  11358. if( ! geometry.__webglVertexBuffer ) {
  11359. createRibbonBuffers( geometry );
  11360. initRibbonBuffers( geometry );
  11361. geometry.verticesNeedUpdate = true;
  11362. geometry.colorsNeedUpdate = true;
  11363. }
  11364. } else if ( object instanceof THREE.Line ) {
  11365. geometry = object.geometry;
  11366. if( ! geometry.__webglVertexBuffer ) {
  11367. createLineBuffers( geometry );
  11368. initLineBuffers( geometry, object );
  11369. geometry.verticesNeedUpdate = true;
  11370. geometry.colorsNeedUpdate = true;
  11371. }
  11372. } else if ( object instanceof THREE.ParticleSystem ) {
  11373. geometry = object.geometry;
  11374. if ( ! geometry.__webglVertexBuffer ) {
  11375. createParticleBuffers( geometry );
  11376. initParticleBuffers( geometry, object );
  11377. geometry.verticesNeedUpdate = true;
  11378. geometry.colorsNeedUpdate = true;
  11379. }
  11380. }
  11381. }
  11382. if ( ! object.__webglActive ) {
  11383. if ( object instanceof THREE.Mesh ) {
  11384. geometry = object.geometry;
  11385. if ( geometry instanceof THREE.BufferGeometry ) {
  11386. addBuffer( scene.__webglObjects, geometry, object );
  11387. } else {
  11388. for ( g in geometry.geometryGroups ) {
  11389. geometryGroup = geometry.geometryGroups[ g ];
  11390. addBuffer( scene.__webglObjects, geometryGroup, object );
  11391. }
  11392. }
  11393. } else if ( object instanceof THREE.Ribbon ||
  11394. object instanceof THREE.Line ||
  11395. object instanceof THREE.ParticleSystem ) {
  11396. geometry = object.geometry;
  11397. addBuffer( scene.__webglObjects, geometry, object );
  11398. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11399. addBufferImmediate( scene.__webglObjectsImmediate, object );
  11400. } else if ( object instanceof THREE.Sprite ) {
  11401. scene.__webglSprites.push( object );
  11402. } else if ( object instanceof THREE.LensFlare ) {
  11403. scene.__webglFlares.push( object );
  11404. }
  11405. object.__webglActive = true;
  11406. }
  11407. };
  11408. function addBuffer ( objlist, buffer, object ) {
  11409. objlist.push(
  11410. {
  11411. buffer: buffer,
  11412. object: object,
  11413. opaque: null,
  11414. transparent: null
  11415. }
  11416. );
  11417. };
  11418. function addBufferImmediate ( objlist, object ) {
  11419. objlist.push(
  11420. {
  11421. object: object,
  11422. opaque: null,
  11423. transparent: null
  11424. }
  11425. );
  11426. };
  11427. // Objects updates
  11428. function updateObject ( object ) {
  11429. var geometry = object.geometry,
  11430. geometryGroup, customAttributesDirty, material;
  11431. if ( object instanceof THREE.Mesh ) {
  11432. if ( geometry instanceof THREE.BufferGeometry ) {
  11433. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  11434. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11435. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  11436. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  11437. }
  11438. geometry.verticesNeedUpdate = false;
  11439. geometry.elementsNeedUpdate = false;
  11440. geometry.uvsNeedUpdate = false;
  11441. geometry.normalsNeedUpdate = false;
  11442. geometry.colorsNeedUpdate = false;
  11443. geometry.tangentsNeedUpdate = false;
  11444. } else {
  11445. // check all geometry groups
  11446. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  11447. geometryGroup = geometry.geometryGroupsList[ i ];
  11448. material = getBufferMaterial( object, geometryGroup );
  11449. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11450. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  11451. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11452. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  11453. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  11454. }
  11455. }
  11456. geometry.verticesNeedUpdate = false;
  11457. geometry.morphTargetsNeedUpdate = false;
  11458. geometry.elementsNeedUpdate = false;
  11459. geometry.uvsNeedUpdate = false;
  11460. geometry.normalsNeedUpdate = false;
  11461. geometry.colorsNeedUpdate = false;
  11462. geometry.tangentsNeedUpdate = false;
  11463. material.attributes && clearCustomAttributes( material );
  11464. }
  11465. } else if ( object instanceof THREE.Ribbon ) {
  11466. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  11467. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  11468. }
  11469. geometry.verticesNeedUpdate = false;
  11470. geometry.colorsNeedUpdate = false;
  11471. } else if ( object instanceof THREE.Line ) {
  11472. material = getBufferMaterial( object, geometryGroup );
  11473. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11474. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) {
  11475. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  11476. }
  11477. geometry.verticesNeedUpdate = false;
  11478. geometry.colorsNeedUpdate = false;
  11479. material.attributes && clearCustomAttributes( material );
  11480. } else if ( object instanceof THREE.ParticleSystem ) {
  11481. material = getBufferMaterial( object, geometryGroup );
  11482. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11483. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  11484. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  11485. }
  11486. geometry.verticesNeedUpdate = false;
  11487. geometry.colorsNeedUpdate = false;
  11488. material.attributes && clearCustomAttributes( material );
  11489. }
  11490. };
  11491. // Objects updates - custom attributes check
  11492. function areCustomAttributesDirty ( material ) {
  11493. for ( var a in material.attributes ) {
  11494. if ( material.attributes[ a ].needsUpdate ) return true;
  11495. }
  11496. return false;
  11497. };
  11498. function clearCustomAttributes ( material ) {
  11499. for ( var a in material.attributes ) {
  11500. material.attributes[ a ].needsUpdate = false;
  11501. }
  11502. };
  11503. // Objects removal
  11504. function removeObject ( object, scene ) {
  11505. if ( object instanceof THREE.Mesh ||
  11506. object instanceof THREE.ParticleSystem ||
  11507. object instanceof THREE.Ribbon ||
  11508. object instanceof THREE.Line ) {
  11509. removeInstances( scene.__webglObjects, object );
  11510. } else if ( object instanceof THREE.Sprite ) {
  11511. removeInstancesDirect( scene.__webglSprites, object );
  11512. } else if ( object instanceof THREE.LensFlare ) {
  11513. removeInstancesDirect( scene.__webglFlares, object );
  11514. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11515. removeInstances( scene.__webglObjectsImmediate, object );
  11516. }
  11517. object.__webglActive = false;
  11518. };
  11519. function removeInstances ( objlist, object ) {
  11520. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  11521. if ( objlist[ o ].object === object ) {
  11522. objlist.splice( o, 1 );
  11523. }
  11524. }
  11525. };
  11526. function removeInstancesDirect ( objlist, object ) {
  11527. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  11528. if ( objlist[ o ] === object ) {
  11529. objlist.splice( o, 1 );
  11530. }
  11531. }
  11532. };
  11533. // Materials
  11534. this.initMaterial = function ( material, lights, fog, object ) {
  11535. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  11536. if ( material instanceof THREE.MeshDepthMaterial ) {
  11537. shaderID = 'depth';
  11538. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  11539. shaderID = 'normal';
  11540. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  11541. shaderID = 'basic';
  11542. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  11543. shaderID = 'lambert';
  11544. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  11545. shaderID = 'phong';
  11546. } else if ( material instanceof THREE.LineBasicMaterial ) {
  11547. shaderID = 'basic';
  11548. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  11549. shaderID = 'particle_basic';
  11550. }
  11551. if ( shaderID ) {
  11552. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  11553. }
  11554. // heuristics to create shader parameters according to lights in the scene
  11555. // (not to blow over maxLights budget)
  11556. maxLightCount = allocateLights( lights );
  11557. maxShadows = allocateShadows( lights );
  11558. maxBones = allocateBones( object );
  11559. parameters = {
  11560. map: !!material.map,
  11561. envMap: !!material.envMap,
  11562. lightMap: !!material.lightMap,
  11563. bumpMap: !!material.bumpMap,
  11564. specularMap: !!material.specularMap,
  11565. vertexColors: material.vertexColors,
  11566. fog: fog,
  11567. useFog: material.fog,
  11568. sizeAttenuation: material.sizeAttenuation,
  11569. skinning: material.skinning,
  11570. maxBones: maxBones,
  11571. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  11572. boneTextureWidth: object && object.boneTextureWidth,
  11573. boneTextureHeight: object && object.boneTextureHeight,
  11574. morphTargets: material.morphTargets,
  11575. morphNormals: material.morphNormals,
  11576. maxMorphTargets: this.maxMorphTargets,
  11577. maxMorphNormals: this.maxMorphNormals,
  11578. maxDirLights: maxLightCount.directional,
  11579. maxPointLights: maxLightCount.point,
  11580. maxSpotLights: maxLightCount.spot,
  11581. maxShadows: maxShadows,
  11582. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  11583. shadowMapSoft: this.shadowMapSoft,
  11584. shadowMapDebug: this.shadowMapDebug,
  11585. shadowMapCascade: this.shadowMapCascade,
  11586. alphaTest: material.alphaTest,
  11587. metal: material.metal,
  11588. perPixel: material.perPixel,
  11589. wrapAround: material.wrapAround,
  11590. doubleSided: material.side === THREE.DoubleSide
  11591. };
  11592. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, parameters );
  11593. var attributes = material.program.attributes;
  11594. if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
  11595. if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
  11596. if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
  11597. if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );
  11598. if ( material.skinning &&
  11599. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11600. _gl.enableVertexAttribArray( attributes.skinIndex );
  11601. _gl.enableVertexAttribArray( attributes.skinWeight );
  11602. }
  11603. if ( material.attributes ) {
  11604. for ( a in material.attributes ) {
  11605. if( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );
  11606. }
  11607. }
  11608. if ( material.morphTargets ) {
  11609. material.numSupportedMorphTargets = 0;
  11610. var id, base = "morphTarget";
  11611. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  11612. id = base + i;
  11613. if ( attributes[ id ] >= 0 ) {
  11614. _gl.enableVertexAttribArray( attributes[ id ] );
  11615. material.numSupportedMorphTargets ++;
  11616. }
  11617. }
  11618. }
  11619. if ( material.morphNormals ) {
  11620. material.numSupportedMorphNormals = 0;
  11621. var id, base = "morphNormal";
  11622. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  11623. id = base + i;
  11624. if ( attributes[ id ] >= 0 ) {
  11625. _gl.enableVertexAttribArray( attributes[ id ] );
  11626. material.numSupportedMorphNormals ++;
  11627. }
  11628. }
  11629. }
  11630. material.uniformsList = [];
  11631. for ( u in material.uniforms ) {
  11632. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  11633. }
  11634. };
  11635. function setMaterialShaders( material, shaders ) {
  11636. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  11637. material.vertexShader = shaders.vertexShader;
  11638. material.fragmentShader = shaders.fragmentShader;
  11639. };
  11640. function setProgram( camera, lights, fog, material, object ) {
  11641. _usedTextureUnits = 0;
  11642. if ( material.needsUpdate ) {
  11643. if ( material.program ) _this.deallocateMaterial( material );
  11644. _this.initMaterial( material, lights, fog, object );
  11645. material.needsUpdate = false;
  11646. }
  11647. if ( material.morphTargets ) {
  11648. if ( ! object.__webglMorphTargetInfluences ) {
  11649. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  11650. }
  11651. }
  11652. var refreshMaterial = false;
  11653. var program = material.program,
  11654. p_uniforms = program.uniforms,
  11655. m_uniforms = material.uniforms;
  11656. if ( program !== _currentProgram ) {
  11657. _gl.useProgram( program );
  11658. _currentProgram = program;
  11659. refreshMaterial = true;
  11660. }
  11661. if ( material.id !== _currentMaterialId ) {
  11662. _currentMaterialId = material.id;
  11663. refreshMaterial = true;
  11664. }
  11665. if ( refreshMaterial || camera !== _currentCamera ) {
  11666. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  11667. if ( camera !== _currentCamera ) _currentCamera = camera;
  11668. }
  11669. // skinning uniforms must be set even if material didn't change
  11670. // auto-setting of texture unit for bone texture must go before other textures
  11671. // not sure why, but otherwise weird things happen
  11672. if ( material.skinning ) {
  11673. if ( _supportsBoneTextures && object.useVertexTexture ) {
  11674. if ( p_uniforms.boneTexture !== null ) {
  11675. var textureUnit = getTextureUnit();
  11676. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  11677. _this.setTexture( object.boneTexture, textureUnit );
  11678. }
  11679. } else {
  11680. if ( p_uniforms.boneGlobalMatrices !== null ) {
  11681. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  11682. }
  11683. }
  11684. }
  11685. if ( refreshMaterial ) {
  11686. // refresh uniforms common to several materials
  11687. if ( fog && material.fog ) {
  11688. refreshUniformsFog( m_uniforms, fog );
  11689. }
  11690. if ( material instanceof THREE.MeshPhongMaterial ||
  11691. material instanceof THREE.MeshLambertMaterial ||
  11692. material.lights ) {
  11693. if ( _lightsNeedUpdate ) {
  11694. setupLights( program, lights );
  11695. _lightsNeedUpdate = false;
  11696. }
  11697. refreshUniformsLights( m_uniforms, _lights );
  11698. }
  11699. if ( material instanceof THREE.MeshBasicMaterial ||
  11700. material instanceof THREE.MeshLambertMaterial ||
  11701. material instanceof THREE.MeshPhongMaterial ) {
  11702. refreshUniformsCommon( m_uniforms, material );
  11703. }
  11704. // refresh single material specific uniforms
  11705. if ( material instanceof THREE.LineBasicMaterial ) {
  11706. refreshUniformsLine( m_uniforms, material );
  11707. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  11708. refreshUniformsParticle( m_uniforms, material );
  11709. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  11710. refreshUniformsPhong( m_uniforms, material );
  11711. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  11712. refreshUniformsLambert( m_uniforms, material );
  11713. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  11714. m_uniforms.mNear.value = camera.near;
  11715. m_uniforms.mFar.value = camera.far;
  11716. m_uniforms.opacity.value = material.opacity;
  11717. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  11718. m_uniforms.opacity.value = material.opacity;
  11719. }
  11720. if ( object.receiveShadow && ! material._shadowPass ) {
  11721. refreshUniformsShadow( m_uniforms, lights );
  11722. }
  11723. // load common uniforms
  11724. loadUniformsGeneric( program, material.uniformsList );
  11725. // load material specific uniforms
  11726. // (shader material also gets them for the sake of genericity)
  11727. if ( material instanceof THREE.ShaderMaterial ||
  11728. material instanceof THREE.MeshPhongMaterial ||
  11729. material.envMap ) {
  11730. if ( p_uniforms.cameraPosition !== null ) {
  11731. var position = camera.matrixWorld.getPosition();
  11732. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  11733. }
  11734. }
  11735. if ( material instanceof THREE.MeshPhongMaterial ||
  11736. material instanceof THREE.MeshLambertMaterial ||
  11737. material instanceof THREE.ShaderMaterial ||
  11738. material.skinning ) {
  11739. if ( p_uniforms.viewMatrix !== null ) {
  11740. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  11741. }
  11742. }
  11743. }
  11744. loadUniformsMatrices( p_uniforms, object );
  11745. if ( p_uniforms.modelMatrix !== null ) {
  11746. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  11747. }
  11748. return program;
  11749. };
  11750. // Uniforms (refresh uniforms objects)
  11751. function refreshUniformsCommon ( uniforms, material ) {
  11752. uniforms.opacity.value = material.opacity;
  11753. if ( _this.gammaInput ) {
  11754. uniforms.diffuse.value.copyGammaToLinear( material.color );
  11755. } else {
  11756. uniforms.diffuse.value = material.color;
  11757. }
  11758. uniforms.map.value = material.map;
  11759. uniforms.lightMap.value = material.lightMap;
  11760. uniforms.specularMap.value = material.specularMap;
  11761. if ( material.bumpMap ) {
  11762. uniforms.bumpMap.value = material.bumpMap;
  11763. uniforms.bumpScale.value = material.bumpScale;
  11764. }
  11765. // uv repeat and offset setting priorities
  11766. // 1. color map
  11767. // 2. specular map
  11768. // 3. bump map
  11769. var uvScaleMap;
  11770. if ( material.map ) {
  11771. uvScaleMap = material.map;
  11772. } else if ( material.specularMap ) {
  11773. uvScaleMap = material.specularMap;
  11774. } else if ( material.bumpMap ) {
  11775. uvScaleMap = material.bumpMap;
  11776. }
  11777. if ( uvScaleMap !== undefined ) {
  11778. var offset = uvScaleMap.offset;
  11779. var repeat = uvScaleMap.repeat;
  11780. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  11781. }
  11782. uniforms.envMap.value = material.envMap;
  11783. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  11784. if ( _this.gammaInput ) {
  11785. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  11786. uniforms.reflectivity.value = material.reflectivity;
  11787. } else {
  11788. uniforms.reflectivity.value = material.reflectivity;
  11789. }
  11790. uniforms.refractionRatio.value = material.refractionRatio;
  11791. uniforms.combine.value = material.combine;
  11792. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  11793. };
  11794. function refreshUniformsLine ( uniforms, material ) {
  11795. uniforms.diffuse.value = material.color;
  11796. uniforms.opacity.value = material.opacity;
  11797. };
  11798. function refreshUniformsParticle ( uniforms, material ) {
  11799. uniforms.psColor.value = material.color;
  11800. uniforms.opacity.value = material.opacity;
  11801. uniforms.size.value = material.size;
  11802. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  11803. uniforms.map.value = material.map;
  11804. };
  11805. function refreshUniformsFog ( uniforms, fog ) {
  11806. uniforms.fogColor.value = fog.color;
  11807. if ( fog instanceof THREE.Fog ) {
  11808. uniforms.fogNear.value = fog.near;
  11809. uniforms.fogFar.value = fog.far;
  11810. } else if ( fog instanceof THREE.FogExp2 ) {
  11811. uniforms.fogDensity.value = fog.density;
  11812. }
  11813. };
  11814. function refreshUniformsPhong ( uniforms, material ) {
  11815. uniforms.shininess.value = material.shininess;
  11816. if ( _this.gammaInput ) {
  11817. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  11818. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  11819. uniforms.specular.value.copyGammaToLinear( material.specular );
  11820. } else {
  11821. uniforms.ambient.value = material.ambient;
  11822. uniforms.emissive.value = material.emissive;
  11823. uniforms.specular.value = material.specular;
  11824. }
  11825. if ( material.wrapAround ) {
  11826. uniforms.wrapRGB.value.copy( material.wrapRGB );
  11827. }
  11828. };
  11829. function refreshUniformsLambert ( uniforms, material ) {
  11830. if ( _this.gammaInput ) {
  11831. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  11832. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  11833. } else {
  11834. uniforms.ambient.value = material.ambient;
  11835. uniforms.emissive.value = material.emissive;
  11836. }
  11837. if ( material.wrapAround ) {
  11838. uniforms.wrapRGB.value.copy( material.wrapRGB );
  11839. }
  11840. };
  11841. function refreshUniformsLights ( uniforms, lights ) {
  11842. uniforms.ambientLightColor.value = lights.ambient;
  11843. uniforms.directionalLightColor.value = lights.directional.colors;
  11844. uniforms.directionalLightDirection.value = lights.directional.positions;
  11845. uniforms.pointLightColor.value = lights.point.colors;
  11846. uniforms.pointLightPosition.value = lights.point.positions;
  11847. uniforms.pointLightDistance.value = lights.point.distances;
  11848. uniforms.spotLightColor.value = lights.spot.colors;
  11849. uniforms.spotLightPosition.value = lights.spot.positions;
  11850. uniforms.spotLightDistance.value = lights.spot.distances;
  11851. uniforms.spotLightDirection.value = lights.spot.directions;
  11852. uniforms.spotLightAngle.value = lights.spot.angles;
  11853. uniforms.spotLightExponent.value = lights.spot.exponents;
  11854. };
  11855. function refreshUniformsShadow ( uniforms, lights ) {
  11856. if ( uniforms.shadowMatrix ) {
  11857. var j = 0;
  11858. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  11859. var light = lights[ i ];
  11860. if ( ! light.castShadow ) continue;
  11861. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  11862. uniforms.shadowMap.value[ j ] = light.shadowMap;
  11863. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  11864. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  11865. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  11866. uniforms.shadowBias.value[ j ] = light.shadowBias;
  11867. j ++;
  11868. }
  11869. }
  11870. }
  11871. };
  11872. // Uniforms (load to GPU)
  11873. function loadUniformsMatrices ( uniforms, object ) {
  11874. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  11875. if ( uniforms.normalMatrix ) {
  11876. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  11877. }
  11878. };
  11879. function getTextureUnit() {
  11880. var textureUnit = _usedTextureUnits;
  11881. if ( textureUnit >= _maxTextures ) {
  11882. console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  11883. }
  11884. _usedTextureUnits += 1;
  11885. return textureUnit;
  11886. };
  11887. function loadUniformsGeneric ( program, uniforms ) {
  11888. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  11889. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  11890. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  11891. if ( !location ) continue;
  11892. uniform = uniforms[ j ][ 0 ];
  11893. type = uniform.type;
  11894. value = uniform.value;
  11895. if ( type === "i" ) { // single integer
  11896. _gl.uniform1i( location, value );
  11897. } else if ( type === "f" ) { // single float
  11898. _gl.uniform1f( location, value );
  11899. } else if ( type === "v2" ) { // single THREE.Vector2
  11900. _gl.uniform2f( location, value.x, value.y );
  11901. } else if ( type === "v3" ) { // single THREE.Vector3
  11902. _gl.uniform3f( location, value.x, value.y, value.z );
  11903. } else if ( type === "v4" ) { // single THREE.Vector4
  11904. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  11905. } else if ( type === "c" ) { // single THREE.Color
  11906. _gl.uniform3f( location, value.r, value.g, value.b );
  11907. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  11908. _gl.uniform1iv( location, value );
  11909. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  11910. _gl.uniform3iv( location, value );
  11911. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  11912. _gl.uniform1fv( location, value );
  11913. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  11914. _gl.uniform3fv( location, value );
  11915. } else if ( type === "v2v" ) { // array of THREE.Vector2
  11916. if ( uniform._array === undefined ) {
  11917. uniform._array = new Float32Array( 2 * value.length );
  11918. }
  11919. for ( i = 0, il = value.length; i < il; i ++ ) {
  11920. offset = i * 2;
  11921. uniform._array[ offset ] = value[ i ].x;
  11922. uniform._array[ offset + 1 ] = value[ i ].y;
  11923. }
  11924. _gl.uniform2fv( location, uniform._array );
  11925. } else if ( type === "v3v" ) { // array of THREE.Vector3
  11926. if ( uniform._array === undefined ) {
  11927. uniform._array = new Float32Array( 3 * value.length );
  11928. }
  11929. for ( i = 0, il = value.length; i < il; i ++ ) {
  11930. offset = i * 3;
  11931. uniform._array[ offset ] = value[ i ].x;
  11932. uniform._array[ offset + 1 ] = value[ i ].y;
  11933. uniform._array[ offset + 2 ] = value[ i ].z;
  11934. }
  11935. _gl.uniform3fv( location, uniform._array );
  11936. } else if ( type === "v4v" ) { // array of THREE.Vector4
  11937. if ( uniform._array === undefined ) {
  11938. uniform._array = new Float32Array( 4 * value.length );
  11939. }
  11940. for ( i = 0, il = value.length; i < il; i ++ ) {
  11941. offset = i * 4;
  11942. uniform._array[ offset ] = value[ i ].x;
  11943. uniform._array[ offset + 1 ] = value[ i ].y;
  11944. uniform._array[ offset + 2 ] = value[ i ].z;
  11945. uniform._array[ offset + 3 ] = value[ i ].w;
  11946. }
  11947. _gl.uniform4fv( location, uniform._array );
  11948. } else if ( type === "m4") { // single THREE.Matrix4
  11949. if ( uniform._array === undefined ) {
  11950. uniform._array = new Float32Array( 16 );
  11951. }
  11952. value.flattenToArray( uniform._array );
  11953. _gl.uniformMatrix4fv( location, false, uniform._array );
  11954. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  11955. if ( uniform._array === undefined ) {
  11956. uniform._array = new Float32Array( 16 * value.length );
  11957. }
  11958. for ( i = 0, il = value.length; i < il; i ++ ) {
  11959. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  11960. }
  11961. _gl.uniformMatrix4fv( location, false, uniform._array );
  11962. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  11963. texture = value;
  11964. textureUnit = getTextureUnit();
  11965. _gl.uniform1i( location, textureUnit );
  11966. if ( !texture ) continue;
  11967. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  11968. setCubeTexture( texture, textureUnit );
  11969. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  11970. setCubeTextureDynamic( texture, textureUnit );
  11971. } else {
  11972. _this.setTexture( texture, textureUnit );
  11973. }
  11974. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  11975. if ( uniform._array === undefined ) {
  11976. uniform._array = [];
  11977. }
  11978. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  11979. uniform._array[ i ] = getTextureUnit();
  11980. }
  11981. _gl.uniform1iv( location, uniform._array );
  11982. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  11983. texture = uniform.value[ i ];
  11984. textureUnit = uniform._array[ i ];
  11985. if ( !texture ) continue;
  11986. _this.setTexture( texture, textureUnit );
  11987. }
  11988. }
  11989. }
  11990. };
  11991. function setupMatrices ( object, camera ) {
  11992. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  11993. object._normalMatrix.getInverse( object._modelViewMatrix );
  11994. object._normalMatrix.transpose();
  11995. };
  11996. function setupLights ( program, lights ) {
  11997. var l, ll, light, n,
  11998. r = 0, g = 0, b = 0,
  11999. color, position, intensity, distance,
  12000. zlights = _lights,
  12001. dcolors = zlights.directional.colors,
  12002. dpositions = zlights.directional.positions,
  12003. pcolors = zlights.point.colors,
  12004. ppositions = zlights.point.positions,
  12005. pdistances = zlights.point.distances,
  12006. scolors = zlights.spot.colors,
  12007. spositions = zlights.spot.positions,
  12008. sdistances = zlights.spot.distances,
  12009. sdirections = zlights.spot.directions,
  12010. sangles = zlights.spot.angles,
  12011. sexponents = zlights.spot.exponents,
  12012. dlength = 0,
  12013. plength = 0,
  12014. slength = 0,
  12015. doffset = 0,
  12016. poffset = 0,
  12017. soffset = 0;
  12018. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12019. light = lights[ l ];
  12020. if ( light.onlyShadow || ! light.visible ) continue;
  12021. color = light.color;
  12022. intensity = light.intensity;
  12023. distance = light.distance;
  12024. if ( light instanceof THREE.AmbientLight ) {
  12025. if ( _this.gammaInput ) {
  12026. r += color.r * color.r;
  12027. g += color.g * color.g;
  12028. b += color.b * color.b;
  12029. } else {
  12030. r += color.r;
  12031. g += color.g;
  12032. b += color.b;
  12033. }
  12034. } else if ( light instanceof THREE.DirectionalLight ) {
  12035. doffset = dlength * 3;
  12036. if ( _this.gammaInput ) {
  12037. dcolors[ doffset ] = color.r * color.r * intensity * intensity;
  12038. dcolors[ doffset + 1 ] = color.g * color.g * intensity * intensity;
  12039. dcolors[ doffset + 2 ] = color.b * color.b * intensity * intensity;
  12040. } else {
  12041. dcolors[ doffset ] = color.r * intensity;
  12042. dcolors[ doffset + 1 ] = color.g * intensity;
  12043. dcolors[ doffset + 2 ] = color.b * intensity;
  12044. }
  12045. _direction.copy( light.matrixWorld.getPosition() );
  12046. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12047. _direction.normalize();
  12048. dpositions[ doffset ] = _direction.x;
  12049. dpositions[ doffset + 1 ] = _direction.y;
  12050. dpositions[ doffset + 2 ] = _direction.z;
  12051. dlength += 1;
  12052. } else if( light instanceof THREE.PointLight ) {
  12053. poffset = plength * 3;
  12054. if ( _this.gammaInput ) {
  12055. pcolors[ poffset ] = color.r * color.r * intensity * intensity;
  12056. pcolors[ poffset + 1 ] = color.g * color.g * intensity * intensity;
  12057. pcolors[ poffset + 2 ] = color.b * color.b * intensity * intensity;
  12058. } else {
  12059. pcolors[ poffset ] = color.r * intensity;
  12060. pcolors[ poffset + 1 ] = color.g * intensity;
  12061. pcolors[ poffset + 2 ] = color.b * intensity;
  12062. }
  12063. position = light.matrixWorld.getPosition();
  12064. ppositions[ poffset ] = position.x;
  12065. ppositions[ poffset + 1 ] = position.y;
  12066. ppositions[ poffset + 2 ] = position.z;
  12067. pdistances[ plength ] = distance;
  12068. plength += 1;
  12069. } else if( light instanceof THREE.SpotLight ) {
  12070. soffset = slength * 3;
  12071. if ( _this.gammaInput ) {
  12072. scolors[ soffset ] = color.r * color.r * intensity * intensity;
  12073. scolors[ soffset + 1 ] = color.g * color.g * intensity * intensity;
  12074. scolors[ soffset + 2 ] = color.b * color.b * intensity * intensity;
  12075. } else {
  12076. scolors[ soffset ] = color.r * intensity;
  12077. scolors[ soffset + 1 ] = color.g * intensity;
  12078. scolors[ soffset + 2 ] = color.b * intensity;
  12079. }
  12080. position = light.matrixWorld.getPosition();
  12081. spositions[ soffset ] = position.x;
  12082. spositions[ soffset + 1 ] = position.y;
  12083. spositions[ soffset + 2 ] = position.z;
  12084. sdistances[ slength ] = distance;
  12085. _direction.copy( position );
  12086. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12087. _direction.normalize();
  12088. sdirections[ soffset ] = _direction.x;
  12089. sdirections[ soffset + 1 ] = _direction.y;
  12090. sdirections[ soffset + 2 ] = _direction.z;
  12091. sangles[ slength ] = Math.cos( light.angle );
  12092. sexponents[ slength ] = light.exponent;
  12093. slength += 1;
  12094. }
  12095. }
  12096. // null eventual remains from removed lights
  12097. // (this is to avoid if in shader)
  12098. for ( l = dlength * 3, ll = dcolors.length; l < ll; l ++ ) dcolors[ l ] = 0.0;
  12099. for ( l = plength * 3, ll = pcolors.length; l < ll; l ++ ) pcolors[ l ] = 0.0;
  12100. for ( l = slength * 3, ll = scolors.length; l < ll; l ++ ) scolors[ l ] = 0.0;
  12101. zlights.directional.length = dlength;
  12102. zlights.point.length = plength;
  12103. zlights.spot.length = slength;
  12104. zlights.ambient[ 0 ] = r;
  12105. zlights.ambient[ 1 ] = g;
  12106. zlights.ambient[ 2 ] = b;
  12107. };
  12108. // GL state setting
  12109. this.setFaceCulling = function ( cullFace, frontFace ) {
  12110. if ( cullFace ) {
  12111. if ( !frontFace || frontFace === "ccw" ) {
  12112. _gl.frontFace( _gl.CCW );
  12113. } else {
  12114. _gl.frontFace( _gl.CW );
  12115. }
  12116. if( cullFace === "back" ) {
  12117. _gl.cullFace( _gl.BACK );
  12118. } else if( cullFace === "front" ) {
  12119. _gl.cullFace( _gl.FRONT );
  12120. } else {
  12121. _gl.cullFace( _gl.FRONT_AND_BACK );
  12122. }
  12123. _gl.enable( _gl.CULL_FACE );
  12124. } else {
  12125. _gl.disable( _gl.CULL_FACE );
  12126. }
  12127. };
  12128. this.setMaterialFaces = function ( material ) {
  12129. var doubleSided = material.side === THREE.DoubleSide;
  12130. var flipSided = material.side === THREE.BackSide;
  12131. if ( _oldDoubleSided !== doubleSided ) {
  12132. if ( doubleSided ) {
  12133. _gl.disable( _gl.CULL_FACE );
  12134. } else {
  12135. _gl.enable( _gl.CULL_FACE );
  12136. }
  12137. _oldDoubleSided = doubleSided;
  12138. }
  12139. if ( _oldFlipSided !== flipSided ) {
  12140. if ( flipSided ) {
  12141. _gl.frontFace( _gl.CW );
  12142. } else {
  12143. _gl.frontFace( _gl.CCW );
  12144. }
  12145. _oldFlipSided = flipSided;
  12146. }
  12147. };
  12148. this.setDepthTest = function ( depthTest ) {
  12149. if ( _oldDepthTest !== depthTest ) {
  12150. if ( depthTest ) {
  12151. _gl.enable( _gl.DEPTH_TEST );
  12152. } else {
  12153. _gl.disable( _gl.DEPTH_TEST );
  12154. }
  12155. _oldDepthTest = depthTest;
  12156. }
  12157. };
  12158. this.setDepthWrite = function ( depthWrite ) {
  12159. if ( _oldDepthWrite !== depthWrite ) {
  12160. _gl.depthMask( depthWrite );
  12161. _oldDepthWrite = depthWrite;
  12162. }
  12163. };
  12164. function setLineWidth ( width ) {
  12165. if ( width !== _oldLineWidth ) {
  12166. _gl.lineWidth( width );
  12167. _oldLineWidth = width;
  12168. }
  12169. };
  12170. function setPolygonOffset ( polygonoffset, factor, units ) {
  12171. if ( _oldPolygonOffset !== polygonoffset ) {
  12172. if ( polygonoffset ) {
  12173. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  12174. } else {
  12175. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  12176. }
  12177. _oldPolygonOffset = polygonoffset;
  12178. }
  12179. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  12180. _gl.polygonOffset( factor, units );
  12181. _oldPolygonOffsetFactor = factor;
  12182. _oldPolygonOffsetUnits = units;
  12183. }
  12184. };
  12185. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  12186. if ( blending !== _oldBlending ) {
  12187. if ( blending === THREE.NoBlending ) {
  12188. _gl.disable( _gl.BLEND );
  12189. } else if ( blending === THREE.AdditiveBlending ) {
  12190. _gl.enable( _gl.BLEND );
  12191. _gl.blendEquation( _gl.FUNC_ADD );
  12192. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  12193. } else if ( blending === THREE.SubtractiveBlending ) {
  12194. // TODO: Find blendFuncSeparate() combination
  12195. _gl.enable( _gl.BLEND );
  12196. _gl.blendEquation( _gl.FUNC_ADD );
  12197. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  12198. } else if ( blending === THREE.MultiplyBlending ) {
  12199. // TODO: Find blendFuncSeparate() combination
  12200. _gl.enable( _gl.BLEND );
  12201. _gl.blendEquation( _gl.FUNC_ADD );
  12202. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  12203. } else if ( blending === THREE.CustomBlending ) {
  12204. _gl.enable( _gl.BLEND );
  12205. } else {
  12206. _gl.enable( _gl.BLEND );
  12207. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  12208. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  12209. }
  12210. _oldBlending = blending;
  12211. }
  12212. if ( blending === THREE.CustomBlending ) {
  12213. if ( blendEquation !== _oldBlendEquation ) {
  12214. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  12215. _oldBlendEquation = blendEquation;
  12216. }
  12217. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  12218. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  12219. _oldBlendSrc = blendSrc;
  12220. _oldBlendDst = blendDst;
  12221. }
  12222. } else {
  12223. _oldBlendEquation = null;
  12224. _oldBlendSrc = null;
  12225. _oldBlendDst = null;
  12226. }
  12227. };
  12228. // Shaders
  12229. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, parameters ) {
  12230. var p, pl, program, code;
  12231. var chunks = [];
  12232. // Generate code
  12233. if ( shaderID ) {
  12234. chunks.push( shaderID );
  12235. } else {
  12236. chunks.push( fragmentShader );
  12237. chunks.push( vertexShader );
  12238. }
  12239. for ( p in parameters ) {
  12240. chunks.push( p );
  12241. chunks.push( parameters[ p ] );
  12242. }
  12243. code = chunks.join();
  12244. // Check if code has been already compiled
  12245. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  12246. var programInfo = _programs[ p ];
  12247. if ( programInfo.code === code ) {
  12248. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  12249. programInfo.usedTimes ++;
  12250. return programInfo.program;
  12251. }
  12252. }
  12253. //console.log( "building new program " );
  12254. //
  12255. program = _gl.createProgram();
  12256. var prefix_vertex = [
  12257. "precision " + _precision + " float;",
  12258. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  12259. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  12260. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  12261. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  12262. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  12263. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  12264. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  12265. "#define MAX_SHADOWS " + parameters.maxShadows,
  12266. "#define MAX_BONES " + parameters.maxBones,
  12267. parameters.map ? "#define USE_MAP" : "",
  12268. parameters.envMap ? "#define USE_ENVMAP" : "",
  12269. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  12270. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  12271. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  12272. parameters.vertexColors ? "#define USE_COLOR" : "",
  12273. parameters.skinning ? "#define USE_SKINNING" : "",
  12274. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  12275. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  12276. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  12277. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  12278. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  12279. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  12280. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  12281. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  12282. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  12283. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  12284. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  12285. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  12286. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  12287. "uniform mat4 modelMatrix;",
  12288. "uniform mat4 modelViewMatrix;",
  12289. "uniform mat4 projectionMatrix;",
  12290. "uniform mat4 viewMatrix;",
  12291. "uniform mat3 normalMatrix;",
  12292. "uniform vec3 cameraPosition;",
  12293. "attribute vec3 position;",
  12294. "attribute vec3 normal;",
  12295. "attribute vec2 uv;",
  12296. "attribute vec2 uv2;",
  12297. "#ifdef USE_COLOR",
  12298. "attribute vec3 color;",
  12299. "#endif",
  12300. "#ifdef USE_MORPHTARGETS",
  12301. "attribute vec3 morphTarget0;",
  12302. "attribute vec3 morphTarget1;",
  12303. "attribute vec3 morphTarget2;",
  12304. "attribute vec3 morphTarget3;",
  12305. "#ifdef USE_MORPHNORMALS",
  12306. "attribute vec3 morphNormal0;",
  12307. "attribute vec3 morphNormal1;",
  12308. "attribute vec3 morphNormal2;",
  12309. "attribute vec3 morphNormal3;",
  12310. "#else",
  12311. "attribute vec3 morphTarget4;",
  12312. "attribute vec3 morphTarget5;",
  12313. "attribute vec3 morphTarget6;",
  12314. "attribute vec3 morphTarget7;",
  12315. "#endif",
  12316. "#endif",
  12317. "#ifdef USE_SKINNING",
  12318. "attribute vec4 skinIndex;",
  12319. "attribute vec4 skinWeight;",
  12320. "#endif",
  12321. ""
  12322. ].join("\n");
  12323. var prefix_fragment = [
  12324. "precision " + _precision + " float;",
  12325. parameters.bumpMap ? "#extension GL_OES_standard_derivatives : enable" : "",
  12326. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  12327. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  12328. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  12329. "#define MAX_SHADOWS " + parameters.maxShadows,
  12330. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  12331. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  12332. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  12333. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  12334. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  12335. ( parameters.useFog && parameters.fog instanceof THREE.FogExp2 ) ? "#define FOG_EXP2" : "",
  12336. parameters.map ? "#define USE_MAP" : "",
  12337. parameters.envMap ? "#define USE_ENVMAP" : "",
  12338. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  12339. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  12340. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  12341. parameters.vertexColors ? "#define USE_COLOR" : "",
  12342. parameters.metal ? "#define METAL" : "",
  12343. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  12344. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  12345. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  12346. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  12347. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  12348. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  12349. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  12350. "uniform mat4 viewMatrix;",
  12351. "uniform vec3 cameraPosition;",
  12352. ""
  12353. ].join("\n");
  12354. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  12355. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  12356. _gl.attachShader( program, glVertexShader );
  12357. _gl.attachShader( program, glFragmentShader );
  12358. _gl.linkProgram( program );
  12359. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  12360. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  12361. }
  12362. // clean up
  12363. _gl.deleteShader( glFragmentShader );
  12364. _gl.deleteShader( glVertexShader );
  12365. //console.log( prefix_fragment + fragmentShader );
  12366. //console.log( prefix_vertex + vertexShader );
  12367. program.uniforms = {};
  12368. program.attributes = {};
  12369. var identifiers, u, a, i;
  12370. // cache uniform locations
  12371. identifiers = [
  12372. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  12373. 'morphTargetInfluences'
  12374. ];
  12375. if ( parameters.useVertexTexture ) {
  12376. identifiers.push( 'boneTexture' );
  12377. } else {
  12378. identifiers.push( 'boneGlobalMatrices' );
  12379. }
  12380. for ( u in uniforms ) {
  12381. identifiers.push( u );
  12382. }
  12383. cacheUniformLocations( program, identifiers );
  12384. // cache attributes locations
  12385. identifiers = [
  12386. "position", "normal", "uv", "uv2", "tangent", "color",
  12387. "skinIndex", "skinWeight"
  12388. ];
  12389. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  12390. identifiers.push( "morphTarget" + i );
  12391. }
  12392. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  12393. identifiers.push( "morphNormal" + i );
  12394. }
  12395. for ( a in attributes ) {
  12396. identifiers.push( a );
  12397. }
  12398. cacheAttributeLocations( program, identifiers );
  12399. program.id = _programs_counter ++;
  12400. _programs.push( { program: program, code: code, usedTimes: 1 } );
  12401. _this.info.memory.programs = _programs.length;
  12402. return program;
  12403. };
  12404. // Shader parameters cache
  12405. function cacheUniformLocations ( program, identifiers ) {
  12406. var i, l, id;
  12407. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  12408. id = identifiers[ i ];
  12409. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  12410. }
  12411. };
  12412. function cacheAttributeLocations ( program, identifiers ) {
  12413. var i, l, id;
  12414. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  12415. id = identifiers[ i ];
  12416. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  12417. }
  12418. };
  12419. function addLineNumbers ( string ) {
  12420. var chunks = string.split( "\n" );
  12421. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  12422. // Chrome reports shader errors on lines
  12423. // starting counting from 1
  12424. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  12425. }
  12426. return chunks.join( "\n" );
  12427. };
  12428. function getShader ( type, string ) {
  12429. var shader;
  12430. if ( type === "fragment" ) {
  12431. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  12432. } else if ( type === "vertex" ) {
  12433. shader = _gl.createShader( _gl.VERTEX_SHADER );
  12434. }
  12435. _gl.shaderSource( shader, string );
  12436. _gl.compileShader( shader );
  12437. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  12438. console.error( _gl.getShaderInfoLog( shader ) );
  12439. console.error( addLineNumbers( string ) );
  12440. return null;
  12441. }
  12442. return shader;
  12443. };
  12444. // Textures
  12445. function isPowerOfTwo ( value ) {
  12446. return ( value & ( value - 1 ) ) === 0;
  12447. };
  12448. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  12449. if ( isImagePowerOfTwo ) {
  12450. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  12451. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  12452. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  12453. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  12454. } else {
  12455. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  12456. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  12457. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  12458. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  12459. }
  12460. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  12461. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  12462. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  12463. texture.__oldAnisotropy = texture.anisotropy;
  12464. }
  12465. }
  12466. };
  12467. this.setTexture = function ( texture, slot ) {
  12468. if ( texture.needsUpdate ) {
  12469. if ( ! texture.__webglInit ) {
  12470. texture.__webglInit = true;
  12471. texture.__webglTexture = _gl.createTexture();
  12472. _this.info.memory.textures ++;
  12473. }
  12474. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12475. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  12476. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  12477. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  12478. var image = texture.image,
  12479. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  12480. glFormat = paramThreeToGL( texture.format ),
  12481. glType = paramThreeToGL( texture.type );
  12482. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  12483. if ( texture instanceof THREE.DataTexture ) {
  12484. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  12485. } else {
  12486. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  12487. }
  12488. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  12489. texture.needsUpdate = false;
  12490. if ( texture.onUpdate ) texture.onUpdate();
  12491. } else {
  12492. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12493. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  12494. }
  12495. };
  12496. function clampToMaxSize ( image, maxSize ) {
  12497. if ( image.width <= maxSize && image.height <= maxSize ) {
  12498. return image;
  12499. }
  12500. // Warning: Scaling through the canvas will only work with images that use
  12501. // premultiplied alpha.
  12502. var maxDimension = Math.max( image.width, image.height );
  12503. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  12504. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  12505. var canvas = document.createElement( 'canvas' );
  12506. canvas.width = newWidth;
  12507. canvas.height = newHeight;
  12508. var ctx = canvas.getContext( "2d" );
  12509. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  12510. return canvas;
  12511. }
  12512. function setCubeTexture ( texture, slot ) {
  12513. if ( texture.image.length === 6 ) {
  12514. if ( texture.needsUpdate ) {
  12515. if ( ! texture.image.__webglTextureCube ) {
  12516. texture.image.__webglTextureCube = _gl.createTexture();
  12517. }
  12518. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12519. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  12520. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  12521. var cubeImage = [];
  12522. for ( var i = 0; i < 6; i ++ ) {
  12523. if ( _this.autoScaleCubemaps ) {
  12524. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  12525. } else {
  12526. cubeImage[ i ] = texture.image[ i ];
  12527. }
  12528. }
  12529. var image = cubeImage[ 0 ],
  12530. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  12531. glFormat = paramThreeToGL( texture.format ),
  12532. glType = paramThreeToGL( texture.type );
  12533. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  12534. for ( var i = 0; i < 6; i ++ ) {
  12535. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  12536. }
  12537. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  12538. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  12539. }
  12540. texture.needsUpdate = false;
  12541. if ( texture.onUpdate ) texture.onUpdate();
  12542. } else {
  12543. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12544. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  12545. }
  12546. }
  12547. };
  12548. function setCubeTextureDynamic ( texture, slot ) {
  12549. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12550. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  12551. };
  12552. // Render targets
  12553. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  12554. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12555. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  12556. };
  12557. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  12558. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  12559. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  12560. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  12561. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  12562. /* For some reason this is not working. Defaulting to RGBA4.
  12563. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  12564. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  12565. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  12566. */
  12567. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  12568. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  12569. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  12570. } else {
  12571. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  12572. }
  12573. };
  12574. this.setRenderTarget = function ( renderTarget ) {
  12575. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  12576. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  12577. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  12578. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  12579. renderTarget.__webglTexture = _gl.createTexture();
  12580. // Setup texture, create render and frame buffers
  12581. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  12582. glFormat = paramThreeToGL( renderTarget.format ),
  12583. glType = paramThreeToGL( renderTarget.type );
  12584. if ( isCube ) {
  12585. renderTarget.__webglFramebuffer = [];
  12586. renderTarget.__webglRenderbuffer = [];
  12587. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  12588. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  12589. for ( var i = 0; i < 6; i ++ ) {
  12590. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  12591. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  12592. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  12593. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  12594. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  12595. }
  12596. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  12597. } else {
  12598. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  12599. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  12600. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  12601. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  12602. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  12603. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  12604. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  12605. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  12606. }
  12607. // Release everything
  12608. if ( isCube ) {
  12609. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  12610. } else {
  12611. _gl.bindTexture( _gl.TEXTURE_2D, null );
  12612. }
  12613. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  12614. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  12615. }
  12616. var framebuffer, width, height, vx, vy;
  12617. if ( renderTarget ) {
  12618. if ( isCube ) {
  12619. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  12620. } else {
  12621. framebuffer = renderTarget.__webglFramebuffer;
  12622. }
  12623. width = renderTarget.width;
  12624. height = renderTarget.height;
  12625. vx = 0;
  12626. vy = 0;
  12627. } else {
  12628. framebuffer = null;
  12629. width = _viewportWidth;
  12630. height = _viewportHeight;
  12631. vx = _viewportX;
  12632. vy = _viewportY;
  12633. }
  12634. if ( framebuffer !== _currentFramebuffer ) {
  12635. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12636. _gl.viewport( vx, vy, width, height );
  12637. _currentFramebuffer = framebuffer;
  12638. }
  12639. _currentWidth = width;
  12640. _currentHeight = height;
  12641. };
  12642. function updateRenderTargetMipmap ( renderTarget ) {
  12643. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12644. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  12645. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  12646. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  12647. } else {
  12648. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  12649. _gl.generateMipmap( _gl.TEXTURE_2D );
  12650. _gl.bindTexture( _gl.TEXTURE_2D, null );
  12651. }
  12652. };
  12653. // Fallback filters for non-power-of-2 textures
  12654. function filterFallback ( f ) {
  12655. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  12656. return _gl.NEAREST;
  12657. }
  12658. return _gl.LINEAR;
  12659. };
  12660. // Map three.js constants to WebGL constants
  12661. function paramThreeToGL ( p ) {
  12662. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  12663. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  12664. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  12665. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  12666. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  12667. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  12668. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  12669. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  12670. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  12671. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  12672. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  12673. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  12674. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  12675. if ( p === THREE.ByteType ) return _gl.BYTE;
  12676. if ( p === THREE.ShortType ) return _gl.SHORT;
  12677. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  12678. if ( p === THREE.IntType ) return _gl.INT;
  12679. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  12680. if ( p === THREE.FloatType ) return _gl.FLOAT;
  12681. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  12682. if ( p === THREE.RGBFormat ) return _gl.RGB;
  12683. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  12684. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  12685. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  12686. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  12687. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  12688. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  12689. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  12690. if ( p === THREE.OneFactor ) return _gl.ONE;
  12691. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  12692. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  12693. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  12694. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  12695. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  12696. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  12697. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  12698. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  12699. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  12700. return 0;
  12701. };
  12702. // Allocations
  12703. function allocateBones ( object ) {
  12704. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  12705. return 1024;
  12706. } else {
  12707. // default for when object is not specified
  12708. // ( for example when prebuilding shader
  12709. // to be used with multiple objects )
  12710. //
  12711. // - leave some extra space for other uniforms
  12712. // - limit here is ANGLE's 254 max uniform vectors
  12713. // (up to 54 should be safe)
  12714. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  12715. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  12716. var maxBones = nVertexMatrices;
  12717. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  12718. maxBones = Math.min( object.bones.length, maxBones );
  12719. if ( maxBones < object.bones.length ) {
  12720. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  12721. }
  12722. }
  12723. return maxBones;
  12724. }
  12725. };
  12726. function allocateLights ( lights ) {
  12727. var l, ll, light, dirLights, pointLights, spotLights, maxDirLights, maxPointLights, maxSpotLights;
  12728. dirLights = pointLights = spotLights = maxDirLights = maxPointLights = maxSpotLights = 0;
  12729. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12730. light = lights[ l ];
  12731. if ( light.onlyShadow ) continue;
  12732. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  12733. if ( light instanceof THREE.PointLight ) pointLights ++;
  12734. if ( light instanceof THREE.SpotLight ) spotLights ++;
  12735. }
  12736. if ( ( pointLights + spotLights + dirLights ) <= _maxLights ) {
  12737. maxDirLights = dirLights;
  12738. maxPointLights = pointLights;
  12739. maxSpotLights = spotLights;
  12740. } else {
  12741. maxDirLights = Math.ceil( _maxLights * dirLights / ( pointLights + dirLights ) );
  12742. maxPointLights = _maxLights - maxDirLights;
  12743. maxSpotLights = maxPointLights; // this is not really correct
  12744. }
  12745. return { 'directional' : maxDirLights, 'point' : maxPointLights, 'spot': maxSpotLights };
  12746. };
  12747. function allocateShadows ( lights ) {
  12748. var l, ll, light, maxShadows = 0;
  12749. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  12750. light = lights[ l ];
  12751. if ( ! light.castShadow ) continue;
  12752. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  12753. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  12754. }
  12755. return maxShadows;
  12756. };
  12757. // Initialization
  12758. function initGL () {
  12759. try {
  12760. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  12761. throw 'Error creating WebGL context.';
  12762. }
  12763. } catch ( error ) {
  12764. console.error( error );
  12765. }
  12766. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  12767. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  12768. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  12769. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  12770. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  12771. if ( ! _glExtensionTextureFloat ) {
  12772. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  12773. }
  12774. if ( ! _glExtensionStandardDerivatives ) {
  12775. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  12776. }
  12777. if ( ! _glExtensionTextureFilterAnisotropic ) {
  12778. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  12779. }
  12780. };
  12781. function setDefaultGLState () {
  12782. _gl.clearColor( 0, 0, 0, 1 );
  12783. _gl.clearDepth( 1 );
  12784. _gl.clearStencil( 0 );
  12785. _gl.enable( _gl.DEPTH_TEST );
  12786. _gl.depthFunc( _gl.LEQUAL );
  12787. _gl.frontFace( _gl.CCW );
  12788. _gl.cullFace( _gl.BACK );
  12789. _gl.enable( _gl.CULL_FACE );
  12790. _gl.enable( _gl.BLEND );
  12791. _gl.blendEquation( _gl.FUNC_ADD );
  12792. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  12793. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12794. };
  12795. // default plugins (order is important)
  12796. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  12797. this.addPrePlugin( this.shadowMapPlugin );
  12798. this.addPostPlugin( new THREE.SpritePlugin() );
  12799. this.addPostPlugin( new THREE.LensFlarePlugin() );
  12800. };
  12801. /**
  12802. * @author szimek / https://github.com/szimek/
  12803. * @author alteredq / http://alteredqualia.com/
  12804. */
  12805. THREE.WebGLRenderTarget = function ( width, height, options ) {
  12806. this.width = width;
  12807. this.height = height;
  12808. options = options || {};
  12809. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  12810. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  12811. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  12812. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  12813. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  12814. this.offset = new THREE.Vector2( 0, 0 );
  12815. this.repeat = new THREE.Vector2( 1, 1 );
  12816. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  12817. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  12818. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  12819. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  12820. this.generateMipmaps = true;
  12821. };
  12822. THREE.WebGLRenderTarget.prototype.clone = function() {
  12823. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  12824. tmp.wrapS = this.wrapS;
  12825. tmp.wrapT = this.wrapT;
  12826. tmp.magFilter = this.magFilter;
  12827. tmp.anisotropy = this.anisotropy;
  12828. tmp.minFilter = this.minFilter;
  12829. tmp.offset.copy( this.offset );
  12830. tmp.repeat.copy( this.repeat );
  12831. tmp.format = this.format;
  12832. tmp.type = this.type;
  12833. tmp.depthBuffer = this.depthBuffer;
  12834. tmp.stencilBuffer = this.stencilBuffer;
  12835. tmp.generateMipmaps = this.generateMipmaps;
  12836. return tmp;
  12837. };
  12838. /**
  12839. * @author alteredq / http://alteredqualia.com
  12840. */
  12841. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  12842. THREE.WebGLRenderTarget.call( this, width, height, options );
  12843. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  12844. };
  12845. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  12846. /**
  12847. * @author mrdoob / http://mrdoob.com/
  12848. */
  12849. THREE.RenderableVertex = function () {
  12850. this.positionWorld = new THREE.Vector3();
  12851. this.positionScreen = new THREE.Vector4();
  12852. this.visible = true;
  12853. };
  12854. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  12855. this.positionWorld.copy( vertex.positionWorld );
  12856. this.positionScreen.copy( vertex.positionScreen );
  12857. }
  12858. /**
  12859. * @author mrdoob / http://mrdoob.com/
  12860. */
  12861. THREE.RenderableFace3 = function () {
  12862. this.v1 = new THREE.RenderableVertex();
  12863. this.v2 = new THREE.RenderableVertex();
  12864. this.v3 = new THREE.RenderableVertex();
  12865. this.centroidWorld = new THREE.Vector3();
  12866. this.centroidScreen = new THREE.Vector3();
  12867. this.normalWorld = new THREE.Vector3();
  12868. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  12869. this.vertexNormalsLength = 0;
  12870. this.material = null;
  12871. this.uvs = [[]];
  12872. this.z = null;
  12873. };
  12874. /**
  12875. * @author mrdoob / http://mrdoob.com/
  12876. */
  12877. THREE.RenderableFace4 = function () {
  12878. this.v1 = new THREE.RenderableVertex();
  12879. this.v2 = new THREE.RenderableVertex();
  12880. this.v3 = new THREE.RenderableVertex();
  12881. this.v4 = new THREE.RenderableVertex();
  12882. this.centroidWorld = new THREE.Vector3();
  12883. this.centroidScreen = new THREE.Vector3();
  12884. this.normalWorld = new THREE.Vector3();
  12885. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  12886. this.vertexNormalsLength = 0;
  12887. this.material = null;
  12888. this.uvs = [[]];
  12889. this.z = null;
  12890. };
  12891. /**
  12892. * @author mrdoob / http://mrdoob.com/
  12893. */
  12894. THREE.RenderableObject = function () {
  12895. this.object = null;
  12896. this.z = null;
  12897. };
  12898. /**
  12899. * @author mrdoob / http://mrdoob.com/
  12900. */
  12901. THREE.RenderableParticle = function () {
  12902. this.object = null;
  12903. this.x = null;
  12904. this.y = null;
  12905. this.z = null;
  12906. this.rotation = null;
  12907. this.scale = new THREE.Vector2();
  12908. this.material = null;
  12909. };
  12910. /**
  12911. * @author mrdoob / http://mrdoob.com/
  12912. */
  12913. THREE.RenderableLine = function () {
  12914. this.z = null;
  12915. this.v1 = new THREE.RenderableVertex();
  12916. this.v2 = new THREE.RenderableVertex();
  12917. this.material = null;
  12918. };
  12919. /**
  12920. * @author alteredq / http://alteredqualia.com/
  12921. */
  12922. THREE.ColorUtils = {
  12923. adjustHSV : function ( color, h, s, v ) {
  12924. var hsv = THREE.ColorUtils.__hsv;
  12925. THREE.ColorUtils.rgbToHsv( color, hsv );
  12926. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  12927. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  12928. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  12929. color.setHSV( hsv.h, hsv.s, hsv.v );
  12930. },
  12931. // based on MochiKit implementation by Bob Ippolito
  12932. rgbToHsv : function ( color, hsv ) {
  12933. var r = color.r;
  12934. var g = color.g;
  12935. var b = color.b;
  12936. var max = Math.max( Math.max( r, g ), b );
  12937. var min = Math.min( Math.min( r, g ), b );
  12938. var hue;
  12939. var saturation;
  12940. var value = max;
  12941. if ( min === max ) {
  12942. hue = 0;
  12943. saturation = 0;
  12944. } else {
  12945. var delta = ( max - min );
  12946. saturation = delta / max;
  12947. if ( r === max ) {
  12948. hue = ( g - b ) / delta;
  12949. } else if ( g === max ) {
  12950. hue = 2 + ( ( b - r ) / delta );
  12951. } else {
  12952. hue = 4 + ( ( r - g ) / delta );
  12953. }
  12954. hue /= 6;
  12955. if ( hue < 0 ) {
  12956. hue += 1;
  12957. }
  12958. if ( hue > 1 ) {
  12959. hue -= 1;
  12960. }
  12961. }
  12962. if ( hsv === undefined ) {
  12963. hsv = { h: 0, s: 0, v: 0 };
  12964. }
  12965. hsv.h = hue;
  12966. hsv.s = saturation;
  12967. hsv.v = value;
  12968. return hsv;
  12969. }
  12970. };
  12971. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  12972. * @author mrdoob / http://mrdoob.com/
  12973. * @author alteredq / http://alteredqualia.com/
  12974. */
  12975. THREE.GeometryUtils = {
  12976. // Merge two geometries or geometry and geometry from object (using object's transform)
  12977. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  12978. var matrix, matrixRotation,
  12979. vertexOffset = geometry1.vertices.length,
  12980. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  12981. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  12982. vertices1 = geometry1.vertices,
  12983. vertices2 = geometry2.vertices,
  12984. faces1 = geometry1.faces,
  12985. faces2 = geometry2.faces,
  12986. uvs1 = geometry1.faceVertexUvs[ 0 ],
  12987. uvs2 = geometry2.faceVertexUvs[ 0 ];
  12988. var geo1MaterialsMap = {};
  12989. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  12990. var id = geometry1.materials[ i ].id;
  12991. geo1MaterialsMap[ id ] = i;
  12992. }
  12993. if ( object2 instanceof THREE.Mesh ) {
  12994. object2.matrixAutoUpdate && object2.updateMatrix();
  12995. matrix = object2.matrix;
  12996. matrixRotation = new THREE.Matrix4();
  12997. matrixRotation.extractRotation( matrix, object2.scale );
  12998. }
  12999. // vertices
  13000. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  13001. var vertex = vertices2[ i ];
  13002. var vertexCopy = vertex.clone();
  13003. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  13004. vertices1.push( vertexCopy );
  13005. }
  13006. // faces
  13007. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  13008. var face = faces2[ i ], faceCopy, normal, color,
  13009. faceVertexNormals = face.vertexNormals,
  13010. faceVertexColors = face.vertexColors;
  13011. if ( face instanceof THREE.Face3 ) {
  13012. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  13013. } else if ( face instanceof THREE.Face4 ) {
  13014. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  13015. }
  13016. faceCopy.normal.copy( face.normal );
  13017. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  13018. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  13019. normal = faceVertexNormals[ j ].clone();
  13020. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  13021. faceCopy.vertexNormals.push( normal );
  13022. }
  13023. faceCopy.color.copy( face.color );
  13024. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  13025. color = faceVertexColors[ j ];
  13026. faceCopy.vertexColors.push( color.clone() );
  13027. }
  13028. if ( face.materialIndex !== undefined ) {
  13029. var material2 = geometry2.materials[ face.materialIndex ];
  13030. var materialId2 = material2.id;
  13031. var materialIndex = geo1MaterialsMap[ materialId2 ];
  13032. if ( materialIndex === undefined ) {
  13033. materialIndex = geometry1.materials.length;
  13034. geo1MaterialsMap[ materialId2 ] = materialIndex;
  13035. geometry1.materials.push( material2 );
  13036. }
  13037. faceCopy.materialIndex = materialIndex;
  13038. }
  13039. faceCopy.centroid.copy( face.centroid );
  13040. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  13041. faces1.push( faceCopy );
  13042. }
  13043. // uvs
  13044. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  13045. var uv = uvs2[ i ], uvCopy = [];
  13046. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13047. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13048. }
  13049. uvs1.push( uvCopy );
  13050. }
  13051. },
  13052. clone: function ( geometry ) {
  13053. var cloneGeo = new THREE.Geometry();
  13054. var i, il;
  13055. var vertices = geometry.vertices,
  13056. faces = geometry.faces,
  13057. uvs = geometry.faceVertexUvs[ 0 ];
  13058. // materials
  13059. if ( geometry.materials ) {
  13060. cloneGeo.materials = geometry.materials.slice();
  13061. }
  13062. // vertices
  13063. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  13064. var vertex = vertices[ i ];
  13065. cloneGeo.vertices.push( vertex.clone() );
  13066. }
  13067. // faces
  13068. for ( i = 0, il = faces.length; i < il; i ++ ) {
  13069. var face = faces[ i ];
  13070. cloneGeo.faces.push( face.clone() );
  13071. }
  13072. // uvs
  13073. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  13074. var uv = uvs[ i ], uvCopy = [];
  13075. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13076. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13077. }
  13078. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  13079. }
  13080. return cloneGeo;
  13081. },
  13082. // Get random point in triangle (via barycentric coordinates)
  13083. // (uniform distribution)
  13084. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  13085. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  13086. var a, b, c,
  13087. point = new THREE.Vector3(),
  13088. tmp = THREE.GeometryUtils.__v1;
  13089. a = THREE.GeometryUtils.random();
  13090. b = THREE.GeometryUtils.random();
  13091. if ( ( a + b ) > 1 ) {
  13092. a = 1 - a;
  13093. b = 1 - b;
  13094. }
  13095. c = 1 - a - b;
  13096. point.copy( vectorA );
  13097. point.multiplyScalar( a );
  13098. tmp.copy( vectorB );
  13099. tmp.multiplyScalar( b );
  13100. point.addSelf( tmp );
  13101. tmp.copy( vectorC );
  13102. tmp.multiplyScalar( c );
  13103. point.addSelf( tmp );
  13104. return point;
  13105. },
  13106. // Get random point in face (triangle / quad)
  13107. // (uniform distribution)
  13108. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  13109. var vA, vB, vC, vD;
  13110. if ( face instanceof THREE.Face3 ) {
  13111. vA = geometry.vertices[ face.a ];
  13112. vB = geometry.vertices[ face.b ];
  13113. vC = geometry.vertices[ face.c ];
  13114. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  13115. } else if ( face instanceof THREE.Face4 ) {
  13116. vA = geometry.vertices[ face.a ];
  13117. vB = geometry.vertices[ face.b ];
  13118. vC = geometry.vertices[ face.c ];
  13119. vD = geometry.vertices[ face.d ];
  13120. var area1, area2;
  13121. if ( useCachedAreas ) {
  13122. if ( face._area1 && face._area2 ) {
  13123. area1 = face._area1;
  13124. area2 = face._area2;
  13125. } else {
  13126. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13127. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13128. face._area1 = area1;
  13129. face._area2 = area2;
  13130. }
  13131. } else {
  13132. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  13133. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13134. }
  13135. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  13136. if ( r < area1 ) {
  13137. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  13138. } else {
  13139. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  13140. }
  13141. }
  13142. },
  13143. // Get uniformly distributed random points in mesh
  13144. // - create array with cumulative sums of face areas
  13145. // - pick random number from 0 to total area
  13146. // - find corresponding place in area array by binary search
  13147. // - get random point in face
  13148. randomPointsInGeometry: function ( geometry, n ) {
  13149. var face, i,
  13150. faces = geometry.faces,
  13151. vertices = geometry.vertices,
  13152. il = faces.length,
  13153. totalArea = 0,
  13154. cumulativeAreas = [],
  13155. vA, vB, vC, vD;
  13156. // precompute face areas
  13157. for ( i = 0; i < il; i ++ ) {
  13158. face = faces[ i ];
  13159. if ( face instanceof THREE.Face3 ) {
  13160. vA = vertices[ face.a ];
  13161. vB = vertices[ face.b ];
  13162. vC = vertices[ face.c ];
  13163. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  13164. } else if ( face instanceof THREE.Face4 ) {
  13165. vA = vertices[ face.a ];
  13166. vB = vertices[ face.b ];
  13167. vC = vertices[ face.c ];
  13168. vD = vertices[ face.d ];
  13169. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13170. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13171. face._area = face._area1 + face._area2;
  13172. }
  13173. totalArea += face._area;
  13174. cumulativeAreas[ i ] = totalArea;
  13175. }
  13176. // binary search cumulative areas array
  13177. function binarySearchIndices( value ) {
  13178. function binarySearch( start, end ) {
  13179. // return closest larger index
  13180. // if exact number is not found
  13181. if ( end < start )
  13182. return start;
  13183. var mid = start + Math.floor( ( end - start ) / 2 );
  13184. if ( cumulativeAreas[ mid ] > value ) {
  13185. return binarySearch( start, mid - 1 );
  13186. } else if ( cumulativeAreas[ mid ] < value ) {
  13187. return binarySearch( mid + 1, end );
  13188. } else {
  13189. return mid;
  13190. }
  13191. }
  13192. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  13193. return result;
  13194. }
  13195. // pick random face weighted by face area
  13196. var r, index,
  13197. result = [];
  13198. var stats = {};
  13199. for ( i = 0; i < n; i ++ ) {
  13200. r = THREE.GeometryUtils.random() * totalArea;
  13201. index = binarySearchIndices( r );
  13202. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  13203. if ( ! stats[ index ] ) {
  13204. stats[ index ] = 1;
  13205. } else {
  13206. stats[ index ] += 1;
  13207. }
  13208. }
  13209. return result;
  13210. },
  13211. // Get triangle area (by Heron's formula)
  13212. // http://en.wikipedia.org/wiki/Heron%27s_formula
  13213. triangleArea: function ( vectorA, vectorB, vectorC ) {
  13214. var s, a, b, c,
  13215. tmp = THREE.GeometryUtils.__v1;
  13216. tmp.sub( vectorA, vectorB );
  13217. a = tmp.length();
  13218. tmp.sub( vectorA, vectorC );
  13219. b = tmp.length();
  13220. tmp.sub( vectorB, vectorC );
  13221. c = tmp.length();
  13222. s = 0.5 * ( a + b + c );
  13223. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  13224. },
  13225. // Center geometry so that 0,0,0 is in center of bounding box
  13226. center: function ( geometry ) {
  13227. geometry.computeBoundingBox();
  13228. var bb = geometry.boundingBox;
  13229. var offset = new THREE.Vector3();
  13230. offset.add( bb.min, bb.max );
  13231. offset.multiplyScalar( -0.5 );
  13232. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  13233. geometry.computeBoundingBox();
  13234. return offset;
  13235. },
  13236. // Normalize UVs to be from <0,1>
  13237. // (for now just the first set of UVs)
  13238. normalizeUVs: function ( geometry ) {
  13239. var uvSet = geometry.faceVertexUvs[ 0 ];
  13240. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  13241. var uvs = uvSet[ i ];
  13242. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  13243. // texture repeat
  13244. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  13245. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  13246. }
  13247. }
  13248. },
  13249. triangulateQuads: function ( geometry ) {
  13250. var i, il, j, jl;
  13251. var faces = [];
  13252. var faceUvs = [];
  13253. var faceVertexUvs = [];
  13254. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  13255. faceUvs[ i ] = [];
  13256. }
  13257. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13258. faceVertexUvs[ i ] = [];
  13259. }
  13260. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13261. var face = geometry.faces[ i ];
  13262. if ( face instanceof THREE.Face4 ) {
  13263. var a = face.a;
  13264. var b = face.b;
  13265. var c = face.c;
  13266. var d = face.d;
  13267. var triA = new THREE.Face3();
  13268. var triB = new THREE.Face3();
  13269. triA.color.copy( face.color );
  13270. triB.color.copy( face.color );
  13271. triA.materialIndex = face.materialIndex;
  13272. triB.materialIndex = face.materialIndex;
  13273. triA.a = a;
  13274. triA.b = b;
  13275. triA.c = d;
  13276. triB.a = b;
  13277. triB.b = c;
  13278. triB.c = d;
  13279. if ( face.vertexColors.length === 4 ) {
  13280. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  13281. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  13282. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13283. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  13284. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  13285. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13286. }
  13287. faces.push( triA, triB );
  13288. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13289. if ( geometry.faceVertexUvs[ j ].length ) {
  13290. var uvs = geometry.faceVertexUvs[ j ][ i ];
  13291. var uvA = uvs[ 0 ];
  13292. var uvB = uvs[ 1 ];
  13293. var uvC = uvs[ 2 ];
  13294. var uvD = uvs[ 3 ];
  13295. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  13296. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  13297. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  13298. }
  13299. }
  13300. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13301. if ( geometry.faceUvs[ j ].length ) {
  13302. var faceUv = geometry.faceUvs[ j ][ i ];
  13303. faceUvs[ j ].push( faceUv, faceUv );
  13304. }
  13305. }
  13306. } else {
  13307. faces.push( face );
  13308. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13309. faceUvs[ j ].push( geometry.faceUvs[ j ] );
  13310. }
  13311. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13312. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  13313. }
  13314. }
  13315. }
  13316. geometry.faces = faces;
  13317. geometry.faceUvs = faceUvs;
  13318. geometry.faceVertexUvs = faceVertexUvs;
  13319. geometry.computeCentroids();
  13320. geometry.computeFaceNormals();
  13321. geometry.computeVertexNormals();
  13322. if ( geometry.hasTangents ) geometry.computeTangents();
  13323. },
  13324. // Make all faces use unique vertices
  13325. // so that each face can be separated from others
  13326. explode: function( geometry ) {
  13327. var vertices = [];
  13328. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13329. var n = vertices.length;
  13330. var face = geometry.faces[ i ];
  13331. if ( face instanceof THREE.Face4 ) {
  13332. var a = face.a;
  13333. var b = face.b;
  13334. var c = face.c;
  13335. var d = face.d;
  13336. var va = geometry.vertices[ a ];
  13337. var vb = geometry.vertices[ b ];
  13338. var vc = geometry.vertices[ c ];
  13339. var vd = geometry.vertices[ d ];
  13340. vertices.push( va.clone() );
  13341. vertices.push( vb.clone() );
  13342. vertices.push( vc.clone() );
  13343. vertices.push( vd.clone() );
  13344. face.a = n;
  13345. face.b = n + 1;
  13346. face.c = n + 2;
  13347. face.d = n + 3;
  13348. } else {
  13349. var a = face.a;
  13350. var b = face.b;
  13351. var c = face.c;
  13352. var va = geometry.vertices[ a ];
  13353. var vb = geometry.vertices[ b ];
  13354. var vc = geometry.vertices[ c ];
  13355. vertices.push( va.clone() );
  13356. vertices.push( vb.clone() );
  13357. vertices.push( vc.clone() );
  13358. face.a = n;
  13359. face.b = n + 1;
  13360. face.c = n + 2;
  13361. }
  13362. }
  13363. geometry.vertices = vertices;
  13364. delete geometry.__tmpVertices;
  13365. },
  13366. // Break faces with edges longer than maxEdgeLength
  13367. // - not recursive
  13368. tessellate: function ( geometry, maxEdgeLength ) {
  13369. var i, il, face,
  13370. a, b, c, d,
  13371. va, vb, vc, vd,
  13372. dab, dbc, dac, dcd, dad,
  13373. m, m1, m2,
  13374. vm, vm1, vm2,
  13375. vnm, vnm1, vnm2,
  13376. vcm, vcm1, vcm2,
  13377. triA, triB,
  13378. quadA, quadB,
  13379. edge;
  13380. var faces = [];
  13381. var faceVertexUvs = [];
  13382. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13383. faceVertexUvs[ i ] = [];
  13384. }
  13385. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13386. face = geometry.faces[ i ];
  13387. if ( face instanceof THREE.Face3 ) {
  13388. a = face.a;
  13389. b = face.b;
  13390. c = face.c;
  13391. va = geometry.vertices[ a ];
  13392. vb = geometry.vertices[ b ];
  13393. vc = geometry.vertices[ c ];
  13394. dab = va.distanceTo( vb );
  13395. dbc = vb.distanceTo( vc );
  13396. dac = va.distanceTo( vc );
  13397. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  13398. m = geometry.vertices.length;
  13399. triA = face.clone();
  13400. triB = face.clone();
  13401. if ( dab >= dbc && dab >= dac ) {
  13402. vm = va.clone();
  13403. vm.lerpSelf( vb, 0.5 );
  13404. triA.a = a;
  13405. triA.b = m;
  13406. triA.c = c;
  13407. triB.a = m;
  13408. triB.b = b;
  13409. triB.c = c;
  13410. if ( face.vertexNormals.length === 3 ) {
  13411. vnm = face.vertexNormals[ 0 ].clone();
  13412. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  13413. triA.vertexNormals[ 1 ].copy( vnm );
  13414. triB.vertexNormals[ 0 ].copy( vnm );
  13415. }
  13416. if ( face.vertexColors.length === 3 ) {
  13417. vcm = face.vertexColors[ 0 ].clone();
  13418. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  13419. triA.vertexColors[ 1 ].copy( vcm );
  13420. triB.vertexColors[ 0 ].copy( vcm );
  13421. }
  13422. edge = 0;
  13423. } else if ( dbc >= dab && dbc >= dac ) {
  13424. vm = vb.clone();
  13425. vm.lerpSelf( vc, 0.5 );
  13426. triA.a = a;
  13427. triA.b = b;
  13428. triA.c = m;
  13429. triB.a = m;
  13430. triB.b = c;
  13431. triB.c = a;
  13432. if ( face.vertexNormals.length === 3 ) {
  13433. vnm = face.vertexNormals[ 1 ].clone();
  13434. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  13435. triA.vertexNormals[ 2 ].copy( vnm );
  13436. triB.vertexNormals[ 0 ].copy( vnm );
  13437. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  13438. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  13439. }
  13440. if ( face.vertexColors.length === 3 ) {
  13441. vcm = face.vertexColors[ 1 ].clone();
  13442. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  13443. triA.vertexColors[ 2 ].copy( vcm );
  13444. triB.vertexColors[ 0 ].copy( vcm );
  13445. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  13446. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  13447. }
  13448. edge = 1;
  13449. } else {
  13450. vm = va.clone();
  13451. vm.lerpSelf( vc, 0.5 );
  13452. triA.a = a;
  13453. triA.b = b;
  13454. triA.c = m;
  13455. triB.a = m;
  13456. triB.b = b;
  13457. triB.c = c;
  13458. if ( face.vertexNormals.length === 3 ) {
  13459. vnm = face.vertexNormals[ 0 ].clone();
  13460. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  13461. triA.vertexNormals[ 2 ].copy( vnm );
  13462. triB.vertexNormals[ 0 ].copy( vnm );
  13463. }
  13464. if ( face.vertexColors.length === 3 ) {
  13465. vcm = face.vertexColors[ 0 ].clone();
  13466. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  13467. triA.vertexColors[ 2 ].copy( vcm );
  13468. triB.vertexColors[ 0 ].copy( vcm );
  13469. }
  13470. edge = 2;
  13471. }
  13472. faces.push( triA, triB );
  13473. geometry.vertices.push( vm );
  13474. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  13475. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13476. if ( geometry.faceVertexUvs[ j ].length ) {
  13477. uvs = geometry.faceVertexUvs[ j ][ i ];
  13478. uvA = uvs[ 0 ];
  13479. uvB = uvs[ 1 ];
  13480. uvC = uvs[ 2 ];
  13481. // AB
  13482. if ( edge === 0 ) {
  13483. uvM = uvA.clone();
  13484. uvM.lerpSelf( uvB, 0.5 );
  13485. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  13486. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  13487. // BC
  13488. } else if ( edge === 1 ) {
  13489. uvM = uvB.clone();
  13490. uvM.lerpSelf( uvC, 0.5 );
  13491. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  13492. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  13493. // AC
  13494. } else {
  13495. uvM = uvA.clone();
  13496. uvM.lerpSelf( uvC, 0.5 );
  13497. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  13498. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  13499. }
  13500. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  13501. }
  13502. }
  13503. } else {
  13504. faces.push( face );
  13505. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13506. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  13507. }
  13508. }
  13509. } else {
  13510. a = face.a;
  13511. b = face.b;
  13512. c = face.c;
  13513. d = face.d;
  13514. va = geometry.vertices[ a ];
  13515. vb = geometry.vertices[ b ];
  13516. vc = geometry.vertices[ c ];
  13517. vd = geometry.vertices[ d ];
  13518. dab = va.distanceTo( vb );
  13519. dbc = vb.distanceTo( vc );
  13520. dcd = vc.distanceTo( vd );
  13521. dad = va.distanceTo( vd );
  13522. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  13523. m1 = geometry.vertices.length;
  13524. m2 = geometry.vertices.length + 1;
  13525. quadA = face.clone();
  13526. quadB = face.clone();
  13527. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  13528. vm1 = va.clone();
  13529. vm1.lerpSelf( vb, 0.5 );
  13530. vm2 = vc.clone();
  13531. vm2.lerpSelf( vd, 0.5 );
  13532. quadA.a = a;
  13533. quadA.b = m1;
  13534. quadA.c = m2;
  13535. quadA.d = d;
  13536. quadB.a = m1;
  13537. quadB.b = b;
  13538. quadB.c = c;
  13539. quadB.d = m2;
  13540. if ( face.vertexNormals.length === 4 ) {
  13541. vnm1 = face.vertexNormals[ 0 ].clone();
  13542. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  13543. vnm2 = face.vertexNormals[ 2 ].clone();
  13544. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  13545. quadA.vertexNormals[ 1 ].copy( vnm1 );
  13546. quadA.vertexNormals[ 2 ].copy( vnm2 );
  13547. quadB.vertexNormals[ 0 ].copy( vnm1 );
  13548. quadB.vertexNormals[ 3 ].copy( vnm2 );
  13549. }
  13550. if ( face.vertexColors.length === 4 ) {
  13551. vcm1 = face.vertexColors[ 0 ].clone();
  13552. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  13553. vcm2 = face.vertexColors[ 2 ].clone();
  13554. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  13555. quadA.vertexColors[ 1 ].copy( vcm1 );
  13556. quadA.vertexColors[ 2 ].copy( vcm2 );
  13557. quadB.vertexColors[ 0 ].copy( vcm1 );
  13558. quadB.vertexColors[ 3 ].copy( vcm2 );
  13559. }
  13560. edge = 0;
  13561. } else {
  13562. vm1 = vb.clone();
  13563. vm1.lerpSelf( vc, 0.5 );
  13564. vm2 = vd.clone();
  13565. vm2.lerpSelf( va, 0.5 );
  13566. quadA.a = a;
  13567. quadA.b = b;
  13568. quadA.c = m1;
  13569. quadA.d = m2;
  13570. quadB.a = m2;
  13571. quadB.b = m1;
  13572. quadB.c = c;
  13573. quadB.d = d;
  13574. if ( face.vertexNormals.length === 4 ) {
  13575. vnm1 = face.vertexNormals[ 1 ].clone();
  13576. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  13577. vnm2 = face.vertexNormals[ 3 ].clone();
  13578. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  13579. quadA.vertexNormals[ 2 ].copy( vnm1 );
  13580. quadA.vertexNormals[ 3 ].copy( vnm2 );
  13581. quadB.vertexNormals[ 0 ].copy( vnm2 );
  13582. quadB.vertexNormals[ 1 ].copy( vnm1 );
  13583. }
  13584. if ( face.vertexColors.length === 4 ) {
  13585. vcm1 = face.vertexColors[ 1 ].clone();
  13586. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  13587. vcm2 = face.vertexColors[ 3 ].clone();
  13588. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  13589. quadA.vertexColors[ 2 ].copy( vcm1 );
  13590. quadA.vertexColors[ 3 ].copy( vcm2 );
  13591. quadB.vertexColors[ 0 ].copy( vcm2 );
  13592. quadB.vertexColors[ 1 ].copy( vcm1 );
  13593. }
  13594. edge = 1;
  13595. }
  13596. faces.push( quadA, quadB );
  13597. geometry.vertices.push( vm1, vm2 );
  13598. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  13599. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13600. if ( geometry.faceVertexUvs[ j ].length ) {
  13601. uvs = geometry.faceVertexUvs[ j ][ i ];
  13602. uvA = uvs[ 0 ];
  13603. uvB = uvs[ 1 ];
  13604. uvC = uvs[ 2 ];
  13605. uvD = uvs[ 3 ];
  13606. // AB + CD
  13607. if ( edge === 0 ) {
  13608. uvM1 = uvA.clone();
  13609. uvM1.lerpSelf( uvB, 0.5 );
  13610. uvM2 = uvC.clone();
  13611. uvM2.lerpSelf( uvD, 0.5 );
  13612. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  13613. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  13614. // BC + AD
  13615. } else {
  13616. uvM1 = uvB.clone();
  13617. uvM1.lerpSelf( uvC, 0.5 );
  13618. uvM2 = uvD.clone();
  13619. uvM2.lerpSelf( uvA, 0.5 );
  13620. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  13621. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  13622. }
  13623. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  13624. }
  13625. }
  13626. } else {
  13627. faces.push( face );
  13628. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13629. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  13630. }
  13631. }
  13632. }
  13633. }
  13634. geometry.faces = faces;
  13635. geometry.faceVertexUvs = faceVertexUvs;
  13636. }
  13637. };
  13638. THREE.GeometryUtils.random = THREE.Math.random16;
  13639. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  13640. /**
  13641. * @author alteredq / http://alteredqualia.com/
  13642. * @author mrdoob / http://mrdoob.com/
  13643. */
  13644. THREE.ImageUtils = {
  13645. crossOrigin: 'anonymous',
  13646. loadTexture: function ( url, mapping, onLoad, onError ) {
  13647. var image = new Image();
  13648. var texture = new THREE.Texture( image, mapping );
  13649. var loader = new THREE.ImageLoader();
  13650. loader.addEventListener( 'load', function ( event ) {
  13651. texture.image = event.content;
  13652. texture.needsUpdate = true;
  13653. if ( onLoad ) onLoad( texture );
  13654. } );
  13655. loader.addEventListener( 'error', function ( event ) {
  13656. if ( onError ) onError( event.message );
  13657. } );
  13658. loader.crossOrigin = this.crossOrigin;
  13659. loader.load( url, image );
  13660. return texture;
  13661. },
  13662. loadTextureCube: function ( array, mapping, onLoad ) {
  13663. var i, l, images = [];
  13664. var texture = new THREE.Texture( images, mapping );
  13665. texture.flipY = false;
  13666. images.loadCount = 0;
  13667. for ( i = 0, l = array.length; i < l; ++ i ) {
  13668. images[ i ] = new Image();
  13669. images[ i ].onload = function () {
  13670. images.loadCount += 1;
  13671. if ( images.loadCount === 6 ) {
  13672. texture.needsUpdate = true;
  13673. if ( onLoad ) onLoad();
  13674. }
  13675. };
  13676. images[ i ].crossOrigin = this.crossOrigin;
  13677. images[ i ].src = array[ i ];
  13678. }
  13679. return texture;
  13680. },
  13681. getNormalMap: function ( image, depth ) {
  13682. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  13683. var cross = function ( a, b ) {
  13684. 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 ] ];
  13685. }
  13686. var subtract = function ( a, b ) {
  13687. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  13688. }
  13689. var normalize = function ( a ) {
  13690. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  13691. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  13692. }
  13693. depth = depth | 1;
  13694. var width = image.width;
  13695. var height = image.height;
  13696. var canvas = document.createElement( 'canvas' );
  13697. canvas.width = width;
  13698. canvas.height = height;
  13699. var context = canvas.getContext( '2d' );
  13700. context.drawImage( image, 0, 0 );
  13701. var data = context.getImageData( 0, 0, width, height ).data;
  13702. var imageData = context.createImageData( width, height );
  13703. var output = imageData.data;
  13704. for ( var x = 0; x < width; x ++ ) {
  13705. for ( var y = 0; y < height; y ++ ) {
  13706. var ly = y - 1 < 0 ? 0 : y - 1;
  13707. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  13708. var lx = x - 1 < 0 ? 0 : x - 1;
  13709. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  13710. var points = [];
  13711. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  13712. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  13713. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  13714. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  13715. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  13716. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  13717. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  13718. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  13719. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  13720. var normals = [];
  13721. var num_points = points.length;
  13722. for ( var i = 0; i < num_points; i ++ ) {
  13723. var v1 = points[ i ];
  13724. var v2 = points[ ( i + 1 ) % num_points ];
  13725. v1 = subtract( v1, origin );
  13726. v2 = subtract( v2, origin );
  13727. normals.push( normalize( cross( v1, v2 ) ) );
  13728. }
  13729. var normal = [ 0, 0, 0 ];
  13730. for ( var i = 0; i < normals.length; i ++ ) {
  13731. normal[ 0 ] += normals[ i ][ 0 ];
  13732. normal[ 1 ] += normals[ i ][ 1 ];
  13733. normal[ 2 ] += normals[ i ][ 2 ];
  13734. }
  13735. normal[ 0 ] /= normals.length;
  13736. normal[ 1 ] /= normals.length;
  13737. normal[ 2 ] /= normals.length;
  13738. var idx = ( y * width + x ) * 4;
  13739. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  13740. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  13741. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  13742. output[ idx + 3 ] = 255;
  13743. }
  13744. }
  13745. context.putImageData( imageData, 0, 0 );
  13746. return canvas;
  13747. },
  13748. generateDataTexture: function ( width, height, color ) {
  13749. var size = width * height;
  13750. var data = new Uint8Array( 3 * size );
  13751. var r = Math.floor( color.r * 255 );
  13752. var g = Math.floor( color.g * 255 );
  13753. var b = Math.floor( color.b * 255 );
  13754. for ( var i = 0; i < size; i ++ ) {
  13755. data[ i * 3 ] = r;
  13756. data[ i * 3 + 1 ] = g;
  13757. data[ i * 3 + 2 ] = b;
  13758. }
  13759. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  13760. texture.needsUpdate = true;
  13761. return texture;
  13762. }
  13763. };
  13764. /**
  13765. * @author alteredq / http://alteredqualia.com/
  13766. */
  13767. THREE.SceneUtils = {
  13768. showHierarchy : function ( root, visible ) {
  13769. THREE.SceneUtils.traverseHierarchy( root, function( node ) { node.visible = visible; } );
  13770. },
  13771. traverseHierarchy : function ( root, callback ) {
  13772. var n, i, l = root.children.length;
  13773. for ( i = 0; i < l; i ++ ) {
  13774. n = root.children[ i ];
  13775. callback( n );
  13776. THREE.SceneUtils.traverseHierarchy( n, callback );
  13777. }
  13778. },
  13779. createMultiMaterialObject : function ( geometry, materials ) {
  13780. var i, il = materials.length,
  13781. group = new THREE.Object3D();
  13782. for ( i = 0; i < il; i ++ ) {
  13783. var object = new THREE.Mesh( geometry, materials[ i ] );
  13784. group.add( object );
  13785. }
  13786. return group;
  13787. },
  13788. cloneObject: function ( source ) {
  13789. var object;
  13790. // subclass specific properties
  13791. // (must process in order from more specific subclasses to more abstract classes)
  13792. if ( source instanceof THREE.MorphAnimMesh ) {
  13793. object = new THREE.MorphAnimMesh( source.geometry, source.material );
  13794. object.duration = source.duration;
  13795. object.mirroredLoop = source.mirroredLoop;
  13796. object.time = source.time;
  13797. object.lastKeyframe = source.lastKeyframe;
  13798. object.currentKeyframe = source.currentKeyframe;
  13799. object.direction = source.direction;
  13800. object.directionBackwards = source.directionBackwards;
  13801. } else if ( source instanceof THREE.SkinnedMesh ) {
  13802. object = new THREE.SkinnedMesh( source.geometry, source.material );
  13803. } else if ( source instanceof THREE.Mesh ) {
  13804. object = new THREE.Mesh( source.geometry, source.material );
  13805. } else if ( source instanceof THREE.Line ) {
  13806. object = new THREE.Line( source.geometry, source.material, source.type );
  13807. } else if ( source instanceof THREE.Ribbon ) {
  13808. object = new THREE.Ribbon( source.geometry, source.material );
  13809. } else if ( source instanceof THREE.ParticleSystem ) {
  13810. object = new THREE.ParticleSystem( source.geometry, source.material );
  13811. object.sortParticles = source.sortParticles;
  13812. } else if ( source instanceof THREE.Particle ) {
  13813. object = new THREE.Particle( source.material );
  13814. } else if ( source instanceof THREE.Sprite ) {
  13815. object = new THREE.Sprite( {} );
  13816. object.color.copy( source.color );
  13817. object.map = source.map;
  13818. object.blending = source.blending;
  13819. object.useScreenCoordinates = source.useScreenCoordinates;
  13820. object.mergeWith3D = source.mergeWith3D;
  13821. object.affectedByDistance = source.affectedByDistance;
  13822. object.scaleByViewport = source.scaleByViewport;
  13823. object.alignment = source.alignment;
  13824. object.rotation3d.copy( source.rotation3d );
  13825. object.rotation = source.rotation;
  13826. object.opacity = source.opacity;
  13827. object.uvOffset.copy( source.uvOffset );
  13828. object.uvScale.copy( source.uvScale);
  13829. } else if ( source instanceof THREE.LOD ) {
  13830. object = new THREE.LOD();
  13831. /*
  13832. } else if ( source instanceof THREE.MarchingCubes ) {
  13833. object = new THREE.MarchingCubes( source.resolution, source.material );
  13834. object.field.set( source.field );
  13835. object.isolation = source.isolation;
  13836. */
  13837. } else if ( source instanceof THREE.Object3D ) {
  13838. object = new THREE.Object3D();
  13839. }
  13840. // base class properties
  13841. object.name = source.name;
  13842. object.parent = source.parent;
  13843. object.up.copy( source.up );
  13844. object.position.copy( source.position );
  13845. // because of Sprite madness
  13846. if ( object.rotation instanceof THREE.Vector3 )
  13847. object.rotation.copy( source.rotation );
  13848. object.eulerOrder = source.eulerOrder;
  13849. object.scale.copy( source.scale );
  13850. object.dynamic = source.dynamic;
  13851. object.renderDepth = source.renderDepth;
  13852. object.rotationAutoUpdate = source.rotationAutoUpdate;
  13853. object.matrix.copy( source.matrix );
  13854. object.matrixWorld.copy( source.matrixWorld );
  13855. object.matrixRotationWorld.copy( source.matrixRotationWorld );
  13856. object.matrixAutoUpdate = source.matrixAutoUpdate;
  13857. object.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  13858. object.quaternion.copy( source.quaternion );
  13859. object.useQuaternion = source.useQuaternion;
  13860. object.boundRadius = source.boundRadius;
  13861. object.boundRadiusScale = source.boundRadiusScale;
  13862. object.visible = source.visible;
  13863. object.castShadow = source.castShadow;
  13864. object.receiveShadow = source.receiveShadow;
  13865. object.frustumCulled = source.frustumCulled;
  13866. // children
  13867. for ( var i = 0; i < source.children.length; i ++ ) {
  13868. var child = THREE.SceneUtils.cloneObject( source.children[ i ] );
  13869. object.children[ i ] = child;
  13870. child.parent = object;
  13871. }
  13872. // LODs need to be patched separately to use cloned children
  13873. if ( source instanceof THREE.LOD ) {
  13874. for ( var i = 0; i < source.LODs.length; i ++ ) {
  13875. var lod = source.LODs[ i ];
  13876. object.LODs[ i ] = { visibleAtDistance: lod.visibleAtDistance, object3D: object.children[ i ] };
  13877. }
  13878. }
  13879. return object;
  13880. },
  13881. detach : function ( child, parent, scene ) {
  13882. child.applyMatrix( parent.matrixWorld );
  13883. parent.remove( child );
  13884. scene.add( child );
  13885. },
  13886. attach: function ( child, scene, parent ) {
  13887. var matrixWorldInverse = new THREE.Matrix4();
  13888. matrixWorldInverse.getInverse( parent.matrixWorld );
  13889. child.applyMatrix( matrixWorldInverse );
  13890. scene.remove( child );
  13891. parent.add( child );
  13892. }
  13893. };
  13894. /**
  13895. * @author alteredq / http://alteredqualia.com/
  13896. * @author mrdoob / http://mrdoob.com/
  13897. *
  13898. * ShaderUtils currently contains:
  13899. *
  13900. * fresnel
  13901. * normal
  13902. * cube
  13903. *
  13904. */
  13905. if ( THREE.WebGLRenderer ) {
  13906. THREE.ShaderUtils = {
  13907. lib: {
  13908. /* -------------------------------------------------------------------------
  13909. // Fresnel shader
  13910. // - based on Nvidia Cg tutorial
  13911. ------------------------------------------------------------------------- */
  13912. 'fresnel': {
  13913. uniforms: {
  13914. "mRefractionRatio": { type: "f", value: 1.02 },
  13915. "mFresnelBias": { type: "f", value: 0.1 },
  13916. "mFresnelPower": { type: "f", value: 2.0 },
  13917. "mFresnelScale": { type: "f", value: 1.0 },
  13918. "tCube": { type: "t", value: null }
  13919. },
  13920. fragmentShader: [
  13921. "uniform samplerCube tCube;",
  13922. "varying vec3 vReflect;",
  13923. "varying vec3 vRefract[3];",
  13924. "varying float vReflectionFactor;",
  13925. "void main() {",
  13926. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  13927. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  13928. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  13929. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  13930. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  13931. "refractedColor.a = 1.0;",
  13932. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  13933. "}"
  13934. ].join("\n"),
  13935. vertexShader: [
  13936. "uniform float mRefractionRatio;",
  13937. "uniform float mFresnelBias;",
  13938. "uniform float mFresnelScale;",
  13939. "uniform float mFresnelPower;",
  13940. "varying vec3 vReflect;",
  13941. "varying vec3 vRefract[3];",
  13942. "varying float vReflectionFactor;",
  13943. "void main() {",
  13944. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  13945. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  13946. "vec3 nWorld = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  13947. "vec3 I = mPosition.xyz - cameraPosition;",
  13948. "vReflect = reflect( I, nWorld );",
  13949. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  13950. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  13951. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  13952. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  13953. "gl_Position = projectionMatrix * mvPosition;",
  13954. "}"
  13955. ].join("\n")
  13956. },
  13957. /* -------------------------------------------------------------------------
  13958. // Normal map shader
  13959. // - Blinn-Phong
  13960. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  13961. // - point and directional lights (use with "lights: true" material option)
  13962. ------------------------------------------------------------------------- */
  13963. 'normal' : {
  13964. uniforms: THREE.UniformsUtils.merge( [
  13965. THREE.UniformsLib[ "fog" ],
  13966. THREE.UniformsLib[ "lights" ],
  13967. THREE.UniformsLib[ "shadowmap" ],
  13968. {
  13969. "enableAO" : { type: "i", value: 0 },
  13970. "enableDiffuse" : { type: "i", value: 0 },
  13971. "enableSpecular" : { type: "i", value: 0 },
  13972. "enableReflection": { type: "i", value: 0 },
  13973. "enableDisplacement": { type: "i", value: 0 },
  13974. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  13975. "tDiffuse" : { type: "t", value: null },
  13976. "tCube" : { type: "t", value: null },
  13977. "tNormal" : { type: "t", value: null },
  13978. "tSpecular" : { type: "t", value: null },
  13979. "tAO" : { type: "t", value: null },
  13980. "uNormalScale": { type: "f", value: 1.0 },
  13981. "uDisplacementBias": { type: "f", value: 0.0 },
  13982. "uDisplacementScale": { type: "f", value: 1.0 },
  13983. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  13984. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  13985. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  13986. "uShininess": { type: "f", value: 30 },
  13987. "uOpacity": { type: "f", value: 1 },
  13988. "useRefract": { type: "i", value: 0 },
  13989. "uRefractionRatio": { type: "f", value: 0.98 },
  13990. "uReflectivity": { type: "f", value: 0.5 },
  13991. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  13992. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  13993. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  13994. }
  13995. ] ),
  13996. fragmentShader: [
  13997. "uniform vec3 uAmbientColor;",
  13998. "uniform vec3 uDiffuseColor;",
  13999. "uniform vec3 uSpecularColor;",
  14000. "uniform float uShininess;",
  14001. "uniform float uOpacity;",
  14002. "uniform bool enableDiffuse;",
  14003. "uniform bool enableSpecular;",
  14004. "uniform bool enableAO;",
  14005. "uniform bool enableReflection;",
  14006. "uniform sampler2D tDiffuse;",
  14007. "uniform sampler2D tNormal;",
  14008. "uniform sampler2D tSpecular;",
  14009. "uniform sampler2D tAO;",
  14010. "uniform samplerCube tCube;",
  14011. "uniform float uNormalScale;",
  14012. "uniform bool useRefract;",
  14013. "uniform float uRefractionRatio;",
  14014. "uniform float uReflectivity;",
  14015. "varying vec3 vTangent;",
  14016. "varying vec3 vBinormal;",
  14017. "varying vec3 vNormal;",
  14018. "varying vec2 vUv;",
  14019. "uniform vec3 ambientLightColor;",
  14020. "#if MAX_DIR_LIGHTS > 0",
  14021. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  14022. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  14023. "#endif",
  14024. "#if MAX_POINT_LIGHTS > 0",
  14025. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  14026. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  14027. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  14028. "#endif",
  14029. "#if MAX_SPOT_LIGHTS > 0",
  14030. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  14031. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  14032. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  14033. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  14034. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  14035. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  14036. "#endif",
  14037. "#ifdef WRAP_AROUND",
  14038. "uniform vec3 wrapRGB;",
  14039. "#endif",
  14040. "varying vec3 vWorldPosition;",
  14041. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14042. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14043. "void main() {",
  14044. "vec3 vViewPosition = cameraPosition - vWorldPosition;",
  14045. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  14046. "vec3 specularTex = vec3( 1.0 );",
  14047. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  14048. "normalTex.xy *= uNormalScale;",
  14049. "normalTex = normalize( normalTex );",
  14050. "if( enableDiffuse ) {",
  14051. "#ifdef GAMMA_INPUT",
  14052. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  14053. "texelColor.xyz *= texelColor.xyz;",
  14054. "gl_FragColor = gl_FragColor * texelColor;",
  14055. "#else",
  14056. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  14057. "#endif",
  14058. "}",
  14059. "if( enableAO ) {",
  14060. "#ifdef GAMMA_INPUT",
  14061. "vec4 aoColor = texture2D( tAO, vUv );",
  14062. "aoColor.xyz *= aoColor.xyz;",
  14063. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  14064. "#else",
  14065. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  14066. "#endif",
  14067. "}",
  14068. "if( enableSpecular )",
  14069. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  14070. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  14071. "vec3 finalNormal = tsb * normalTex;",
  14072. "vec3 normal = normalize( finalNormal );",
  14073. "vec3 viewPosition = normalize( vViewPosition );",
  14074. // point lights
  14075. "#if MAX_POINT_LIGHTS > 0",
  14076. "vec3 pointDiffuse = vec3( 0.0 );",
  14077. "vec3 pointSpecular = vec3( 0.0 );",
  14078. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  14079. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  14080. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  14081. "float pointDistance = 1.0;",
  14082. "if ( pointLightDistance[ i ] > 0.0 )",
  14083. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  14084. "pointVector = normalize( pointVector );",
  14085. // diffuse
  14086. "#ifdef WRAP_AROUND",
  14087. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  14088. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  14089. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  14090. "#else",
  14091. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  14092. "#endif",
  14093. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  14094. // specular
  14095. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  14096. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  14097. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  14098. "#ifdef PHYSICALLY_BASED_SHADING",
  14099. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14100. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14101. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  14102. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  14103. "#else",
  14104. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  14105. "#endif",
  14106. "}",
  14107. "#endif",
  14108. // spot lights
  14109. "#if MAX_SPOT_LIGHTS > 0",
  14110. "vec3 spotDiffuse = vec3( 0.0 );",
  14111. "vec3 spotSpecular = vec3( 0.0 );",
  14112. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  14113. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  14114. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  14115. "float spotDistance = 1.0;",
  14116. "if ( spotLightDistance[ i ] > 0.0 )",
  14117. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  14118. "spotVector = normalize( spotVector );",
  14119. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  14120. "if ( spotEffect > spotLightAngle[ i ] ) {",
  14121. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  14122. // diffuse
  14123. "#ifdef WRAP_AROUND",
  14124. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  14125. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  14126. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  14127. "#else",
  14128. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  14129. "#endif",
  14130. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  14131. // specular
  14132. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  14133. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  14134. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  14135. "#ifdef PHYSICALLY_BASED_SHADING",
  14136. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14137. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14138. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  14139. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  14140. "#else",
  14141. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  14142. "#endif",
  14143. "}",
  14144. "}",
  14145. "#endif",
  14146. // directional lights
  14147. "#if MAX_DIR_LIGHTS > 0",
  14148. "vec3 dirDiffuse = vec3( 0.0 );",
  14149. "vec3 dirSpecular = vec3( 0.0 );",
  14150. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  14151. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  14152. "vec3 dirVector = normalize( lDirection.xyz );",
  14153. // diffuse
  14154. "#ifdef WRAP_AROUND",
  14155. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  14156. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  14157. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  14158. "#else",
  14159. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  14160. "#endif",
  14161. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  14162. // specular
  14163. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  14164. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  14165. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  14166. "#ifdef PHYSICALLY_BASED_SHADING",
  14167. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14168. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14169. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  14170. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  14171. "#else",
  14172. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  14173. "#endif",
  14174. "}",
  14175. "#endif",
  14176. // all lights contribution summation
  14177. "vec3 totalDiffuse = vec3( 0.0 );",
  14178. "vec3 totalSpecular = vec3( 0.0 );",
  14179. "#if MAX_DIR_LIGHTS > 0",
  14180. "totalDiffuse += dirDiffuse;",
  14181. "totalSpecular += dirSpecular;",
  14182. "#endif",
  14183. "#if MAX_POINT_LIGHTS > 0",
  14184. "totalDiffuse += pointDiffuse;",
  14185. "totalSpecular += pointSpecular;",
  14186. "#endif",
  14187. "#if MAX_SPOT_LIGHTS > 0",
  14188. "totalDiffuse += spotDiffuse;",
  14189. "totalSpecular += spotSpecular;",
  14190. "#endif",
  14191. "#ifdef METAL",
  14192. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  14193. "#else",
  14194. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  14195. "#endif",
  14196. "if ( enableReflection ) {",
  14197. "vec3 vReflect;",
  14198. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  14199. "if ( useRefract ) {",
  14200. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  14201. "} else {",
  14202. "vReflect = reflect( cameraToVertex, normal );",
  14203. "}",
  14204. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14205. "#ifdef GAMMA_INPUT",
  14206. "cubeColor.xyz *= cubeColor.xyz;",
  14207. "#endif",
  14208. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  14209. "}",
  14210. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14211. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14212. THREE.ShaderChunk[ "fog_fragment" ],
  14213. "}"
  14214. ].join("\n"),
  14215. vertexShader: [
  14216. "attribute vec4 tangent;",
  14217. "uniform vec2 uOffset;",
  14218. "uniform vec2 uRepeat;",
  14219. "uniform bool enableDisplacement;",
  14220. "#ifdef VERTEX_TEXTURES",
  14221. "uniform sampler2D tDisplacement;",
  14222. "uniform float uDisplacementScale;",
  14223. "uniform float uDisplacementBias;",
  14224. "#endif",
  14225. "varying vec3 vTangent;",
  14226. "varying vec3 vBinormal;",
  14227. "varying vec3 vNormal;",
  14228. "varying vec2 vUv;",
  14229. "varying vec3 vWorldPosition;",
  14230. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14231. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14232. "void main() {",
  14233. THREE.ShaderChunk[ "skinbase_vertex" ],
  14234. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14235. // normal, tangent and binormal vectors
  14236. "#ifdef USE_SKINNING",
  14237. "vNormal = normalMatrix * skinnedNormal.xyz;",
  14238. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  14239. "vTangent = normalMatrix * skinnedTangent.xyz;",
  14240. "#else",
  14241. "vNormal = normalMatrix * normal;",
  14242. "vTangent = normalMatrix * tangent.xyz;",
  14243. "#endif",
  14244. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  14245. "vUv = uv * uRepeat + uOffset;",
  14246. // displacement mapping
  14247. "vec3 displacedPosition;",
  14248. "#ifdef VERTEX_TEXTURES",
  14249. "if ( enableDisplacement ) {",
  14250. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  14251. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  14252. "displacedPosition = position + normalize( normal ) * df;",
  14253. "} else {",
  14254. "#ifdef USE_SKINNING",
  14255. "vec4 skinVertex = vec4( position, 1.0 );",
  14256. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  14257. "skinned += boneMatY * skinVertex * skinWeight.y;",
  14258. "displacedPosition = skinned.xyz;",
  14259. "#else",
  14260. "displacedPosition = position;",
  14261. "#endif",
  14262. "}",
  14263. "#else",
  14264. "#ifdef USE_SKINNING",
  14265. "vec4 skinVertex = vec4( position, 1.0 );",
  14266. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  14267. "skinned += boneMatY * skinVertex * skinWeight.y;",
  14268. "displacedPosition = skinned.xyz;",
  14269. "#else",
  14270. "displacedPosition = position;",
  14271. "#endif",
  14272. "#endif",
  14273. //
  14274. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  14275. "vec4 mPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  14276. "gl_Position = projectionMatrix * mvPosition;",
  14277. //
  14278. "vWorldPosition = mPosition.xyz;",
  14279. // shadows
  14280. "#ifdef USE_SHADOWMAP",
  14281. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  14282. "vShadowCoord[ i ] = shadowMatrix[ i ] * mPosition;",
  14283. "}",
  14284. "#endif",
  14285. "}"
  14286. ].join("\n")
  14287. },
  14288. /* -------------------------------------------------------------------------
  14289. // Cube map shader
  14290. ------------------------------------------------------------------------- */
  14291. 'cube': {
  14292. uniforms: { "tCube": { type: "t", value: null },
  14293. "tFlip": { type: "f", value: -1 } },
  14294. vertexShader: [
  14295. "varying vec3 vViewPosition;",
  14296. "void main() {",
  14297. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  14298. "vViewPosition = cameraPosition - mPosition.xyz;",
  14299. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  14300. "}"
  14301. ].join("\n"),
  14302. fragmentShader: [
  14303. "uniform samplerCube tCube;",
  14304. "uniform float tFlip;",
  14305. "varying vec3 vViewPosition;",
  14306. "void main() {",
  14307. "vec3 wPos = cameraPosition - vViewPosition;",
  14308. "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
  14309. "}"
  14310. ].join("\n")
  14311. }
  14312. }
  14313. };
  14314. };
  14315. /**
  14316. * @author zz85 / http://www.lab4games.net/zz85/blog
  14317. * @author alteredq / http://alteredqualia.com/
  14318. *
  14319. * For Text operations in three.js (See TextGeometry)
  14320. *
  14321. * It uses techniques used in:
  14322. *
  14323. * typeface.js and canvastext
  14324. * For converting fonts and rendering with javascript
  14325. * http://typeface.neocracy.org
  14326. *
  14327. * Triangulation ported from AS3
  14328. * Simple Polygon Triangulation
  14329. * http://actionsnippet.com/?p=1462
  14330. *
  14331. * A Method to triangulate shapes with holes
  14332. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  14333. *
  14334. */
  14335. THREE.FontUtils = {
  14336. faces : {},
  14337. // Just for now. face[weight][style]
  14338. face : "helvetiker",
  14339. weight: "normal",
  14340. style : "normal",
  14341. size : 150,
  14342. divisions : 10,
  14343. getFace : function() {
  14344. return this.faces[ this.face ][ this.weight ][ this.style ];
  14345. },
  14346. loadFace : function( data ) {
  14347. var family = data.familyName.toLowerCase();
  14348. var ThreeFont = this;
  14349. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  14350. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  14351. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  14352. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  14353. return data;
  14354. },
  14355. drawText : function( text ) {
  14356. var characterPts = [], allPts = [];
  14357. // RenderText
  14358. var i, p,
  14359. face = this.getFace(),
  14360. scale = this.size / face.resolution,
  14361. offset = 0,
  14362. chars = String( text ).split( '' ),
  14363. length = chars.length;
  14364. var fontPaths = [];
  14365. for ( i = 0; i < length; i ++ ) {
  14366. var path = new THREE.Path();
  14367. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  14368. offset += ret.offset;
  14369. fontPaths.push( ret.path );
  14370. }
  14371. // get the width
  14372. var width = offset / 2;
  14373. //
  14374. // for ( p = 0; p < allPts.length; p++ ) {
  14375. //
  14376. // allPts[ p ].x -= width;
  14377. //
  14378. // }
  14379. //var extract = this.extractPoints( allPts, characterPts );
  14380. //extract.contour = allPts;
  14381. //extract.paths = fontPaths;
  14382. //extract.offset = width;
  14383. return { paths : fontPaths, offset : width };
  14384. },
  14385. extractGlyphPoints : function( c, face, scale, offset, path ) {
  14386. var pts = [];
  14387. var i, i2, divisions,
  14388. outline, action, length,
  14389. scaleX, scaleY,
  14390. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  14391. laste,
  14392. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  14393. if ( !glyph ) return;
  14394. if ( glyph.o ) {
  14395. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  14396. length = outline.length;
  14397. scaleX = scale;
  14398. scaleY = scale;
  14399. for ( i = 0; i < length; ) {
  14400. action = outline[ i ++ ];
  14401. //console.log( action );
  14402. switch( action ) {
  14403. case 'm':
  14404. // Move To
  14405. x = outline[ i++ ] * scaleX + offset;
  14406. y = outline[ i++ ] * scaleY;
  14407. path.moveTo( x, y );
  14408. break;
  14409. case 'l':
  14410. // Line To
  14411. x = outline[ i++ ] * scaleX + offset;
  14412. y = outline[ i++ ] * scaleY;
  14413. path.lineTo(x,y);
  14414. break;
  14415. case 'q':
  14416. // QuadraticCurveTo
  14417. cpx = outline[ i++ ] * scaleX + offset;
  14418. cpy = outline[ i++ ] * scaleY;
  14419. cpx1 = outline[ i++ ] * scaleX + offset;
  14420. cpy1 = outline[ i++ ] * scaleY;
  14421. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  14422. laste = pts[ pts.length - 1 ];
  14423. if ( laste ) {
  14424. cpx0 = laste.x;
  14425. cpy0 = laste.y;
  14426. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  14427. var t = i2 / divisions;
  14428. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  14429. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  14430. }
  14431. }
  14432. break;
  14433. case 'b':
  14434. // Cubic Bezier Curve
  14435. cpx = outline[ i++ ] * scaleX + offset;
  14436. cpy = outline[ i++ ] * scaleY;
  14437. cpx1 = outline[ i++ ] * scaleX + offset;
  14438. cpy1 = outline[ i++ ] * -scaleY;
  14439. cpx2 = outline[ i++ ] * scaleX + offset;
  14440. cpy2 = outline[ i++ ] * -scaleY;
  14441. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  14442. laste = pts[ pts.length - 1 ];
  14443. if ( laste ) {
  14444. cpx0 = laste.x;
  14445. cpy0 = laste.y;
  14446. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  14447. var t = i2 / divisions;
  14448. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  14449. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  14450. }
  14451. }
  14452. break;
  14453. }
  14454. }
  14455. }
  14456. return { offset: glyph.ha*scale, path:path};
  14457. }
  14458. };
  14459. THREE.FontUtils.generateShapes = function( text, parameters ) {
  14460. // Parameters
  14461. parameters = parameters || {};
  14462. var size = parameters.size !== undefined ? parameters.size : 100;
  14463. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  14464. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  14465. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  14466. var style = parameters.style !== undefined ? parameters.style : "normal";
  14467. THREE.FontUtils.size = size;
  14468. THREE.FontUtils.divisions = curveSegments;
  14469. THREE.FontUtils.face = font;
  14470. THREE.FontUtils.weight = weight;
  14471. THREE.FontUtils.style = style;
  14472. // Get a Font data json object
  14473. var data = THREE.FontUtils.drawText( text );
  14474. var paths = data.paths;
  14475. var shapes = [];
  14476. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  14477. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  14478. }
  14479. return shapes;
  14480. };
  14481. /**
  14482. * This code is a quick port of code written in C++ which was submitted to
  14483. * flipcode.com by John W. Ratcliff // July 22, 2000
  14484. * See original code and more information here:
  14485. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  14486. *
  14487. * ported to actionscript by Zevan Rosser
  14488. * www.actionsnippet.com
  14489. *
  14490. * ported to javascript by Joshua Koo
  14491. * http://www.lab4games.net/zz85/blog
  14492. *
  14493. */
  14494. ( function( namespace ) {
  14495. var EPSILON = 0.0000000001;
  14496. // takes in an contour array and returns
  14497. var process = function( contour, indices ) {
  14498. var n = contour.length;
  14499. if ( n < 3 ) return null;
  14500. var result = [],
  14501. verts = [],
  14502. vertIndices = [];
  14503. /* we want a counter-clockwise polygon in verts */
  14504. var u, v, w;
  14505. if ( area( contour ) > 0.0 ) {
  14506. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  14507. } else {
  14508. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  14509. }
  14510. var nv = n;
  14511. /* remove nv - 2 vertices, creating 1 triangle every time */
  14512. var count = 2 * nv; /* error detection */
  14513. for( v = nv - 1; nv > 2; ) {
  14514. /* if we loop, it is probably a non-simple polygon */
  14515. if ( ( count-- ) <= 0 ) {
  14516. //** Triangulate: ERROR - probable bad polygon!
  14517. //throw ( "Warning, unable to triangulate polygon!" );
  14518. //return null;
  14519. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  14520. console.log( "Warning, unable to triangulate polygon!" );
  14521. if ( indices ) return vertIndices;
  14522. return result;
  14523. }
  14524. /* three consecutive vertices in current polygon, <u,v,w> */
  14525. u = v; if ( nv <= u ) u = 0; /* previous */
  14526. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  14527. w = v + 1; if ( nv <= w ) w = 0; /* next */
  14528. if ( snip( contour, u, v, w, nv, verts ) ) {
  14529. var a, b, c, s, t;
  14530. /* true names of the vertices */
  14531. a = verts[ u ];
  14532. b = verts[ v ];
  14533. c = verts[ w ];
  14534. /* output Triangle */
  14535. /*
  14536. result.push( contour[ a ] );
  14537. result.push( contour[ b ] );
  14538. result.push( contour[ c ] );
  14539. */
  14540. result.push( [ contour[ a ],
  14541. contour[ b ],
  14542. contour[ c ] ] );
  14543. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  14544. /* remove v from the remaining polygon */
  14545. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  14546. verts[ s ] = verts[ t ];
  14547. }
  14548. nv--;
  14549. /* reset error detection counter */
  14550. count = 2 * nv;
  14551. }
  14552. }
  14553. if ( indices ) return vertIndices;
  14554. return result;
  14555. };
  14556. // calculate area of the contour polygon
  14557. var area = function ( contour ) {
  14558. var n = contour.length;
  14559. var a = 0.0;
  14560. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  14561. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  14562. }
  14563. return a * 0.5;
  14564. };
  14565. // see if p is inside triangle abc
  14566. var insideTriangle = function( ax, ay,
  14567. bx, by,
  14568. cx, cy,
  14569. px, py ) {
  14570. var aX, aY, bX, bY;
  14571. var cX, cY, apx, apy;
  14572. var bpx, bpy, cpx, cpy;
  14573. var cCROSSap, bCROSScp, aCROSSbp;
  14574. aX = cx - bx; aY = cy - by;
  14575. bX = ax - cx; bY = ay - cy;
  14576. cX = bx - ax; cY = by - ay;
  14577. apx= px -ax; apy= py - ay;
  14578. bpx= px - bx; bpy= py - by;
  14579. cpx= px - cx; cpy= py - cy;
  14580. aCROSSbp = aX*bpy - aY*bpx;
  14581. cCROSSap = cX*apy - cY*apx;
  14582. bCROSScp = bX*cpy - bY*cpx;
  14583. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  14584. };
  14585. var snip = function ( contour, u, v, w, n, verts ) {
  14586. var p;
  14587. var ax, ay, bx, by;
  14588. var cx, cy, px, py;
  14589. ax = contour[ verts[ u ] ].x;
  14590. ay = contour[ verts[ u ] ].y;
  14591. bx = contour[ verts[ v ] ].x;
  14592. by = contour[ verts[ v ] ].y;
  14593. cx = contour[ verts[ w ] ].x;
  14594. cy = contour[ verts[ w ] ].y;
  14595. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  14596. for ( p = 0; p < n; p++ ) {
  14597. if( (p == u) || (p == v) || (p == w) ) continue;
  14598. px = contour[ verts[ p ] ].x
  14599. py = contour[ verts[ p ] ].y
  14600. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  14601. }
  14602. return true;
  14603. };
  14604. namespace.Triangulate = process;
  14605. namespace.Triangulate.area = area;
  14606. return namespace;
  14607. })(THREE.FontUtils);
  14608. // To use the typeface.js face files, hook up the API
  14609. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  14610. * @author zz85 / http://www.lab4games.net/zz85/blog
  14611. * Extensible curve object
  14612. *
  14613. * Some common of Curve methods
  14614. * .getPoint(t), getTangent(t)
  14615. * .getPointAt(u), getTagentAt(u)
  14616. * .getPoints(), .getSpacedPoints()
  14617. * .getLength()
  14618. * .updateArcLengths()
  14619. *
  14620. * This file contains following classes:
  14621. *
  14622. * -- 2d classes --
  14623. * THREE.Curve
  14624. * THREE.LineCurve
  14625. * THREE.QuadraticBezierCurve
  14626. * THREE.CubicBezierCurve
  14627. * THREE.SplineCurve
  14628. * THREE.ArcCurve
  14629. * THREE.EllipseCurve
  14630. *
  14631. * -- 3d classes --
  14632. * THREE.LineCurve3
  14633. * THREE.QuadraticBezierCurve3
  14634. * THREE.CubicBezierCurve3
  14635. * THREE.SplineCurve3
  14636. * THREE.ClosedSplineCurve3
  14637. *
  14638. * A series of curves can be represented as a THREE.CurvePath
  14639. *
  14640. **/
  14641. /**************************************************************
  14642. * Abstract Curve base class
  14643. **************************************************************/
  14644. THREE.Curve = function () {
  14645. };
  14646. // Virtual base class method to overwrite and implement in subclasses
  14647. // - t [0 .. 1]
  14648. THREE.Curve.prototype.getPoint = function ( t ) {
  14649. console.log( "Warning, getPoint() not implemented!" );
  14650. return null;
  14651. };
  14652. // Get point at relative position in curve according to arc length
  14653. // - u [0 .. 1]
  14654. THREE.Curve.prototype.getPointAt = function ( u ) {
  14655. var t = this.getUtoTmapping( u );
  14656. return this.getPoint( t );
  14657. };
  14658. // Get sequence of points using getPoint( t )
  14659. THREE.Curve.prototype.getPoints = function ( divisions ) {
  14660. if ( !divisions ) divisions = 5;
  14661. var d, pts = [];
  14662. for ( d = 0; d <= divisions; d ++ ) {
  14663. pts.push( this.getPoint( d / divisions ) );
  14664. }
  14665. return pts;
  14666. };
  14667. // Get sequence of points using getPointAt( u )
  14668. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  14669. if ( !divisions ) divisions = 5;
  14670. var d, pts = [];
  14671. for ( d = 0; d <= divisions; d ++ ) {
  14672. pts.push( this.getPointAt( d / divisions ) );
  14673. }
  14674. return pts;
  14675. };
  14676. // Get total curve arc length
  14677. THREE.Curve.prototype.getLength = function () {
  14678. var lengths = this.getLengths();
  14679. return lengths[ lengths.length - 1 ];
  14680. };
  14681. // Get list of cumulative segment lengths
  14682. THREE.Curve.prototype.getLengths = function ( divisions ) {
  14683. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  14684. if ( this.cacheArcLengths
  14685. && ( this.cacheArcLengths.length == divisions + 1 )
  14686. && !this.needsUpdate) {
  14687. //console.log( "cached", this.cacheArcLengths );
  14688. return this.cacheArcLengths;
  14689. }
  14690. this.needsUpdate = false;
  14691. var cache = [];
  14692. var current, last = this.getPoint( 0 );
  14693. var p, sum = 0;
  14694. cache.push( 0 );
  14695. for ( p = 1; p <= divisions; p ++ ) {
  14696. current = this.getPoint ( p / divisions );
  14697. sum += current.distanceTo( last );
  14698. cache.push( sum );
  14699. last = current;
  14700. }
  14701. this.cacheArcLengths = cache;
  14702. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  14703. };
  14704. THREE.Curve.prototype.updateArcLengths = function() {
  14705. this.needsUpdate = true;
  14706. this.getLengths();
  14707. };
  14708. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  14709. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  14710. var arcLengths = this.getLengths();
  14711. var i = 0, il = arcLengths.length;
  14712. var targetArcLength; // The targeted u distance value to get
  14713. if ( distance ) {
  14714. targetArcLength = distance;
  14715. } else {
  14716. targetArcLength = u * arcLengths[ il - 1 ];
  14717. }
  14718. //var time = Date.now();
  14719. // binary search for the index with largest value smaller than target u distance
  14720. var low = 0, high = il - 1, comparison;
  14721. while ( low <= high ) {
  14722. 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
  14723. comparison = arcLengths[ i ] - targetArcLength;
  14724. if ( comparison < 0 ) {
  14725. low = i + 1;
  14726. continue;
  14727. } else if ( comparison > 0 ) {
  14728. high = i - 1;
  14729. continue;
  14730. } else {
  14731. high = i;
  14732. break;
  14733. // DONE
  14734. }
  14735. }
  14736. i = high;
  14737. //console.log('b' , i, low, high, Date.now()- time);
  14738. if ( arcLengths[ i ] == targetArcLength ) {
  14739. var t = i / ( il - 1 );
  14740. return t;
  14741. }
  14742. // we could get finer grain at lengths, or use simple interpolatation between two points
  14743. var lengthBefore = arcLengths[ i ];
  14744. var lengthAfter = arcLengths[ i + 1 ];
  14745. var segmentLength = lengthAfter - lengthBefore;
  14746. // determine where we are between the 'before' and 'after' points
  14747. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  14748. // add that fractional amount to t
  14749. var t = ( i + segmentFraction ) / ( il -1 );
  14750. return t;
  14751. };
  14752. // In 2D space, there are actually 2 normal vectors,
  14753. // and in 3D space, infinte
  14754. // TODO this should be depreciated.
  14755. THREE.Curve.prototype.getNormalVector = function( t ) {
  14756. var vec = this.getTangent( t );
  14757. return new THREE.Vector2( -vec.y , vec.x );
  14758. };
  14759. // Returns a unit vector tangent at t
  14760. // In case any sub curve does not implement its tangent / normal finding,
  14761. // we get 2 points with a small delta and find a gradient of the 2 points
  14762. // which seems to make a reasonable approximation
  14763. THREE.Curve.prototype.getTangent = function( t ) {
  14764. var delta = 0.0001;
  14765. var t1 = t - delta;
  14766. var t2 = t + delta;
  14767. // Capping in case of danger
  14768. if ( t1 < 0 ) t1 = 0;
  14769. if ( t2 > 1 ) t2 = 1;
  14770. var pt1 = this.getPoint( t1 );
  14771. var pt2 = this.getPoint( t2 );
  14772. var vec = pt2.clone().subSelf(pt1);
  14773. return vec.normalize();
  14774. };
  14775. THREE.Curve.prototype.getTangentAt = function ( u ) {
  14776. var t = this.getUtoTmapping( u );
  14777. return this.getTangent( t );
  14778. };
  14779. /**************************************************************
  14780. * Line
  14781. **************************************************************/
  14782. THREE.LineCurve = function ( v1, v2 ) {
  14783. this.v1 = v1;
  14784. this.v2 = v2;
  14785. };
  14786. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  14787. THREE.LineCurve.prototype.getPoint = function ( t ) {
  14788. var point = this.v2.clone().subSelf(this.v1);
  14789. point.multiplyScalar( t ).addSelf( this.v1 );
  14790. return point;
  14791. };
  14792. // Line curve is linear, so we can overwrite default getPointAt
  14793. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  14794. return this.getPoint( u );
  14795. };
  14796. THREE.LineCurve.prototype.getTangent = function( t ) {
  14797. var tangent = this.v2.clone().subSelf(this.v1);
  14798. return tangent.normalize();
  14799. };
  14800. /**************************************************************
  14801. * Quadratic Bezier curve
  14802. **************************************************************/
  14803. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  14804. this.v0 = v0;
  14805. this.v1 = v1;
  14806. this.v2 = v2;
  14807. };
  14808. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  14809. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  14810. var tx, ty;
  14811. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  14812. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  14813. return new THREE.Vector2( tx, ty );
  14814. };
  14815. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  14816. var tx, ty;
  14817. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  14818. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  14819. // returns unit vector
  14820. var tangent = new THREE.Vector2( tx, ty );
  14821. tangent.normalize();
  14822. return tangent;
  14823. };
  14824. /**************************************************************
  14825. * Cubic Bezier curve
  14826. **************************************************************/
  14827. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  14828. this.v0 = v0;
  14829. this.v1 = v1;
  14830. this.v2 = v2;
  14831. this.v3 = v3;
  14832. };
  14833. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  14834. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  14835. var tx, ty;
  14836. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  14837. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  14838. return new THREE.Vector2( tx, ty );
  14839. };
  14840. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  14841. var tx, ty;
  14842. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  14843. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  14844. var tangent = new THREE.Vector2( tx, ty );
  14845. tangent.normalize();
  14846. return tangent;
  14847. };
  14848. /**************************************************************
  14849. * Spline curve
  14850. **************************************************************/
  14851. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  14852. this.points = (points == undefined) ? [] : points;
  14853. };
  14854. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  14855. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  14856. var v = new THREE.Vector2();
  14857. var c = [];
  14858. var points = this.points, point, intPoint, weight;
  14859. point = ( points.length - 1 ) * t;
  14860. intPoint = Math.floor( point );
  14861. weight = point - intPoint;
  14862. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  14863. c[ 1 ] = intPoint;
  14864. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  14865. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  14866. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  14867. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  14868. return v;
  14869. };
  14870. /**************************************************************
  14871. * Ellipse curve
  14872. **************************************************************/
  14873. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  14874. aStartAngle, aEndAngle,
  14875. aClockwise ) {
  14876. this.aX = aX;
  14877. this.aY = aY;
  14878. this.xRadius = xRadius;
  14879. this.yRadius = yRadius;
  14880. this.aStartAngle = aStartAngle;
  14881. this.aEndAngle = aEndAngle;
  14882. this.aClockwise = aClockwise;
  14883. };
  14884. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  14885. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  14886. var deltaAngle = this.aEndAngle - this.aStartAngle;
  14887. if ( !this.aClockwise ) {
  14888. t = 1 - t;
  14889. }
  14890. var angle = this.aStartAngle + t * deltaAngle;
  14891. var tx = this.aX + this.xRadius * Math.cos( angle );
  14892. var ty = this.aY + this.yRadius * Math.sin( angle );
  14893. return new THREE.Vector2( tx, ty );
  14894. };
  14895. /**************************************************************
  14896. * Arc curve
  14897. **************************************************************/
  14898. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  14899. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  14900. };
  14901. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  14902. /**************************************************************
  14903. * Utils
  14904. **************************************************************/
  14905. THREE.Curve.Utils = {
  14906. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  14907. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  14908. },
  14909. // Puay Bing, thanks for helping with this derivative!
  14910. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  14911. return -3 * p0 * (1 - t) * (1 - t) +
  14912. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  14913. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  14914. 3 * t * t * p3;
  14915. },
  14916. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  14917. // To check if my formulas are correct
  14918. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  14919. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  14920. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  14921. var h11 = 3 * t * t - 2 * t; // t3 − t2
  14922. return h00 + h10 + h01 + h11;
  14923. },
  14924. // Catmull-Rom
  14925. interpolate: function( p0, p1, p2, p3, t ) {
  14926. var v0 = ( p2 - p0 ) * 0.5;
  14927. var v1 = ( p3 - p1 ) * 0.5;
  14928. var t2 = t * t;
  14929. var t3 = t * t2;
  14930. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  14931. }
  14932. };
  14933. // TODO: Transformation for Curves?
  14934. /**************************************************************
  14935. * 3D Curves
  14936. **************************************************************/
  14937. // A Factory method for creating new curve subclasses
  14938. THREE.Curve.create = function ( constructor, getPointFunc ) {
  14939. constructor.prototype = Object.create( THREE.Curve.prototype );
  14940. constructor.prototype.getPoint = getPointFunc;
  14941. return constructor;
  14942. };
  14943. /**************************************************************
  14944. * Line3D
  14945. **************************************************************/
  14946. THREE.LineCurve3 = THREE.Curve.create(
  14947. function ( v1, v2 ) {
  14948. this.v1 = v1;
  14949. this.v2 = v2;
  14950. },
  14951. function ( t ) {
  14952. var r = new THREE.Vector3();
  14953. r.sub( this.v2, this.v1 ); // diff
  14954. r.multiplyScalar( t );
  14955. r.addSelf( this.v1 );
  14956. return r;
  14957. }
  14958. );
  14959. /**************************************************************
  14960. * Quadratic Bezier 3D curve
  14961. **************************************************************/
  14962. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  14963. function ( v0, v1, v2 ) {
  14964. this.v0 = v0;
  14965. this.v1 = v1;
  14966. this.v2 = v2;
  14967. },
  14968. function ( t ) {
  14969. var tx, ty, tz;
  14970. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  14971. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  14972. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  14973. return new THREE.Vector3( tx, ty, tz );
  14974. }
  14975. );
  14976. /**************************************************************
  14977. * Cubic Bezier 3D curve
  14978. **************************************************************/
  14979. THREE.CubicBezierCurve3 = THREE.Curve.create(
  14980. function ( v0, v1, v2, v3 ) {
  14981. this.v0 = v0;
  14982. this.v1 = v1;
  14983. this.v2 = v2;
  14984. this.v3 = v3;
  14985. },
  14986. function ( t ) {
  14987. var tx, ty, tz;
  14988. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  14989. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  14990. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  14991. return new THREE.Vector3( tx, ty, tz );
  14992. }
  14993. );
  14994. /**************************************************************
  14995. * Spline 3D curve
  14996. **************************************************************/
  14997. THREE.SplineCurve3 = THREE.Curve.create(
  14998. function ( points /* array of Vector3 */) {
  14999. this.points = (points == undefined) ? [] : points;
  15000. },
  15001. function ( t ) {
  15002. var v = new THREE.Vector3();
  15003. var c = [];
  15004. var points = this.points, point, intPoint, weight;
  15005. point = ( points.length - 1 ) * t;
  15006. intPoint = Math.floor( point );
  15007. weight = point - intPoint;
  15008. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15009. c[ 1 ] = intPoint;
  15010. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15011. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15012. var pt0 = points[ c[0] ],
  15013. pt1 = points[ c[1] ],
  15014. pt2 = points[ c[2] ],
  15015. pt3 = points[ c[3] ];
  15016. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  15017. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  15018. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  15019. return v;
  15020. }
  15021. );
  15022. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  15023. // var v = new THREE.Vector3();
  15024. // var c = [];
  15025. // var points = this.points, point, intPoint, weight;
  15026. // point = ( points.length - 1 ) * t;
  15027. // intPoint = Math.floor( point );
  15028. // weight = point - intPoint;
  15029. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15030. // c[ 1 ] = intPoint;
  15031. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15032. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15033. // var pt0 = points[ c[0] ],
  15034. // pt1 = points[ c[1] ],
  15035. // pt2 = points[ c[2] ],
  15036. // pt3 = points[ c[3] ];
  15037. // // t = weight;
  15038. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  15039. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  15040. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  15041. // return v;
  15042. // }
  15043. /**************************************************************
  15044. * Closed Spline 3D curve
  15045. **************************************************************/
  15046. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  15047. function ( points /* array of Vector3 */) {
  15048. this.points = (points == undefined) ? [] : points;
  15049. },
  15050. function ( t ) {
  15051. var v = new THREE.Vector3();
  15052. var c = [];
  15053. var points = this.points, point, intPoint, weight;
  15054. point = ( points.length - 0 ) * t;
  15055. // This needs to be from 0-length +1
  15056. intPoint = Math.floor( point );
  15057. weight = point - intPoint;
  15058. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  15059. c[ 0 ] = ( intPoint - 1 ) % points.length;
  15060. c[ 1 ] = ( intPoint ) % points.length;
  15061. c[ 2 ] = ( intPoint + 1 ) % points.length;
  15062. c[ 3 ] = ( intPoint + 2 ) % points.length;
  15063. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15064. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15065. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  15066. return v;
  15067. }
  15068. );
  15069. /**
  15070. * @author zz85 / http://www.lab4games.net/zz85/blog
  15071. *
  15072. **/
  15073. /**************************************************************
  15074. * Curved Path - a curve path is simply a array of connected
  15075. * curves, but retains the api of a curve
  15076. **************************************************************/
  15077. THREE.CurvePath = function () {
  15078. this.curves = [];
  15079. this.bends = [];
  15080. this.autoClose = false; // Automatically closes the path
  15081. };
  15082. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  15083. THREE.CurvePath.prototype.add = function ( curve ) {
  15084. this.curves.push( curve );
  15085. };
  15086. THREE.CurvePath.prototype.checkConnection = function() {
  15087. // TODO
  15088. // If the ending of curve is not connected to the starting
  15089. // or the next curve, then, this is not a real path
  15090. };
  15091. THREE.CurvePath.prototype.closePath = function() {
  15092. // TODO Test
  15093. // and verify for vector3 (needs to implement equals)
  15094. // Add a line curve if start and end of lines are not connected
  15095. var startPoint = this.curves[0].getPoint(0);
  15096. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  15097. if (!startPoint.equals(endPoint)) {
  15098. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  15099. }
  15100. };
  15101. // To get accurate point with reference to
  15102. // entire path distance at time t,
  15103. // following has to be done:
  15104. // 1. Length of each sub path have to be known
  15105. // 2. Locate and identify type of curve
  15106. // 3. Get t for the curve
  15107. // 4. Return curve.getPointAt(t')
  15108. THREE.CurvePath.prototype.getPoint = function( t ) {
  15109. var d = t * this.getLength();
  15110. var curveLengths = this.getCurveLengths();
  15111. var i = 0, diff, curve;
  15112. // To think about boundaries points.
  15113. while ( i < curveLengths.length ) {
  15114. if ( curveLengths[ i ] >= d ) {
  15115. diff = curveLengths[ i ] - d;
  15116. curve = this.curves[ i ];
  15117. var u = 1 - diff / curve.getLength();
  15118. return curve.getPointAt( u );
  15119. break;
  15120. }
  15121. i ++;
  15122. }
  15123. return null;
  15124. // loop where sum != 0, sum > d , sum+1 <d
  15125. };
  15126. /*
  15127. THREE.CurvePath.prototype.getTangent = function( t ) {
  15128. };*/
  15129. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  15130. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  15131. // getPoint() depends on getLength
  15132. THREE.CurvePath.prototype.getLength = function() {
  15133. var lens = this.getCurveLengths();
  15134. return lens[ lens.length - 1 ];
  15135. };
  15136. // Compute lengths and cache them
  15137. // We cannot overwrite getLengths() because UtoT mapping uses it.
  15138. THREE.CurvePath.prototype.getCurveLengths = function() {
  15139. // We use cache values if curves and cache array are same length
  15140. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  15141. return this.cacheLengths;
  15142. };
  15143. // Get length of subsurve
  15144. // Push sums into cached array
  15145. var lengths = [], sums = 0;
  15146. var i, il = this.curves.length;
  15147. for ( i = 0; i < il; i ++ ) {
  15148. sums += this.curves[ i ].getLength();
  15149. lengths.push( sums );
  15150. }
  15151. this.cacheLengths = lengths;
  15152. return lengths;
  15153. };
  15154. // Returns min and max coordinates, as well as centroid
  15155. THREE.CurvePath.prototype.getBoundingBox = function () {
  15156. var points = this.getPoints();
  15157. var maxX, maxY, maxZ;
  15158. var minX, minY, minZ;
  15159. maxX = maxY = Number.NEGATIVE_INFINITY;
  15160. minX = minY = Number.POSITIVE_INFINITY;
  15161. var p, i, il, sum;
  15162. var v3 = points[0] instanceof THREE.Vector3;
  15163. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  15164. for ( i = 0, il = points.length; i < il; i ++ ) {
  15165. p = points[ i ];
  15166. if ( p.x > maxX ) maxX = p.x;
  15167. else if ( p.x < minX ) minX = p.x;
  15168. if ( p.y > maxY ) maxY = p.y;
  15169. else if ( p.y < minY ) minY = p.y;
  15170. if (v3) {
  15171. if ( p.z > maxZ ) maxZ = p.z;
  15172. else if ( p.z < minZ ) minZ = p.z;
  15173. }
  15174. sum.addSelf( p );
  15175. }
  15176. var ret = {
  15177. minX: minX,
  15178. minY: minY,
  15179. maxX: maxX,
  15180. maxY: maxY,
  15181. centroid: sum.divideScalar( il )
  15182. };
  15183. if (v3) {
  15184. ret.maxZ = maxZ;
  15185. ret.minZ = minZ;
  15186. }
  15187. return ret;
  15188. };
  15189. /**************************************************************
  15190. * Create Geometries Helpers
  15191. **************************************************************/
  15192. /// Generate geometry from path points (for Line or ParticleSystem objects)
  15193. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  15194. var pts = this.getPoints( divisions, true );
  15195. return this.createGeometry( pts );
  15196. };
  15197. // Generate geometry from equidistance sampling along the path
  15198. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  15199. var pts = this.getSpacedPoints( divisions, true );
  15200. return this.createGeometry( pts );
  15201. };
  15202. THREE.CurvePath.prototype.createGeometry = function( points ) {
  15203. var geometry = new THREE.Geometry();
  15204. for ( var i = 0; i < points.length; i ++ ) {
  15205. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  15206. }
  15207. return geometry;
  15208. };
  15209. /**************************************************************
  15210. * Bend / Wrap Helper Methods
  15211. **************************************************************/
  15212. // Wrap path / Bend modifiers?
  15213. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  15214. this.bends.push( bendpath );
  15215. };
  15216. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  15217. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  15218. var i, il;
  15219. if ( !bends ) {
  15220. bends = this.bends;
  15221. }
  15222. for ( i = 0, il = bends.length; i < il; i ++ ) {
  15223. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  15224. }
  15225. return oldPts;
  15226. };
  15227. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  15228. var oldPts = this.getSpacedPoints( segments );
  15229. var i, il;
  15230. if ( !bends ) {
  15231. bends = this.bends;
  15232. }
  15233. for ( i = 0, il = bends.length; i < il; i ++ ) {
  15234. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  15235. }
  15236. return oldPts;
  15237. };
  15238. // This returns getPoints() bend/wrapped around the contour of a path.
  15239. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  15240. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  15241. var bounds = this.getBoundingBox();
  15242. var i, il, p, oldX, oldY, xNorm;
  15243. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  15244. p = oldPts[ i ];
  15245. oldX = p.x;
  15246. oldY = p.y;
  15247. xNorm = oldX / bounds.maxX;
  15248. // If using actual distance, for length > path, requires line extrusions
  15249. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  15250. xNorm = path.getUtoTmapping( xNorm, oldX );
  15251. // check for out of bounds?
  15252. var pathPt = path.getPoint( xNorm );
  15253. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  15254. p.x = pathPt.x + normal.x;
  15255. p.y = pathPt.y + normal.y;
  15256. }
  15257. return oldPts;
  15258. };
  15259. /**
  15260. * @author alteredq / http://alteredqualia.com/
  15261. */
  15262. THREE.Gyroscope = function () {
  15263. THREE.Object3D.call( this );
  15264. };
  15265. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  15266. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  15267. this.matrixAutoUpdate && this.updateMatrix();
  15268. // update matrixWorld
  15269. if ( this.matrixWorldNeedsUpdate || force ) {
  15270. if ( this.parent ) {
  15271. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  15272. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  15273. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  15274. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  15275. } else {
  15276. this.matrixWorld.copy( this.matrix );
  15277. }
  15278. this.matrixWorldNeedsUpdate = false;
  15279. force = true;
  15280. }
  15281. // update children
  15282. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  15283. this.children[ i ].updateMatrixWorld( force );
  15284. }
  15285. };
  15286. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  15287. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  15288. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  15289. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  15290. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  15291. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  15292. /**
  15293. * @author zz85 / http://www.lab4games.net/zz85/blog
  15294. * Creates free form 2d path using series of points, lines or curves.
  15295. *
  15296. **/
  15297. THREE.Path = function ( points ) {
  15298. THREE.CurvePath.call(this);
  15299. this.actions = [];
  15300. if ( points ) {
  15301. this.fromPoints( points );
  15302. }
  15303. };
  15304. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  15305. THREE.PathActions = {
  15306. MOVE_TO: 'moveTo',
  15307. LINE_TO: 'lineTo',
  15308. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  15309. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  15310. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  15311. ARC: 'arc', // Circle
  15312. ELLIPSE: 'ellipse'
  15313. };
  15314. // TODO Clean up PATH API
  15315. // Create path using straight lines to connect all points
  15316. // - vectors: array of Vector2
  15317. THREE.Path.prototype.fromPoints = function ( vectors ) {
  15318. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  15319. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  15320. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  15321. };
  15322. };
  15323. // startPath() endPath()?
  15324. THREE.Path.prototype.moveTo = function ( x, y ) {
  15325. var args = Array.prototype.slice.call( arguments );
  15326. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  15327. };
  15328. THREE.Path.prototype.lineTo = function ( x, y ) {
  15329. var args = Array.prototype.slice.call( arguments );
  15330. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15331. var x0 = lastargs[ lastargs.length - 2 ];
  15332. var y0 = lastargs[ lastargs.length - 1 ];
  15333. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  15334. this.curves.push( curve );
  15335. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  15336. };
  15337. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  15338. var args = Array.prototype.slice.call( arguments );
  15339. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15340. var x0 = lastargs[ lastargs.length - 2 ];
  15341. var y0 = lastargs[ lastargs.length - 1 ];
  15342. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  15343. new THREE.Vector2( aCPx, aCPy ),
  15344. new THREE.Vector2( aX, aY ) );
  15345. this.curves.push( curve );
  15346. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  15347. };
  15348. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  15349. aCP2x, aCP2y,
  15350. aX, aY ) {
  15351. var args = Array.prototype.slice.call( arguments );
  15352. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15353. var x0 = lastargs[ lastargs.length - 2 ];
  15354. var y0 = lastargs[ lastargs.length - 1 ];
  15355. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  15356. new THREE.Vector2( aCP1x, aCP1y ),
  15357. new THREE.Vector2( aCP2x, aCP2y ),
  15358. new THREE.Vector2( aX, aY ) );
  15359. this.curves.push( curve );
  15360. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  15361. };
  15362. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  15363. var args = Array.prototype.slice.call( arguments );
  15364. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15365. var x0 = lastargs[ lastargs.length - 2 ];
  15366. var y0 = lastargs[ lastargs.length - 1 ];
  15367. //---
  15368. var npts = [ new THREE.Vector2( x0, y0 ) ];
  15369. Array.prototype.push.apply( npts, pts );
  15370. var curve = new THREE.SplineCurve( npts );
  15371. this.curves.push( curve );
  15372. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  15373. };
  15374. // FUTURE: Change the API or follow canvas API?
  15375. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  15376. aStartAngle, aEndAngle, aClockwise ) {
  15377. var lastargs = this.actions[ this.actions.length - 1].args;
  15378. var x0 = lastargs[ lastargs.length - 2 ];
  15379. var y0 = lastargs[ lastargs.length - 1 ];
  15380. this.absarc(aX + x0, aY + y0, aRadius,
  15381. aStartAngle, aEndAngle, aClockwise );
  15382. };
  15383. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  15384. aStartAngle, aEndAngle, aClockwise ) {
  15385. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  15386. };
  15387. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  15388. aStartAngle, aEndAngle, aClockwise ) {
  15389. var lastargs = this.actions[ this.actions.length - 1].args;
  15390. var x0 = lastargs[ lastargs.length - 2 ];
  15391. var y0 = lastargs[ lastargs.length - 1 ];
  15392. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  15393. aStartAngle, aEndAngle, aClockwise );
  15394. };
  15395. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  15396. aStartAngle, aEndAngle, aClockwise ) {
  15397. var args = Array.prototype.slice.call( arguments );
  15398. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  15399. aStartAngle, aEndAngle, aClockwise );
  15400. this.curves.push( curve );
  15401. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  15402. args.push(lastPoint.x);
  15403. args.push(lastPoint.y);
  15404. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  15405. };
  15406. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  15407. if ( ! divisions ) divisions = 40;
  15408. var points = [];
  15409. for ( var i = 0; i < divisions; i ++ ) {
  15410. points.push( this.getPoint( i / divisions ) );
  15411. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  15412. }
  15413. // if ( closedPath ) {
  15414. //
  15415. // points.push( points[ 0 ] );
  15416. //
  15417. // }
  15418. return points;
  15419. };
  15420. /* Return an array of vectors based on contour of the path */
  15421. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  15422. if (this.useSpacedPoints) {
  15423. console.log('tata');
  15424. return this.getSpacedPoints( divisions, closedPath );
  15425. }
  15426. divisions = divisions || 12;
  15427. var points = [];
  15428. var i, il, item, action, args;
  15429. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  15430. laste, j,
  15431. t, tx, ty;
  15432. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  15433. item = this.actions[ i ];
  15434. action = item.action;
  15435. args = item.args;
  15436. switch( action ) {
  15437. case THREE.PathActions.MOVE_TO:
  15438. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  15439. break;
  15440. case THREE.PathActions.LINE_TO:
  15441. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  15442. break;
  15443. case THREE.PathActions.QUADRATIC_CURVE_TO:
  15444. cpx = args[ 2 ];
  15445. cpy = args[ 3 ];
  15446. cpx1 = args[ 0 ];
  15447. cpy1 = args[ 1 ];
  15448. if ( points.length > 0 ) {
  15449. laste = points[ points.length - 1 ];
  15450. cpx0 = laste.x;
  15451. cpy0 = laste.y;
  15452. } else {
  15453. laste = this.actions[ i - 1 ].args;
  15454. cpx0 = laste[ laste.length - 2 ];
  15455. cpy0 = laste[ laste.length - 1 ];
  15456. }
  15457. for ( j = 1; j <= divisions; j ++ ) {
  15458. t = j / divisions;
  15459. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15460. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15461. points.push( new THREE.Vector2( tx, ty ) );
  15462. }
  15463. break;
  15464. case THREE.PathActions.BEZIER_CURVE_TO:
  15465. cpx = args[ 4 ];
  15466. cpy = args[ 5 ];
  15467. cpx1 = args[ 0 ];
  15468. cpy1 = args[ 1 ];
  15469. cpx2 = args[ 2 ];
  15470. cpy2 = args[ 3 ];
  15471. if ( points.length > 0 ) {
  15472. laste = points[ points.length - 1 ];
  15473. cpx0 = laste.x;
  15474. cpy0 = laste.y;
  15475. } else {
  15476. laste = this.actions[ i - 1 ].args;
  15477. cpx0 = laste[ laste.length - 2 ];
  15478. cpy0 = laste[ laste.length - 1 ];
  15479. }
  15480. for ( j = 1; j <= divisions; j ++ ) {
  15481. t = j / divisions;
  15482. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15483. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15484. points.push( new THREE.Vector2( tx, ty ) );
  15485. }
  15486. break;
  15487. case THREE.PathActions.CSPLINE_THRU:
  15488. laste = this.actions[ i - 1 ].args;
  15489. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  15490. var spts = [ last ];
  15491. var n = divisions * args[ 0 ].length;
  15492. spts = spts.concat( args[ 0 ] );
  15493. var spline = new THREE.SplineCurve( spts );
  15494. for ( j = 1; j <= n; j ++ ) {
  15495. points.push( spline.getPointAt( j / n ) ) ;
  15496. }
  15497. break;
  15498. case THREE.PathActions.ARC:
  15499. var aX = args[ 0 ], aY = args[ 1 ],
  15500. aRadius = args[ 2 ],
  15501. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  15502. aClockwise = !!args[ 5 ];
  15503. var deltaAngle = aEndAngle - aStartAngle;
  15504. var angle;
  15505. var tdivisions = divisions * 2;
  15506. for ( j = 1; j <= tdivisions; j ++ ) {
  15507. t = j / tdivisions;
  15508. if ( ! aClockwise ) {
  15509. t = 1 - t;
  15510. }
  15511. angle = aStartAngle + t * deltaAngle;
  15512. tx = aX + aRadius * Math.cos( angle );
  15513. ty = aY + aRadius * Math.sin( angle );
  15514. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  15515. points.push( new THREE.Vector2( tx, ty ) );
  15516. }
  15517. //console.log(points);
  15518. break;
  15519. case THREE.PathActions.ELLIPSE:
  15520. var aX = args[ 0 ], aY = args[ 1 ],
  15521. xRadius = args[ 2 ],
  15522. yRadius = args[ 3 ],
  15523. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  15524. aClockwise = !!args[ 6 ];
  15525. var deltaAngle = aEndAngle - aStartAngle;
  15526. var angle;
  15527. var tdivisions = divisions * 2;
  15528. for ( j = 1; j <= tdivisions; j ++ ) {
  15529. t = j / tdivisions;
  15530. if ( ! aClockwise ) {
  15531. t = 1 - t;
  15532. }
  15533. angle = aStartAngle + t * deltaAngle;
  15534. tx = aX + xRadius * Math.cos( angle );
  15535. ty = aY + yRadius * Math.sin( angle );
  15536. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  15537. points.push( new THREE.Vector2( tx, ty ) );
  15538. }
  15539. //console.log(points);
  15540. break;
  15541. } // end switch
  15542. }
  15543. // Normalize to remove the closing point by default.
  15544. var lastPoint = points[ points.length - 1];
  15545. var EPSILON = 0.0000000001;
  15546. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  15547. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  15548. points.splice( points.length - 1, 1);
  15549. if ( closedPath ) {
  15550. points.push( points[ 0 ] );
  15551. }
  15552. return points;
  15553. };
  15554. // Breaks path into shapes
  15555. THREE.Path.prototype.toShapes = function() {
  15556. var i, il, item, action, args;
  15557. var subPaths = [], lastPath = new THREE.Path();
  15558. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  15559. item = this.actions[ i ];
  15560. args = item.args;
  15561. action = item.action;
  15562. if ( action == THREE.PathActions.MOVE_TO ) {
  15563. if ( lastPath.actions.length != 0 ) {
  15564. subPaths.push( lastPath );
  15565. lastPath = new THREE.Path();
  15566. }
  15567. }
  15568. lastPath[ action ].apply( lastPath, args );
  15569. }
  15570. if ( lastPath.actions.length != 0 ) {
  15571. subPaths.push( lastPath );
  15572. }
  15573. // console.log(subPaths);
  15574. if ( subPaths.length == 0 ) return [];
  15575. var tmpPath, tmpShape, shapes = [];
  15576. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  15577. // console.log("Holes first", holesFirst);
  15578. if ( subPaths.length == 1) {
  15579. tmpPath = subPaths[0];
  15580. tmpShape = new THREE.Shape();
  15581. tmpShape.actions = tmpPath.actions;
  15582. tmpShape.curves = tmpPath.curves;
  15583. shapes.push( tmpShape );
  15584. return shapes;
  15585. };
  15586. if ( holesFirst ) {
  15587. tmpShape = new THREE.Shape();
  15588. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  15589. tmpPath = subPaths[ i ];
  15590. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  15591. tmpShape.actions = tmpPath.actions;
  15592. tmpShape.curves = tmpPath.curves;
  15593. shapes.push( tmpShape );
  15594. tmpShape = new THREE.Shape();
  15595. //console.log('cw', i);
  15596. } else {
  15597. tmpShape.holes.push( tmpPath );
  15598. //console.log('ccw', i);
  15599. }
  15600. }
  15601. } else {
  15602. // Shapes first
  15603. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  15604. tmpPath = subPaths[ i ];
  15605. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  15606. if ( tmpShape ) shapes.push( tmpShape );
  15607. tmpShape = new THREE.Shape();
  15608. tmpShape.actions = tmpPath.actions;
  15609. tmpShape.curves = tmpPath.curves;
  15610. } else {
  15611. tmpShape.holes.push( tmpPath );
  15612. }
  15613. }
  15614. shapes.push( tmpShape );
  15615. }
  15616. //console.log("shape", shapes);
  15617. return shapes;
  15618. };
  15619. /**
  15620. * @author zz85 / http://www.lab4games.net/zz85/blog
  15621. * Defines a 2d shape plane using paths.
  15622. **/
  15623. // STEP 1 Create a path.
  15624. // STEP 2 Turn path into shape.
  15625. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  15626. // STEP 3a - Extract points from each shape, turn to vertices
  15627. // STEP 3b - Triangulate each shape, add faces.
  15628. THREE.Shape = function ( ) {
  15629. THREE.Path.apply( this, arguments );
  15630. this.holes = [];
  15631. };
  15632. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  15633. // Convenience method to return ExtrudeGeometry
  15634. THREE.Shape.prototype.extrude = function ( options ) {
  15635. var extruded = new THREE.ExtrudeGeometry( this, options );
  15636. return extruded;
  15637. };
  15638. // Get points of holes
  15639. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  15640. var i, il = this.holes.length, holesPts = [];
  15641. for ( i = 0; i < il; i ++ ) {
  15642. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  15643. }
  15644. return holesPts;
  15645. };
  15646. // Get points of holes (spaced by regular distance)
  15647. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  15648. var i, il = this.holes.length, holesPts = [];
  15649. for ( i = 0; i < il; i ++ ) {
  15650. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  15651. }
  15652. return holesPts;
  15653. };
  15654. // Get points of shape and holes (keypoints based on segments parameter)
  15655. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  15656. return {
  15657. shape: this.getTransformedPoints( divisions ),
  15658. holes: this.getPointsHoles( divisions )
  15659. };
  15660. };
  15661. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  15662. if (this.useSpacedPoints) {
  15663. return this.extractAllSpacedPoints(divisions);
  15664. }
  15665. return this.extractAllPoints(divisions);
  15666. };
  15667. //
  15668. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  15669. //
  15670. // return {
  15671. //
  15672. // shape: this.transform( bend, divisions ),
  15673. // holes: this.getPointsHoles( divisions, bend )
  15674. //
  15675. // };
  15676. //
  15677. // };
  15678. // Get points of shape and holes (spaced by regular distance)
  15679. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  15680. return {
  15681. shape: this.getTransformedSpacedPoints( divisions ),
  15682. holes: this.getSpacedPointsHoles( divisions )
  15683. };
  15684. };
  15685. /**************************************************************
  15686. * Utils
  15687. **************************************************************/
  15688. THREE.Shape.Utils = {
  15689. /*
  15690. contour - array of vector2 for contour
  15691. holes - array of array of vector2
  15692. */
  15693. removeHoles: function ( contour, holes ) {
  15694. var shape = contour.concat(); // work on this shape
  15695. var allpoints = shape.concat();
  15696. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  15697. var prevShapeVert, nextShapeVert,
  15698. prevHoleVert, nextHoleVert,
  15699. holeIndex, shapeIndex,
  15700. shapeId, shapeGroup,
  15701. h, h2,
  15702. hole, shortest, d,
  15703. p, pts1, pts2,
  15704. tmpShape1, tmpShape2,
  15705. tmpHole1, tmpHole2,
  15706. verts = [];
  15707. for ( h = 0; h < holes.length; h ++ ) {
  15708. hole = holes[ h ];
  15709. /*
  15710. shapeholes[ h ].concat(); // preserves original
  15711. holes.push( hole );
  15712. */
  15713. Array.prototype.push.apply( allpoints, hole );
  15714. shortest = Number.POSITIVE_INFINITY;
  15715. // Find the shortest pair of pts between shape and hole
  15716. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  15717. // Using distanceToSquared() intead of distanceTo() should speed a little
  15718. // since running square roots operations are reduced.
  15719. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  15720. pts1 = hole[ h2 ];
  15721. var dist = [];
  15722. for ( p = 0; p < shape.length; p++ ) {
  15723. pts2 = shape[ p ];
  15724. d = pts1.distanceToSquared( pts2 );
  15725. dist.push( d );
  15726. if ( d < shortest ) {
  15727. shortest = d;
  15728. holeIndex = h2;
  15729. shapeIndex = p;
  15730. }
  15731. }
  15732. }
  15733. //console.log("shortest", shortest, dist);
  15734. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  15735. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  15736. var areaapts = [
  15737. hole[ holeIndex ],
  15738. shape[ shapeIndex ],
  15739. shape[ prevShapeVert ]
  15740. ];
  15741. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  15742. var areabpts = [
  15743. hole[ holeIndex ],
  15744. hole[ prevHoleVert ],
  15745. shape[ shapeIndex ]
  15746. ];
  15747. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  15748. var shapeOffset = 1;
  15749. var holeOffset = -1;
  15750. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  15751. shapeIndex += shapeOffset;
  15752. holeIndex += holeOffset;
  15753. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  15754. shapeIndex %= shape.length;
  15755. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  15756. holeIndex %= hole.length;
  15757. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  15758. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  15759. areaapts = [
  15760. hole[ holeIndex ],
  15761. shape[ shapeIndex ],
  15762. shape[ prevShapeVert ]
  15763. ];
  15764. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  15765. areabpts = [
  15766. hole[ holeIndex ],
  15767. hole[ prevHoleVert ],
  15768. shape[ shapeIndex ]
  15769. ];
  15770. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  15771. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  15772. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  15773. // In case areas are not correct.
  15774. //console.log("USE THIS");
  15775. shapeIndex = oldShapeIndex;
  15776. holeIndex = oldHoleIndex ;
  15777. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  15778. shapeIndex %= shape.length;
  15779. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  15780. holeIndex %= hole.length;
  15781. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  15782. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  15783. } else {
  15784. //console.log("USE THAT ")
  15785. }
  15786. tmpShape1 = shape.slice( 0, shapeIndex );
  15787. tmpShape2 = shape.slice( shapeIndex );
  15788. tmpHole1 = hole.slice( holeIndex );
  15789. tmpHole2 = hole.slice( 0, holeIndex );
  15790. // Should check orders here again?
  15791. var trianglea = [
  15792. hole[ holeIndex ],
  15793. shape[ shapeIndex ],
  15794. shape[ prevShapeVert ]
  15795. ];
  15796. var triangleb = [
  15797. hole[ holeIndex ] ,
  15798. hole[ prevHoleVert ],
  15799. shape[ shapeIndex ]
  15800. ];
  15801. verts.push( trianglea );
  15802. verts.push( triangleb );
  15803. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15804. }
  15805. return {
  15806. shape:shape, /* shape with no holes */
  15807. isolatedPts: verts, /* isolated faces */
  15808. allpoints: allpoints
  15809. }
  15810. },
  15811. triangulateShape: function ( contour, holes ) {
  15812. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  15813. var shape = shapeWithoutHoles.shape,
  15814. allpoints = shapeWithoutHoles.allpoints,
  15815. isolatedPts = shapeWithoutHoles.isolatedPts;
  15816. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  15817. // 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.
  15818. //console.log( "triangles",triangles, triangles.length );
  15819. //console.log( "allpoints",allpoints, allpoints.length );
  15820. var i, il, f, face,
  15821. key, index,
  15822. allPointsMap = {},
  15823. isolatedPointsMap = {};
  15824. // prepare all points map
  15825. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15826. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  15827. if ( allPointsMap[ key ] !== undefined ) {
  15828. console.log( "Duplicate point", key );
  15829. }
  15830. allPointsMap[ key ] = i;
  15831. }
  15832. // check all face vertices against all points map
  15833. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15834. face = triangles[ i ];
  15835. for ( f = 0; f < 3; f ++ ) {
  15836. key = face[ f ].x + ":" + face[ f ].y;
  15837. index = allPointsMap[ key ];
  15838. if ( index !== undefined ) {
  15839. face[ f ] = index;
  15840. }
  15841. }
  15842. }
  15843. // check isolated points vertices against all points map
  15844. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  15845. face = isolatedPts[ i ];
  15846. for ( f = 0; f < 3; f ++ ) {
  15847. key = face[ f ].x + ":" + face[ f ].y;
  15848. index = allPointsMap[ key ];
  15849. if ( index !== undefined ) {
  15850. face[ f ] = index;
  15851. }
  15852. }
  15853. }
  15854. return triangles.concat( isolatedPts );
  15855. }, // end triangulate shapes
  15856. /*
  15857. triangulate2 : function( pts, holes ) {
  15858. // For use with Poly2Tri.js
  15859. var allpts = pts.concat();
  15860. var shape = [];
  15861. for (var p in pts) {
  15862. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  15863. }
  15864. var swctx = new js.poly2tri.SweepContext(shape);
  15865. for (var h in holes) {
  15866. var aHole = holes[h];
  15867. var newHole = []
  15868. for (i in aHole) {
  15869. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  15870. allpts.push(aHole[i]);
  15871. }
  15872. swctx.AddHole(newHole);
  15873. }
  15874. var find;
  15875. var findIndexForPt = function (pt) {
  15876. find = new THREE.Vector2(pt.x, pt.y);
  15877. var p;
  15878. for (p=0, pl = allpts.length; p<pl; p++) {
  15879. if (allpts[p].equals(find)) return p;
  15880. }
  15881. return -1;
  15882. };
  15883. // triangulate
  15884. js.poly2tri.sweep.Triangulate(swctx);
  15885. var triangles = swctx.GetTriangles();
  15886. var tr ;
  15887. var facesPts = [];
  15888. for (var t in triangles) {
  15889. tr = triangles[t];
  15890. facesPts.push([
  15891. findIndexForPt(tr.GetPoint(0)),
  15892. findIndexForPt(tr.GetPoint(1)),
  15893. findIndexForPt(tr.GetPoint(2))
  15894. ]);
  15895. }
  15896. // console.log(facesPts);
  15897. // console.log("triangles", triangles.length, triangles);
  15898. // Returns array of faces with 3 element each
  15899. return facesPts;
  15900. },
  15901. */
  15902. isClockWise: function ( pts ) {
  15903. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  15904. },
  15905. // Bezier Curves formulas obtained from
  15906. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  15907. // Quad Bezier Functions
  15908. b2p0: function ( t, p ) {
  15909. var k = 1 - t;
  15910. return k * k * p;
  15911. },
  15912. b2p1: function ( t, p ) {
  15913. return 2 * ( 1 - t ) * t * p;
  15914. },
  15915. b2p2: function ( t, p ) {
  15916. return t * t * p;
  15917. },
  15918. b2: function ( t, p0, p1, p2 ) {
  15919. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  15920. },
  15921. // Cubic Bezier Functions
  15922. b3p0: function ( t, p ) {
  15923. var k = 1 - t;
  15924. return k * k * k * p;
  15925. },
  15926. b3p1: function ( t, p ) {
  15927. var k = 1 - t;
  15928. return 3 * k * k * t * p;
  15929. },
  15930. b3p2: function ( t, p ) {
  15931. var k = 1 - t;
  15932. return 3 * k * t * t * p;
  15933. },
  15934. b3p3: function ( t, p ) {
  15935. return t * t * t * p;
  15936. },
  15937. b3: function ( t, p0, p1, p2, p3 ) {
  15938. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  15939. }
  15940. };
  15941. /**
  15942. * @author mikael emtinger / http://gomo.se/
  15943. */
  15944. THREE.AnimationHandler = (function() {
  15945. var playing = [];
  15946. var library = {};
  15947. var that = {};
  15948. //--- update ---
  15949. that.update = function( deltaTimeMS ) {
  15950. for( var i = 0; i < playing.length; i ++ )
  15951. playing[ i ].update( deltaTimeMS );
  15952. };
  15953. //--- add ---
  15954. that.addToUpdate = function( animation ) {
  15955. if ( playing.indexOf( animation ) === -1 )
  15956. playing.push( animation );
  15957. };
  15958. //--- remove ---
  15959. that.removeFromUpdate = function( animation ) {
  15960. var index = playing.indexOf( animation );
  15961. if( index !== -1 )
  15962. playing.splice( index, 1 );
  15963. };
  15964. //--- add ---
  15965. that.add = function( data ) {
  15966. if ( library[ data.name ] !== undefined )
  15967. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  15968. library[ data.name ] = data;
  15969. initData( data );
  15970. };
  15971. //--- get ---
  15972. that.get = function( name ) {
  15973. if ( typeof name === "string" ) {
  15974. if ( library[ name ] ) {
  15975. return library[ name ];
  15976. } else {
  15977. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  15978. return null;
  15979. }
  15980. } else {
  15981. // todo: add simple tween library
  15982. }
  15983. };
  15984. //--- parse ---
  15985. that.parse = function( root ) {
  15986. // setup hierarchy
  15987. var hierarchy = [];
  15988. if ( root instanceof THREE.SkinnedMesh ) {
  15989. for( var b = 0; b < root.bones.length; b++ ) {
  15990. hierarchy.push( root.bones[ b ] );
  15991. }
  15992. } else {
  15993. parseRecurseHierarchy( root, hierarchy );
  15994. }
  15995. return hierarchy;
  15996. };
  15997. var parseRecurseHierarchy = function( root, hierarchy ) {
  15998. hierarchy.push( root );
  15999. for( var c = 0; c < root.children.length; c++ )
  16000. parseRecurseHierarchy( root.children[ c ], hierarchy );
  16001. }
  16002. //--- init data ---
  16003. var initData = function( data ) {
  16004. if( data.initialized === true )
  16005. return;
  16006. // loop through all keys
  16007. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  16008. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16009. // remove minus times
  16010. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  16011. data.hierarchy[ h ].keys[ k ].time = 0;
  16012. // create quaternions
  16013. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  16014. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  16015. var quat = data.hierarchy[ h ].keys[ k ].rot;
  16016. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  16017. }
  16018. }
  16019. // prepare morph target keys
  16020. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  16021. // get all used
  16022. var usedMorphTargets = {};
  16023. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16024. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16025. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  16026. usedMorphTargets[ morphTargetName ] = -1;
  16027. }
  16028. }
  16029. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  16030. // set all used on all frames
  16031. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16032. var influences = {};
  16033. for ( var morphTargetName in usedMorphTargets ) {
  16034. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16035. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  16036. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  16037. break;
  16038. }
  16039. }
  16040. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  16041. influences[ morphTargetName ] = 0;
  16042. }
  16043. }
  16044. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  16045. }
  16046. }
  16047. // remove all keys that are on the same time
  16048. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16049. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  16050. data.hierarchy[ h ].keys.splice( k, 1 );
  16051. k --;
  16052. }
  16053. }
  16054. // set index
  16055. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16056. data.hierarchy[ h ].keys[ k ].index = k;
  16057. }
  16058. }
  16059. // JIT
  16060. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  16061. data.JIT = {};
  16062. data.JIT.hierarchy = [];
  16063. for( var h = 0; h < data.hierarchy.length; h ++ )
  16064. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  16065. // done
  16066. data.initialized = true;
  16067. };
  16068. // interpolation types
  16069. that.LINEAR = 0;
  16070. that.CATMULLROM = 1;
  16071. that.CATMULLROM_FORWARD = 2;
  16072. return that;
  16073. }());
  16074. /**
  16075. * @author mikael emtinger / http://gomo.se/
  16076. * @author mrdoob / http://mrdoob.com/
  16077. * @author alteredq / http://alteredqualia.com/
  16078. */
  16079. THREE.Animation = function ( root, name, interpolationType ) {
  16080. this.root = root;
  16081. this.data = THREE.AnimationHandler.get( name );
  16082. this.hierarchy = THREE.AnimationHandler.parse( root );
  16083. this.currentTime = 0;
  16084. this.timeScale = 1;
  16085. this.isPlaying = false;
  16086. this.isPaused = true;
  16087. this.loop = true;
  16088. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  16089. this.points = [];
  16090. this.target = new THREE.Vector3();
  16091. };
  16092. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  16093. if ( this.isPlaying === false ) {
  16094. this.isPlaying = true;
  16095. this.loop = loop !== undefined ? loop : true;
  16096. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  16097. // reset key cache
  16098. var h, hl = this.hierarchy.length,
  16099. object;
  16100. for ( h = 0; h < hl; h ++ ) {
  16101. object = this.hierarchy[ h ];
  16102. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16103. object.useQuaternion = true;
  16104. }
  16105. object.matrixAutoUpdate = true;
  16106. if ( object.animationCache === undefined ) {
  16107. object.animationCache = {};
  16108. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  16109. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  16110. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  16111. }
  16112. var prevKey = object.animationCache.prevKey;
  16113. var nextKey = object.animationCache.nextKey;
  16114. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  16115. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  16116. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  16117. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  16118. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  16119. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  16120. }
  16121. this.update( 0 );
  16122. }
  16123. this.isPaused = false;
  16124. THREE.AnimationHandler.addToUpdate( this );
  16125. };
  16126. THREE.Animation.prototype.pause = function() {
  16127. if ( this.isPaused === true ) {
  16128. THREE.AnimationHandler.addToUpdate( this );
  16129. } else {
  16130. THREE.AnimationHandler.removeFromUpdate( this );
  16131. }
  16132. this.isPaused = !this.isPaused;
  16133. };
  16134. THREE.Animation.prototype.stop = function() {
  16135. this.isPlaying = false;
  16136. this.isPaused = false;
  16137. THREE.AnimationHandler.removeFromUpdate( this );
  16138. };
  16139. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  16140. // early out
  16141. if ( this.isPlaying === false ) return;
  16142. // vars
  16143. var types = [ "pos", "rot", "scl" ];
  16144. var type;
  16145. var scale;
  16146. var vector;
  16147. var prevXYZ, nextXYZ;
  16148. var prevKey, nextKey;
  16149. var object;
  16150. var animationCache;
  16151. var frame;
  16152. var JIThierarchy = this.data.JIT.hierarchy;
  16153. var currentTime, unloopedCurrentTime;
  16154. var currentPoint, forwardPoint, angle;
  16155. this.currentTime += deltaTimeMS * this.timeScale;
  16156. unloopedCurrentTime = this.currentTime;
  16157. currentTime = this.currentTime = this.currentTime % this.data.length;
  16158. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  16159. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  16160. object = this.hierarchy[ h ];
  16161. animationCache = object.animationCache;
  16162. // loop through pos/rot/scl
  16163. for ( var t = 0; t < 3; t ++ ) {
  16164. // get keys
  16165. type = types[ t ];
  16166. prevKey = animationCache.prevKey[ type ];
  16167. nextKey = animationCache.nextKey[ type ];
  16168. // switch keys?
  16169. if ( nextKey.time <= unloopedCurrentTime ) {
  16170. // did we loop?
  16171. if ( currentTime < unloopedCurrentTime ) {
  16172. if ( this.loop ) {
  16173. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  16174. nextKey = this.getNextKeyWith( type, h, 1 );
  16175. while( nextKey.time < currentTime ) {
  16176. prevKey = nextKey;
  16177. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16178. }
  16179. } else {
  16180. this.stop();
  16181. return;
  16182. }
  16183. } else {
  16184. do {
  16185. prevKey = nextKey;
  16186. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16187. } while( nextKey.time < currentTime )
  16188. }
  16189. animationCache.prevKey[ type ] = prevKey;
  16190. animationCache.nextKey[ type ] = nextKey;
  16191. }
  16192. object.matrixAutoUpdate = true;
  16193. object.matrixWorldNeedsUpdate = true;
  16194. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  16195. prevXYZ = prevKey[ type ];
  16196. nextXYZ = nextKey[ type ];
  16197. // check scale error
  16198. if ( scale < 0 || scale > 1 ) {
  16199. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  16200. scale = scale < 0 ? 0 : 1;
  16201. }
  16202. // interpolate
  16203. if ( type === "pos" ) {
  16204. vector = object.position;
  16205. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  16206. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  16207. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  16208. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  16209. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16210. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16211. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  16212. this.points[ 1 ] = prevXYZ;
  16213. this.points[ 2 ] = nextXYZ;
  16214. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  16215. scale = scale * 0.33 + 0.33;
  16216. currentPoint = this.interpolateCatmullRom( this.points, scale );
  16217. vector.x = currentPoint[ 0 ];
  16218. vector.y = currentPoint[ 1 ];
  16219. vector.z = currentPoint[ 2 ];
  16220. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16221. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  16222. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  16223. this.target.subSelf( vector );
  16224. this.target.y = 0;
  16225. this.target.normalize();
  16226. angle = Math.atan2( this.target.x, this.target.z );
  16227. object.rotation.set( 0, angle, 0 );
  16228. }
  16229. }
  16230. } else if ( type === "rot" ) {
  16231. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  16232. } else if ( type === "scl" ) {
  16233. vector = object.scale;
  16234. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  16235. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  16236. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  16237. }
  16238. }
  16239. }
  16240. };
  16241. // Catmull-Rom spline
  16242. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  16243. var c = [], v3 = [],
  16244. point, intPoint, weight, w2, w3,
  16245. pa, pb, pc, pd;
  16246. point = ( points.length - 1 ) * scale;
  16247. intPoint = Math.floor( point );
  16248. weight = point - intPoint;
  16249. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  16250. c[ 1 ] = intPoint;
  16251. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  16252. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  16253. pa = points[ c[ 0 ] ];
  16254. pb = points[ c[ 1 ] ];
  16255. pc = points[ c[ 2 ] ];
  16256. pd = points[ c[ 3 ] ];
  16257. w2 = weight * weight;
  16258. w3 = weight * w2;
  16259. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  16260. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  16261. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  16262. return v3;
  16263. };
  16264. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  16265. var v0 = ( p2 - p0 ) * 0.5,
  16266. v1 = ( p3 - p1 ) * 0.5;
  16267. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16268. };
  16269. // Get next key with
  16270. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  16271. var keys = this.data.hierarchy[ h ].keys;
  16272. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16273. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16274. key = key < keys.length - 1 ? key : keys.length - 1;
  16275. } else {
  16276. key = key % keys.length;
  16277. }
  16278. for ( ; key < keys.length; key++ ) {
  16279. if ( keys[ key ][ type ] !== undefined ) {
  16280. return keys[ key ];
  16281. }
  16282. }
  16283. return this.data.hierarchy[ h ].keys[ 0 ];
  16284. };
  16285. // Get previous key with
  16286. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  16287. var keys = this.data.hierarchy[ h ].keys;
  16288. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16289. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16290. key = key > 0 ? key : 0;
  16291. } else {
  16292. key = key >= 0 ? key : key + keys.length;
  16293. }
  16294. for ( ; key >= 0; key -- ) {
  16295. if ( keys[ key ][ type ] !== undefined ) {
  16296. return keys[ key ];
  16297. }
  16298. }
  16299. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  16300. };
  16301. /**
  16302. * @author mikael emtinger / http://gomo.se/
  16303. * @author mrdoob / http://mrdoob.com/
  16304. * @author alteredq / http://alteredqualia.com/
  16305. * @author khang duong
  16306. * @author erik kitson
  16307. */
  16308. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  16309. this.root = root;
  16310. this.data = THREE.AnimationHandler.get( data );
  16311. this.hierarchy = THREE.AnimationHandler.parse( root );
  16312. this.currentTime = 0;
  16313. this.timeScale = 0.001;
  16314. this.isPlaying = false;
  16315. this.isPaused = true;
  16316. this.loop = true;
  16317. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  16318. // initialize to first keyframes
  16319. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  16320. var keys = this.data.hierarchy[h].keys,
  16321. sids = this.data.hierarchy[h].sids,
  16322. obj = this.hierarchy[h];
  16323. if ( keys.length && sids ) {
  16324. for ( var s = 0; s < sids.length; s++ ) {
  16325. var sid = sids[ s ],
  16326. next = this.getNextKeyWith( sid, h, 0 );
  16327. if ( next ) {
  16328. next.apply( sid );
  16329. }
  16330. }
  16331. obj.matrixAutoUpdate = false;
  16332. this.data.hierarchy[h].node.updateMatrix();
  16333. obj.matrixWorldNeedsUpdate = true;
  16334. }
  16335. }
  16336. };
  16337. // Play
  16338. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  16339. if( !this.isPlaying ) {
  16340. this.isPlaying = true;
  16341. this.loop = loop !== undefined ? loop : true;
  16342. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  16343. this.startTimeMs = startTimeMS;
  16344. this.startTime = 10000000;
  16345. this.endTime = -this.startTime;
  16346. // reset key cache
  16347. var h, hl = this.hierarchy.length,
  16348. object,
  16349. node;
  16350. for ( h = 0; h < hl; h++ ) {
  16351. object = this.hierarchy[ h ];
  16352. node = this.data.hierarchy[ h ];
  16353. object.useQuaternion = true;
  16354. if ( node.animationCache === undefined ) {
  16355. node.animationCache = {};
  16356. node.animationCache.prevKey = null;
  16357. node.animationCache.nextKey = null;
  16358. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  16359. }
  16360. var keys = this.data.hierarchy[h].keys;
  16361. if (keys.length) {
  16362. node.animationCache.prevKey = keys[ 0 ];
  16363. node.animationCache.nextKey = keys[ 1 ];
  16364. this.startTime = Math.min( keys[0].time, this.startTime );
  16365. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  16366. }
  16367. }
  16368. this.update( 0 );
  16369. }
  16370. this.isPaused = false;
  16371. THREE.AnimationHandler.addToUpdate( this );
  16372. };
  16373. // Pause
  16374. THREE.KeyFrameAnimation.prototype.pause = function() {
  16375. if( this.isPaused ) {
  16376. THREE.AnimationHandler.addToUpdate( this );
  16377. } else {
  16378. THREE.AnimationHandler.removeFromUpdate( this );
  16379. }
  16380. this.isPaused = !this.isPaused;
  16381. };
  16382. // Stop
  16383. THREE.KeyFrameAnimation.prototype.stop = function() {
  16384. this.isPlaying = false;
  16385. this.isPaused = false;
  16386. THREE.AnimationHandler.removeFromUpdate( this );
  16387. // reset JIT matrix and remove cache
  16388. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  16389. var obj = this.hierarchy[ h ];
  16390. var node = this.data.hierarchy[ h ];
  16391. if ( node.animationCache !== undefined ) {
  16392. var original = node.animationCache.originalMatrix;
  16393. if( obj instanceof THREE.Bone ) {
  16394. original.copy( obj.skinMatrix );
  16395. obj.skinMatrix = original;
  16396. } else {
  16397. original.copy( obj.matrix );
  16398. obj.matrix = original;
  16399. }
  16400. delete node.animationCache;
  16401. }
  16402. }
  16403. };
  16404. // Update
  16405. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  16406. // early out
  16407. if( !this.isPlaying ) return;
  16408. // vars
  16409. var prevKey, nextKey;
  16410. var object;
  16411. var node;
  16412. var frame;
  16413. var JIThierarchy = this.data.JIT.hierarchy;
  16414. var currentTime, unloopedCurrentTime;
  16415. var looped;
  16416. // update
  16417. this.currentTime += deltaTimeMS * this.timeScale;
  16418. unloopedCurrentTime = this.currentTime;
  16419. currentTime = this.currentTime = this.currentTime % this.data.length;
  16420. // if looped around, the current time should be based on the startTime
  16421. if ( currentTime < this.startTimeMs ) {
  16422. currentTime = this.currentTime = this.startTimeMs + currentTime;
  16423. }
  16424. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  16425. looped = currentTime < unloopedCurrentTime;
  16426. if ( looped && !this.loop ) {
  16427. // Set the animation to the last keyframes and stop
  16428. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  16429. var keys = this.data.hierarchy[h].keys,
  16430. sids = this.data.hierarchy[h].sids,
  16431. end = keys.length-1,
  16432. obj = this.hierarchy[h];
  16433. if ( keys.length ) {
  16434. for ( var s = 0; s < sids.length; s++ ) {
  16435. var sid = sids[ s ],
  16436. prev = this.getPrevKeyWith( sid, h, end );
  16437. if ( prev ) {
  16438. prev.apply( sid );
  16439. }
  16440. }
  16441. this.data.hierarchy[h].node.updateMatrix();
  16442. obj.matrixWorldNeedsUpdate = true;
  16443. }
  16444. }
  16445. this.stop();
  16446. return;
  16447. }
  16448. // check pre-infinity
  16449. if ( currentTime < this.startTime ) {
  16450. return;
  16451. }
  16452. // update
  16453. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  16454. object = this.hierarchy[ h ];
  16455. node = this.data.hierarchy[ h ];
  16456. var keys = node.keys,
  16457. animationCache = node.animationCache;
  16458. // use JIT?
  16459. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  16460. if( object instanceof THREE.Bone ) {
  16461. object.skinMatrix = JIThierarchy[ h ][ frame ];
  16462. object.matrixWorldNeedsUpdate = false;
  16463. } else {
  16464. object.matrix = JIThierarchy[ h ][ frame ];
  16465. object.matrixWorldNeedsUpdate = true;
  16466. }
  16467. // use interpolation
  16468. } else if ( keys.length ) {
  16469. // make sure so original matrix and not JIT matrix is set
  16470. if ( this.JITCompile && animationCache ) {
  16471. if( object instanceof THREE.Bone ) {
  16472. object.skinMatrix = animationCache.originalMatrix;
  16473. } else {
  16474. object.matrix = animationCache.originalMatrix;
  16475. }
  16476. }
  16477. prevKey = animationCache.prevKey;
  16478. nextKey = animationCache.nextKey;
  16479. if ( prevKey && nextKey ) {
  16480. // switch keys?
  16481. if ( nextKey.time <= unloopedCurrentTime ) {
  16482. // did we loop?
  16483. if ( looped && this.loop ) {
  16484. prevKey = keys[ 0 ];
  16485. nextKey = keys[ 1 ];
  16486. while ( nextKey.time < currentTime ) {
  16487. prevKey = nextKey;
  16488. nextKey = keys[ prevKey.index + 1 ];
  16489. }
  16490. } else if ( !looped ) {
  16491. var lastIndex = keys.length - 1;
  16492. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  16493. prevKey = nextKey;
  16494. nextKey = keys[ prevKey.index + 1 ];
  16495. }
  16496. }
  16497. animationCache.prevKey = prevKey;
  16498. animationCache.nextKey = nextKey;
  16499. }
  16500. if(nextKey.time >= currentTime)
  16501. prevKey.interpolate( nextKey, currentTime );
  16502. else
  16503. prevKey.interpolate( nextKey, nextKey.time);
  16504. }
  16505. this.data.hierarchy[h].node.updateMatrix();
  16506. object.matrixWorldNeedsUpdate = true;
  16507. }
  16508. }
  16509. // update JIT?
  16510. if ( this.JITCompile ) {
  16511. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  16512. this.hierarchy[ 0 ].updateMatrixWorld( true );
  16513. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  16514. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  16515. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  16516. } else {
  16517. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  16518. }
  16519. }
  16520. }
  16521. }
  16522. };
  16523. // Get next key with
  16524. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  16525. var keys = this.data.hierarchy[ h ].keys;
  16526. key = key % keys.length;
  16527. for ( ; key < keys.length; key++ ) {
  16528. if ( keys[ key ].hasTarget( sid ) ) {
  16529. return keys[ key ];
  16530. }
  16531. }
  16532. return keys[ 0 ];
  16533. };
  16534. // Get previous key with
  16535. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  16536. var keys = this.data.hierarchy[ h ].keys;
  16537. key = key >= 0 ? key : key + keys.length;
  16538. for ( ; key >= 0; key-- ) {
  16539. if ( keys[ key ].hasTarget( sid ) ) {
  16540. return keys[ key ];
  16541. }
  16542. }
  16543. return keys[ keys.length - 1 ];
  16544. };
  16545. /**
  16546. * Camera for rendering cube maps
  16547. * - renders scene into axis-aligned cube
  16548. *
  16549. * @author alteredq / http://alteredqualia.com/
  16550. */
  16551. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  16552. THREE.Object3D.call( this );
  16553. var fov = 90, aspect = 1;
  16554. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16555. cameraPX.up.set( 0, -1, 0 );
  16556. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  16557. this.add( cameraPX );
  16558. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16559. cameraNX.up.set( 0, -1, 0 );
  16560. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  16561. this.add( cameraNX );
  16562. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16563. cameraPY.up.set( 0, 0, 1 );
  16564. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  16565. this.add( cameraPY );
  16566. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16567. cameraNY.up.set( 0, 0, -1 );
  16568. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  16569. this.add( cameraNY );
  16570. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16571. cameraPZ.up.set( 0, -1, 0 );
  16572. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  16573. this.add( cameraPZ );
  16574. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16575. cameraNZ.up.set( 0, -1, 0 );
  16576. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  16577. this.add( cameraNZ );
  16578. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  16579. this.updateCubeMap = function ( renderer, scene ) {
  16580. var renderTarget = this.renderTarget;
  16581. var generateMipmaps = renderTarget.generateMipmaps;
  16582. renderTarget.generateMipmaps = false;
  16583. renderTarget.activeCubeFace = 0;
  16584. renderer.render( scene, cameraPX, renderTarget );
  16585. renderTarget.activeCubeFace = 1;
  16586. renderer.render( scene, cameraNX, renderTarget );
  16587. renderTarget.activeCubeFace = 2;
  16588. renderer.render( scene, cameraPY, renderTarget );
  16589. renderTarget.activeCubeFace = 3;
  16590. renderer.render( scene, cameraNY, renderTarget );
  16591. renderTarget.activeCubeFace = 4;
  16592. renderer.render( scene, cameraPZ, renderTarget );
  16593. renderTarget.generateMipmaps = generateMipmaps;
  16594. renderTarget.activeCubeFace = 5;
  16595. renderer.render( scene, cameraNZ, renderTarget );
  16596. };
  16597. };
  16598. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  16599. /*
  16600. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  16601. *
  16602. * A general perpose camera, for setting FOV, Lens Focal Length,
  16603. * and switching between perspective and orthographic views easily.
  16604. * Use this only if you do not wish to manage
  16605. * both a Orthographic and Perspective Camera
  16606. *
  16607. */
  16608. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  16609. THREE.Camera.call( this );
  16610. this.fov = fov;
  16611. this.left = -width / 2;
  16612. this.right = width / 2
  16613. this.top = height / 2;
  16614. this.bottom = -height / 2;
  16615. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  16616. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  16617. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  16618. this.zoom = 1;
  16619. this.toPerspective();
  16620. var aspect = width/height;
  16621. };
  16622. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  16623. THREE.CombinedCamera.prototype.toPerspective = function () {
  16624. // Switches to the Perspective Camera
  16625. this.near = this.cameraP.near;
  16626. this.far = this.cameraP.far;
  16627. this.cameraP.fov = this.fov / this.zoom ;
  16628. this.cameraP.updateProjectionMatrix();
  16629. this.projectionMatrix = this.cameraP.projectionMatrix;
  16630. this.inPerspectiveMode = true;
  16631. this.inOrthographicMode = false;
  16632. };
  16633. THREE.CombinedCamera.prototype.toOrthographic = function () {
  16634. // Switches to the Orthographic camera estimating viewport from Perspective
  16635. var fov = this.fov;
  16636. var aspect = this.cameraP.aspect;
  16637. var near = this.cameraP.near;
  16638. var far = this.cameraP.far;
  16639. // The size that we set is the mid plane of the viewing frustum
  16640. var hyperfocus = ( near + far ) / 2;
  16641. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  16642. var planeHeight = 2 * halfHeight;
  16643. var planeWidth = planeHeight * aspect;
  16644. var halfWidth = planeWidth / 2;
  16645. halfHeight /= this.zoom;
  16646. halfWidth /= this.zoom;
  16647. this.cameraO.left = -halfWidth;
  16648. this.cameraO.right = halfWidth;
  16649. this.cameraO.top = halfHeight;
  16650. this.cameraO.bottom = -halfHeight;
  16651. // this.cameraO.left = -farHalfWidth;
  16652. // this.cameraO.right = farHalfWidth;
  16653. // this.cameraO.top = farHalfHeight;
  16654. // this.cameraO.bottom = -farHalfHeight;
  16655. // this.cameraO.left = this.left / this.zoom;
  16656. // this.cameraO.right = this.right / this.zoom;
  16657. // this.cameraO.top = this.top / this.zoom;
  16658. // this.cameraO.bottom = this.bottom / this.zoom;
  16659. this.cameraO.updateProjectionMatrix();
  16660. this.near = this.cameraO.near;
  16661. this.far = this.cameraO.far;
  16662. this.projectionMatrix = this.cameraO.projectionMatrix;
  16663. this.inPerspectiveMode = false;
  16664. this.inOrthographicMode = true;
  16665. };
  16666. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  16667. this.cameraP.aspect = width / height;
  16668. this.left = -width / 2;
  16669. this.right = width / 2
  16670. this.top = height / 2;
  16671. this.bottom = -height / 2;
  16672. };
  16673. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  16674. this.fov = fov;
  16675. if ( this.inPerspectiveMode ) {
  16676. this.toPerspective();
  16677. } else {
  16678. this.toOrthographic();
  16679. }
  16680. };
  16681. // For mantaining similar API with PerspectiveCamera
  16682. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  16683. if ( this.inPerspectiveMode ) {
  16684. this.toPerspective();
  16685. } else {
  16686. this.toPerspective();
  16687. this.toOrthographic();
  16688. }
  16689. };
  16690. /*
  16691. * Uses Focal Length (in mm) to estimate and set FOV
  16692. * 35mm (fullframe) camera is used if frame size is not specified;
  16693. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  16694. */
  16695. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  16696. if ( frameHeight === undefined ) frameHeight = 24;
  16697. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  16698. this.setFov( fov );
  16699. return fov;
  16700. };
  16701. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  16702. this.zoom = zoom;
  16703. if ( this.inPerspectiveMode ) {
  16704. this.toPerspective();
  16705. } else {
  16706. this.toOrthographic();
  16707. }
  16708. };
  16709. THREE.CombinedCamera.prototype.toFrontView = function() {
  16710. this.rotation.x = 0;
  16711. this.rotation.y = 0;
  16712. this.rotation.z = 0;
  16713. // should we be modifing the matrix instead?
  16714. this.rotationAutoUpdate = false;
  16715. };
  16716. THREE.CombinedCamera.prototype.toBackView = function() {
  16717. this.rotation.x = 0;
  16718. this.rotation.y = Math.PI;
  16719. this.rotation.z = 0;
  16720. this.rotationAutoUpdate = false;
  16721. };
  16722. THREE.CombinedCamera.prototype.toLeftView = function() {
  16723. this.rotation.x = 0;
  16724. this.rotation.y = - Math.PI / 2;
  16725. this.rotation.z = 0;
  16726. this.rotationAutoUpdate = false;
  16727. };
  16728. THREE.CombinedCamera.prototype.toRightView = function() {
  16729. this.rotation.x = 0;
  16730. this.rotation.y = Math.PI / 2;
  16731. this.rotation.z = 0;
  16732. this.rotationAutoUpdate = false;
  16733. };
  16734. THREE.CombinedCamera.prototype.toTopView = function() {
  16735. this.rotation.x = - Math.PI / 2;
  16736. this.rotation.y = 0;
  16737. this.rotation.z = 0;
  16738. this.rotationAutoUpdate = false;
  16739. };
  16740. THREE.CombinedCamera.prototype.toBottomView = function() {
  16741. this.rotation.x = Math.PI / 2;
  16742. this.rotation.y = 0;
  16743. this.rotation.z = 0;
  16744. this.rotationAutoUpdate = false;
  16745. };
  16746. /**
  16747. * @author mrdoob / http://mrdoob.com/
  16748. * @author alteredq / http://alteredqualia.com/
  16749. * @author paulirish / http://paulirish.com/
  16750. */
  16751. THREE.FirstPersonControls = function ( object, domElement ) {
  16752. this.object = object;
  16753. this.target = new THREE.Vector3( 0, 0, 0 );
  16754. this.domElement = ( domElement !== undefined ) ? domElement : document;
  16755. this.movementSpeed = 1.0;
  16756. this.lookSpeed = 0.005;
  16757. this.lookVertical = true;
  16758. this.autoForward = false;
  16759. // this.invertVertical = false;
  16760. this.activeLook = true;
  16761. this.heightSpeed = false;
  16762. this.heightCoef = 1.0;
  16763. this.heightMin = 0.0;
  16764. this.heightMax = 1.0;
  16765. this.constrainVertical = false;
  16766. this.verticalMin = 0;
  16767. this.verticalMax = Math.PI;
  16768. this.autoSpeedFactor = 0.0;
  16769. this.mouseX = 0;
  16770. this.mouseY = 0;
  16771. this.lat = 0;
  16772. this.lon = 0;
  16773. this.phi = 0;
  16774. this.theta = 0;
  16775. this.moveForward = false;
  16776. this.moveBackward = false;
  16777. this.moveLeft = false;
  16778. this.moveRight = false;
  16779. this.freeze = false;
  16780. this.mouseDragOn = false;
  16781. this.viewHalfX = 0;
  16782. this.viewHalfY = 0;
  16783. if ( this.domElement !== document ) {
  16784. this.domElement.setAttribute( 'tabindex', -1 );
  16785. }
  16786. //
  16787. this.handleResize = function () {
  16788. if ( this.domElement === document ) {
  16789. this.viewHalfX = window.innerWidth / 2;
  16790. this.viewHalfY = window.innerHeight / 2;
  16791. } else {
  16792. this.viewHalfX = this.domElement.offsetWidth / 2;
  16793. this.viewHalfY = this.domElement.offsetHeight / 2;
  16794. }
  16795. };
  16796. this.onMouseDown = function ( event ) {
  16797. if ( this.domElement !== document ) {
  16798. this.domElement.focus();
  16799. }
  16800. event.preventDefault();
  16801. event.stopPropagation();
  16802. if ( this.activeLook ) {
  16803. switch ( event.button ) {
  16804. case 0: this.moveForward = true; break;
  16805. case 2: this.moveBackward = true; break;
  16806. }
  16807. }
  16808. this.mouseDragOn = true;
  16809. };
  16810. this.onMouseUp = function ( event ) {
  16811. event.preventDefault();
  16812. event.stopPropagation();
  16813. if ( this.activeLook ) {
  16814. switch ( event.button ) {
  16815. case 0: this.moveForward = false; break;
  16816. case 2: this.moveBackward = false; break;
  16817. }
  16818. }
  16819. this.mouseDragOn = false;
  16820. };
  16821. this.onMouseMove = function ( event ) {
  16822. if ( this.domElement === document ) {
  16823. this.mouseX = event.pageX - this.viewHalfX;
  16824. this.mouseY = event.pageY - this.viewHalfY;
  16825. } else {
  16826. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  16827. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  16828. }
  16829. };
  16830. this.onKeyDown = function ( event ) {
  16831. //event.preventDefault();
  16832. switch ( event.keyCode ) {
  16833. case 38: /*up*/
  16834. case 87: /*W*/ this.moveForward = true; break;
  16835. case 37: /*left*/
  16836. case 65: /*A*/ this.moveLeft = true; break;
  16837. case 40: /*down*/
  16838. case 83: /*S*/ this.moveBackward = true; break;
  16839. case 39: /*right*/
  16840. case 68: /*D*/ this.moveRight = true; break;
  16841. case 82: /*R*/ this.moveUp = true; break;
  16842. case 70: /*F*/ this.moveDown = true; break;
  16843. case 81: /*Q*/ this.freeze = !this.freeze; break;
  16844. }
  16845. };
  16846. this.onKeyUp = function ( event ) {
  16847. switch( event.keyCode ) {
  16848. case 38: /*up*/
  16849. case 87: /*W*/ this.moveForward = false; break;
  16850. case 37: /*left*/
  16851. case 65: /*A*/ this.moveLeft = false; break;
  16852. case 40: /*down*/
  16853. case 83: /*S*/ this.moveBackward = false; break;
  16854. case 39: /*right*/
  16855. case 68: /*D*/ this.moveRight = false; break;
  16856. case 82: /*R*/ this.moveUp = false; break;
  16857. case 70: /*F*/ this.moveDown = false; break;
  16858. }
  16859. };
  16860. this.update = function( delta ) {
  16861. var actualMoveSpeed = 0;
  16862. if ( this.freeze ) {
  16863. return;
  16864. } else {
  16865. if ( this.heightSpeed ) {
  16866. var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
  16867. var heightDelta = y - this.heightMin;
  16868. this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );
  16869. } else {
  16870. this.autoSpeedFactor = 0.0;
  16871. }
  16872. actualMoveSpeed = delta * this.movementSpeed;
  16873. if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
  16874. if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed );
  16875. if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed );
  16876. if ( this.moveRight ) this.object.translateX( actualMoveSpeed );
  16877. if ( this.moveUp ) this.object.translateY( actualMoveSpeed );
  16878. if ( this.moveDown ) this.object.translateY( - actualMoveSpeed );
  16879. var actualLookSpeed = delta * this.lookSpeed;
  16880. if ( !this.activeLook ) {
  16881. actualLookSpeed = 0;
  16882. }
  16883. this.lon += this.mouseX * actualLookSpeed;
  16884. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed; // * this.invertVertical?-1:1;
  16885. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  16886. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  16887. this.theta = this.lon * Math.PI / 180;
  16888. var targetPosition = this.target,
  16889. position = this.object.position;
  16890. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  16891. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  16892. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  16893. }
  16894. var verticalLookRatio = 1;
  16895. if ( this.constrainVertical ) {
  16896. verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );
  16897. }
  16898. this.lon += this.mouseX * actualLookSpeed;
  16899. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;
  16900. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  16901. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  16902. this.theta = this.lon * Math.PI / 180;
  16903. if ( this.constrainVertical ) {
  16904. this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );
  16905. }
  16906. var targetPosition = this.target,
  16907. position = this.object.position;
  16908. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  16909. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  16910. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  16911. this.object.lookAt( targetPosition );
  16912. };
  16913. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  16914. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  16915. this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
  16916. this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
  16917. this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
  16918. this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
  16919. function bind( scope, fn ) {
  16920. return function () {
  16921. fn.apply( scope, arguments );
  16922. };
  16923. };
  16924. this.handleResize();
  16925. };
  16926. /**
  16927. * @author alteredq / http://alteredqualia.com/
  16928. */
  16929. THREE.PathControls = function ( object, domElement ) {
  16930. this.object = object;
  16931. this.domElement = ( domElement !== undefined ) ? domElement : document;
  16932. this.id = "PathControls" + THREE.PathControlsIdCounter ++;
  16933. // API
  16934. this.duration = 10 * 1000; // milliseconds
  16935. this.waypoints = [];
  16936. this.useConstantSpeed = true;
  16937. this.resamplingCoef = 50;
  16938. this.debugPath = new THREE.Object3D();
  16939. this.debugDummy = new THREE.Object3D();
  16940. this.animationParent = new THREE.Object3D();
  16941. this.lookSpeed = 0.005;
  16942. this.lookVertical = true;
  16943. this.lookHorizontal = true;
  16944. this.verticalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  16945. this.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  16946. // internals
  16947. this.target = new THREE.Object3D();
  16948. this.mouseX = 0;
  16949. this.mouseY = 0;
  16950. this.lat = 0;
  16951. this.lon = 0;
  16952. this.phi = 0;
  16953. this.theta = 0;
  16954. var PI2 = Math.PI * 2,
  16955. PI180 = Math.PI / 180;
  16956. this.viewHalfX = 0;
  16957. this.viewHalfY = 0;
  16958. if ( this.domElement !== document ) {
  16959. this.domElement.setAttribute( 'tabindex', -1 );
  16960. }
  16961. // methods
  16962. this.handleResize = function () {
  16963. if ( this.domElement === document ) {
  16964. this.viewHalfX = window.innerWidth / 2;
  16965. this.viewHalfY = window.innerHeight / 2;
  16966. } else {
  16967. this.viewHalfX = this.domElement.offsetWidth / 2;
  16968. this.viewHalfY = this.domElement.offsetHeight / 2;
  16969. }
  16970. };
  16971. this.update = function ( delta ) {
  16972. var srcRange, dstRange;
  16973. if( this.lookHorizontal ) this.lon += this.mouseX * this.lookSpeed * delta;
  16974. if( this.lookVertical ) this.lat -= this.mouseY * this.lookSpeed * delta;
  16975. this.lon = Math.max( 0, Math.min( 360, this.lon ) );
  16976. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  16977. this.phi = ( 90 - this.lat ) * PI180;
  16978. this.theta = this.lon * PI180;
  16979. this.phi = normalize_angle_rad( this.phi );
  16980. // constrain vertical look angle
  16981. srcRange = this.verticalAngleMap.srcRange;
  16982. dstRange = this.verticalAngleMap.dstRange;
  16983. var tmpPhi = THREE.Math.mapLinear( this.phi, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  16984. var tmpPhiFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  16985. var tmpPhiNormalized = ( tmpPhi - dstRange[ 0 ] ) / tmpPhiFullRange;
  16986. this.phi = QuadraticEaseInOut( tmpPhiNormalized ) * tmpPhiFullRange + dstRange[ 0 ];
  16987. // constrain horizontal look angle
  16988. srcRange = this.horizontalAngleMap.srcRange;
  16989. dstRange = this.horizontalAngleMap.dstRange;
  16990. var tmpTheta = THREE.Math.mapLinear( this.theta, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  16991. var tmpThetaFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  16992. var tmpThetaNormalized = ( tmpTheta - dstRange[ 0 ] ) / tmpThetaFullRange;
  16993. this.theta = QuadraticEaseInOut( tmpThetaNormalized ) * tmpThetaFullRange + dstRange[ 0 ];
  16994. var targetPosition = this.target.position,
  16995. position = this.object.position;
  16996. targetPosition.x = 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  16997. targetPosition.y = 100 * Math.cos( this.phi );
  16998. targetPosition.z = 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  16999. this.object.lookAt( this.target.position );
  17000. };
  17001. this.onMouseMove = function ( event ) {
  17002. if ( this.domElement === document ) {
  17003. this.mouseX = event.pageX - this.viewHalfX;
  17004. this.mouseY = event.pageY - this.viewHalfY;
  17005. } else {
  17006. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  17007. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  17008. }
  17009. };
  17010. // utils
  17011. function normalize_angle_rad( a ) {
  17012. var b = a % PI2;
  17013. return b >= 0 ? b : b + PI2;
  17014. };
  17015. function distance( a, b ) {
  17016. var dx = a[ 0 ] - b[ 0 ],
  17017. dy = a[ 1 ] - b[ 1 ],
  17018. dz = a[ 2 ] - b[ 2 ];
  17019. return Math.sqrt( dx * dx + dy * dy + dz * dz );
  17020. };
  17021. function QuadraticEaseInOut ( k ) {
  17022. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  17023. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  17024. };
  17025. function bind( scope, fn ) {
  17026. return function () {
  17027. fn.apply( scope, arguments );
  17028. };
  17029. };
  17030. function initAnimationPath( parent, spline, name, duration ) {
  17031. var animationData = {
  17032. name: name,
  17033. fps: 0.6,
  17034. length: duration,
  17035. hierarchy: []
  17036. };
  17037. var i,
  17038. parentAnimation, childAnimation,
  17039. path = spline.getControlPointsArray(),
  17040. sl = spline.getLength(),
  17041. pl = path.length,
  17042. t = 0,
  17043. first = 0,
  17044. last = pl - 1;
  17045. parentAnimation = { parent: -1, keys: [] };
  17046. parentAnimation.keys[ first ] = { time: 0, pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  17047. parentAnimation.keys[ last ] = { time: duration, pos: path[ last ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  17048. for ( i = 1; i < pl - 1; i++ ) {
  17049. // real distance (approximation via linear segments)
  17050. t = duration * sl.chunks[ i ] / sl.total;
  17051. // equal distance
  17052. //t = duration * ( i / pl );
  17053. // linear distance
  17054. //t += duration * distance( path[ i ], path[ i - 1 ] ) / sl.total;
  17055. parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };
  17056. }
  17057. animationData.hierarchy[ 0 ] = parentAnimation;
  17058. THREE.AnimationHandler.add( animationData );
  17059. return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );
  17060. };
  17061. function createSplineGeometry( spline, n_sub ) {
  17062. var i, index, position,
  17063. geometry = new THREE.Geometry();
  17064. for ( i = 0; i < spline.points.length * n_sub; i ++ ) {
  17065. index = i / ( spline.points.length * n_sub );
  17066. position = spline.getPoint( index );
  17067. geometry.vertices[ i ] = new THREE.Vector3( position.x, position.y, position.z );
  17068. }
  17069. return geometry;
  17070. };
  17071. function createPath( parent, spline ) {
  17072. var lineGeo = createSplineGeometry( spline, 10 ),
  17073. particleGeo = createSplineGeometry( spline, 10 ),
  17074. lineMat = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 3 } ),
  17075. lineObj = new THREE.Line( lineGeo, lineMat ),
  17076. particleObj = new THREE.ParticleSystem( particleGeo, new THREE.ParticleBasicMaterial( { color: 0xffaa00, size: 3 } ) );
  17077. lineObj.scale.set( 1, 1, 1 );
  17078. parent.add( lineObj );
  17079. particleObj.scale.set( 1, 1, 1 );
  17080. parent.add( particleObj );
  17081. var waypoint,
  17082. geo = new THREE.SphereGeometry( 1, 16, 8 ),
  17083. mat = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  17084. for ( var i = 0; i < spline.points.length; i ++ ) {
  17085. waypoint = new THREE.Mesh( geo, mat );
  17086. waypoint.position.copy( spline.points[ i ] );
  17087. parent.add( waypoint );
  17088. }
  17089. };
  17090. this.init = function ( ) {
  17091. // constructor
  17092. this.spline = new THREE.Spline();
  17093. this.spline.initFromArray( this.waypoints );
  17094. if ( this.useConstantSpeed ) {
  17095. this.spline.reparametrizeByArcLength( this.resamplingCoef );
  17096. }
  17097. if ( this.createDebugDummy ) {
  17098. var dummyParentMaterial = new THREE.MeshLambertMaterial( { color: 0x0077ff } ),
  17099. dummyChildMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ),
  17100. dummyParentGeo = new THREE.CubeGeometry( 10, 10, 20 ),
  17101. dummyChildGeo = new THREE.CubeGeometry( 2, 2, 10 );
  17102. this.animationParent = new THREE.Mesh( dummyParentGeo, dummyParentMaterial );
  17103. var dummyChild = new THREE.Mesh( dummyChildGeo, dummyChildMaterial );
  17104. dummyChild.position.set( 0, 10, 0 );
  17105. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  17106. this.animationParent.add( this.object );
  17107. this.animationParent.add( this.target );
  17108. this.animationParent.add( dummyChild );
  17109. } else {
  17110. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  17111. this.animationParent.add( this.target );
  17112. this.animationParent.add( this.object );
  17113. }
  17114. if ( this.createDebugPath ) {
  17115. createPath( this.debugPath, this.spline );
  17116. }
  17117. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  17118. };
  17119. this.handleResize();
  17120. };
  17121. THREE.PathControlsIdCounter = 0;
  17122. /**
  17123. * @author James Baicoianu / http://www.baicoianu.com/
  17124. */
  17125. THREE.FlyControls = function ( object, domElement ) {
  17126. this.object = object;
  17127. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17128. if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );
  17129. // API
  17130. this.movementSpeed = 1.0;
  17131. this.rollSpeed = 0.005;
  17132. this.dragToLook = false;
  17133. this.autoForward = false;
  17134. // disable default target object behavior
  17135. this.object.useQuaternion = true;
  17136. // internals
  17137. this.tmpQuaternion = new THREE.Quaternion();
  17138. this.mouseStatus = 0;
  17139. this.moveState = { up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0 };
  17140. this.moveVector = new THREE.Vector3( 0, 0, 0 );
  17141. this.rotationVector = new THREE.Vector3( 0, 0, 0 );
  17142. this.handleEvent = function ( event ) {
  17143. if ( typeof this[ event.type ] == 'function' ) {
  17144. this[ event.type ]( event );
  17145. }
  17146. };
  17147. this.keydown = function( event ) {
  17148. if ( event.altKey ) {
  17149. return;
  17150. }
  17151. //event.preventDefault();
  17152. switch ( event.keyCode ) {
  17153. case 16: /* shift */ this.movementSpeedMultiplier = .1; break;
  17154. case 87: /*W*/ this.moveState.forward = 1; break;
  17155. case 83: /*S*/ this.moveState.back = 1; break;
  17156. case 65: /*A*/ this.moveState.left = 1; break;
  17157. case 68: /*D*/ this.moveState.right = 1; break;
  17158. case 82: /*R*/ this.moveState.up = 1; break;
  17159. case 70: /*F*/ this.moveState.down = 1; break;
  17160. case 38: /*up*/ this.moveState.pitchUp = 1; break;
  17161. case 40: /*down*/ this.moveState.pitchDown = 1; break;
  17162. case 37: /*left*/ this.moveState.yawLeft = 1; break;
  17163. case 39: /*right*/ this.moveState.yawRight = 1; break;
  17164. case 81: /*Q*/ this.moveState.rollLeft = 1; break;
  17165. case 69: /*E*/ this.moveState.rollRight = 1; break;
  17166. }
  17167. this.updateMovementVector();
  17168. this.updateRotationVector();
  17169. };
  17170. this.keyup = function( event ) {
  17171. switch( event.keyCode ) {
  17172. case 16: /* shift */ this.movementSpeedMultiplier = 1; break;
  17173. case 87: /*W*/ this.moveState.forward = 0; break;
  17174. case 83: /*S*/ this.moveState.back = 0; break;
  17175. case 65: /*A*/ this.moveState.left = 0; break;
  17176. case 68: /*D*/ this.moveState.right = 0; break;
  17177. case 82: /*R*/ this.moveState.up = 0; break;
  17178. case 70: /*F*/ this.moveState.down = 0; break;
  17179. case 38: /*up*/ this.moveState.pitchUp = 0; break;
  17180. case 40: /*down*/ this.moveState.pitchDown = 0; break;
  17181. case 37: /*left*/ this.moveState.yawLeft = 0; break;
  17182. case 39: /*right*/ this.moveState.yawRight = 0; break;
  17183. case 81: /*Q*/ this.moveState.rollLeft = 0; break;
  17184. case 69: /*E*/ this.moveState.rollRight = 0; break;
  17185. }
  17186. this.updateMovementVector();
  17187. this.updateRotationVector();
  17188. };
  17189. this.mousedown = function( event ) {
  17190. if ( this.domElement !== document ) {
  17191. this.domElement.focus();
  17192. }
  17193. event.preventDefault();
  17194. event.stopPropagation();
  17195. if ( this.dragToLook ) {
  17196. this.mouseStatus ++;
  17197. } else {
  17198. switch ( event.button ) {
  17199. case 0: this.object.moveForward = true; break;
  17200. case 2: this.object.moveBackward = true; break;
  17201. }
  17202. }
  17203. };
  17204. this.mousemove = function( event ) {
  17205. if ( !this.dragToLook || this.mouseStatus > 0 ) {
  17206. var container = this.getContainerDimensions();
  17207. var halfWidth = container.size[ 0 ] / 2;
  17208. var halfHeight = container.size[ 1 ] / 2;
  17209. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  17210. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  17211. this.updateRotationVector();
  17212. }
  17213. };
  17214. this.mouseup = function( event ) {
  17215. event.preventDefault();
  17216. event.stopPropagation();
  17217. if ( this.dragToLook ) {
  17218. this.mouseStatus --;
  17219. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  17220. } else {
  17221. switch ( event.button ) {
  17222. case 0: this.moveForward = false; break;
  17223. case 2: this.moveBackward = false; break;
  17224. }
  17225. }
  17226. this.updateRotationVector();
  17227. };
  17228. this.update = function( delta ) {
  17229. var moveMult = delta * this.movementSpeed;
  17230. var rotMult = delta * this.rollSpeed;
  17231. this.object.translateX( this.moveVector.x * moveMult );
  17232. this.object.translateY( this.moveVector.y * moveMult );
  17233. this.object.translateZ( this.moveVector.z * moveMult );
  17234. this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
  17235. this.object.quaternion.multiplySelf( this.tmpQuaternion );
  17236. this.object.matrix.setPosition( this.object.position );
  17237. this.object.matrix.setRotationFromQuaternion( this.object.quaternion );
  17238. this.object.matrixWorldNeedsUpdate = true;
  17239. };
  17240. this.updateMovementVector = function() {
  17241. var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;
  17242. this.moveVector.x = ( -this.moveState.left + this.moveState.right );
  17243. this.moveVector.y = ( -this.moveState.down + this.moveState.up );
  17244. this.moveVector.z = ( -forward + this.moveState.back );
  17245. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  17246. };
  17247. this.updateRotationVector = function() {
  17248. this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
  17249. this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
  17250. this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
  17251. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  17252. };
  17253. this.getContainerDimensions = function() {
  17254. if ( this.domElement != document ) {
  17255. return {
  17256. size : [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  17257. offset : [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  17258. };
  17259. } else {
  17260. return {
  17261. size : [ window.innerWidth, window.innerHeight ],
  17262. offset : [ 0, 0 ]
  17263. };
  17264. }
  17265. };
  17266. function bind( scope, fn ) {
  17267. return function () {
  17268. fn.apply( scope, arguments );
  17269. };
  17270. };
  17271. this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
  17272. this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
  17273. this.domElement.addEventListener( 'mouseup', bind( this, this.mouseup ), false );
  17274. this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
  17275. this.domElement.addEventListener( 'keyup', bind( this, this.keyup ), false );
  17276. this.updateMovementVector();
  17277. this.updateRotationVector();
  17278. };
  17279. /**
  17280. * @author mikael emtinger / http://gomo.se/
  17281. * @author alteredq / http://alteredqualia.com/
  17282. */
  17283. THREE.RollControls = function ( object, domElement ) {
  17284. this.object = object;
  17285. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17286. // API
  17287. this.mouseLook = true;
  17288. this.autoForward = false;
  17289. this.lookSpeed = 1;
  17290. this.movementSpeed = 1;
  17291. this.rollSpeed = 1;
  17292. this.constrainVertical = [ -0.9, 0.9 ];
  17293. // disable default target object behavior
  17294. this.object.matrixAutoUpdate = false;
  17295. // internals
  17296. this.forward = new THREE.Vector3( 0, 0, 1 );
  17297. this.roll = 0;
  17298. var xTemp = new THREE.Vector3();
  17299. var yTemp = new THREE.Vector3();
  17300. var zTemp = new THREE.Vector3();
  17301. var rollMatrix = new THREE.Matrix4();
  17302. var doRoll = false, rollDirection = 1, forwardSpeed = 0, sideSpeed = 0, upSpeed = 0;
  17303. var mouseX = 0, mouseY = 0;
  17304. var windowHalfX = 0;
  17305. var windowHalfY = 0;
  17306. //
  17307. this.handleResize = function () {
  17308. windowHalfX = window.innerWidth / 2;
  17309. windowHalfY = window.innerHeight / 2;
  17310. };
  17311. // custom update
  17312. this.update = function ( delta ) {
  17313. if ( this.mouseLook ) {
  17314. var actualLookSpeed = delta * this.lookSpeed;
  17315. this.rotateHorizontally( actualLookSpeed * mouseX );
  17316. this.rotateVertically( actualLookSpeed * mouseY );
  17317. }
  17318. var actualSpeed = delta * this.movementSpeed;
  17319. var forwardOrAuto = ( forwardSpeed > 0 || ( this.autoForward && ! ( forwardSpeed < 0 ) ) ) ? 1 : forwardSpeed;
  17320. this.object.translateZ( -actualSpeed * forwardOrAuto );
  17321. this.object.translateX( actualSpeed * sideSpeed );
  17322. this.object.translateY( actualSpeed * upSpeed );
  17323. if( doRoll ) {
  17324. this.roll += this.rollSpeed * delta * rollDirection;
  17325. }
  17326. // cap forward up / down
  17327. if( this.forward.y > this.constrainVertical[ 1 ] ) {
  17328. this.forward.y = this.constrainVertical[ 1 ];
  17329. this.forward.normalize();
  17330. } else if( this.forward.y < this.constrainVertical[ 0 ] ) {
  17331. this.forward.y = this.constrainVertical[ 0 ];
  17332. this.forward.normalize();
  17333. }
  17334. // construct unrolled camera matrix
  17335. zTemp.copy( this.forward );
  17336. yTemp.set( 0, 1, 0 );
  17337. xTemp.cross( yTemp, zTemp ).normalize();
  17338. yTemp.cross( zTemp, xTemp ).normalize();
  17339. this.object.matrix.elements[0] = xTemp.x; this.object.matrix.elements[4] = yTemp.x; this.object.matrix.elements[8] = zTemp.x;
  17340. this.object.matrix.elements[1] = xTemp.y; this.object.matrix.elements[5] = yTemp.y; this.object.matrix.elements[9] = zTemp.y;
  17341. this.object.matrix.elements[2] = xTemp.z; this.object.matrix.elements[6] = yTemp.z; this.object.matrix.elements[10] = zTemp.z;
  17342. // calculate roll matrix
  17343. rollMatrix.identity();
  17344. rollMatrix.elements[0] = Math.cos( this.roll ); rollMatrix.elements[4] = -Math.sin( this.roll );
  17345. rollMatrix.elements[1] = Math.sin( this.roll ); rollMatrix.elements[5] = Math.cos( this.roll );
  17346. // multiply camera with roll
  17347. this.object.matrix.multiplySelf( rollMatrix );
  17348. this.object.matrixWorldNeedsUpdate = true;
  17349. // set position
  17350. this.object.matrix.elements[12] = this.object.position.x;
  17351. this.object.matrix.elements[13] = this.object.position.y;
  17352. this.object.matrix.elements[14] = this.object.position.z;
  17353. };
  17354. this.translateX = function ( distance ) {
  17355. this.object.position.x += this.object.matrix.elements[0] * distance;
  17356. this.object.position.y += this.object.matrix.elements[1] * distance;
  17357. this.object.position.z += this.object.matrix.elements[2] * distance;
  17358. };
  17359. this.translateY = function ( distance ) {
  17360. this.object.position.x += this.object.matrix.elements[4] * distance;
  17361. this.object.position.y += this.object.matrix.elements[5] * distance;
  17362. this.object.position.z += this.object.matrix.elements[6] * distance;
  17363. };
  17364. this.translateZ = function ( distance ) {
  17365. this.object.position.x -= this.object.matrix.elements[8] * distance;
  17366. this.object.position.y -= this.object.matrix.elements[9] * distance;
  17367. this.object.position.z -= this.object.matrix.elements[10] * distance;
  17368. };
  17369. this.rotateHorizontally = function ( amount ) {
  17370. // please note that the amount is NOT degrees, but a scale value
  17371. xTemp.set( this.object.matrix.elements[0], this.object.matrix.elements[1], this.object.matrix.elements[2] );
  17372. xTemp.multiplyScalar( amount );
  17373. this.forward.subSelf( xTemp );
  17374. this.forward.normalize();
  17375. };
  17376. this.rotateVertically = function ( amount ) {
  17377. // please note that the amount is NOT degrees, but a scale value
  17378. yTemp.set( this.object.matrix.elements[4], this.object.matrix.elements[5], this.object.matrix.elements[6] );
  17379. yTemp.multiplyScalar( amount );
  17380. this.forward.addSelf( yTemp );
  17381. this.forward.normalize();
  17382. };
  17383. function onKeyDown( event ) {
  17384. //event.preventDefault();
  17385. switch ( event.keyCode ) {
  17386. case 38: /*up*/
  17387. case 87: /*W*/ forwardSpeed = 1; break;
  17388. case 37: /*left*/
  17389. case 65: /*A*/ sideSpeed = -1; break;
  17390. case 40: /*down*/
  17391. case 83: /*S*/ forwardSpeed = -1; break;
  17392. case 39: /*right*/
  17393. case 68: /*D*/ sideSpeed = 1; break;
  17394. case 81: /*Q*/ doRoll = true; rollDirection = 1; break;
  17395. case 69: /*E*/ doRoll = true; rollDirection = -1; break;
  17396. case 82: /*R*/ upSpeed = 1; break;
  17397. case 70: /*F*/ upSpeed = -1; break;
  17398. }
  17399. };
  17400. function onKeyUp( event ) {
  17401. switch( event.keyCode ) {
  17402. case 38: /*up*/
  17403. case 87: /*W*/ forwardSpeed = 0; break;
  17404. case 37: /*left*/
  17405. case 65: /*A*/ sideSpeed = 0; break;
  17406. case 40: /*down*/
  17407. case 83: /*S*/ forwardSpeed = 0; break;
  17408. case 39: /*right*/
  17409. case 68: /*D*/ sideSpeed = 0; break;
  17410. case 81: /*Q*/ doRoll = false; break;
  17411. case 69: /*E*/ doRoll = false; break;
  17412. case 82: /*R*/ upSpeed = 0; break;
  17413. case 70: /*F*/ upSpeed = 0; break;
  17414. }
  17415. };
  17416. function onMouseMove( event ) {
  17417. mouseX = ( event.clientX - windowHalfX ) / window.innerWidth;
  17418. mouseY = ( event.clientY - windowHalfY ) / window.innerHeight;
  17419. };
  17420. function onMouseDown ( event ) {
  17421. event.preventDefault();
  17422. event.stopPropagation();
  17423. switch ( event.button ) {
  17424. case 0: forwardSpeed = 1; break;
  17425. case 2: forwardSpeed = -1; break;
  17426. }
  17427. };
  17428. function onMouseUp ( event ) {
  17429. event.preventDefault();
  17430. event.stopPropagation();
  17431. switch ( event.button ) {
  17432. case 0: forwardSpeed = 0; break;
  17433. case 2: forwardSpeed = 0; break;
  17434. }
  17435. };
  17436. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17437. this.domElement.addEventListener( 'mousemove', onMouseMove, false );
  17438. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  17439. this.domElement.addEventListener( 'mouseup', onMouseUp, false );
  17440. this.domElement.addEventListener( 'keydown', onKeyDown, false );
  17441. this.domElement.addEventListener( 'keyup', onKeyUp, false );
  17442. this.handleResize();
  17443. };
  17444. /**
  17445. * @author Eberhard Graether / http://egraether.com/
  17446. */
  17447. THREE.TrackballControls = function ( object, domElement ) {
  17448. THREE.EventTarget.call( this );
  17449. var _this = this,
  17450. STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };
  17451. this.object = object;
  17452. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17453. // API
  17454. this.enabled = true;
  17455. this.screen = { width: 0, height: 0, offsetLeft: 0, offsetTop: 0 };
  17456. this.radius = ( this.screen.width + this.screen.height ) / 4;
  17457. this.rotateSpeed = 1.0;
  17458. this.zoomSpeed = 1.2;
  17459. this.panSpeed = 0.3;
  17460. this.noRotate = false;
  17461. this.noZoom = false;
  17462. this.noPan = false;
  17463. this.staticMoving = false;
  17464. this.dynamicDampingFactor = 0.2;
  17465. this.minDistance = 0;
  17466. this.maxDistance = Infinity;
  17467. this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
  17468. // internals
  17469. this.target = new THREE.Vector3();
  17470. var lastPosition = new THREE.Vector3();
  17471. var _keyPressed = false,
  17472. _state = STATE.NONE,
  17473. _eye = new THREE.Vector3(),
  17474. _rotateStart = new THREE.Vector3(),
  17475. _rotateEnd = new THREE.Vector3(),
  17476. _zoomStart = new THREE.Vector2(),
  17477. _zoomEnd = new THREE.Vector2(),
  17478. _panStart = new THREE.Vector2(),
  17479. _panEnd = new THREE.Vector2();
  17480. // events
  17481. var changeEvent = { type: 'change' };
  17482. // methods
  17483. this.handleResize = function () {
  17484. this.screen.width = window.innerWidth;
  17485. this.screen.height = window.innerHeight;
  17486. this.screen.offsetLeft = 0;
  17487. this.screen.offsetTop = 0;
  17488. this.radius = ( this.screen.width + this.screen.height ) / 4;
  17489. };
  17490. this.handleEvent = function ( event ) {
  17491. if ( typeof this[ event.type ] == 'function' ) {
  17492. this[ event.type ]( event );
  17493. }
  17494. };
  17495. this.getMouseOnScreen = function ( clientX, clientY ) {
  17496. return new THREE.Vector2(
  17497. ( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
  17498. ( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
  17499. );
  17500. };
  17501. this.getMouseProjectionOnBall = function ( clientX, clientY ) {
  17502. var mouseOnBall = new THREE.Vector3(
  17503. ( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
  17504. ( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
  17505. 0.0
  17506. );
  17507. var length = mouseOnBall.length();
  17508. if ( length > 1.0 ) {
  17509. mouseOnBall.normalize();
  17510. } else {
  17511. mouseOnBall.z = Math.sqrt( 1.0 - length * length );
  17512. }
  17513. _eye.copy( _this.object.position ).subSelf( _this.target );
  17514. var projection = _this.object.up.clone().setLength( mouseOnBall.y );
  17515. projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
  17516. projection.addSelf( _eye.setLength( mouseOnBall.z ) );
  17517. return projection;
  17518. };
  17519. this.rotateCamera = function () {
  17520. var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
  17521. if ( angle ) {
  17522. var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
  17523. quaternion = new THREE.Quaternion();
  17524. angle *= _this.rotateSpeed;
  17525. quaternion.setFromAxisAngle( axis, -angle );
  17526. quaternion.multiplyVector3( _eye );
  17527. quaternion.multiplyVector3( _this.object.up );
  17528. quaternion.multiplyVector3( _rotateEnd );
  17529. if ( _this.staticMoving ) {
  17530. _rotateStart = _rotateEnd;
  17531. } else {
  17532. quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
  17533. quaternion.multiplyVector3( _rotateStart );
  17534. }
  17535. }
  17536. };
  17537. this.zoomCamera = function () {
  17538. var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
  17539. if ( factor !== 1.0 && factor > 0.0 ) {
  17540. _eye.multiplyScalar( factor );
  17541. if ( _this.staticMoving ) {
  17542. _zoomStart = _zoomEnd;
  17543. } else {
  17544. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  17545. }
  17546. }
  17547. };
  17548. this.panCamera = function () {
  17549. var mouseChange = _panEnd.clone().subSelf( _panStart );
  17550. if ( mouseChange.lengthSq() ) {
  17551. mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
  17552. var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
  17553. pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );
  17554. _this.object.position.addSelf( pan );
  17555. _this.target.addSelf( pan );
  17556. if ( _this.staticMoving ) {
  17557. _panStart = _panEnd;
  17558. } else {
  17559. _panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
  17560. }
  17561. }
  17562. };
  17563. this.checkDistances = function () {
  17564. if ( !_this.noZoom || !_this.noPan ) {
  17565. if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {
  17566. _this.object.position.setLength( _this.maxDistance );
  17567. }
  17568. if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
  17569. _this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );
  17570. }
  17571. }
  17572. };
  17573. this.update = function () {
  17574. _eye.copy( _this.object.position ).subSelf( _this.target );
  17575. if ( !_this.noRotate ) {
  17576. _this.rotateCamera();
  17577. }
  17578. if ( !_this.noZoom ) {
  17579. _this.zoomCamera();
  17580. }
  17581. if ( !_this.noPan ) {
  17582. _this.panCamera();
  17583. }
  17584. _this.object.position.add( _this.target, _eye );
  17585. _this.checkDistances();
  17586. _this.object.lookAt( _this.target );
  17587. if ( lastPosition.distanceToSquared( _this.object.position ) > 0 ) {
  17588. _this.dispatchEvent( changeEvent );
  17589. lastPosition.copy( _this.object.position );
  17590. }
  17591. };
  17592. // listeners
  17593. function keydown( event ) {
  17594. if ( ! _this.enabled ) return;
  17595. //event.preventDefault();
  17596. if ( _state !== STATE.NONE ) {
  17597. return;
  17598. } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
  17599. _state = STATE.ROTATE;
  17600. } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
  17601. _state = STATE.ZOOM;
  17602. } else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
  17603. _state = STATE.PAN;
  17604. }
  17605. if ( _state !== STATE.NONE ) {
  17606. _keyPressed = true;
  17607. }
  17608. }
  17609. function keyup( event ) {
  17610. if ( ! _this.enabled ) return;
  17611. if ( _state !== STATE.NONE ) {
  17612. _state = STATE.NONE;
  17613. }
  17614. }
  17615. function mousedown( event ) {
  17616. if ( ! _this.enabled ) return;
  17617. event.preventDefault();
  17618. event.stopPropagation();
  17619. if ( _state === STATE.NONE ) {
  17620. _state = event.button;
  17621. if ( _state === STATE.ROTATE && !_this.noRotate ) {
  17622. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  17623. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  17624. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17625. } else if ( !this.noPan ) {
  17626. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17627. }
  17628. }
  17629. }
  17630. function mousemove( event ) {
  17631. if ( ! _this.enabled ) return;
  17632. if ( _keyPressed ) {
  17633. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  17634. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17635. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17636. _keyPressed = false;
  17637. }
  17638. if ( _state === STATE.NONE ) {
  17639. return;
  17640. } else if ( _state === STATE.ROTATE && !_this.noRotate ) {
  17641. _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  17642. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  17643. _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17644. } else if ( _state === STATE.PAN && !_this.noPan ) {
  17645. _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17646. }
  17647. }
  17648. function mouseup( event ) {
  17649. if ( ! _this.enabled ) return;
  17650. event.preventDefault();
  17651. event.stopPropagation();
  17652. _state = STATE.NONE;
  17653. }
  17654. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17655. this.domElement.addEventListener( 'mousemove', mousemove, false );
  17656. this.domElement.addEventListener( 'mousedown', mousedown, false );
  17657. this.domElement.addEventListener( 'mouseup', mouseup, false );
  17658. // this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false );
  17659. // this.domElement.addEventListener( 'mousewheel', mousewheel, false );
  17660. window.addEventListener( 'keydown', keydown, false );
  17661. window.addEventListener( 'keyup', keyup, false );
  17662. this.handleResize();
  17663. };
  17664. /**
  17665. * @author qiao / https://github.com/qiao
  17666. * @author mrdoob / http://mrdoob.com
  17667. * @author alteredq / http://alteredqualia.com/
  17668. */
  17669. THREE.OrbitControls = function ( object, domElement ) {
  17670. THREE.EventTarget.call( this );
  17671. this.object = object;
  17672. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17673. // API
  17674. this.center = new THREE.Vector3();
  17675. this.userZoom = true;
  17676. this.userZoomSpeed = 1.0;
  17677. this.userRotate = true;
  17678. this.userRotateSpeed = 1.0;
  17679. this.autoRotate = false;
  17680. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  17681. // internals
  17682. var scope = this;
  17683. var EPS = 0.000001;
  17684. var PIXELS_PER_ROUND = 1800;
  17685. var rotateStart = new THREE.Vector2();
  17686. var rotateEnd = new THREE.Vector2();
  17687. var rotateDelta = new THREE.Vector2();
  17688. var zoomStart = new THREE.Vector2();
  17689. var zoomEnd = new THREE.Vector2();
  17690. var zoomDelta = new THREE.Vector2();
  17691. var phiDelta = 0;
  17692. var thetaDelta = 0;
  17693. var scale = 1;
  17694. var lastPosition = new THREE.Vector3();
  17695. var STATE = { NONE : -1, ROTATE : 0, ZOOM : 1 };
  17696. var state = STATE.NONE;
  17697. // events
  17698. var changeEvent = { type: 'change' };
  17699. this.rotateLeft = function ( angle ) {
  17700. if ( angle === undefined ) {
  17701. angle = getAutoRotationAngle();
  17702. }
  17703. thetaDelta -= angle;
  17704. };
  17705. this.rotateRight = function ( angle ) {
  17706. if ( angle === undefined ) {
  17707. angle = getAutoRotationAngle();
  17708. }
  17709. thetaDelta += angle;
  17710. };
  17711. this.rotateUp = function ( angle ) {
  17712. if ( angle === undefined ) {
  17713. angle = getAutoRotationAngle();
  17714. }
  17715. phiDelta -= angle;
  17716. };
  17717. this.rotateDown = function ( angle ) {
  17718. if ( angle === undefined ) {
  17719. angle = getAutoRotationAngle();
  17720. }
  17721. phiDelta += angle;
  17722. };
  17723. this.zoomIn = function ( zoomScale ) {
  17724. if ( zoomScale === undefined ) {
  17725. zoomScale = getZoomScale();
  17726. }
  17727. scale /= zoomScale;
  17728. };
  17729. this.zoomOut = function ( zoomScale ) {
  17730. if ( zoomScale === undefined ) {
  17731. zoomScale = getZoomScale();
  17732. }
  17733. scale *= zoomScale;
  17734. };
  17735. this.update = function () {
  17736. var position = this.object.position;
  17737. var offset = position.clone().subSelf( this.center )
  17738. // angle from z-axis around y-axis
  17739. var theta = Math.atan2( offset.x, offset.z );
  17740. // angle from y-axis
  17741. var phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y );
  17742. if ( this.autoRotate ) {
  17743. this.rotateLeft( getAutoRotationAngle() );
  17744. }
  17745. theta += thetaDelta;
  17746. phi += phiDelta;
  17747. // restrict phi to be betwee EPS and PI-EPS
  17748. phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) );
  17749. var radius = offset.length();
  17750. offset.x = radius * Math.sin( phi ) * Math.sin( theta );
  17751. offset.y = radius * Math.cos( phi );
  17752. offset.z = radius * Math.sin( phi ) * Math.cos( theta );
  17753. offset.multiplyScalar( scale );
  17754. position.copy( this.center ).addSelf( offset );
  17755. this.object.lookAt( this.center );
  17756. thetaDelta = 0;
  17757. phiDelta = 0;
  17758. scale = 1;
  17759. if ( lastPosition.distanceTo( this.object.position ) > 0 ) {
  17760. this.dispatchEvent( changeEvent );
  17761. lastPosition.copy( this.object.position );
  17762. }
  17763. };
  17764. function getAutoRotationAngle() {
  17765. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  17766. }
  17767. function getZoomScale() {
  17768. return Math.pow( 0.95, scope.userZoomSpeed );
  17769. }
  17770. function onMouseDown( event ) {
  17771. if ( !scope.userRotate ) return;
  17772. event.preventDefault();
  17773. if ( event.button === 0 || event.button === 2 ) {
  17774. state = STATE.ROTATE;
  17775. rotateStart.set( event.clientX, event.clientY );
  17776. } else if ( event.button === 1 ) {
  17777. state = STATE.ZOOM;
  17778. zoomStart.set( event.clientX, event.clientY );
  17779. }
  17780. document.addEventListener( 'mousemove', onMouseMove, false );
  17781. document.addEventListener( 'mouseup', onMouseUp, false );
  17782. }
  17783. function onMouseMove( event ) {
  17784. event.preventDefault();
  17785. if ( state === STATE.ROTATE ) {
  17786. rotateEnd.set( event.clientX, event.clientY );
  17787. rotateDelta.sub( rotateEnd, rotateStart );
  17788. scope.rotateLeft( 2 * Math.PI * rotateDelta.x / PIXELS_PER_ROUND * scope.userRotateSpeed );
  17789. scope.rotateUp( 2 * Math.PI * rotateDelta.y / PIXELS_PER_ROUND * scope.userRotateSpeed );
  17790. rotateStart.copy( rotateEnd );
  17791. } else if ( state === STATE.ZOOM ) {
  17792. zoomEnd.set( event.clientX, event.clientY );
  17793. zoomDelta.sub( zoomEnd, zoomStart );
  17794. if ( zoomDelta.y > 0 ) {
  17795. scope.zoomIn();
  17796. } else {
  17797. scope.zoomOut();
  17798. }
  17799. zoomStart.copy( zoomEnd );
  17800. }
  17801. }
  17802. function onMouseUp( event ) {
  17803. if ( ! scope.userRotate ) return;
  17804. document.removeEventListener( 'mousemove', onMouseMove, false );
  17805. document.removeEventListener( 'mouseup', onMouseUp, false );
  17806. state = STATE.NONE;
  17807. }
  17808. function onMouseWheel( event ) {
  17809. if ( ! scope.userZoom ) return;
  17810. if ( event.wheelDelta > 0 ) {
  17811. scope.zoomOut();
  17812. } else {
  17813. scope.zoomIn();
  17814. }
  17815. }
  17816. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17817. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  17818. this.domElement.addEventListener( 'mousewheel', onMouseWheel, false );
  17819. };
  17820. /**
  17821. * @author hughes
  17822. */
  17823. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  17824. THREE.Geometry.call( this );
  17825. radius = radius || 50;
  17826. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17827. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17828. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17829. var i, uvs = [],
  17830. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  17831. this.vertices.push(center);
  17832. uvs.push( centerUV );
  17833. for ( i = 0; i <= segments; i ++ ) {
  17834. var vertex = new THREE.Vector3();
  17835. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  17836. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  17837. this.vertices.push( vertex );
  17838. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  17839. }
  17840. var n = new THREE.Vector3( 0, 0, -1 );
  17841. for ( i = 1; i <= segments; i ++ ) {
  17842. var v1 = i;
  17843. var v2 = i + 1 ;
  17844. var v3 = 0;
  17845. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  17846. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  17847. }
  17848. this.computeCentroids();
  17849. this.computeFaceNormals();
  17850. this.boundingSphere = { radius: radius };
  17851. };
  17852. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17853. /**
  17854. * @author mrdoob / http://mrdoob.com/
  17855. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  17856. */
  17857. THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
  17858. THREE.Geometry.call( this );
  17859. var scope = this,
  17860. width_half = width / 2,
  17861. height_half = height / 2,
  17862. depth_half = depth / 2;
  17863. var mpx, mpy, mpz, mnx, mny, mnz;
  17864. if ( materials !== undefined ) {
  17865. if ( materials instanceof Array ) {
  17866. this.materials = materials;
  17867. } else {
  17868. this.materials = [];
  17869. for ( var i = 0; i < 6; i ++ ) {
  17870. this.materials.push( materials );
  17871. }
  17872. }
  17873. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  17874. } else {
  17875. this.materials = [];
  17876. }
  17877. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  17878. if ( sides != undefined ) {
  17879. for ( var s in sides ) {
  17880. if ( this.sides[ s ] !== undefined ) {
  17881. this.sides[ s ] = sides[ s ];
  17882. }
  17883. }
  17884. }
  17885. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
  17886. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, mnx ); // nx
  17887. this.sides.py && buildPlane( 'x', 'z', 1, 1, width, depth, height_half, mpy ); // py
  17888. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, mny ); // ny
  17889. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, mpz ); // pz
  17890. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz
  17891. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  17892. var w, ix, iy,
  17893. gridX = segmentsWidth || 1,
  17894. gridY = segmentsHeight || 1,
  17895. width_half = width / 2,
  17896. height_half = height / 2,
  17897. offset = scope.vertices.length;
  17898. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  17899. w = 'z';
  17900. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  17901. w = 'y';
  17902. gridY = segmentsDepth || 1;
  17903. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  17904. w = 'x';
  17905. gridX = segmentsDepth || 1;
  17906. }
  17907. var gridX1 = gridX + 1,
  17908. gridY1 = gridY + 1,
  17909. segment_width = width / gridX,
  17910. segment_height = height / gridY,
  17911. normal = new THREE.Vector3();
  17912. normal[ w ] = depth > 0 ? 1 : - 1;
  17913. for ( iy = 0; iy < gridY1; iy ++ ) {
  17914. for ( ix = 0; ix < gridX1; ix ++ ) {
  17915. var vector = new THREE.Vector3();
  17916. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  17917. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  17918. vector[ w ] = depth;
  17919. scope.vertices.push( vector );
  17920. }
  17921. }
  17922. for ( iy = 0; iy < gridY; iy++ ) {
  17923. for ( ix = 0; ix < gridX; ix++ ) {
  17924. var a = ix + gridX1 * iy;
  17925. var b = ix + gridX1 * ( iy + 1 );
  17926. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  17927. var d = ( ix + 1 ) + gridX1 * iy;
  17928. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  17929. face.normal.copy( normal );
  17930. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  17931. face.materialIndex = material;
  17932. scope.faces.push( face );
  17933. scope.faceVertexUvs[ 0 ].push( [
  17934. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  17935. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  17936. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  17937. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  17938. ] );
  17939. }
  17940. }
  17941. }
  17942. this.computeCentroids();
  17943. this.mergeVertices();
  17944. };
  17945. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17946. /**
  17947. * @author mrdoob / http://mrdoob.com/
  17948. */
  17949. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded ) {
  17950. THREE.Geometry.call( this );
  17951. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  17952. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  17953. height = height !== undefined ? height : 100;
  17954. var heightHalf = height / 2;
  17955. var segmentsX = segmentsRadius || 8;
  17956. var segmentsY = segmentsHeight || 1;
  17957. var x, y, vertices = [], uvs = [];
  17958. for ( y = 0; y <= segmentsY; y ++ ) {
  17959. var verticesRow = [];
  17960. var uvsRow = [];
  17961. var v = y / segmentsY;
  17962. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17963. for ( x = 0; x <= segmentsX; x ++ ) {
  17964. var u = x / segmentsX;
  17965. var vertex = new THREE.Vector3();
  17966. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  17967. vertex.y = - v * height + heightHalf;
  17968. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  17969. this.vertices.push( vertex );
  17970. verticesRow.push( this.vertices.length - 1 );
  17971. uvsRow.push( new THREE.UV( u, 1 - v ) );
  17972. }
  17973. vertices.push( verticesRow );
  17974. uvs.push( uvsRow );
  17975. }
  17976. var tanTheta = ( radiusBottom - radiusTop ) / height;
  17977. var na, nb;
  17978. for ( x = 0; x < segmentsX; x ++ ) {
  17979. if ( radiusTop !== 0 ) {
  17980. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  17981. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  17982. } else {
  17983. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  17984. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  17985. }
  17986. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  17987. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  17988. for ( y = 0; y < segmentsY; y ++ ) {
  17989. var v1 = vertices[ y ][ x ];
  17990. var v2 = vertices[ y + 1 ][ x ];
  17991. var v3 = vertices[ y + 1 ][ x + 1 ];
  17992. var v4 = vertices[ y ][ x + 1 ];
  17993. var n1 = na.clone();
  17994. var n2 = na.clone();
  17995. var n3 = nb.clone();
  17996. var n4 = nb.clone();
  17997. var uv1 = uvs[ y ][ x ].clone();
  17998. var uv2 = uvs[ y + 1 ][ x ].clone();
  17999. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18000. var uv4 = uvs[ y ][ x + 1 ].clone();
  18001. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18002. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18003. }
  18004. }
  18005. // top cap
  18006. if ( !openEnded && radiusTop > 0 ) {
  18007. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18008. for ( x = 0; x < segmentsX; x ++ ) {
  18009. var v1 = vertices[ 0 ][ x ];
  18010. var v2 = vertices[ 0 ][ x + 1 ];
  18011. var v3 = this.vertices.length - 1;
  18012. var n1 = new THREE.Vector3( 0, 1, 0 );
  18013. var n2 = new THREE.Vector3( 0, 1, 0 );
  18014. var n3 = new THREE.Vector3( 0, 1, 0 );
  18015. var uv1 = uvs[ 0 ][ x ].clone();
  18016. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18017. var uv3 = new THREE.UV( uv2.u, 0 );
  18018. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18019. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18020. }
  18021. }
  18022. // bottom cap
  18023. if ( !openEnded && radiusBottom > 0 ) {
  18024. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18025. for ( x = 0; x < segmentsX; x ++ ) {
  18026. var v1 = vertices[ y ][ x + 1 ];
  18027. var v2 = vertices[ y ][ x ];
  18028. var v3 = this.vertices.length - 1;
  18029. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18030. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18031. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18032. var uv1 = uvs[ y ][ x + 1 ].clone();
  18033. var uv2 = uvs[ y ][ x ].clone();
  18034. var uv3 = new THREE.UV( uv2.u, 1 );
  18035. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18036. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18037. }
  18038. }
  18039. this.computeCentroids();
  18040. this.computeFaceNormals();
  18041. }
  18042. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18043. /**
  18044. * @author zz85 / http://www.lab4games.net/zz85/blog
  18045. *
  18046. * Creates extruded geometry from a path shape.
  18047. *
  18048. * parameters = {
  18049. *
  18050. * size: <float>, // size of the text
  18051. * height: <float>, // thickness to extrude text
  18052. * curveSegments: <int>, // number of points on the curves
  18053. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18054. * amount: <int>, // Amount
  18055. *
  18056. * bevelEnabled: <bool>, // turn on bevel
  18057. * bevelThickness: <float>, // how deep into text bevel goes
  18058. * bevelSize: <float>, // how far from text outline is bevel
  18059. * bevelSegments: <int>, // number of bevel layers
  18060. *
  18061. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18062. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18063. *
  18064. * material: <int> // material index for front and back faces
  18065. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18066. * uvGenerator: <Object> // object that provides UV generator functions
  18067. *
  18068. * }
  18069. **/
  18070. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18071. if ( typeof( shapes ) === "undefined" ) {
  18072. shapes = [];
  18073. return;
  18074. }
  18075. THREE.Geometry.call( this );
  18076. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18077. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18078. this.addShapeList( shapes, options );
  18079. this.computeCentroids();
  18080. this.computeFaceNormals();
  18081. // can't really use automatic vertex normals
  18082. // as then front and back sides get smoothed too
  18083. // should do separate smoothing just for sides
  18084. //this.computeVertexNormals();
  18085. //console.log( "took", ( Date.now() - startTime ) );
  18086. };
  18087. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18088. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18089. var sl = shapes.length;
  18090. for ( var s = 0; s < sl; s ++ ) {
  18091. var shape = shapes[ s ];
  18092. this.addShape( shape, options );
  18093. }
  18094. };
  18095. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18096. var amount = options.amount !== undefined ? options.amount : 100;
  18097. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18098. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18099. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18100. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18101. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18102. var steps = options.steps !== undefined ? options.steps : 1;
  18103. var extrudePath = options.extrudePath;
  18104. var extrudePts, extrudeByPath = false;
  18105. var material = options.material;
  18106. var extrudeMaterial = options.extrudeMaterial;
  18107. // Use default WorldUVGenerator if no UV generators are specified.
  18108. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18109. var shapebb = this.shapebb;
  18110. //shapebb = shape.getBoundingBox();
  18111. var splineTube, binormal, normal, position2;
  18112. if ( extrudePath ) {
  18113. extrudePts = extrudePath.getSpacedPoints( steps );
  18114. extrudeByPath = true;
  18115. bevelEnabled = false; // bevels not supported for path extrusion
  18116. // SETUP TNB variables
  18117. // Reuse TNB from TubeGeomtry for now.
  18118. // TODO1 - have a .isClosed in spline?
  18119. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18120. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18121. binormal = new THREE.Vector3();
  18122. normal = new THREE.Vector3();
  18123. position2 = new THREE.Vector3();
  18124. }
  18125. // Safeguards if bevels are not enabled
  18126. if ( ! bevelEnabled ) {
  18127. bevelSegments = 0;
  18128. bevelThickness = 0;
  18129. bevelSize = 0;
  18130. }
  18131. // Variables initalization
  18132. var ahole, h, hl; // looping of holes
  18133. var scope = this;
  18134. var bevelPoints = [];
  18135. var shapesOffset = this.vertices.length;
  18136. var shapePoints = shape.extractPoints();
  18137. var vertices = shapePoints.shape;
  18138. var holes = shapePoints.holes;
  18139. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18140. if ( reverse ) {
  18141. vertices = vertices.reverse();
  18142. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18143. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18144. ahole = holes[ h ];
  18145. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18146. holes[ h ] = ahole.reverse();
  18147. }
  18148. }
  18149. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18150. }
  18151. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18152. /* Vertices */
  18153. var contour = vertices; // vertices has all points but contour has only points of circumference
  18154. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18155. ahole = holes[ h ];
  18156. vertices = vertices.concat( ahole );
  18157. }
  18158. function scalePt2 ( pt, vec, size ) {
  18159. if ( !vec ) console.log( "die" );
  18160. return vec.clone().multiplyScalar( size ).addSelf( pt );
  18161. }
  18162. var b, bs, t, z,
  18163. vert, vlen = vertices.length,
  18164. face, flen = faces.length,
  18165. cont, clen = contour.length;
  18166. // Find directions for point movement
  18167. var RAD_TO_DEGREES = 180 / Math.PI;
  18168. function getBevelVec( pt_i, pt_j, pt_k ) {
  18169. // Algorithm 2
  18170. return getBevelVec2( pt_i, pt_j, pt_k );
  18171. }
  18172. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18173. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18174. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18175. if ( anglea > angleb ) {
  18176. angleb += Math.PI * 2;
  18177. }
  18178. var anglec = ( anglea + angleb ) / 2;
  18179. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18180. var x = - Math.cos( anglec );
  18181. var y = - Math.sin( anglec );
  18182. var vec = new THREE.Vector2( x, y ); //.normalize();
  18183. return vec;
  18184. }
  18185. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18186. var a = THREE.ExtrudeGeometry.__v1,
  18187. b = THREE.ExtrudeGeometry.__v2,
  18188. v_hat = THREE.ExtrudeGeometry.__v3,
  18189. w_hat = THREE.ExtrudeGeometry.__v4,
  18190. p = THREE.ExtrudeGeometry.__v5,
  18191. q = THREE.ExtrudeGeometry.__v6,
  18192. v, w,
  18193. v_dot_w_hat, q_sub_p_dot_w_hat,
  18194. s, intersection;
  18195. // good reading for line-line intersection
  18196. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18197. // define a as vector j->i
  18198. // define b as vectot k->i
  18199. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18200. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18201. // get unit vectors
  18202. v = a.normalize();
  18203. w = b.normalize();
  18204. // normals from pt i
  18205. v_hat.set( -v.y, v.x );
  18206. w_hat.set( w.y, -w.x );
  18207. // pts from i
  18208. p.copy( pt_i ).addSelf( v_hat );
  18209. q.copy( pt_i ).addSelf( w_hat );
  18210. if ( p.equals( q ) ) {
  18211. //console.log("Warning: lines are straight");
  18212. return w_hat.clone();
  18213. }
  18214. // Points from j, k. helps prevents points cross overover most of the time
  18215. p.copy( pt_j ).addSelf( v_hat );
  18216. q.copy( pt_k ).addSelf( w_hat );
  18217. v_dot_w_hat = v.dot( w_hat );
  18218. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18219. // We should not reach these conditions
  18220. if ( v_dot_w_hat === 0 ) {
  18221. console.log( "Either infinite or no solutions!" );
  18222. if ( q_sub_p_dot_w_hat === 0 ) {
  18223. console.log( "Its finite solutions." );
  18224. } else {
  18225. console.log( "Too bad, no solutions." );
  18226. }
  18227. }
  18228. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18229. if ( s < 0 ) {
  18230. // in case of emergecy, revert to algorithm 1.
  18231. return getBevelVec1( pt_i, pt_j, pt_k );
  18232. }
  18233. intersection = v.multiplyScalar( s ).addSelf( p );
  18234. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18235. }
  18236. var contourMovements = [];
  18237. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18238. if ( j === il ) j = 0;
  18239. if ( k === il ) k = 0;
  18240. // (j)---(i)---(k)
  18241. // console.log('i,j,k', i, j , k)
  18242. var pt_i = contour[ i ];
  18243. var pt_j = contour[ j ];
  18244. var pt_k = contour[ k ];
  18245. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18246. }
  18247. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18248. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18249. ahole = holes[ h ];
  18250. oneHoleMovements = [];
  18251. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18252. if ( j === il ) j = 0;
  18253. if ( k === il ) k = 0;
  18254. // (j)---(i)---(k)
  18255. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18256. }
  18257. holesMovements.push( oneHoleMovements );
  18258. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18259. }
  18260. // Loop bevelSegments, 1 for the front, 1 for the back
  18261. for ( b = 0; b < bevelSegments; b ++ ) {
  18262. //for ( b = bevelSegments; b > 0; b -- ) {
  18263. t = b / bevelSegments;
  18264. z = bevelThickness * ( 1 - t );
  18265. //z = bevelThickness * t;
  18266. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18267. //bs = bevelSize * t ; // linear
  18268. // contract shape
  18269. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18270. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18271. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18272. v( vert.x, vert.y, - z );
  18273. }
  18274. // expand holes
  18275. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18276. ahole = holes[ h ];
  18277. oneHoleMovements = holesMovements[ h ];
  18278. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18279. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18280. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18281. v( vert.x, vert.y, -z );
  18282. }
  18283. }
  18284. }
  18285. bs = bevelSize;
  18286. // Back facing vertices
  18287. for ( i = 0; i < vlen; i ++ ) {
  18288. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18289. if ( !extrudeByPath ) {
  18290. v( vert.x, vert.y, 0 );
  18291. } else {
  18292. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18293. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18294. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18295. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  18296. v( position2.x, position2.y, position2.z );
  18297. }
  18298. }
  18299. // Add stepped vertices...
  18300. // Including front facing vertices
  18301. var s;
  18302. for ( s = 1; s <= steps; s ++ ) {
  18303. for ( i = 0; i < vlen; i ++ ) {
  18304. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18305. if ( !extrudeByPath ) {
  18306. v( vert.x, vert.y, amount / steps * s );
  18307. } else {
  18308. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18309. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18310. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18311. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  18312. v( position2.x, position2.y, position2.z );
  18313. }
  18314. }
  18315. }
  18316. // Add bevel segments planes
  18317. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18318. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18319. t = b / bevelSegments;
  18320. z = bevelThickness * ( 1 - t );
  18321. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18322. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18323. // contract shape
  18324. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18325. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18326. v( vert.x, vert.y, amount + z );
  18327. }
  18328. // expand holes
  18329. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18330. ahole = holes[ h ];
  18331. oneHoleMovements = holesMovements[ h ];
  18332. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18333. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18334. if ( !extrudeByPath ) {
  18335. v( vert.x, vert.y, amount + z );
  18336. } else {
  18337. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18338. }
  18339. }
  18340. }
  18341. }
  18342. /* Faces */
  18343. // Top and bottom faces
  18344. buildLidFaces();
  18345. // Sides faces
  18346. buildSideFaces();
  18347. ///// Internal functions
  18348. function buildLidFaces() {
  18349. if ( bevelEnabled ) {
  18350. var layer = 0 ; // steps + 1
  18351. var offset = vlen * layer;
  18352. // Bottom faces
  18353. for ( i = 0; i < flen; i ++ ) {
  18354. face = faces[ i ];
  18355. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18356. }
  18357. layer = steps + bevelSegments * 2;
  18358. offset = vlen * layer;
  18359. // Top faces
  18360. for ( i = 0; i < flen; i ++ ) {
  18361. face = faces[ i ];
  18362. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18363. }
  18364. } else {
  18365. // Bottom faces
  18366. for ( i = 0; i < flen; i++ ) {
  18367. face = faces[ i ];
  18368. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18369. }
  18370. // Top faces
  18371. for ( i = 0; i < flen; i ++ ) {
  18372. face = faces[ i ];
  18373. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18374. }
  18375. }
  18376. }
  18377. // Create faces for the z-sides of the shape
  18378. function buildSideFaces() {
  18379. var layeroffset = 0;
  18380. sidewalls( contour, layeroffset );
  18381. layeroffset += contour.length;
  18382. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18383. ahole = holes[ h ];
  18384. sidewalls( ahole, layeroffset );
  18385. //, true
  18386. layeroffset += ahole.length;
  18387. }
  18388. }
  18389. function sidewalls( contour, layeroffset ) {
  18390. var j, k;
  18391. i = contour.length;
  18392. while ( --i >= 0 ) {
  18393. j = i;
  18394. k = i - 1;
  18395. if ( k < 0 ) k = contour.length - 1;
  18396. //console.log('b', i,j, i-1, k,vertices.length);
  18397. var s = 0, sl = steps + bevelSegments * 2;
  18398. for ( s = 0; s < sl; s ++ ) {
  18399. var slen1 = vlen * s;
  18400. var slen2 = vlen * ( s + 1 );
  18401. var a = layeroffset + j + slen1,
  18402. b = layeroffset + k + slen1,
  18403. c = layeroffset + k + slen2,
  18404. d = layeroffset + j + slen2;
  18405. f4( a, b, c, d, contour, s, sl, j, k );
  18406. }
  18407. }
  18408. }
  18409. function v( x, y, z ) {
  18410. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18411. }
  18412. function f3( a, b, c, isBottom ) {
  18413. a += shapesOffset;
  18414. b += shapesOffset;
  18415. c += shapesOffset;
  18416. // normal, color, material
  18417. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18418. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18419. scope.faceVertexUvs[ 0 ].push( uvs );
  18420. }
  18421. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18422. a += shapesOffset;
  18423. b += shapesOffset;
  18424. c += shapesOffset;
  18425. d += shapesOffset;
  18426. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18427. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18428. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18429. scope.faceVertexUvs[ 0 ].push( uvs );
  18430. }
  18431. };
  18432. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18433. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18434. var ax = geometry.vertices[ indexA ].x,
  18435. ay = geometry.vertices[ indexA ].y,
  18436. bx = geometry.vertices[ indexB ].x,
  18437. by = geometry.vertices[ indexB ].y,
  18438. cx = geometry.vertices[ indexC ].x,
  18439. cy = geometry.vertices[ indexC ].y;
  18440. return [
  18441. new THREE.UV( ax, ay ),
  18442. new THREE.UV( bx, by ),
  18443. new THREE.UV( cx, cy )
  18444. ];
  18445. },
  18446. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18447. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18448. },
  18449. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18450. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18451. contourIndex1, contourIndex2 ) {
  18452. var ax = geometry.vertices[ indexA ].x,
  18453. ay = geometry.vertices[ indexA ].y,
  18454. az = geometry.vertices[ indexA ].z,
  18455. bx = geometry.vertices[ indexB ].x,
  18456. by = geometry.vertices[ indexB ].y,
  18457. bz = geometry.vertices[ indexB ].z,
  18458. cx = geometry.vertices[ indexC ].x,
  18459. cy = geometry.vertices[ indexC ].y,
  18460. cz = geometry.vertices[ indexC ].z,
  18461. dx = geometry.vertices[ indexD ].x,
  18462. dy = geometry.vertices[ indexD ].y,
  18463. dz = geometry.vertices[ indexD ].z;
  18464. if ( Math.abs( ay - by ) < 0.01 ) {
  18465. return [
  18466. new THREE.UV( ax, 1 - az ),
  18467. new THREE.UV( bx, 1 - bz ),
  18468. new THREE.UV( cx, 1 - cz ),
  18469. new THREE.UV( dx, 1 - dz )
  18470. ];
  18471. } else {
  18472. return [
  18473. new THREE.UV( ay, 1 - az ),
  18474. new THREE.UV( by, 1 - bz ),
  18475. new THREE.UV( cy, 1 - cz ),
  18476. new THREE.UV( dy, 1 - dz )
  18477. ];
  18478. }
  18479. }
  18480. };
  18481. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18482. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18483. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18484. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18485. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18486. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18487. /**
  18488. * @author astrodud / http://astrodud.isgreat.org/
  18489. * @author zz85 / https://github.com/zz85
  18490. */
  18491. THREE.LatheGeometry = function ( points, steps, angle ) {
  18492. THREE.Geometry.call( this );
  18493. var _steps = steps || 12;
  18494. var _angle = angle || 2 * Math.PI;
  18495. var _newV = [];
  18496. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  18497. for ( var j = 0; j < points.length; j ++ ) {
  18498. _newV[ j ] = points[ j ].clone();
  18499. this.vertices.push( _newV[ j ] );
  18500. }
  18501. var i, il = _steps + 1;
  18502. for ( i = 0; i < il; i ++ ) {
  18503. for ( var j = 0; j < _newV.length; j ++ ) {
  18504. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  18505. this.vertices.push( _newV[ j ] );
  18506. }
  18507. }
  18508. for ( i = 0; i < _steps; i ++ ) {
  18509. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  18510. var a = i * kl + k;
  18511. var b = ( ( i + 1 ) % il ) * kl + k;
  18512. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  18513. var d = i * kl + ( k + 1 ) % kl;
  18514. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18515. this.faceVertexUvs[ 0 ].push( [
  18516. new THREE.UV( 1 - i / _steps, k / kl ),
  18517. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  18518. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  18519. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  18520. ] );
  18521. }
  18522. }
  18523. this.computeCentroids();
  18524. this.computeFaceNormals();
  18525. this.computeVertexNormals();
  18526. };
  18527. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18528. /**
  18529. * @author mrdoob / http://mrdoob.com/
  18530. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18531. */
  18532. THREE.PlaneGeometry = function ( width, height, segmentsWidth, segmentsheight ) {
  18533. THREE.Geometry.call( this );
  18534. var ix, iz,
  18535. width_half = width / 2,
  18536. height_half = height / 2,
  18537. gridX = segmentsWidth || 1,
  18538. gridZ = segmentsheight || 1,
  18539. gridX1 = gridX + 1,
  18540. gridZ1 = gridZ + 1,
  18541. segment_width = width / gridX,
  18542. segment_height = height / gridZ,
  18543. normal = new THREE.Vector3( 0, 0, 1 );
  18544. for ( iz = 0; iz < gridZ1; iz ++ ) {
  18545. for ( ix = 0; ix < gridX1; ix ++ ) {
  18546. var x = ix * segment_width - width_half;
  18547. var y = iz * segment_height - height_half;
  18548. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  18549. }
  18550. }
  18551. for ( iz = 0; iz < gridZ; iz ++ ) {
  18552. for ( ix = 0; ix < gridX; ix ++ ) {
  18553. var a = ix + gridX1 * iz;
  18554. var b = ix + gridX1 * ( iz + 1 );
  18555. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  18556. var d = ( ix + 1 ) + gridX1 * iz;
  18557. var face = new THREE.Face4( a, b, c, d );
  18558. face.normal.copy( normal );
  18559. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18560. this.faces.push( face );
  18561. this.faceVertexUvs[ 0 ].push( [
  18562. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  18563. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  18564. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  18565. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  18566. ] );
  18567. }
  18568. }
  18569. this.computeCentroids();
  18570. };
  18571. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18572. /**
  18573. * @author mrdoob / http://mrdoob.com/
  18574. */
  18575. THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength ) {
  18576. THREE.Geometry.call( this );
  18577. radius = radius || 50;
  18578. phiStart = phiStart !== undefined ? phiStart : 0;
  18579. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18580. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18581. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18582. var segmentsX = Math.max( 3, Math.floor( segmentsWidth ) || 8 );
  18583. var segmentsY = Math.max( 2, Math.floor( segmentsHeight ) || 6 );
  18584. var x, y, vertices = [], uvs = [];
  18585. for ( y = 0; y <= segmentsY; y ++ ) {
  18586. var verticesRow = [];
  18587. var uvsRow = [];
  18588. for ( x = 0; x <= segmentsX; x ++ ) {
  18589. var u = x / segmentsX;
  18590. var v = y / segmentsY;
  18591. var vertex = new THREE.Vector3();
  18592. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18593. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  18594. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18595. this.vertices.push( vertex );
  18596. verticesRow.push( this.vertices.length - 1 );
  18597. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18598. }
  18599. vertices.push( verticesRow );
  18600. uvs.push( uvsRow );
  18601. }
  18602. for ( y = 0; y < segmentsY; y ++ ) {
  18603. for ( x = 0; x < segmentsX; x ++ ) {
  18604. var v1 = vertices[ y ][ x + 1 ];
  18605. var v2 = vertices[ y ][ x ];
  18606. var v3 = vertices[ y + 1 ][ x ];
  18607. var v4 = vertices[ y + 1 ][ x + 1 ];
  18608. var n1 = this.vertices[ v1 ].clone().normalize();
  18609. var n2 = this.vertices[ v2 ].clone().normalize();
  18610. var n3 = this.vertices[ v3 ].clone().normalize();
  18611. var n4 = this.vertices[ v4 ].clone().normalize();
  18612. var uv1 = uvs[ y ][ x + 1 ].clone();
  18613. var uv2 = uvs[ y ][ x ].clone();
  18614. var uv3 = uvs[ y + 1 ][ x ].clone();
  18615. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  18616. if ( Math.abs( this.vertices[ v1 ].y ) == radius ) {
  18617. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  18618. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  18619. } else if ( Math.abs( this.vertices[ v3 ].y ) == radius ) {
  18620. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18621. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18622. } else {
  18623. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18624. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18625. }
  18626. }
  18627. }
  18628. this.computeCentroids();
  18629. this.computeFaceNormals();
  18630. this.boundingSphere = { radius: radius };
  18631. };
  18632. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18633. /**
  18634. * @author zz85 / http://www.lab4games.net/zz85/blog
  18635. * @author alteredq / http://alteredqualia.com/
  18636. *
  18637. * For creating 3D text geometry in three.js
  18638. *
  18639. * Text = 3D Text
  18640. *
  18641. * parameters = {
  18642. * size: <float>, // size of the text
  18643. * height: <float>, // thickness to extrude text
  18644. * curveSegments: <int>, // number of points on the curves
  18645. *
  18646. * font: <string>, // font name
  18647. * weight: <string>, // font weight (normal, bold)
  18648. * style: <string>, // font style (normal, italics)
  18649. *
  18650. * bevelEnabled: <bool>, // turn on bevel
  18651. * bevelThickness: <float>, // how deep into text bevel goes
  18652. * bevelSize: <float>, // how far from text outline is bevel
  18653. * }
  18654. *
  18655. */
  18656. /* Usage Examples
  18657. // TextGeometry wrapper
  18658. var text3d = new TextGeometry( text, options );
  18659. // Complete manner
  18660. var textShapes = THREE.FontUtils.generateShapes( text, options );
  18661. var text3d = new ExtrudeGeometry( textShapes, options );
  18662. */
  18663. THREE.TextGeometry = function ( text, parameters ) {
  18664. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  18665. // translate parameters to ExtrudeGeometry API
  18666. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  18667. // defaults
  18668. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18669. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18670. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18671. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  18672. };
  18673. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  18674. /**
  18675. * @author oosmoxiecode
  18676. * @author mrdoob / http://mrdoob.com/
  18677. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  18678. */
  18679. THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {
  18680. THREE.Geometry.call( this );
  18681. var scope = this;
  18682. this.radius = radius || 100;
  18683. this.tube = tube || 40;
  18684. this.segmentsR = segmentsR || 8;
  18685. this.segmentsT = segmentsT || 6;
  18686. this.arc = arc || Math.PI * 2;
  18687. var center = new THREE.Vector3(), uvs = [], normals = [];
  18688. for ( var j = 0; j <= this.segmentsR; j ++ ) {
  18689. for ( var i = 0; i <= this.segmentsT; i ++ ) {
  18690. var u = i / this.segmentsT * this.arc;
  18691. var v = j / this.segmentsR * Math.PI * 2;
  18692. center.x = this.radius * Math.cos( u );
  18693. center.y = this.radius * Math.sin( u );
  18694. var vertex = new THREE.Vector3();
  18695. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  18696. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  18697. vertex.z = this.tube * Math.sin( v );
  18698. this.vertices.push( vertex );
  18699. uvs.push( new THREE.UV( i / this.segmentsT, j / this.segmentsR ) );
  18700. normals.push( vertex.clone().subSelf( center ).normalize() );
  18701. }
  18702. }
  18703. for ( var j = 1; j <= this.segmentsR; j ++ ) {
  18704. for ( var i = 1; i <= this.segmentsT; i ++ ) {
  18705. var a = ( this.segmentsT + 1 ) * j + i - 1;
  18706. var b = ( this.segmentsT + 1 ) * ( j - 1 ) + i - 1;
  18707. var c = ( this.segmentsT + 1 ) * ( j - 1 ) + i;
  18708. var d = ( this.segmentsT + 1 ) * j + i;
  18709. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  18710. face.normal.addSelf( normals[ a ] );
  18711. face.normal.addSelf( normals[ b ] );
  18712. face.normal.addSelf( normals[ c ] );
  18713. face.normal.addSelf( normals[ d ] );
  18714. face.normal.normalize();
  18715. this.faces.push( face );
  18716. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  18717. }
  18718. }
  18719. this.computeCentroids();
  18720. };
  18721. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18722. /**
  18723. * @author oosmoxiecode
  18724. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  18725. */
  18726. THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {
  18727. THREE.Geometry.call( this );
  18728. var scope = this;
  18729. this.radius = radius || 200;
  18730. this.tube = tube || 40;
  18731. this.segmentsR = segmentsR || 64;
  18732. this.segmentsT = segmentsT || 8;
  18733. this.p = p || 2;
  18734. this.q = q || 3;
  18735. this.heightScale = heightScale || 1;
  18736. this.grid = new Array(this.segmentsR);
  18737. var tang = new THREE.Vector3();
  18738. var n = new THREE.Vector3();
  18739. var bitan = new THREE.Vector3();
  18740. for ( var i = 0; i < this.segmentsR; ++ i ) {
  18741. this.grid[ i ] = new Array( this.segmentsT );
  18742. for ( var j = 0; j < this.segmentsT; ++ j ) {
  18743. var u = i / this.segmentsR * 2 * this.p * Math.PI;
  18744. var v = j / this.segmentsT * 2 * Math.PI;
  18745. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  18746. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  18747. var cx, cy;
  18748. tang.sub( p2, p1 );
  18749. n.add( p2, p1 );
  18750. bitan.cross( tang, n );
  18751. n.cross( bitan, tang );
  18752. bitan.normalize();
  18753. n.normalize();
  18754. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18755. cy = this.tube * Math.sin( v );
  18756. p1.x += cx * n.x + cy * bitan.x;
  18757. p1.y += cx * n.y + cy * bitan.y;
  18758. p1.z += cx * n.z + cy * bitan.z;
  18759. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  18760. }
  18761. }
  18762. for ( var i = 0; i < this.segmentsR; ++ i ) {
  18763. for ( var j = 0; j < this.segmentsT; ++ j ) {
  18764. var ip = ( i + 1 ) % this.segmentsR;
  18765. var jp = ( j + 1 ) % this.segmentsT;
  18766. var a = this.grid[ i ][ j ];
  18767. var b = this.grid[ ip ][ j ];
  18768. var c = this.grid[ ip ][ jp ];
  18769. var d = this.grid[ i ][ jp ];
  18770. var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
  18771. var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
  18772. var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
  18773. var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );
  18774. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18775. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  18776. }
  18777. }
  18778. this.computeCentroids();
  18779. this.computeFaceNormals();
  18780. this.computeVertexNormals();
  18781. function vert( x, y, z ) {
  18782. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18783. }
  18784. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  18785. var cu = Math.cos( u );
  18786. var cv = Math.cos( v );
  18787. var su = Math.sin( u );
  18788. var quOverP = in_q / in_p * u;
  18789. var cs = Math.cos( quOverP );
  18790. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  18791. var ty = radius * ( 2 + cs ) * su * 0.5;
  18792. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  18793. return new THREE.Vector3( tx, ty, tz );
  18794. }
  18795. };
  18796. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18797. /**
  18798. * @author WestLangley / https://github.com/WestLangley
  18799. * @author zz85 / https://github.com/zz85
  18800. * @author miningold / https://github.com/miningold
  18801. *
  18802. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18803. *
  18804. * Creates a tube which extrudes along a 3d spline
  18805. *
  18806. * Uses parallel transport frames as described in
  18807. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18808. */
  18809. THREE.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {
  18810. THREE.Geometry.call( this );
  18811. this.path = path;
  18812. this.segments = segments || 64;
  18813. this.radius = radius || 1;
  18814. this.segmentsRadius = segmentsRadius || 8;
  18815. this.closed = closed || false;
  18816. if ( debug ) this.debug = new THREE.Object3D();
  18817. this.grid = [];
  18818. var scope = this,
  18819. tangent,
  18820. normal,
  18821. binormal,
  18822. numpoints = this.segments + 1,
  18823. x, y, z,
  18824. tx, ty, tz,
  18825. u, v,
  18826. cx, cy,
  18827. pos, pos2 = new THREE.Vector3(),
  18828. i, j,
  18829. ip, jp,
  18830. a, b, c, d,
  18831. uva, uvb, uvc, uvd;
  18832. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  18833. tangents = frames.tangents,
  18834. normals = frames.normals,
  18835. binormals = frames.binormals;
  18836. // proxy internals
  18837. this.tangents = tangents;
  18838. this.normals = normals;
  18839. this.binormals = binormals;
  18840. function vert( x, y, z ) {
  18841. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18842. }
  18843. // consruct the grid
  18844. for ( i = 0; i < numpoints; i++ ) {
  18845. this.grid[ i ] = [];
  18846. u = i / ( numpoints - 1 );
  18847. pos = path.getPointAt( u );
  18848. tangent = tangents[ i ];
  18849. normal = normals[ i ];
  18850. binormal = binormals[ i ];
  18851. if ( this.debug ) {
  18852. this.debug.add(new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff));
  18853. this.debug.add(new THREE.ArrowHelper(normal, pos, radius, 0xff0000));
  18854. this.debug.add(new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00));
  18855. }
  18856. for ( j = 0; j < this.segmentsRadius; j++ ) {
  18857. v = j / this.segmentsRadius * 2 * Math.PI;
  18858. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18859. cy = this.radius * Math.sin( v );
  18860. pos2.copy( pos );
  18861. pos2.x += cx * normal.x + cy * binormal.x;
  18862. pos2.y += cx * normal.y + cy * binormal.y;
  18863. pos2.z += cx * normal.z + cy * binormal.z;
  18864. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18865. }
  18866. }
  18867. // construct the mesh
  18868. for ( i = 0; i < this.segments; i++ ) {
  18869. for ( j = 0; j < this.segmentsRadius; j++ ) {
  18870. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  18871. jp = (j + 1) % this.segmentsRadius;
  18872. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18873. b = this.grid[ ip ][ j ];
  18874. c = this.grid[ ip ][ jp ];
  18875. d = this.grid[ i ][ jp ];
  18876. uva = new THREE.UV( i / this.segments, j / this.segmentsRadius );
  18877. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.segmentsRadius );
  18878. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.segmentsRadius );
  18879. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.segmentsRadius );
  18880. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18881. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  18882. }
  18883. }
  18884. this.computeCentroids();
  18885. this.computeFaceNormals();
  18886. this.computeVertexNormals();
  18887. };
  18888. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18889. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  18890. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  18891. var
  18892. tangent = new THREE.Vector3(),
  18893. normal = new THREE.Vector3(),
  18894. binormal = new THREE.Vector3(),
  18895. tangents = [],
  18896. normals = [],
  18897. binormals = [],
  18898. vec = new THREE.Vector3(),
  18899. mat = new THREE.Matrix4(),
  18900. numpoints = segments + 1,
  18901. theta,
  18902. epsilon = 0.0001,
  18903. smallest,
  18904. tx, ty, tz,
  18905. i, u, v;
  18906. // expose internals
  18907. this.tangents = tangents;
  18908. this.normals = normals;
  18909. this.binormals = binormals;
  18910. // compute the tangent vectors for each segment on the path
  18911. for ( i = 0; i < numpoints; i++ ) {
  18912. u = i / ( numpoints - 1 );
  18913. tangents[ i ] = path.getTangentAt( u );
  18914. tangents[ i ].normalize();
  18915. }
  18916. initialNormal3();
  18917. function initialNormal1(lastBinormal) {
  18918. // fixed start binormal. Has dangers of 0 vectors
  18919. normals[ 0 ] = new THREE.Vector3();
  18920. binormals[ 0 ] = new THREE.Vector3();
  18921. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  18922. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  18923. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18924. }
  18925. function initialNormal2() {
  18926. // This uses the Frenet-Serret formula for deriving binormal
  18927. var t2 = path.getTangentAt( epsilon );
  18928. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  18929. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  18930. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  18931. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18932. }
  18933. function initialNormal3() {
  18934. // select an initial normal vector perpenicular to the first tangent vector,
  18935. // and in the direction of the smallest tangent xyz component
  18936. normals[ 0 ] = new THREE.Vector3();
  18937. binormals[ 0 ] = new THREE.Vector3();
  18938. smallest = Number.MAX_VALUE;
  18939. tx = Math.abs( tangents[ 0 ].x );
  18940. ty = Math.abs( tangents[ 0 ].y );
  18941. tz = Math.abs( tangents[ 0 ].z );
  18942. if ( tx <= smallest ) {
  18943. smallest = tx;
  18944. normal.set( 1, 0, 0 );
  18945. }
  18946. if ( ty <= smallest ) {
  18947. smallest = ty;
  18948. normal.set( 0, 1, 0 );
  18949. }
  18950. if ( tz <= smallest ) {
  18951. normal.set( 0, 0, 1 );
  18952. }
  18953. vec.cross( tangents[ 0 ], normal ).normalize();
  18954. normals[ 0 ].cross( tangents[ 0 ], vec );
  18955. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  18956. }
  18957. // compute the slowly-varying normal and binormal vectors for each segment on the path
  18958. for ( i = 1; i < numpoints; i++ ) {
  18959. normals[ i ] = normals[ i-1 ].clone();
  18960. binormals[ i ] = binormals[ i-1 ].clone();
  18961. vec.cross( tangents[ i-1 ], tangents[ i ] );
  18962. if ( vec.length() > epsilon ) {
  18963. vec.normalize();
  18964. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  18965. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  18966. }
  18967. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  18968. }
  18969. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18970. if ( closed ) {
  18971. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  18972. theta /= ( numpoints - 1 );
  18973. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  18974. theta = -theta;
  18975. }
  18976. for ( i = 1; i < numpoints; i++ ) {
  18977. // twist a little...
  18978. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  18979. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  18980. }
  18981. }
  18982. };
  18983. /**
  18984. * @author clockworkgeek / https://github.com/clockworkgeek
  18985. * @author timothypratley / https://github.com/timothypratley
  18986. */
  18987. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  18988. THREE.Geometry.call( this );
  18989. radius = radius || 1;
  18990. detail = detail || 0;
  18991. var that = this;
  18992. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  18993. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  18994. }
  18995. var midpoints = [], p = this.vertices;
  18996. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  18997. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  18998. }
  18999. this.mergeVertices();
  19000. // Apply radius
  19001. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19002. this.vertices[ i ].multiplyScalar( radius );
  19003. }
  19004. // Project vector onto sphere's surface
  19005. function prepare( vector ) {
  19006. var vertex = vector.normalize().clone();
  19007. vertex.index = that.vertices.push( vertex ) - 1;
  19008. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19009. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19010. var v = inclination( vector ) / Math.PI + 0.5;
  19011. vertex.uv = new THREE.UV( u, 1 - v );
  19012. return vertex;
  19013. }
  19014. // Approximate a curved face with recursively sub-divided triangles.
  19015. function make( v1, v2, v3, detail ) {
  19016. if ( detail < 1 ) {
  19017. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19018. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  19019. face.normal = face.centroid.clone().normalize();
  19020. that.faces.push( face );
  19021. var azi = azimuth( face.centroid );
  19022. that.faceVertexUvs[ 0 ].push( [
  19023. correctUV( v1.uv, v1, azi ),
  19024. correctUV( v2.uv, v2, azi ),
  19025. correctUV( v3.uv, v3, azi )
  19026. ] );
  19027. } else {
  19028. detail -= 1;
  19029. // split triangle into 4 smaller triangles
  19030. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19031. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19032. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19033. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19034. }
  19035. }
  19036. function midpoint( v1, v2 ) {
  19037. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19038. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19039. var mid = midpoints[ v1.index ][ v2.index ];
  19040. if ( mid === undefined ) {
  19041. // generate mean point and project to surface with prepare()
  19042. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19043. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  19044. );
  19045. }
  19046. return mid;
  19047. }
  19048. // Angle around the Y axis, counter-clockwise when looking from above.
  19049. function azimuth( vector ) {
  19050. return Math.atan2( vector.z, -vector.x );
  19051. }
  19052. // Angle above the XZ plane.
  19053. function inclination( vector ) {
  19054. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19055. }
  19056. // Texture fixing helper. Spheres have some odd behaviours.
  19057. function correctUV( uv, vector, azimuth ) {
  19058. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  19059. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  19060. return uv;
  19061. }
  19062. this.computeCentroids();
  19063. this.boundingSphere = { radius: radius };
  19064. };
  19065. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19066. /**
  19067. * @author timothypratley / https://github.com/timothypratley
  19068. */
  19069. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19070. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19071. var vertices = [
  19072. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19073. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19074. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19075. ];
  19076. var faces = [
  19077. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19078. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19079. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19080. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19081. ];
  19082. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19083. };
  19084. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19085. /**
  19086. * @author timothypratley / https://github.com/timothypratley
  19087. */
  19088. THREE.OctahedronGeometry = function ( radius, detail ) {
  19089. var vertices = [
  19090. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19091. ];
  19092. var faces = [
  19093. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19094. ];
  19095. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19096. };
  19097. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19098. /**
  19099. * @author timothypratley / https://github.com/timothypratley
  19100. */
  19101. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19102. var vertices = [
  19103. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19104. ];
  19105. var faces = [
  19106. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19107. ];
  19108. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19109. };
  19110. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19111. /**
  19112. * @author zz85 / https://github.com/zz85
  19113. * Parametric Surfaces Geometry
  19114. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19115. *
  19116. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19117. *
  19118. */
  19119. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19120. THREE.Geometry.call( this );
  19121. var verts = this.vertices;
  19122. var faces = this.faces;
  19123. var uvs = this.faceVertexUvs[ 0 ];
  19124. useTris = (useTris === undefined) ? false : useTris;
  19125. var i, il, j, p;
  19126. var u, v;
  19127. var stackCount = stacks + 1;
  19128. var sliceCount = slices + 1;
  19129. for ( i = 0; i <= stacks; i ++ ) {
  19130. v = i / stacks;
  19131. for ( j = 0; j <= slices; j ++ ) {
  19132. u = j / slices;
  19133. p = func( u, v );
  19134. verts.push( p );
  19135. }
  19136. }
  19137. var a, b, c, d;
  19138. var uva, uvb, uvc, uvd;
  19139. for ( i = 0; i < stacks; i ++ ) {
  19140. for ( j = 0; j < slices; j ++ ) {
  19141. a = i * sliceCount + j;
  19142. b = i * sliceCount + j + 1;
  19143. c = (i + 1) * sliceCount + j;
  19144. d = (i + 1) * sliceCount + j + 1;
  19145. uva = new THREE.UV( j / slices, i / stacks );
  19146. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  19147. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  19148. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19149. if ( useTris ) {
  19150. faces.push( new THREE.Face3( a, b, c ) );
  19151. faces.push( new THREE.Face3( b, d, c ) );
  19152. uvs.push( [ uva, uvb, uvc ] );
  19153. uvs.push( [ uvb, uvd, uvc ] );
  19154. } else {
  19155. faces.push( new THREE.Face4( a, b, d, c ) );
  19156. uvs.push( [ uva, uvb, uvd, uvc ] );
  19157. }
  19158. }
  19159. }
  19160. // console.log(this);
  19161. // magic bullet
  19162. // var diff = this.mergeVertices();
  19163. // console.log('removed ', diff, ' vertices by merging');
  19164. this.computeCentroids();
  19165. this.computeFaceNormals();
  19166. this.computeVertexNormals();
  19167. };
  19168. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19169. /**
  19170. * @author qiao / https://github.com/qiao
  19171. * @fileoverview This is a convex hull generator using the incremental method.
  19172. * The complexity is O(n^2) where n is the number of vertices.
  19173. * O(nlogn) algorithms do exist, but they are much more complicated.
  19174. *
  19175. * Benchmark:
  19176. *
  19177. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19178. *
  19179. * Num Vertices Time(ms)
  19180. *
  19181. * 10 1
  19182. * 20 3
  19183. * 30 19
  19184. * 40 48
  19185. * 50 107
  19186. */
  19187. THREE.ConvexGeometry = function( vertices ) {
  19188. THREE.Geometry.call( this );
  19189. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19190. for ( var i = 3; i < vertices.length; i++ ) {
  19191. addPoint( i );
  19192. }
  19193. function addPoint( vertexId ) {
  19194. var vertex = vertices[ vertexId ].clone();
  19195. var mag = vertex.length();
  19196. vertex.x += mag * randomOffset();
  19197. vertex.y += mag * randomOffset();
  19198. vertex.z += mag * randomOffset();
  19199. var hole = [];
  19200. for ( var f = 0; f < faces.length; ) {
  19201. var face = faces[ f ];
  19202. // for each face, if the vertex can see it,
  19203. // then we try to add the face's edges into the hole.
  19204. if ( visible( face, vertex ) ) {
  19205. for ( var e = 0; e < 3; e++ ) {
  19206. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19207. var boundary = true;
  19208. // remove duplicated edges.
  19209. for ( var h = 0; h < hole.length; h++ ) {
  19210. if ( equalEdge( hole[ h ], edge ) ) {
  19211. hole[ h ] = hole[ hole.length - 1 ];
  19212. hole.pop();
  19213. boundary = false;
  19214. break;
  19215. }
  19216. }
  19217. if ( boundary ) {
  19218. hole.push( edge );
  19219. }
  19220. }
  19221. // remove faces[ f ]
  19222. faces[ f ] = faces[ faces.length - 1 ];
  19223. faces.pop();
  19224. } else { // not visible
  19225. f++;
  19226. }
  19227. }
  19228. // construct the new faces formed by the edges of the hole and the vertex
  19229. for ( var h = 0; h < hole.length; h++ ) {
  19230. faces.push( [
  19231. hole[ h ][ 0 ],
  19232. hole[ h ][ 1 ],
  19233. vertexId
  19234. ] );
  19235. }
  19236. }
  19237. /**
  19238. * Whether the face is visible from the vertex
  19239. */
  19240. function visible( face, vertex ) {
  19241. var va = vertices[ face[ 0 ] ];
  19242. var vb = vertices[ face[ 1 ] ];
  19243. var vc = vertices[ face[ 2 ] ];
  19244. var n = normal( va, vb, vc );
  19245. // distance from face to origin
  19246. var dist = n.dot( va );
  19247. return n.dot( vertex ) >= dist;
  19248. }
  19249. /**
  19250. * Face normal
  19251. */
  19252. function normal( va, vb, vc ) {
  19253. var cb = new THREE.Vector3();
  19254. var ab = new THREE.Vector3();
  19255. cb.sub( vc, vb );
  19256. ab.sub( va, vb );
  19257. cb.crossSelf( ab );
  19258. if ( !cb.isZero() ) {
  19259. cb.normalize();
  19260. }
  19261. return cb;
  19262. }
  19263. /**
  19264. * Detect whether two edges are equal.
  19265. * Note that when constructing the convex hull, two same edges can only
  19266. * be of the negative direction.
  19267. */
  19268. function equalEdge( ea, eb ) {
  19269. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19270. }
  19271. /**
  19272. * Create a random offset between -1e-6 and 1e-6.
  19273. */
  19274. function randomOffset() {
  19275. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19276. }
  19277. /**
  19278. * XXX: Not sure if this is the correct approach. Need someone to review.
  19279. */
  19280. function vertexUv( vertex ) {
  19281. var mag = vertex.length();
  19282. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  19283. }
  19284. // Push vertices into `this.vertices`, skipping those inside the hull
  19285. var id = 0;
  19286. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19287. for ( var i = 0; i < faces.length; i++ ) {
  19288. var face = faces[ i ];
  19289. for ( var j = 0; j < 3; j++ ) {
  19290. if ( newId[ face[ j ] ] === undefined ) {
  19291. newId[ face[ j ] ] = id++;
  19292. this.vertices.push( vertices[ face[ j ] ] );
  19293. }
  19294. face[ j ] = newId[ face[ j ] ];
  19295. }
  19296. }
  19297. // Convert faces into instances of THREE.Face3
  19298. for ( var i = 0; i < faces.length; i++ ) {
  19299. this.faces.push( new THREE.Face3(
  19300. faces[ i ][ 0 ],
  19301. faces[ i ][ 1 ],
  19302. faces[ i ][ 2 ]
  19303. ) );
  19304. }
  19305. // Compute UVs
  19306. for ( var i = 0; i < this.faces.length; i++ ) {
  19307. var face = this.faces[ i ];
  19308. this.faceVertexUvs[ 0 ].push( [
  19309. vertexUv( this.vertices[ face.a ] ),
  19310. vertexUv( this.vertices[ face.b ] ),
  19311. vertexUv( this.vertices[ face.c ])
  19312. ] );
  19313. }
  19314. this.computeCentroids();
  19315. this.computeFaceNormals();
  19316. this.computeVertexNormals();
  19317. };
  19318. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19319. /**
  19320. * @author sroucheray / http://sroucheray.org/
  19321. * @author mrdoob / http://mrdoob.com/
  19322. */
  19323. THREE.AxisHelper = function () {
  19324. THREE.Object3D.call( this );
  19325. var lineGeometry = new THREE.Geometry();
  19326. lineGeometry.vertices.push( new THREE.Vector3() );
  19327. lineGeometry.vertices.push( new THREE.Vector3( 0, 100, 0 ) );
  19328. var coneGeometry = new THREE.CylinderGeometry( 0, 5, 25, 5, 1 );
  19329. var line, cone;
  19330. // x
  19331. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
  19332. line.rotation.z = - Math.PI / 2;
  19333. this.add( line );
  19334. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0xff0000 } ) );
  19335. cone.position.x = 100;
  19336. cone.rotation.z = - Math.PI / 2;
  19337. this.add( cone );
  19338. // y
  19339. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x00ff00 } ) );
  19340. this.add( line );
  19341. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x00ff00 } ) );
  19342. cone.position.y = 100;
  19343. this.add( cone );
  19344. // z
  19345. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
  19346. line.rotation.x = Math.PI / 2;
  19347. this.add( line );
  19348. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x0000ff } ) );
  19349. cone.position.z = 100;
  19350. cone.rotation.x = Math.PI / 2;
  19351. this.add( cone );
  19352. };
  19353. THREE.AxisHelper.prototype = Object.create( THREE.Object3D.prototype );
  19354. /**
  19355. * @author WestLangley / http://github.com/WestLangley
  19356. * @author zz85 / https://github.com/zz85
  19357. *
  19358. * Creates an arrow for visualizing directions
  19359. *
  19360. * Parameters:
  19361. * dir - Vector3
  19362. * origin - Vector3
  19363. * length - Number
  19364. * hex - color in hex value
  19365. */
  19366. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19367. THREE.Object3D.call( this );
  19368. if ( hex === undefined ) hex = 0xffff00;
  19369. if ( length === undefined ) length = 20;
  19370. var lineGeometry = new THREE.Geometry();
  19371. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19372. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19373. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19374. this.add( this.line );
  19375. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19376. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19377. this.cone.position.set( 0, 1, 0 );
  19378. this.add( this.cone );
  19379. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19380. this.setDirection( dir );
  19381. this.setLength( length );
  19382. };
  19383. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19384. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19385. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  19386. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  19387. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  19388. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  19389. };
  19390. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19391. this.scale.set( length, length, length );
  19392. };
  19393. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19394. this.line.material.color.setHex( hex );
  19395. this.cone.material.color.setHex( hex );
  19396. };
  19397. /**
  19398. * @author alteredq / http://alteredqualia.com/
  19399. *
  19400. * - shows frustum, line of sight and up of the camera
  19401. * - suitable for fast updates
  19402. * - based on frustum visualization in lightgl.js shadowmap example
  19403. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19404. */
  19405. THREE.CameraHelper = function ( camera ) {
  19406. THREE.Line.call( this );
  19407. var scope = this;
  19408. this.geometry = new THREE.Geometry();
  19409. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19410. this.type = THREE.LinePieces;
  19411. this.matrixWorld = camera.matrixWorld;
  19412. this.matrixAutoUpdate = false;
  19413. this.pointMap = {};
  19414. // colors
  19415. var hexFrustum = 0xffaa00;
  19416. var hexCone = 0xff0000;
  19417. var hexUp = 0x00aaff;
  19418. var hexTarget = 0xffffff;
  19419. var hexCross = 0x333333;
  19420. // near
  19421. addLine( "n1", "n2", hexFrustum );
  19422. addLine( "n2", "n4", hexFrustum );
  19423. addLine( "n4", "n3", hexFrustum );
  19424. addLine( "n3", "n1", hexFrustum );
  19425. // far
  19426. addLine( "f1", "f2", hexFrustum );
  19427. addLine( "f2", "f4", hexFrustum );
  19428. addLine( "f4", "f3", hexFrustum );
  19429. addLine( "f3", "f1", hexFrustum );
  19430. // sides
  19431. addLine( "n1", "f1", hexFrustum );
  19432. addLine( "n2", "f2", hexFrustum );
  19433. addLine( "n3", "f3", hexFrustum );
  19434. addLine( "n4", "f4", hexFrustum );
  19435. // cone
  19436. addLine( "p", "n1", hexCone );
  19437. addLine( "p", "n2", hexCone );
  19438. addLine( "p", "n3", hexCone );
  19439. addLine( "p", "n4", hexCone );
  19440. // up
  19441. addLine( "u1", "u2", hexUp );
  19442. addLine( "u2", "u3", hexUp );
  19443. addLine( "u3", "u1", hexUp );
  19444. // target
  19445. addLine( "c", "t", hexTarget );
  19446. addLine( "p", "c", hexCross );
  19447. // cross
  19448. addLine( "cn1", "cn2", hexCross );
  19449. addLine( "cn3", "cn4", hexCross );
  19450. addLine( "cf1", "cf2", hexCross );
  19451. addLine( "cf3", "cf4", hexCross );
  19452. this.camera = camera;
  19453. function addLine( a, b, hex ) {
  19454. addPoint( a, hex );
  19455. addPoint( b, hex );
  19456. }
  19457. function addPoint( id, hex ) {
  19458. scope.geometry.vertices.push( new THREE.Vector3() );
  19459. scope.geometry.colors.push( new THREE.Color( hex ) );
  19460. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  19461. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  19462. }
  19463. this.update( camera );
  19464. };
  19465. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  19466. THREE.CameraHelper.prototype.update = function () {
  19467. var scope = this;
  19468. var w = 1, h = 1;
  19469. // we need just camera projection matrix
  19470. // world matrix must be identity
  19471. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  19472. // center / target
  19473. setPoint( "c", 0, 0, -1 );
  19474. setPoint( "t", 0, 0, 1 );
  19475. // near
  19476. setPoint( "n1", -w, -h, -1 );
  19477. setPoint( "n2", w, -h, -1 );
  19478. setPoint( "n3", -w, h, -1 );
  19479. setPoint( "n4", w, h, -1 );
  19480. // far
  19481. setPoint( "f1", -w, -h, 1 );
  19482. setPoint( "f2", w, -h, 1 );
  19483. setPoint( "f3", -w, h, 1 );
  19484. setPoint( "f4", w, h, 1 );
  19485. // up
  19486. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19487. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19488. setPoint( "u3", 0, h * 2, -1 );
  19489. // cross
  19490. setPoint( "cf1", -w, 0, 1 );
  19491. setPoint( "cf2", w, 0, 1 );
  19492. setPoint( "cf3", 0, -h, 1 );
  19493. setPoint( "cf4", 0, h, 1 );
  19494. setPoint( "cn1", -w, 0, -1 );
  19495. setPoint( "cn2", w, 0, -1 );
  19496. setPoint( "cn3", 0, -h, -1 );
  19497. setPoint( "cn4", 0, h, -1 );
  19498. function setPoint( point, x, y, z ) {
  19499. THREE.CameraHelper.__v.set( x, y, z );
  19500. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19501. var points = scope.pointMap[ point ];
  19502. if ( points !== undefined ) {
  19503. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19504. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  19505. }
  19506. }
  19507. }
  19508. this.geometry.verticesNeedUpdate = true;
  19509. };
  19510. THREE.CameraHelper.__projector = new THREE.Projector();
  19511. THREE.CameraHelper.__v = new THREE.Vector3();
  19512. THREE.CameraHelper.__c = new THREE.Camera();
  19513. /*
  19514. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19515. *
  19516. * Subdivision Geometry Modifier
  19517. * using Catmull-Clark Subdivision Surfaces
  19518. * for creating smooth geometry meshes
  19519. *
  19520. * Note: a modifier modifies vertices and faces of geometry,
  19521. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  19522. *
  19523. * Readings:
  19524. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19525. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  19526. * http://xrt.wikidot.com/blog:31
  19527. * "Subdivision Surfaces in Character Animation"
  19528. *
  19529. * Supports:
  19530. * Closed and Open geometries.
  19531. *
  19532. * TODO:
  19533. * crease vertex and "semi-sharp" features
  19534. * selective subdivision
  19535. */
  19536. THREE.SubdivisionModifier = function( subdivisions ) {
  19537. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  19538. // Settings
  19539. this.useOldVertexColors = false;
  19540. this.supportUVs = true;
  19541. this.debug = false;
  19542. };
  19543. // Applies the "modify" pattern
  19544. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  19545. var repeats = this.subdivisions;
  19546. while ( repeats-- > 0 ) {
  19547. this.smooth( geometry );
  19548. }
  19549. };
  19550. // Performs an iteration of Catmull-Clark Subdivision
  19551. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  19552. //debug( 'running smooth' );
  19553. // New set of vertices, faces and uvs
  19554. var newVertices = [], newFaces = [], newUVs = [];
  19555. function v( x, y, z ) {
  19556. newVertices.push( new THREE.Vector3( x, y, z ) );
  19557. }
  19558. var scope = this;
  19559. function debug() {
  19560. if (scope.debug) console.log.apply(console, arguments);
  19561. }
  19562. function warn() {
  19563. if (console)
  19564. console.log.apply(console, arguments);
  19565. }
  19566. function f4( a, b, c, d, oldFace, orders, facei ) {
  19567. // TODO move vertex selection over here!
  19568. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  19569. if (scope.useOldVertexColors) {
  19570. newFace.vertexColors = [];
  19571. var color, tmpColor, order;
  19572. for (var i=0;i<4;i++) {
  19573. order = orders[i];
  19574. color = new THREE.Color(),
  19575. color.setRGB(0,0,0);
  19576. for (var j=0, jl=0; j<order.length;j++) {
  19577. tmpColor = oldFace.vertexColors[order[j]-1];
  19578. color.r += tmpColor.r;
  19579. color.g += tmpColor.g;
  19580. color.b += tmpColor.b;
  19581. }
  19582. color.r /= order.length;
  19583. color.g /= order.length;
  19584. color.b /= order.length;
  19585. newFace.vertexColors[i] = color;
  19586. }
  19587. }
  19588. newFaces.push( newFace );
  19589. if (scope.supportUVs) {
  19590. var aUv = [
  19591. getUV(a, ''),
  19592. getUV(b, facei),
  19593. getUV(c, facei),
  19594. getUV(d, facei)
  19595. ];
  19596. if (!aUv[0]) debug('a :( ', a+':'+facei);
  19597. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  19598. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  19599. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  19600. else
  19601. newUVs.push( aUv );
  19602. }
  19603. }
  19604. function edge_hash( a, b ) {
  19605. return Math.min( a, b ) + "_" + Math.max( a, b );
  19606. }
  19607. function computeEdgeFaces( geometry ) {
  19608. var i, il, v1, v2, j, k,
  19609. face, faceIndices, faceIndex,
  19610. edge,
  19611. hash,
  19612. edgeFaceMap = {};
  19613. function mapEdgeHash( hash, i ) {
  19614. if ( edgeFaceMap[ hash ] === undefined ) {
  19615. edgeFaceMap[ hash ] = [];
  19616. }
  19617. edgeFaceMap[ hash ].push( i );
  19618. }
  19619. // construct vertex -> face map
  19620. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  19621. face = geometry.faces[ i ];
  19622. if ( face instanceof THREE.Face3 ) {
  19623. hash = edge_hash( face.a, face.b );
  19624. mapEdgeHash( hash, i );
  19625. hash = edge_hash( face.b, face.c );
  19626. mapEdgeHash( hash, i );
  19627. hash = edge_hash( face.c, face.a );
  19628. mapEdgeHash( hash, i );
  19629. } else if ( face instanceof THREE.Face4 ) {
  19630. hash = edge_hash( face.a, face.b );
  19631. mapEdgeHash( hash, i );
  19632. hash = edge_hash( face.b, face.c );
  19633. mapEdgeHash( hash, i );
  19634. hash = edge_hash( face.c, face.d );
  19635. mapEdgeHash( hash, i );
  19636. hash = edge_hash( face.d, face.a );
  19637. mapEdgeHash( hash, i );
  19638. }
  19639. }
  19640. // extract faces
  19641. // var edges = [];
  19642. //
  19643. // var numOfEdges = 0;
  19644. // for (i in edgeFaceMap) {
  19645. // numOfEdges++;
  19646. //
  19647. // edge = edgeFaceMap[i];
  19648. // edges.push(edge);
  19649. //
  19650. // }
  19651. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  19652. return edgeFaceMap;
  19653. }
  19654. var originalPoints = oldGeometry.vertices;
  19655. var originalFaces = oldGeometry.faces;
  19656. var newPoints = originalPoints.concat(); // Vertices
  19657. var facePoints = [], edgePoints = {};
  19658. var sharpEdges = {}, sharpVertices = [], sharpFaces = [];
  19659. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  19660. var originalVerticesLength = originalPoints.length;
  19661. function getUV(vertexNo, oldFaceNo) {
  19662. var j,jl;
  19663. var key = vertexNo+':'+oldFaceNo;
  19664. var theUV = uvForVertices[key];
  19665. if (!theUV) {
  19666. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  19667. debug('face pt');
  19668. } else {
  19669. debug('edge pt');
  19670. }
  19671. warn('warning, UV not found for', key);
  19672. return null;
  19673. }
  19674. return theUV;
  19675. // Original faces -> Vertex Nos.
  19676. // new Facepoint -> Vertex Nos.
  19677. // edge Points
  19678. }
  19679. function addUV(vertexNo, oldFaceNo, value) {
  19680. var key = vertexNo+':'+oldFaceNo;
  19681. if (!(key in uvForVertices)) {
  19682. uvForVertices[key] = value;
  19683. } else {
  19684. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  19685. }
  19686. }
  19687. // Step 1
  19688. // For each face, add a face point
  19689. // Set each face point to be the centroid of all original points for the respective face.
  19690. // debug(oldGeometry);
  19691. var i, il, j, jl, face;
  19692. // For Uvs
  19693. var uvs = oldGeometry.faceVertexUvs[0];
  19694. var abcd = 'abcd', vertice;
  19695. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  19696. if (scope.supportUVs)
  19697. for (i=0, il = uvs.length; i<il; i++ ) {
  19698. for (j=0,jl=uvs[i].length;j<jl;j++) {
  19699. vertice = originalFaces[i][abcd.charAt(j)];
  19700. addUV(vertice, i, uvs[i][j]);
  19701. }
  19702. }
  19703. if (uvs.length == 0) scope.supportUVs = false;
  19704. // Additional UVs check, if we index original
  19705. var uvCount = 0;
  19706. for (var u in uvForVertices) {
  19707. uvCount++;
  19708. }
  19709. if (!uvCount) {
  19710. scope.supportUVs = false;
  19711. debug('no uvs');
  19712. }
  19713. debug('-- Original Faces + Vertices UVs completed', uvForVertices, 'vs', uvs.length);
  19714. var avgUv ;
  19715. for (i=0, il = originalFaces.length; i<il ;i++) {
  19716. face = originalFaces[ i ];
  19717. facePoints.push( face.centroid );
  19718. newPoints.push( face.centroid );
  19719. if (!scope.supportUVs) continue;
  19720. // Prepare subdivided uv
  19721. avgUv = new THREE.UV();
  19722. if ( face instanceof THREE.Face3 ) {
  19723. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  19724. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  19725. avgUv.u /= 3;
  19726. avgUv.v /= 3;
  19727. } else if ( face instanceof THREE.Face4 ) {
  19728. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  19729. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  19730. avgUv.u /= 4;
  19731. avgUv.v /= 4;
  19732. }
  19733. addUV(originalVerticesLength + i, '', avgUv);
  19734. }
  19735. debug('-- added UVs for new Faces', uvForVertices);
  19736. // Step 2
  19737. // For each edge, add an edge point.
  19738. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  19739. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index
  19740. var edge, faceIndexA, faceIndexB, avg;
  19741. // debug('edgeFaceMap', edgeFaceMap);
  19742. var edgeCount = 0;
  19743. var edgeVertex, edgeVertexA, edgeVertexB;
  19744. ////
  19745. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  19746. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  19747. function addVertexEdgeMap(vertex, edge) {
  19748. if (vertexEdgeMap[vertex]===undefined) {
  19749. vertexEdgeMap[vertex] = [];
  19750. }
  19751. vertexEdgeMap[vertex].push(edge);
  19752. }
  19753. function addVertexFaceMap(vertex, face, edge) {
  19754. if (vertexFaceMap[vertex]===undefined) {
  19755. vertexFaceMap[vertex] = {};
  19756. }
  19757. vertexFaceMap[vertex][face] = edge;
  19758. // vertexFaceMap[vertex][face] = null;
  19759. }
  19760. // Prepares vertexEdgeMap and vertexFaceMap
  19761. for (i in edgeFaceMap) { // This is for every edge
  19762. edge = edgeFaceMap[i];
  19763. edgeVertex = i.split('_');
  19764. edgeVertexA = edgeVertex[0];
  19765. edgeVertexB = edgeVertex[1];
  19766. // Maps an edgeVertex to connecting edges
  19767. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  19768. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  19769. for (j=0,jl=edge.length;j<jl;j++) {
  19770. face = edge[j];
  19771. addVertexFaceMap(edgeVertexA, face, i);
  19772. addVertexFaceMap(edgeVertexB, face, i);
  19773. }
  19774. if (edge.length < 2) {
  19775. // edge is "sharp";
  19776. sharpEdges[i] = true;
  19777. sharpVertices[edgeVertexA] = true;
  19778. sharpVertices[edgeVertexB] = true;
  19779. }
  19780. }
  19781. debug('vertexEdgeMap',vertexEdgeMap, 'vertexFaceMap', vertexFaceMap);
  19782. for (i in edgeFaceMap) {
  19783. edge = edgeFaceMap[i];
  19784. faceIndexA = edge[0]; // face index a
  19785. faceIndexB = edge[1]; // face index b
  19786. edgeVertex = i.split('_');
  19787. edgeVertexA = edgeVertex[0];
  19788. edgeVertexB = edgeVertex[1];
  19789. avg = new THREE.Vector3();
  19790. //debug(i, faceIndexB,facePoints[faceIndexB]);
  19791. if (sharpEdges[i]) {
  19792. //debug('warning, ', i, 'edge has only 1 connecting face', edge);
  19793. // For a sharp edge, average the edge end points.
  19794. avg.addSelf(originalPoints[edgeVertexA]);
  19795. avg.addSelf(originalPoints[edgeVertexB]);
  19796. avg.multiplyScalar(0.5);
  19797. sharpVertices[newPoints.length] = true;
  19798. } else {
  19799. avg.addSelf(facePoints[faceIndexA]);
  19800. avg.addSelf(facePoints[faceIndexB]);
  19801. avg.addSelf(originalPoints[edgeVertexA]);
  19802. avg.addSelf(originalPoints[edgeVertexB]);
  19803. avg.multiplyScalar(0.25);
  19804. }
  19805. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  19806. newPoints.push( avg );
  19807. edgeCount ++;
  19808. if (!scope.supportUVs) {
  19809. continue;
  19810. }
  19811. // debug('faceIndexAB', faceIndexA, faceIndexB, sharpEdges[i]);
  19812. // Prepare subdivided uv
  19813. avgUv = new THREE.UV();
  19814. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  19815. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  19816. avgUv.u /= 2;
  19817. avgUv.v /= 2;
  19818. addUV(edgePoints[i], faceIndexA, avgUv);
  19819. if (!sharpEdges[i]) {
  19820. avgUv = new THREE.UV();
  19821. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  19822. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  19823. avgUv.u /= 2;
  19824. avgUv.v /= 2;
  19825. addUV(edgePoints[i], faceIndexB, avgUv);
  19826. }
  19827. }
  19828. debug('-- Step 2 done');
  19829. // Step 3
  19830. // For each face point, add an edge for every edge of the face,
  19831. // connecting the face point to each edge point for the face.
  19832. var facePt, currentVerticeIndex;
  19833. var hashAB, hashBC, hashCD, hashDA, hashCA;
  19834. var abc123 = ['123', '12', '2', '23'];
  19835. var bca123 = ['123', '23', '3', '31'];
  19836. var cab123 = ['123', '31', '1', '12'];
  19837. var abc1234 = ['1234', '12', '2', '23'];
  19838. var bcd1234 = ['1234', '23', '3', '34'];
  19839. var cda1234 = ['1234', '34', '4', '41'];
  19840. var dab1234 = ['1234', '41', '1', '12'];
  19841. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  19842. facePt = facePoints[i];
  19843. face = originalFaces[i];
  19844. currentVerticeIndex = originalVerticesLength+ i;
  19845. if ( face instanceof THREE.Face3 ) {
  19846. // create 3 face4s
  19847. hashAB = edge_hash( face.a, face.b );
  19848. hashBC = edge_hash( face.b, face.c );
  19849. hashCA = edge_hash( face.c, face.a );
  19850. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  19851. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  19852. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  19853. } else if ( face instanceof THREE.Face4 ) {
  19854. // create 4 face4s
  19855. hashAB = edge_hash( face.a, face.b );
  19856. hashBC = edge_hash( face.b, face.c );
  19857. hashCD = edge_hash( face.c, face.d );
  19858. hashDA = edge_hash( face.d, face.a );
  19859. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  19860. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  19861. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  19862. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  19863. } else {
  19864. debug('face should be a face!', face);
  19865. }
  19866. }
  19867. newVertices = newPoints;
  19868. // debug('original ', oldGeometry.vertices.length, oldGeometry.faces.length );
  19869. // debug('new points', newPoints.length, 'faces', newFaces.length );
  19870. // Step 4
  19871. // For each original point P,
  19872. // take the average F of all n face points for faces touching P,
  19873. // and take the average R of all n edge midpoints for edges touching P,
  19874. // where each edge midpoint is the average of its two endpoint vertices.
  19875. // Move each original point to the point
  19876. var F = new THREE.Vector3();
  19877. var R = new THREE.Vector3();
  19878. var n;
  19879. for (i=0, il = originalPoints.length; i<il; i++) {
  19880. // (F + 2R + (n-3)P) / n
  19881. if (vertexEdgeMap[i]===undefined) continue;
  19882. F.set(0,0,0);
  19883. R.set(0,0,0);
  19884. var newPos = new THREE.Vector3(0,0,0);
  19885. var f =0;
  19886. for (j in vertexFaceMap[i]) {
  19887. F.addSelf(facePoints[j]);
  19888. f++;
  19889. }
  19890. var sharpEdgeCount = 0;
  19891. n = vertexEdgeMap[i].length;
  19892. for (j=0;j<n;j++) {
  19893. if (
  19894. sharpEdges[
  19895. edge_hash(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  19896. ]) {
  19897. sharpEdgeCount++;
  19898. }
  19899. }
  19900. if ( sharpEdgeCount==2 ) {
  19901. continue;
  19902. // Do not move vertex if there's 2 connecting sharp edges.
  19903. }
  19904. /*
  19905. if (sharpEdgeCount>2) {
  19906. // TODO
  19907. }
  19908. */
  19909. F.divideScalar(f);
  19910. for (j=0; j<n;j++) {
  19911. edge = vertexEdgeMap[i][j];
  19912. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  19913. R.addSelf(midPt);
  19914. // R.addSelf(originalPoints[edge[0]]);
  19915. // R.addSelf(originalPoints[edge[1]]);
  19916. }
  19917. R.divideScalar(n);
  19918. newPos.addSelf(originalPoints[i]);
  19919. newPos.multiplyScalar(n - 3);
  19920. newPos.addSelf(F);
  19921. newPos.addSelf(R.multiplyScalar(2));
  19922. newPos.divideScalar(n);
  19923. newVertices[i] = newPos;
  19924. }
  19925. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  19926. newGeometry.vertices = newVertices;
  19927. newGeometry.faces = newFaces;
  19928. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  19929. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  19930. newGeometry.computeCentroids();
  19931. newGeometry.computeFaceNormals();
  19932. newGeometry.computeVertexNormals();
  19933. };
  19934. /**
  19935. * @author alteredq / http://alteredqualia.com/
  19936. */
  19937. THREE.ImmediateRenderObject = function ( ) {
  19938. THREE.Object3D.call( this );
  19939. this.render = function ( renderCallback ) { };
  19940. };
  19941. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  19942. /**
  19943. * @author mikael emtinger / http://gomo.se/
  19944. * @author alteredq / http://alteredqualia.com/
  19945. */
  19946. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  19947. THREE.Object3D.call( this );
  19948. this.lensFlares = [];
  19949. this.positionScreen = new THREE.Vector3();
  19950. this.customUpdateCallback = undefined;
  19951. if( texture !== undefined ) {
  19952. this.add( texture, size, distance, blending, color );
  19953. }
  19954. };
  19955. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  19956. /*
  19957. * Add: adds another flare
  19958. */
  19959. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  19960. if( size === undefined ) size = -1;
  19961. if( distance === undefined ) distance = 0;
  19962. if( opacity === undefined ) opacity = 1;
  19963. if( color === undefined ) color = new THREE.Color( 0xffffff );
  19964. if( blending === undefined ) blending = THREE.NormalBlending;
  19965. distance = Math.min( distance, Math.max( 0, distance ) );
  19966. this.lensFlares.push( { texture: texture, // THREE.Texture
  19967. size: size, // size in pixels (-1 = use texture.width)
  19968. distance: distance, // distance (0-1) from light source (0=at light source)
  19969. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  19970. scale: 1, // scale
  19971. rotation: 1, // rotation
  19972. opacity: opacity, // opacity
  19973. color: color, // color
  19974. blending: blending } ); // blending
  19975. };
  19976. /*
  19977. * Update lens flares update positions on all flares based on the screen position
  19978. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  19979. */
  19980. THREE.LensFlare.prototype.updateLensFlares = function () {
  19981. var f, fl = this.lensFlares.length;
  19982. var flare;
  19983. var vecX = -this.positionScreen.x * 2;
  19984. var vecY = -this.positionScreen.y * 2;
  19985. for( f = 0; f < fl; f ++ ) {
  19986. flare = this.lensFlares[ f ];
  19987. flare.x = this.positionScreen.x + vecX * flare.distance;
  19988. flare.y = this.positionScreen.y + vecY * flare.distance;
  19989. flare.wantedRotation = flare.x * Math.PI * 0.25;
  19990. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  19991. }
  19992. };
  19993. /**
  19994. * @author alteredq / http://alteredqualia.com/
  19995. */
  19996. THREE.MorphBlendMesh = function( geometry, material ) {
  19997. THREE.Mesh.call( this, geometry, material );
  19998. this.animationsMap = {};
  19999. this.animationsList = [];
  20000. // prepare default animation
  20001. // (all frames played together in 1 second)
  20002. var numFrames = this.geometry.morphTargets.length;
  20003. var name = "__default";
  20004. var startFrame = 0;
  20005. var endFrame = numFrames - 1;
  20006. var fps = numFrames / 1;
  20007. this.createAnimation( name, startFrame, endFrame, fps );
  20008. this.setAnimationWeight( name, 1 );
  20009. };
  20010. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20011. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20012. var animation = {
  20013. startFrame: start,
  20014. endFrame: end,
  20015. length: end - start + 1,
  20016. fps: fps,
  20017. duration: ( end - start ) / fps,
  20018. lastFrame: 0,
  20019. currentFrame: 0,
  20020. active: false,
  20021. time: 0,
  20022. direction: 1,
  20023. weight: 1,
  20024. directionBackwards: false,
  20025. mirroredLoop: false
  20026. };
  20027. this.animationsMap[ name ] = animation;
  20028. this.animationsList.push( animation );
  20029. };
  20030. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20031. var pattern = /([a-z]+)(\d+)/;
  20032. var firstAnimation, frameRanges = {};
  20033. var geometry = this.geometry;
  20034. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20035. var morph = geometry.morphTargets[ i ];
  20036. var chunks = morph.name.match( pattern );
  20037. if ( chunks && chunks.length > 1 ) {
  20038. var name = chunks[ 1 ];
  20039. var num = chunks[ 2 ];
  20040. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20041. var range = frameRanges[ name ];
  20042. if ( i < range.start ) range.start = i;
  20043. if ( i > range.end ) range.end = i;
  20044. if ( ! firstAnimation ) firstAnimation = name;
  20045. }
  20046. }
  20047. for ( var name in frameRanges ) {
  20048. var range = frameRanges[ name ];
  20049. this.createAnimation( name, range.start, range.end, fps );
  20050. }
  20051. this.firstAnimation = firstAnimation;
  20052. };
  20053. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20054. var animation = this.animationsMap[ name ];
  20055. if ( animation ) {
  20056. animation.direction = 1;
  20057. animation.directionBackwards = false;
  20058. }
  20059. };
  20060. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20061. var animation = this.animationsMap[ name ];
  20062. if ( animation ) {
  20063. animation.direction = -1;
  20064. animation.directionBackwards = true;
  20065. }
  20066. };
  20067. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20068. var animation = this.animationsMap[ name ];
  20069. if ( animation ) {
  20070. animation.fps = fps;
  20071. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20072. }
  20073. };
  20074. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20075. var animation = this.animationsMap[ name ];
  20076. if ( animation ) {
  20077. animation.duration = duration;
  20078. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20079. }
  20080. };
  20081. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20082. var animation = this.animationsMap[ name ];
  20083. if ( animation ) {
  20084. animation.weight = weight;
  20085. }
  20086. };
  20087. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20088. var animation = this.animationsMap[ name ];
  20089. if ( animation ) {
  20090. animation.time = time;
  20091. }
  20092. };
  20093. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20094. var time = 0;
  20095. var animation = this.animationsMap[ name ];
  20096. if ( animation ) {
  20097. time = animation.time;
  20098. }
  20099. return time;
  20100. };
  20101. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20102. var duration = -1;
  20103. var animation = this.animationsMap[ name ];
  20104. if ( animation ) {
  20105. duration = animation.duration;
  20106. }
  20107. return duration;
  20108. };
  20109. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20110. var animation = this.animationsMap[ name ];
  20111. if ( animation ) {
  20112. animation.time = 0;
  20113. animation.active = true;
  20114. } else {
  20115. console.warn( "animation[" + name + "] undefined" );
  20116. }
  20117. };
  20118. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20119. var animation = this.animationsMap[ name ];
  20120. if ( animation ) {
  20121. animation.active = false;
  20122. }
  20123. };
  20124. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20125. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20126. var animation = this.animationsList[ i ];
  20127. if ( ! animation.active ) continue;
  20128. var frameTime = animation.duration / animation.length;
  20129. animation.time += animation.direction * delta;
  20130. if ( animation.mirroredLoop ) {
  20131. if ( animation.time > animation.duration || animation.time < 0 ) {
  20132. animation.direction *= -1;
  20133. if ( animation.time > animation.duration ) {
  20134. animation.time = animation.duration;
  20135. animation.directionBackwards = true;
  20136. }
  20137. if ( animation.time < 0 ) {
  20138. animation.time = 0;
  20139. animation.directionBackwards = false;
  20140. }
  20141. }
  20142. } else {
  20143. animation.time = animation.time % animation.duration;
  20144. if ( animation.time < 0 ) animation.time += animation.duration;
  20145. }
  20146. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20147. var weight = animation.weight;
  20148. if ( keyframe !== animation.currentFrame ) {
  20149. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20150. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20151. this.morphTargetInfluences[ keyframe ] = 0;
  20152. animation.lastFrame = animation.currentFrame;
  20153. animation.currentFrame = keyframe;
  20154. }
  20155. var mix = ( animation.time % frameTime ) / frameTime;
  20156. if ( animation.directionBackwards ) mix = 1 - mix;
  20157. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20158. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20159. }
  20160. };
  20161. /**
  20162. * @author mikael emtinger / http://gomo.se/
  20163. * @author alteredq / http://alteredqualia.com/
  20164. */
  20165. THREE.LensFlarePlugin = function ( ) {
  20166. var _gl, _renderer, _lensFlare = {};
  20167. this.init = function ( renderer ) {
  20168. _gl = renderer.context;
  20169. _renderer = renderer;
  20170. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20171. _lensFlare.faces = new Uint16Array( 6 );
  20172. var i = 0;
  20173. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20174. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20175. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20176. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20177. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20178. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20179. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20180. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20181. i = 0;
  20182. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20183. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20184. // buffers
  20185. _lensFlare.vertexBuffer = _gl.createBuffer();
  20186. _lensFlare.elementBuffer = _gl.createBuffer();
  20187. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20188. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20189. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20190. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20191. // textures
  20192. _lensFlare.tempTexture = _gl.createTexture();
  20193. _lensFlare.occlusionTexture = _gl.createTexture();
  20194. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20195. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20196. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20197. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20198. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20199. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20200. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20201. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20202. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20203. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20204. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20205. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20206. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20207. _lensFlare.hasVertexTexture = false;
  20208. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20209. } else {
  20210. _lensFlare.hasVertexTexture = true;
  20211. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20212. }
  20213. _lensFlare.attributes = {};
  20214. _lensFlare.uniforms = {};
  20215. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20216. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20217. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20218. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20219. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20220. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20221. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20222. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20223. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20224. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20225. _lensFlare.attributesEnabled = false;
  20226. };
  20227. /*
  20228. * Render lens flares
  20229. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20230. * reads these back and calculates occlusion.
  20231. * Then _lensFlare.update_lensFlares() is called to re-position and
  20232. * update transparency of flares. Then they are rendered.
  20233. *
  20234. */
  20235. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20236. var flares = scene.__webglFlares,
  20237. nFlares = flares.length;
  20238. if ( ! nFlares ) return;
  20239. var tempPosition = new THREE.Vector3();
  20240. var invAspect = viewportHeight / viewportWidth,
  20241. halfViewportWidth = viewportWidth * 0.5,
  20242. halfViewportHeight = viewportHeight * 0.5;
  20243. var size = 16 / viewportHeight,
  20244. scale = new THREE.Vector2( size * invAspect, size );
  20245. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20246. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20247. var uniforms = _lensFlare.uniforms,
  20248. attributes = _lensFlare.attributes;
  20249. // set _lensFlare program and reset blending
  20250. _gl.useProgram( _lensFlare.program );
  20251. if ( ! _lensFlare.attributesEnabled ) {
  20252. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20253. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20254. _lensFlare.attributesEnabled = true;
  20255. }
  20256. // loop through all lens flares to update their occlusion and positions
  20257. // setup gl and common used attribs/unforms
  20258. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20259. _gl.uniform1i( uniforms.map, 1 );
  20260. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20261. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20262. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20263. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20264. _gl.disable( _gl.CULL_FACE );
  20265. _gl.depthMask( false );
  20266. var i, j, jl, flare, sprite;
  20267. for ( i = 0; i < nFlares; i ++ ) {
  20268. size = 16 / viewportHeight;
  20269. scale.set( size * invAspect, size );
  20270. // calc object screen position
  20271. flare = flares[ i ];
  20272. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20273. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  20274. camera.projectionMatrix.multiplyVector3( tempPosition );
  20275. // setup arrays for gl programs
  20276. screenPosition.copy( tempPosition )
  20277. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20278. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20279. // screen cull
  20280. if ( _lensFlare.hasVertexTexture || (
  20281. screenPositionPixels.x > 0 &&
  20282. screenPositionPixels.x < viewportWidth &&
  20283. screenPositionPixels.y > 0 &&
  20284. screenPositionPixels.y < viewportHeight ) ) {
  20285. // save current RGB to temp texture
  20286. _gl.activeTexture( _gl.TEXTURE1 );
  20287. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20288. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20289. // render pink quad
  20290. _gl.uniform1i( uniforms.renderType, 0 );
  20291. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20292. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20293. _gl.disable( _gl.BLEND );
  20294. _gl.enable( _gl.DEPTH_TEST );
  20295. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20296. // copy result to occlusionMap
  20297. _gl.activeTexture( _gl.TEXTURE0 );
  20298. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20299. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20300. // restore graphics
  20301. _gl.uniform1i( uniforms.renderType, 1 );
  20302. _gl.disable( _gl.DEPTH_TEST );
  20303. _gl.activeTexture( _gl.TEXTURE1 );
  20304. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20305. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20306. // update object positions
  20307. flare.positionScreen.copy( screenPosition )
  20308. if ( flare.customUpdateCallback ) {
  20309. flare.customUpdateCallback( flare );
  20310. } else {
  20311. flare.updateLensFlares();
  20312. }
  20313. // render flares
  20314. _gl.uniform1i( uniforms.renderType, 2 );
  20315. _gl.enable( _gl.BLEND );
  20316. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20317. sprite = flare.lensFlares[ j ];
  20318. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20319. screenPosition.x = sprite.x;
  20320. screenPosition.y = sprite.y;
  20321. screenPosition.z = sprite.z;
  20322. size = sprite.size * sprite.scale / viewportHeight;
  20323. scale.x = size * invAspect;
  20324. scale.y = size;
  20325. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20326. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20327. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20328. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20329. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20330. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20331. _renderer.setTexture( sprite.texture, 1 );
  20332. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20333. }
  20334. }
  20335. }
  20336. }
  20337. // restore gl
  20338. _gl.enable( _gl.CULL_FACE );
  20339. _gl.enable( _gl.DEPTH_TEST );
  20340. _gl.depthMask( true );
  20341. };
  20342. function createProgram ( shader ) {
  20343. var program = _gl.createProgram();
  20344. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20345. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20346. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20347. _gl.shaderSource( vertexShader, shader.vertexShader );
  20348. _gl.compileShader( fragmentShader );
  20349. _gl.compileShader( vertexShader );
  20350. _gl.attachShader( program, fragmentShader );
  20351. _gl.attachShader( program, vertexShader );
  20352. _gl.linkProgram( program );
  20353. return program;
  20354. };
  20355. };/**
  20356. * @author alteredq / http://alteredqualia.com/
  20357. */
  20358. THREE.ShadowMapPlugin = function ( ) {
  20359. var _gl,
  20360. _renderer,
  20361. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20362. _frustum = new THREE.Frustum(),
  20363. _projScreenMatrix = new THREE.Matrix4(),
  20364. _min = new THREE.Vector3(),
  20365. _max = new THREE.Vector3();
  20366. this.init = function ( renderer ) {
  20367. _gl = renderer.context;
  20368. _renderer = renderer;
  20369. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20370. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20371. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20372. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20373. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20374. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20375. _depthMaterial._shadowPass = true;
  20376. _depthMaterialMorph._shadowPass = true;
  20377. _depthMaterialSkin._shadowPass = true;
  20378. _depthMaterialMorphSkin._shadowPass = true;
  20379. };
  20380. this.render = function ( scene, camera ) {
  20381. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20382. this.update( scene, camera );
  20383. };
  20384. this.update = function ( scene, camera ) {
  20385. var i, il, j, jl, n,
  20386. shadowMap, shadowMatrix, shadowCamera,
  20387. program, buffer, material,
  20388. webglObject, object, light,
  20389. renderList,
  20390. lights = [],
  20391. k = 0,
  20392. fog = null;
  20393. // set GL state for depth map
  20394. _gl.clearColor( 1, 1, 1, 1 );
  20395. _gl.disable( _gl.BLEND );
  20396. _gl.enable( _gl.CULL_FACE );
  20397. if ( _renderer.shadowMapCullFrontFaces ) {
  20398. _gl.cullFace( _gl.FRONT );
  20399. } else {
  20400. _gl.cullFace( _gl.BACK );
  20401. }
  20402. _renderer.setDepthTest( true );
  20403. // preprocess lights
  20404. // - skip lights that are not casting shadows
  20405. // - create virtual lights for cascaded shadow maps
  20406. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20407. light = scene.__lights[ i ];
  20408. if ( ! light.castShadow ) continue;
  20409. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20410. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20411. var virtualLight;
  20412. if ( ! light.shadowCascadeArray[ n ] ) {
  20413. virtualLight = createVirtualLight( light, n );
  20414. virtualLight.originalCamera = camera;
  20415. var gyro = new THREE.Gyroscope();
  20416. gyro.position = light.shadowCascadeOffset;
  20417. gyro.add( virtualLight );
  20418. gyro.add( virtualLight.target );
  20419. camera.add( gyro );
  20420. light.shadowCascadeArray[ n ] = virtualLight;
  20421. console.log( "Created virtualLight", virtualLight );
  20422. } else {
  20423. virtualLight = light.shadowCascadeArray[ n ];
  20424. }
  20425. updateVirtualLight( light, n );
  20426. lights[ k ] = virtualLight;
  20427. k ++;
  20428. }
  20429. } else {
  20430. lights[ k ] = light;
  20431. k ++;
  20432. }
  20433. }
  20434. // render depth map
  20435. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20436. light = lights[ i ];
  20437. if ( ! light.shadowMap ) {
  20438. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  20439. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20440. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20441. light.shadowMatrix = new THREE.Matrix4();
  20442. }
  20443. if ( ! light.shadowCamera ) {
  20444. if ( light instanceof THREE.SpotLight ) {
  20445. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20446. } else if ( light instanceof THREE.DirectionalLight ) {
  20447. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20448. } else {
  20449. console.error( "Unsupported light type for shadow" );
  20450. continue;
  20451. }
  20452. scene.add( light.shadowCamera );
  20453. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20454. }
  20455. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20456. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20457. light.shadowCamera.add( light.cameraHelper );
  20458. }
  20459. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20460. updateShadowCamera( camera, light );
  20461. }
  20462. shadowMap = light.shadowMap;
  20463. shadowMatrix = light.shadowMatrix;
  20464. shadowCamera = light.shadowCamera;
  20465. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20466. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20467. shadowCamera.updateMatrixWorld();
  20468. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20469. if ( light.cameraHelper ) light.cameraHelper.lines.visible = light.shadowCameraVisible;
  20470. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20471. // compute shadow matrix
  20472. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20473. 0.0, 0.5, 0.0, 0.5,
  20474. 0.0, 0.0, 0.5, 0.5,
  20475. 0.0, 0.0, 0.0, 1.0 );
  20476. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  20477. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  20478. // update camera matrices and frustum
  20479. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  20480. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  20481. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  20482. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  20483. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20484. _frustum.setFromMatrix( _projScreenMatrix );
  20485. // render shadow map
  20486. _renderer.setRenderTarget( shadowMap );
  20487. _renderer.clear();
  20488. // set object matrices & frustum culling
  20489. renderList = scene.__webglObjects;
  20490. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20491. webglObject = renderList[ j ];
  20492. object = webglObject.object;
  20493. webglObject.render = false;
  20494. if ( object.visible && object.castShadow ) {
  20495. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20496. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20497. webglObject.render = true;
  20498. }
  20499. }
  20500. }
  20501. // render regular objects
  20502. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20503. webglObject = renderList[ j ];
  20504. if ( webglObject.render ) {
  20505. object = webglObject.object;
  20506. buffer = webglObject.buffer;
  20507. // culling is overriden globally for all objects
  20508. // while rendering depth map
  20509. if ( object.customDepthMaterial ) {
  20510. material = object.customDepthMaterial;
  20511. } else if ( object instanceof THREE.SkinnedMesh ) {
  20512. material = object.geometry.morphTargets.length ? _depthMaterialMorphSkin : _depthMaterialSkin;
  20513. } else if ( object.geometry.morphTargets.length ) {
  20514. material = _depthMaterialMorph;
  20515. } else {
  20516. material = _depthMaterial;
  20517. }
  20518. if ( buffer instanceof THREE.BufferGeometry ) {
  20519. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20520. } else {
  20521. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20522. }
  20523. }
  20524. }
  20525. // set matrices and render immediate objects
  20526. renderList = scene.__webglObjectsImmediate;
  20527. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20528. webglObject = renderList[ j ];
  20529. object = webglObject.object;
  20530. if ( object.visible && object.castShadow ) {
  20531. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20532. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20533. }
  20534. }
  20535. }
  20536. // restore GL state
  20537. var clearColor = _renderer.getClearColor(),
  20538. clearAlpha = _renderer.getClearAlpha();
  20539. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20540. _gl.enable( _gl.BLEND );
  20541. if ( _renderer.shadowMapCullFrontFaces ) {
  20542. _gl.cullFace( _gl.BACK );
  20543. }
  20544. };
  20545. function createVirtualLight( light, cascade ) {
  20546. var virtualLight = new THREE.DirectionalLight();
  20547. virtualLight.isVirtual = true;
  20548. virtualLight.onlyShadow = true;
  20549. virtualLight.castShadow = true;
  20550. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20551. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20552. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20553. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20554. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20555. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20556. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20557. virtualLight.shadowDarkness = light.shadowDarkness;
  20558. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20559. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20560. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20561. virtualLight.pointsWorld = [];
  20562. virtualLight.pointsFrustum = [];
  20563. var pointsWorld = virtualLight.pointsWorld,
  20564. pointsFrustum = virtualLight.pointsFrustum;
  20565. for ( var i = 0; i < 8; i ++ ) {
  20566. pointsWorld[ i ] = new THREE.Vector3();
  20567. pointsFrustum[ i ] = new THREE.Vector3();
  20568. }
  20569. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20570. var farZ = light.shadowCascadeFarZ[ cascade ];
  20571. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20572. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20573. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20574. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20575. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20576. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20577. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20578. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20579. return virtualLight;
  20580. }
  20581. // Synchronize virtual light with the original light
  20582. function updateVirtualLight( light, cascade ) {
  20583. var virtualLight = light.shadowCascadeArray[ cascade ];
  20584. virtualLight.position.copy( light.position );
  20585. virtualLight.target.position.copy( light.target.position );
  20586. virtualLight.lookAt( virtualLight.target );
  20587. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20588. virtualLight.shadowDarkness = light.shadowDarkness;
  20589. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20590. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20591. var farZ = light.shadowCascadeFarZ[ cascade ];
  20592. var pointsFrustum = virtualLight.pointsFrustum;
  20593. pointsFrustum[ 0 ].z = nearZ;
  20594. pointsFrustum[ 1 ].z = nearZ;
  20595. pointsFrustum[ 2 ].z = nearZ;
  20596. pointsFrustum[ 3 ].z = nearZ;
  20597. pointsFrustum[ 4 ].z = farZ;
  20598. pointsFrustum[ 5 ].z = farZ;
  20599. pointsFrustum[ 6 ].z = farZ;
  20600. pointsFrustum[ 7 ].z = farZ;
  20601. }
  20602. // Fit shadow camera's ortho frustum to camera frustum
  20603. function updateShadowCamera( camera, light ) {
  20604. var shadowCamera = light.shadowCamera,
  20605. pointsFrustum = light.pointsFrustum,
  20606. pointsWorld = light.pointsWorld;
  20607. _min.set( Infinity, Infinity, Infinity );
  20608. _max.set( -Infinity, -Infinity, -Infinity );
  20609. for ( var i = 0; i < 8; i ++ ) {
  20610. var p = pointsWorld[ i ];
  20611. p.copy( pointsFrustum[ i ] );
  20612. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  20613. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  20614. if ( p.x < _min.x ) _min.x = p.x;
  20615. if ( p.x > _max.x ) _max.x = p.x;
  20616. if ( p.y < _min.y ) _min.y = p.y;
  20617. if ( p.y > _max.y ) _max.y = p.y;
  20618. if ( p.z < _min.z ) _min.z = p.z;
  20619. if ( p.z > _max.z ) _max.z = p.z;
  20620. }
  20621. shadowCamera.left = _min.x;
  20622. shadowCamera.right = _max.x;
  20623. shadowCamera.top = _max.y;
  20624. shadowCamera.bottom = _min.y;
  20625. // can't really fit near/far
  20626. //shadowCamera.near = _min.z;
  20627. //shadowCamera.far = _max.z;
  20628. shadowCamera.updateProjectionMatrix();
  20629. }
  20630. };
  20631. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  20632. /**
  20633. * @author mikael emtinger / http://gomo.se/
  20634. * @author alteredq / http://alteredqualia.com/
  20635. */
  20636. THREE.SpritePlugin = function ( ) {
  20637. var _gl, _renderer, _sprite = {};
  20638. this.init = function ( renderer ) {
  20639. _gl = renderer.context;
  20640. _renderer = renderer;
  20641. _sprite.vertices = new Float32Array( 8 + 8 );
  20642. _sprite.faces = new Uint16Array( 6 );
  20643. var i = 0;
  20644. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  20645. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  20646. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  20647. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  20648. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  20649. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  20650. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  20651. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  20652. i = 0;
  20653. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  20654. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  20655. _sprite.vertexBuffer = _gl.createBuffer();
  20656. _sprite.elementBuffer = _gl.createBuffer();
  20657. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20658. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  20659. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20660. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  20661. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  20662. _sprite.attributes = {};
  20663. _sprite.uniforms = {};
  20664. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  20665. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  20666. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  20667. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  20668. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  20669. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  20670. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  20671. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  20672. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  20673. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  20674. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  20675. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  20676. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  20677. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  20678. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  20679. _sprite.attributesEnabled = false;
  20680. };
  20681. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20682. var sprites = scene.__webglSprites,
  20683. nSprites = sprites.length;
  20684. if ( ! nSprites ) return;
  20685. var attributes = _sprite.attributes,
  20686. uniforms = _sprite.uniforms;
  20687. var invAspect = viewportHeight / viewportWidth;
  20688. var halfViewportWidth = viewportWidth * 0.5,
  20689. halfViewportHeight = viewportHeight * 0.5;
  20690. var mergeWith3D = true;
  20691. // setup gl
  20692. _gl.useProgram( _sprite.program );
  20693. if ( ! _sprite.attributesEnabled ) {
  20694. _gl.enableVertexAttribArray( attributes.position );
  20695. _gl.enableVertexAttribArray( attributes.uv );
  20696. _sprite.attributesEnabled = true;
  20697. }
  20698. _gl.disable( _gl.CULL_FACE );
  20699. _gl.enable( _gl.BLEND );
  20700. _gl.depthMask( true );
  20701. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20702. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20703. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20704. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20705. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  20706. _gl.activeTexture( _gl.TEXTURE0 );
  20707. _gl.uniform1i( uniforms.map, 0 );
  20708. // update positions and sort
  20709. var i, sprite, screenPosition, size, scale = [];
  20710. for( i = 0; i < nSprites; i ++ ) {
  20711. sprite = sprites[ i ];
  20712. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  20713. if( ! sprite.useScreenCoordinates ) {
  20714. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  20715. sprite.z = - sprite._modelViewMatrix.elements[14];
  20716. } else {
  20717. sprite.z = - sprite.position.z;
  20718. }
  20719. }
  20720. sprites.sort( painterSort );
  20721. // render all sprites
  20722. for( i = 0; i < nSprites; i ++ ) {
  20723. sprite = sprites[ i ];
  20724. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  20725. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  20726. if ( sprite.useScreenCoordinates ) {
  20727. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  20728. _gl.uniform3f( uniforms.screenPosition, ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  20729. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  20730. Math.max( 0, Math.min( 1, sprite.position.z ) ) );
  20731. } else {
  20732. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  20733. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  20734. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  20735. }
  20736. size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
  20737. scale[ 0 ] = size * invAspect * sprite.scale.x;
  20738. scale[ 1 ] = size * sprite.scale.y;
  20739. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  20740. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  20741. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  20742. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20743. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20744. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20745. _gl.uniform2fv( uniforms.scale, scale );
  20746. if ( sprite.mergeWith3D && !mergeWith3D ) {
  20747. _gl.enable( _gl.DEPTH_TEST );
  20748. mergeWith3D = true;
  20749. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  20750. _gl.disable( _gl.DEPTH_TEST );
  20751. mergeWith3D = false;
  20752. }
  20753. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20754. _renderer.setTexture( sprite.map, 0 );
  20755. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20756. }
  20757. }
  20758. // restore gl
  20759. _gl.enable( _gl.CULL_FACE );
  20760. _gl.enable( _gl.DEPTH_TEST );
  20761. _gl.depthMask( true );
  20762. };
  20763. function createProgram ( shader ) {
  20764. var program = _gl.createProgram();
  20765. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20766. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20767. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20768. _gl.shaderSource( vertexShader, shader.vertexShader );
  20769. _gl.compileShader( fragmentShader );
  20770. _gl.compileShader( vertexShader );
  20771. _gl.attachShader( program, fragmentShader );
  20772. _gl.attachShader( program, vertexShader );
  20773. _gl.linkProgram( program );
  20774. return program;
  20775. };
  20776. function painterSort ( a, b ) {
  20777. return b.z - a.z;
  20778. };
  20779. };/**
  20780. * @author alteredq / http://alteredqualia.com/
  20781. */
  20782. THREE.DepthPassPlugin = function ( ) {
  20783. this.enabled = false;
  20784. this.renderTarget = null;
  20785. var _gl,
  20786. _renderer,
  20787. _depthMaterial, _depthMaterialMorph,
  20788. _frustum = new THREE.Frustum(),
  20789. _projScreenMatrix = new THREE.Matrix4();
  20790. this.init = function ( renderer ) {
  20791. _gl = renderer.context;
  20792. _renderer = renderer;
  20793. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20794. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20795. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20796. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20797. _depthMaterial._shadowPass = true;
  20798. _depthMaterialMorph._shadowPass = true;
  20799. };
  20800. this.render = function ( scene, camera ) {
  20801. if ( ! this.enabled ) return;
  20802. this.update( scene, camera );
  20803. };
  20804. this.update = function ( scene, camera ) {
  20805. var i, il, j, jl, n,
  20806. program, buffer, material,
  20807. webglObject, object, light,
  20808. renderList,
  20809. fog = null;
  20810. // set GL state for depth map
  20811. _gl.clearColor( 1, 1, 1, 1 );
  20812. _gl.disable( _gl.BLEND );
  20813. _renderer.setDepthTest( true );
  20814. // update scene
  20815. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20816. // update camera matrices and frustum
  20817. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  20818. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  20819. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  20820. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  20821. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  20822. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  20823. _frustum.setFromMatrix( _projScreenMatrix );
  20824. // render depth map
  20825. _renderer.setRenderTarget( this.renderTarget );
  20826. _renderer.clear();
  20827. // set object matrices & frustum culling
  20828. renderList = scene.__webglObjects;
  20829. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20830. webglObject = renderList[ j ];
  20831. object = webglObject.object;
  20832. webglObject.render = false;
  20833. if ( object.visible ) {
  20834. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20835. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  20836. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  20837. webglObject.render = true;
  20838. }
  20839. }
  20840. }
  20841. // render regular objects
  20842. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20843. webglObject = renderList[ j ];
  20844. if ( webglObject.render ) {
  20845. object = webglObject.object;
  20846. buffer = webglObject.buffer;
  20847. if ( object.material ) _renderer.setMaterialFaces( object.material );
  20848. if ( object.customDepthMaterial ) {
  20849. material = object.customDepthMaterial;
  20850. } else if ( object.geometry.morphTargets.length ) {
  20851. material = _depthMaterialMorph;
  20852. } else {
  20853. material = _depthMaterial;
  20854. }
  20855. if ( buffer instanceof THREE.BufferGeometry ) {
  20856. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  20857. } else {
  20858. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  20859. }
  20860. }
  20861. }
  20862. // set matrices and render immediate objects
  20863. renderList = scene.__webglObjectsImmediate;
  20864. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20865. webglObject = renderList[ j ];
  20866. object = webglObject.object;
  20867. if ( object.visible && object.castShadow ) {
  20868. /*
  20869. if ( object.matrixAutoUpdate ) {
  20870. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  20871. }
  20872. */
  20873. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  20874. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  20875. }
  20876. }
  20877. // restore GL state
  20878. var clearColor = _renderer.getClearColor(),
  20879. clearAlpha = _renderer.getClearAlpha();
  20880. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20881. _gl.enable( _gl.BLEND );
  20882. };
  20883. };
  20884. /**
  20885. * @author mikael emtinger / http://gomo.se/
  20886. *
  20887. */
  20888. THREE.ShaderFlares = {
  20889. 'lensFlareVertexTexture': {
  20890. vertexShader: [
  20891. "uniform vec3 screenPosition;",
  20892. "uniform vec2 scale;",
  20893. "uniform float rotation;",
  20894. "uniform int renderType;",
  20895. "uniform sampler2D occlusionMap;",
  20896. "attribute vec2 position;",
  20897. "attribute vec2 uv;",
  20898. "varying vec2 vUV;",
  20899. "varying float vVisibility;",
  20900. "void main() {",
  20901. "vUV = uv;",
  20902. "vec2 pos = position;",
  20903. "if( renderType == 2 ) {",
  20904. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  20905. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  20906. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  20907. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  20908. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  20909. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  20910. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  20911. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  20912. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  20913. "vVisibility = ( visibility.r / 9.0 ) *",
  20914. "( 1.0 - visibility.g / 9.0 ) *",
  20915. "( visibility.b / 9.0 ) *",
  20916. "( 1.0 - visibility.a / 9.0 );",
  20917. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  20918. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  20919. "}",
  20920. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  20921. "}"
  20922. ].join( "\n" ),
  20923. fragmentShader: [
  20924. "precision mediump float;",
  20925. "uniform sampler2D map;",
  20926. "uniform float opacity;",
  20927. "uniform int renderType;",
  20928. "uniform vec3 color;",
  20929. "varying vec2 vUV;",
  20930. "varying float vVisibility;",
  20931. "void main() {",
  20932. // pink square
  20933. "if( renderType == 0 ) {",
  20934. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  20935. // restore
  20936. "} else if( renderType == 1 ) {",
  20937. "gl_FragColor = texture2D( map, vUV );",
  20938. // flare
  20939. "} else {",
  20940. "vec4 texture = texture2D( map, vUV );",
  20941. "texture.a *= opacity * vVisibility;",
  20942. "gl_FragColor = texture;",
  20943. "gl_FragColor.rgb *= color;",
  20944. "}",
  20945. "}"
  20946. ].join( "\n" )
  20947. },
  20948. 'lensFlare': {
  20949. vertexShader: [
  20950. "uniform vec3 screenPosition;",
  20951. "uniform vec2 scale;",
  20952. "uniform float rotation;",
  20953. "uniform int renderType;",
  20954. "attribute vec2 position;",
  20955. "attribute vec2 uv;",
  20956. "varying vec2 vUV;",
  20957. "void main() {",
  20958. "vUV = uv;",
  20959. "vec2 pos = position;",
  20960. "if( renderType == 2 ) {",
  20961. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  20962. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  20963. "}",
  20964. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  20965. "}"
  20966. ].join( "\n" ),
  20967. fragmentShader: [
  20968. "precision mediump float;",
  20969. "uniform sampler2D map;",
  20970. "uniform sampler2D occlusionMap;",
  20971. "uniform float opacity;",
  20972. "uniform int renderType;",
  20973. "uniform vec3 color;",
  20974. "varying vec2 vUV;",
  20975. "void main() {",
  20976. // pink square
  20977. "if( renderType == 0 ) {",
  20978. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  20979. // restore
  20980. "} else if( renderType == 1 ) {",
  20981. "gl_FragColor = texture2D( map, vUV );",
  20982. // flare
  20983. "} else {",
  20984. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  20985. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  20986. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  20987. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  20988. "visibility = ( 1.0 - visibility / 4.0 );",
  20989. "vec4 texture = texture2D( map, vUV );",
  20990. "texture.a *= opacity * visibility;",
  20991. "gl_FragColor = texture;",
  20992. "gl_FragColor.rgb *= color;",
  20993. "}",
  20994. "}"
  20995. ].join( "\n" )
  20996. }
  20997. };
  20998. /**
  20999. * @author mikael emtinger / http://gomo.se/
  21000. *
  21001. */
  21002. THREE.ShaderSprite = {
  21003. 'sprite': {
  21004. vertexShader: [
  21005. "uniform int useScreenCoordinates;",
  21006. "uniform int affectedByDistance;",
  21007. "uniform vec3 screenPosition;",
  21008. "uniform mat4 modelViewMatrix;",
  21009. "uniform mat4 projectionMatrix;",
  21010. "uniform float rotation;",
  21011. "uniform vec2 scale;",
  21012. "uniform vec2 alignment;",
  21013. "uniform vec2 uvOffset;",
  21014. "uniform vec2 uvScale;",
  21015. "attribute vec2 position;",
  21016. "attribute vec2 uv;",
  21017. "varying vec2 vUV;",
  21018. "void main() {",
  21019. "vUV = uvOffset + uv * uvScale;",
  21020. "vec2 alignedPosition = position + alignment;",
  21021. "vec2 rotatedPosition;",
  21022. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21023. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21024. "vec4 finalPosition;",
  21025. "if( useScreenCoordinates != 0 ) {",
  21026. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21027. "} else {",
  21028. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21029. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  21030. "}",
  21031. "gl_Position = finalPosition;",
  21032. "}"
  21033. ].join( "\n" ),
  21034. fragmentShader: [
  21035. "precision mediump float;",
  21036. "uniform vec3 color;",
  21037. "uniform sampler2D map;",
  21038. "uniform float opacity;",
  21039. "varying vec2 vUV;",
  21040. "void main() {",
  21041. "vec4 texture = texture2D( map, vUV );",
  21042. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21043. "}"
  21044. ].join( "\n" )
  21045. }
  21046. };