three.js 778 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. var THREE = THREE || { REVISION: '50' };
  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. normalize: function () {
  738. return this.divideScalar( this.length() );
  739. },
  740. setLength: function ( l ) {
  741. return this.normalize().multiplyScalar( l );
  742. },
  743. lerpSelf: function ( v, alpha ) {
  744. this.x += ( v.x - this.x ) * alpha;
  745. this.y += ( v.y - this.y ) * alpha;
  746. this.z += ( v.z - this.z ) * alpha;
  747. this.w += ( v.w - this.w ) * alpha;
  748. return this;
  749. },
  750. clone: function () {
  751. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  752. },
  753. setAxisAngleFromQuaternion: function ( q ) {
  754. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  755. // q is assumed to be normalized
  756. this.w = 2 * Math.acos( q.w );
  757. var s = Math.sqrt( 1 - q.w * q.w );
  758. if ( s < 0.0001 ) {
  759. this.x = 1;
  760. this.y = 0;
  761. this.z = 0;
  762. } else {
  763. this.x = q.x / s;
  764. this.y = q.y / s;
  765. this.z = q.z / s;
  766. }
  767. return this;
  768. },
  769. setAxisAngleFromRotationMatrix: function ( m ) {
  770. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  771. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  772. var angle, x, y, z, // variables for result
  773. epsilon = 0.01, // margin to allow for rounding errors
  774. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  775. te = m.elements,
  776. m11 = te[0], m12 = te[4], m13 = te[8],
  777. m21 = te[1], m22 = te[5], m23 = te[9],
  778. m31 = te[2], m32 = te[6], m33 = te[10];
  779. if ( ( Math.abs( m12 - m21 ) < epsilon )
  780. && ( Math.abs( m13 - m31 ) < epsilon )
  781. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  782. // singularity found
  783. // first check for identity matrix which must have +1 for all terms
  784. // in leading diagonal and zero in other terms
  785. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  786. && ( Math.abs( m13 + m31 ) < epsilon2 )
  787. && ( Math.abs( m23 + m32 ) < epsilon2 )
  788. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  789. // this singularity is identity matrix so angle = 0
  790. this.set( 1, 0, 0, 0 );
  791. return this; // zero angle, arbitrary axis
  792. }
  793. // otherwise this singularity is angle = 180
  794. angle = Math.PI;
  795. var xx = ( m11 + 1 ) / 2;
  796. var yy = ( m22 + 1 ) / 2;
  797. var zz = ( m33 + 1 ) / 2;
  798. var xy = ( m12 + m21 ) / 4;
  799. var xz = ( m13 + m31 ) / 4;
  800. var yz = ( m23 + m32 ) / 4;
  801. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  802. if ( xx < epsilon ) {
  803. x = 0;
  804. y = 0.707106781;
  805. z = 0.707106781;
  806. } else {
  807. x = Math.sqrt( xx );
  808. y = xy / x;
  809. z = xz / x;
  810. }
  811. } else if ( yy > zz ) { // m22 is the largest diagonal term
  812. if ( yy < epsilon ) {
  813. x = 0.707106781;
  814. y = 0;
  815. z = 0.707106781;
  816. } else {
  817. y = Math.sqrt( yy );
  818. x = xy / y;
  819. z = yz / y;
  820. }
  821. } else { // m33 is the largest diagonal term so base result on this
  822. if ( zz < epsilon ) {
  823. x = 0.707106781;
  824. y = 0.707106781;
  825. z = 0;
  826. } else {
  827. z = Math.sqrt( zz );
  828. x = xz / z;
  829. y = yz / z;
  830. }
  831. }
  832. this.set( x, y, z, angle );
  833. return this; // return 180 deg rotation
  834. }
  835. // as we have reached here there are no singularities so we can handle normally
  836. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  837. + ( m13 - m31 ) * ( m13 - m31 )
  838. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  839. if ( Math.abs( s ) < 0.001 ) s = 1;
  840. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  841. // caught by singularity test above, but I've left it in just in case
  842. this.x = ( m32 - m23 ) / s;
  843. this.y = ( m13 - m31 ) / s;
  844. this.z = ( m21 - m12 ) / s;
  845. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  846. return this;
  847. }
  848. };
  849. /**
  850. * https://github.com/mrdoob/eventtarget.js/
  851. */
  852. THREE.EventTarget = function () {
  853. var listeners = {};
  854. this.addEventListener = function ( type, listener ) {
  855. if ( listeners[ type ] === undefined ) {
  856. listeners[ type ] = [];
  857. }
  858. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  859. listeners[ type ].push( listener );
  860. }
  861. };
  862. this.dispatchEvent = function ( event ) {
  863. for ( var listener in listeners[ event.type ] ) {
  864. listeners[ event.type ][ listener ]( event );
  865. }
  866. };
  867. this.removeEventListener = function ( type, listener ) {
  868. var index = listeners[ type ].indexOf( listener );
  869. if ( index !== - 1 ) {
  870. listeners[ type ].splice( index, 1 );
  871. }
  872. };
  873. };
  874. /**
  875. * @author mrdoob / http://mrdoob.com/
  876. * @author alteredq / http://alteredqualia.com/
  877. */
  878. THREE.Frustum = function ( ) {
  879. this.planes = [
  880. new THREE.Vector4(),
  881. new THREE.Vector4(),
  882. new THREE.Vector4(),
  883. new THREE.Vector4(),
  884. new THREE.Vector4(),
  885. new THREE.Vector4()
  886. ];
  887. };
  888. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  889. var plane;
  890. var planes = this.planes;
  891. var me = m.elements;
  892. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  893. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  894. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  895. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  896. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  897. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  898. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  899. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  900. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  901. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  902. for ( var i = 0; i < 6; i ++ ) {
  903. plane = planes[ i ];
  904. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  905. }
  906. };
  907. THREE.Frustum.prototype.contains = function ( object ) {
  908. var distance = 0.0;
  909. var planes = this.planes;
  910. var matrix = object.matrixWorld;
  911. var me = matrix.elements;
  912. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  913. for ( var i = 0; i < 6; i ++ ) {
  914. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  915. if ( distance <= radius ) return false;
  916. }
  917. return true;
  918. };
  919. THREE.Frustum.__v1 = new THREE.Vector3();
  920. /**
  921. * @author mrdoob / http://mrdoob.com/
  922. */
  923. THREE.Ray = function ( origin, direction, near, far ) {
  924. this.origin = origin || new THREE.Vector3();
  925. this.direction = direction || new THREE.Vector3();
  926. this.near = near || 0;
  927. this.far = far || Infinity;
  928. //
  929. var a = new THREE.Vector3();
  930. var b = new THREE.Vector3();
  931. var c = new THREE.Vector3();
  932. var d = new THREE.Vector3();
  933. var originCopy = new THREE.Vector3();
  934. var directionCopy = new THREE.Vector3();
  935. var vector = new THREE.Vector3();
  936. var normal = new THREE.Vector3();
  937. var intersectPoint = new THREE.Vector3();
  938. var descSort = function ( a, b ) {
  939. return a.distance - b.distance;
  940. };
  941. //
  942. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  943. var dot, intersect, distance;
  944. var distanceFromIntersection = function ( origin, direction, position ) {
  945. v0.sub( position, origin );
  946. dot = v0.dot( direction );
  947. intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  948. distance = position.distanceTo( intersect );
  949. return distance;
  950. }
  951. // http://www.blackpawn.com/texts/pointinpoly/default.html
  952. var dot00, dot01, dot02, dot11, dot12, invDenom, u, v;
  953. var pointInFace3 = function ( p, a, b, c ) {
  954. v0.sub( c, a );
  955. v1.sub( b, a );
  956. v2.sub( p, a );
  957. dot00 = v0.dot( v0 );
  958. dot01 = v0.dot( v1 );
  959. dot02 = v0.dot( v2 );
  960. dot11 = v1.dot( v1 );
  961. dot12 = v1.dot( v2 );
  962. invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  963. u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  964. v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  965. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  966. }
  967. //
  968. var precision = 0.0001;
  969. this.setPrecision = function ( value ) {
  970. precision = value;
  971. };
  972. this.intersectObject = function ( object, recursive ) {
  973. var intersect, intersects = [];
  974. if ( recursive === true ) {
  975. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  976. Array.prototype.push.apply( intersects, this.intersectObject( object.children[ i ], recursive ) );
  977. }
  978. }
  979. if ( object instanceof THREE.Particle ) {
  980. distance = distanceFromIntersection( this.origin, this.direction, object.matrixWorld.getPosition() );
  981. if ( distance > object.scale.x ) {
  982. return [];
  983. }
  984. intersect = {
  985. distance: distance,
  986. point: object.position,
  987. face: null,
  988. object: object
  989. };
  990. intersects.push( intersect );
  991. } else if ( object instanceof THREE.Mesh ) {
  992. // Checking boundingSphere
  993. var scale = THREE.Frustum.__v1.set( object.matrixWorld.getColumnX().length(), object.matrixWorld.getColumnY().length(), object.matrixWorld.getColumnZ().length() );
  994. var scaledRadius = object.geometry.boundingSphere.radius * Math.max( scale.x, Math.max( scale.y, scale.z ) );
  995. // Checking distance to ray
  996. distance = distanceFromIntersection( this.origin, this.direction, object.matrixWorld.getPosition() );
  997. if ( distance > scaledRadius) {
  998. return intersects;
  999. }
  1000. // Checking faces
  1001. var f, fl, face, dot, scalar,
  1002. rangeSq = this.range * this.range,
  1003. geometry = object.geometry,
  1004. vertices = geometry.vertices,
  1005. objMatrix, geometryMaterials,
  1006. isFaceMaterial, material, side;
  1007. geometryMaterials = object.geometry.materials;
  1008. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  1009. side = object.material.side;
  1010. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  1011. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  1012. face = geometry.faces[ f ];
  1013. material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  1014. if ( material === undefined ) continue;
  1015. side = material.side;
  1016. originCopy.copy( this.origin );
  1017. directionCopy.copy( this.direction );
  1018. objMatrix = object.matrixWorld;
  1019. // determine if ray intersects the plane of the face
  1020. // note: this works regardless of the direction of the face normal
  1021. vector = objMatrix.multiplyVector3( vector.copy( face.centroid ) ).subSelf( originCopy );
  1022. normal = object.matrixRotationWorld.multiplyVector3( normal.copy( face.normal ) );
  1023. dot = directionCopy.dot( normal );
  1024. // bail if ray and plane are parallel
  1025. if ( Math.abs( dot ) < precision ) continue;
  1026. // calc distance to plane
  1027. scalar = normal.dot( vector ) / dot;
  1028. // if negative distance, then plane is behind ray
  1029. if ( scalar < 0 ) continue;
  1030. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  1031. intersectPoint.add( originCopy, directionCopy.multiplyScalar( scalar ) );
  1032. distance = originCopy.distanceTo( intersectPoint );
  1033. if ( distance < this.near ) continue;
  1034. if ( distance > this.far ) continue;
  1035. if ( face instanceof THREE.Face3 ) {
  1036. a = objMatrix.multiplyVector3( a.copy( vertices[ face.a ] ) );
  1037. b = objMatrix.multiplyVector3( b.copy( vertices[ face.b ] ) );
  1038. c = objMatrix.multiplyVector3( c.copy( vertices[ face.c ] ) );
  1039. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  1040. intersect = {
  1041. distance: distance,
  1042. point: intersectPoint.clone(),
  1043. face: face,
  1044. faceIndex: f,
  1045. object: object
  1046. };
  1047. intersects.push( intersect );
  1048. }
  1049. } else if ( face instanceof THREE.Face4 ) {
  1050. a = objMatrix.multiplyVector3( a.copy( vertices[ face.a ] ) );
  1051. b = objMatrix.multiplyVector3( b.copy( vertices[ face.b ] ) );
  1052. c = objMatrix.multiplyVector3( c.copy( vertices[ face.c ] ) );
  1053. d = objMatrix.multiplyVector3( d.copy( vertices[ face.d ] ) );
  1054. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  1055. intersect = {
  1056. distance: distance,
  1057. point: intersectPoint.clone(),
  1058. face: face,
  1059. faceIndex: f,
  1060. object: object
  1061. };
  1062. intersects.push( intersect );
  1063. }
  1064. }
  1065. }
  1066. }
  1067. }
  1068. intersects.sort( descSort );
  1069. return intersects;
  1070. };
  1071. this.intersectObjects = function ( objects, recursive ) {
  1072. var intersects = [];
  1073. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  1074. Array.prototype.push.apply( intersects, this.intersectObject( objects[ i ], recursive ) );
  1075. }
  1076. intersects.sort( descSort );
  1077. return intersects;
  1078. };
  1079. };
  1080. /**
  1081. * @author mrdoob / http://mrdoob.com/
  1082. */
  1083. THREE.Rectangle = function () {
  1084. var _left = 0;
  1085. var _top = 0;
  1086. var _right = 0;
  1087. var _bottom = 0;
  1088. var _width = 0;
  1089. var _height = 0;
  1090. var _isEmpty = true;
  1091. function resize() {
  1092. _width = _right - _left;
  1093. _height = _bottom - _top;
  1094. }
  1095. this.getX = function () {
  1096. return _left;
  1097. };
  1098. this.getY = function () {
  1099. return _top;
  1100. };
  1101. this.getWidth = function () {
  1102. return _width;
  1103. };
  1104. this.getHeight = function () {
  1105. return _height;
  1106. };
  1107. this.getLeft = function() {
  1108. return _left;
  1109. };
  1110. this.getTop = function() {
  1111. return _top;
  1112. };
  1113. this.getRight = function() {
  1114. return _right;
  1115. };
  1116. this.getBottom = function() {
  1117. return _bottom;
  1118. };
  1119. this.set = function ( left, top, right, bottom ) {
  1120. _isEmpty = false;
  1121. _left = left; _top = top;
  1122. _right = right; _bottom = bottom;
  1123. resize();
  1124. };
  1125. this.addPoint = function ( x, y ) {
  1126. if ( _isEmpty === true ) {
  1127. _isEmpty = false;
  1128. _left = x; _top = y;
  1129. _right = x; _bottom = y;
  1130. resize();
  1131. } else {
  1132. _left = _left < x ? _left : x; // Math.min( _left, x );
  1133. _top = _top < y ? _top : y; // Math.min( _top, y );
  1134. _right = _right > x ? _right : x; // Math.max( _right, x );
  1135. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  1136. resize();
  1137. }
  1138. };
  1139. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  1140. if ( _isEmpty === true ) {
  1141. _isEmpty = false;
  1142. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  1143. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  1144. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  1145. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  1146. resize();
  1147. } else {
  1148. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  1149. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  1150. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  1151. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  1152. resize();
  1153. };
  1154. };
  1155. this.addRectangle = function ( r ) {
  1156. if ( _isEmpty === true ) {
  1157. _isEmpty = false;
  1158. _left = r.getLeft(); _top = r.getTop();
  1159. _right = r.getRight(); _bottom = r.getBottom();
  1160. resize();
  1161. } else {
  1162. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  1163. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  1164. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  1165. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  1166. resize();
  1167. }
  1168. };
  1169. this.inflate = function ( v ) {
  1170. _left -= v; _top -= v;
  1171. _right += v; _bottom += v;
  1172. resize();
  1173. };
  1174. this.minSelf = function ( r ) {
  1175. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  1176. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  1177. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  1178. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  1179. resize();
  1180. };
  1181. this.intersects = function ( r ) {
  1182. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  1183. if ( _right < r.getLeft() ) return false;
  1184. if ( _left > r.getRight() ) return false;
  1185. if ( _bottom < r.getTop() ) return false;
  1186. if ( _top > r.getBottom() ) return false;
  1187. return true;
  1188. };
  1189. this.empty = function () {
  1190. _isEmpty = true;
  1191. _left = 0; _top = 0;
  1192. _right = 0; _bottom = 0;
  1193. resize();
  1194. };
  1195. this.isEmpty = function () {
  1196. return _isEmpty;
  1197. };
  1198. };
  1199. /**
  1200. * @author alteredq / http://alteredqualia.com/
  1201. */
  1202. THREE.Math = {
  1203. // Clamp value to range <a, b>
  1204. clamp: function ( x, a, b ) {
  1205. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  1206. },
  1207. // Clamp value to range <a, inf)
  1208. clampBottom: function ( x, a ) {
  1209. return x < a ? a : x;
  1210. },
  1211. // Linear mapping from range <a1, a2> to range <b1, b2>
  1212. mapLinear: function ( x, a1, a2, b1, b2 ) {
  1213. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1214. },
  1215. // Random float from <0, 1> with 16 bits of randomness
  1216. // (standard Math.random() creates repetitive patterns when applied over larger space)
  1217. random16: function () {
  1218. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  1219. },
  1220. // Random integer from <low, high> interval
  1221. randInt: function ( low, high ) {
  1222. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1223. },
  1224. // Random float from <low, high> interval
  1225. randFloat: function ( low, high ) {
  1226. return low + Math.random() * ( high - low );
  1227. },
  1228. // Random float from <-range/2, range/2> interval
  1229. randFloatSpread: function ( range ) {
  1230. return range * ( 0.5 - Math.random() );
  1231. },
  1232. sign: function ( x ) {
  1233. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  1234. }
  1235. };
  1236. /**
  1237. * @author alteredq / http://alteredqualia.com/
  1238. */
  1239. THREE.Matrix3 = function () {
  1240. this.elements = new Float32Array(9);
  1241. };
  1242. THREE.Matrix3.prototype = {
  1243. constructor: THREE.Matrix3,
  1244. getInverse: function ( matrix ) {
  1245. // input: THREE.Matrix4
  1246. // ( based on http://code.google.com/p/webgl-mjs/ )
  1247. var me = matrix.elements;
  1248. var a11 = me[10] * me[5] - me[6] * me[9];
  1249. var a21 = - me[10] * me[1] + me[2] * me[9];
  1250. var a31 = me[6] * me[1] - me[2] * me[5];
  1251. var a12 = - me[10] * me[4] + me[6] * me[8];
  1252. var a22 = me[10] * me[0] - me[2] * me[8];
  1253. var a32 = - me[6] * me[0] + me[2] * me[4];
  1254. var a13 = me[9] * me[4] - me[5] * me[8];
  1255. var a23 = - me[9] * me[0] + me[1] * me[8];
  1256. var a33 = me[5] * me[0] - me[1] * me[4];
  1257. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  1258. // no inverse
  1259. if ( det === 0 ) {
  1260. console.warn( "Matrix3.getInverse(): determinant == 0" );
  1261. }
  1262. var idet = 1.0 / det;
  1263. var m = this.elements;
  1264. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  1265. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  1266. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  1267. return this;
  1268. },
  1269. transpose: function () {
  1270. var tmp, m = this.elements;
  1271. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  1272. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  1273. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  1274. return this;
  1275. },
  1276. transposeIntoArray: function ( r ) {
  1277. var m = this.m;
  1278. r[ 0 ] = m[ 0 ];
  1279. r[ 1 ] = m[ 3 ];
  1280. r[ 2 ] = m[ 6 ];
  1281. r[ 3 ] = m[ 1 ];
  1282. r[ 4 ] = m[ 4 ];
  1283. r[ 5 ] = m[ 7 ];
  1284. r[ 6 ] = m[ 2 ];
  1285. r[ 7 ] = m[ 5 ];
  1286. r[ 8 ] = m[ 8 ];
  1287. return this;
  1288. }
  1289. };
  1290. /**
  1291. * @author mrdoob / http://mrdoob.com/
  1292. * @author supereggbert / http://www.paulbrunt.co.uk/
  1293. * @author philogb / http://blog.thejit.org/
  1294. * @author jordi_ros / http://plattsoft.com
  1295. * @author D1plo1d / http://github.com/D1plo1d
  1296. * @author alteredq / http://alteredqualia.com/
  1297. * @author mikael emtinger / http://gomo.se/
  1298. * @author timknip / http://www.floorplanner.com/
  1299. */
  1300. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1301. this.elements = new Float32Array( 16 );
  1302. this.set(
  1303. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1304. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1305. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1306. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1307. );
  1308. };
  1309. THREE.Matrix4.prototype = {
  1310. constructor: THREE.Matrix4,
  1311. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1312. var te = this.elements;
  1313. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1314. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1315. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1316. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1317. return this;
  1318. },
  1319. identity: function () {
  1320. this.set(
  1321. 1, 0, 0, 0,
  1322. 0, 1, 0, 0,
  1323. 0, 0, 1, 0,
  1324. 0, 0, 0, 1
  1325. );
  1326. return this;
  1327. },
  1328. copy: function ( m ) {
  1329. var me = m.elements;
  1330. this.set(
  1331. me[0], me[4], me[8], me[12],
  1332. me[1], me[5], me[9], me[13],
  1333. me[2], me[6], me[10], me[14],
  1334. me[3], me[7], me[11], me[15]
  1335. );
  1336. return this;
  1337. },
  1338. lookAt: function ( eye, target, up ) {
  1339. var te = this.elements;
  1340. var x = THREE.Matrix4.__v1;
  1341. var y = THREE.Matrix4.__v2;
  1342. var z = THREE.Matrix4.__v3;
  1343. z.sub( eye, target ).normalize();
  1344. if ( z.length() === 0 ) {
  1345. z.z = 1;
  1346. }
  1347. x.cross( up, z ).normalize();
  1348. if ( x.length() === 0 ) {
  1349. z.x += 0.0001;
  1350. x.cross( up, z ).normalize();
  1351. }
  1352. y.cross( z, x );
  1353. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1354. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1355. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1356. return this;
  1357. },
  1358. multiply: function ( a, b ) {
  1359. var ae = a.elements;
  1360. var be = b.elements;
  1361. var te = this.elements;
  1362. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1363. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1364. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1365. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1366. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1367. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1368. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1369. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1370. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1371. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1372. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1373. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1374. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1375. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1376. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1377. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1378. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1379. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1380. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1381. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1382. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1383. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1384. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1385. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1386. return this;
  1387. },
  1388. multiplySelf: function ( m ) {
  1389. return this.multiply( this, m );
  1390. },
  1391. multiplyToArray: function ( a, b, r ) {
  1392. var te = this.elements;
  1393. this.multiply( a, b );
  1394. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1395. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1396. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1397. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1398. return this;
  1399. },
  1400. multiplyScalar: function ( s ) {
  1401. var te = this.elements;
  1402. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1403. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1404. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1405. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1406. return this;
  1407. },
  1408. multiplyVector3: function ( v ) {
  1409. var te = this.elements;
  1410. var vx = v.x, vy = v.y, vz = v.z;
  1411. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1412. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1413. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1414. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1415. return v;
  1416. },
  1417. multiplyVector4: function ( v ) {
  1418. var te = this.elements;
  1419. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1420. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1421. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1422. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1423. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1424. return v;
  1425. },
  1426. multiplyVector3Array: function ( a ) {
  1427. var tmp = THREE.Matrix4.__v1;
  1428. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1429. tmp.x = a[ i ];
  1430. tmp.y = a[ i + 1 ];
  1431. tmp.z = a[ i + 2 ];
  1432. this.multiplyVector3( tmp );
  1433. a[ i ] = tmp.x;
  1434. a[ i + 1 ] = tmp.y;
  1435. a[ i + 2 ] = tmp.z;
  1436. }
  1437. return a;
  1438. },
  1439. rotateAxis: function ( v ) {
  1440. var te = this.elements;
  1441. var vx = v.x, vy = v.y, vz = v.z;
  1442. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1443. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1444. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1445. v.normalize();
  1446. return v;
  1447. },
  1448. crossVector: function ( a ) {
  1449. var te = this.elements;
  1450. var v = new THREE.Vector4();
  1451. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1452. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1453. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1454. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1455. return v;
  1456. },
  1457. determinant: function () {
  1458. var te = this.elements;
  1459. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1460. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1461. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1462. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1463. //TODO: make this more efficient
  1464. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1465. return (
  1466. n14 * n23 * n32 * n41-
  1467. n13 * n24 * n32 * n41-
  1468. n14 * n22 * n33 * n41+
  1469. n12 * n24 * n33 * n41+
  1470. n13 * n22 * n34 * n41-
  1471. n12 * n23 * n34 * n41-
  1472. n14 * n23 * n31 * n42+
  1473. n13 * n24 * n31 * n42+
  1474. n14 * n21 * n33 * n42-
  1475. n11 * n24 * n33 * n42-
  1476. n13 * n21 * n34 * n42+
  1477. n11 * n23 * n34 * n42+
  1478. n14 * n22 * n31 * n43-
  1479. n12 * n24 * n31 * n43-
  1480. n14 * n21 * n32 * n43+
  1481. n11 * n24 * n32 * n43+
  1482. n12 * n21 * n34 * n43-
  1483. n11 * n22 * n34 * n43-
  1484. n13 * n22 * n31 * n44+
  1485. n12 * n23 * n31 * n44+
  1486. n13 * n21 * n32 * n44-
  1487. n11 * n23 * n32 * n44-
  1488. n12 * n21 * n33 * n44+
  1489. n11 * n22 * n33 * n44
  1490. );
  1491. },
  1492. transpose: function () {
  1493. var te = this.elements;
  1494. var tmp;
  1495. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1496. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1497. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1498. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1499. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1500. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1501. return this;
  1502. },
  1503. flattenToArray: function ( flat ) {
  1504. var te = this.elements;
  1505. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1506. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1507. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1508. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1509. return flat;
  1510. },
  1511. flattenToArrayOffset: function( flat, offset ) {
  1512. var te = this.elements;
  1513. flat[ offset ] = te[0];
  1514. flat[ offset + 1 ] = te[1];
  1515. flat[ offset + 2 ] = te[2];
  1516. flat[ offset + 3 ] = te[3];
  1517. flat[ offset + 4 ] = te[4];
  1518. flat[ offset + 5 ] = te[5];
  1519. flat[ offset + 6 ] = te[6];
  1520. flat[ offset + 7 ] = te[7];
  1521. flat[ offset + 8 ] = te[8];
  1522. flat[ offset + 9 ] = te[9];
  1523. flat[ offset + 10 ] = te[10];
  1524. flat[ offset + 11 ] = te[11];
  1525. flat[ offset + 12 ] = te[12];
  1526. flat[ offset + 13 ] = te[13];
  1527. flat[ offset + 14 ] = te[14];
  1528. flat[ offset + 15 ] = te[15];
  1529. return flat;
  1530. },
  1531. getPosition: function () {
  1532. var te = this.elements;
  1533. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1534. },
  1535. setPosition: function ( v ) {
  1536. var te = this.elements;
  1537. te[12] = v.x;
  1538. te[13] = v.y;
  1539. te[14] = v.z;
  1540. return this;
  1541. },
  1542. getColumnX: function () {
  1543. var te = this.elements;
  1544. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1545. },
  1546. getColumnY: function () {
  1547. var te = this.elements;
  1548. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1549. },
  1550. getColumnZ: function() {
  1551. var te = this.elements;
  1552. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1553. },
  1554. getInverse: function ( m ) {
  1555. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1556. var te = this.elements;
  1557. var me = m.elements;
  1558. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1559. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1560. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1561. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1562. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1563. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1564. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1565. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1566. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1567. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1568. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1569. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1570. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1571. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1572. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1573. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1574. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1575. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1576. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1577. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1578. this.multiplyScalar( 1 / m.determinant() );
  1579. return this;
  1580. },
  1581. setRotationFromEuler: function ( v, order ) {
  1582. var te = this.elements;
  1583. var x = v.x, y = v.y, z = v.z;
  1584. var a = Math.cos( x ), b = Math.sin( x );
  1585. var c = Math.cos( y ), d = Math.sin( y );
  1586. var e = Math.cos( z ), f = Math.sin( z );
  1587. if ( order === undefined || order === 'XYZ' ) {
  1588. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1589. te[0] = c * e;
  1590. te[4] = - c * f;
  1591. te[8] = d;
  1592. te[1] = af + be * d;
  1593. te[5] = ae - bf * d;
  1594. te[9] = - b * c;
  1595. te[2] = bf - ae * d;
  1596. te[6] = be + af * d;
  1597. te[10] = a * c;
  1598. } else if ( order === 'YXZ' ) {
  1599. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1600. te[0] = ce + df * b;
  1601. te[4] = de * b - cf;
  1602. te[8] = a * d;
  1603. te[1] = a * f;
  1604. te[5] = a * e;
  1605. te[9] = - b;
  1606. te[2] = cf * b - de;
  1607. te[6] = df + ce * b;
  1608. te[10] = a * c;
  1609. } else if ( order === 'ZXY' ) {
  1610. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1611. te[0] = ce - df * b;
  1612. te[4] = - a * f;
  1613. te[8] = de + cf * b;
  1614. te[1] = cf + de * b;
  1615. te[5] = a * e;
  1616. te[9] = df - ce * b;
  1617. te[2] = - a * d;
  1618. te[6] = b;
  1619. te[10] = a * c;
  1620. } else if ( order === 'ZYX' ) {
  1621. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1622. te[0] = c * e;
  1623. te[4] = be * d - af;
  1624. te[8] = ae * d + bf;
  1625. te[1] = c * f;
  1626. te[5] = bf * d + ae;
  1627. te[9] = af * d - be;
  1628. te[2] = - d;
  1629. te[6] = b * c;
  1630. te[10] = a * c;
  1631. } else if ( order === 'YZX' ) {
  1632. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1633. te[0] = c * e;
  1634. te[4] = bd - ac * f;
  1635. te[8] = bc * f + ad;
  1636. te[1] = f;
  1637. te[5] = a * e;
  1638. te[9] = - b * e;
  1639. te[2] = - d * e;
  1640. te[6] = ad * f + bc;
  1641. te[10] = ac - bd * f;
  1642. } else if ( order === 'XZY' ) {
  1643. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1644. te[0] = c * e;
  1645. te[4] = - f;
  1646. te[8] = d * e;
  1647. te[1] = ac * f + bd;
  1648. te[5] = a * e;
  1649. te[9] = ad * f - bc;
  1650. te[2] = bc * f - ad;
  1651. te[6] = b * e;
  1652. te[10] = bd * f + ac;
  1653. }
  1654. return this;
  1655. },
  1656. setRotationFromQuaternion: function ( q ) {
  1657. var te = this.elements;
  1658. var x = q.x, y = q.y, z = q.z, w = q.w;
  1659. var x2 = x + x, y2 = y + y, z2 = z + z;
  1660. var xx = x * x2, xy = x * y2, xz = x * z2;
  1661. var yy = y * y2, yz = y * z2, zz = z * z2;
  1662. var wx = w * x2, wy = w * y2, wz = w * z2;
  1663. te[0] = 1 - ( yy + zz );
  1664. te[4] = xy - wz;
  1665. te[8] = xz + wy;
  1666. te[1] = xy + wz;
  1667. te[5] = 1 - ( xx + zz );
  1668. te[9] = yz - wx;
  1669. te[2] = xz - wy;
  1670. te[6] = yz + wx;
  1671. te[10] = 1 - ( xx + yy );
  1672. return this;
  1673. },
  1674. compose: function ( translation, rotation, scale ) {
  1675. var te = this.elements;
  1676. var mRotation = THREE.Matrix4.__m1;
  1677. var mScale = THREE.Matrix4.__m2;
  1678. mRotation.identity();
  1679. mRotation.setRotationFromQuaternion( rotation );
  1680. mScale.makeScale( scale.x, scale.y, scale.z );
  1681. this.multiply( mRotation, mScale );
  1682. te[12] = translation.x;
  1683. te[13] = translation.y;
  1684. te[14] = translation.z;
  1685. return this;
  1686. },
  1687. decompose: function ( translation, rotation, scale ) {
  1688. var te = this.elements;
  1689. // grab the axis vectors
  1690. var x = THREE.Matrix4.__v1;
  1691. var y = THREE.Matrix4.__v2;
  1692. var z = THREE.Matrix4.__v3;
  1693. x.set( te[0], te[1], te[2] );
  1694. y.set( te[4], te[5], te[6] );
  1695. z.set( te[8], te[9], te[10] );
  1696. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1697. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1698. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1699. scale.x = x.length();
  1700. scale.y = y.length();
  1701. scale.z = z.length();
  1702. translation.x = te[12];
  1703. translation.y = te[13];
  1704. translation.z = te[14];
  1705. // scale the rotation part
  1706. var matrix = THREE.Matrix4.__m1;
  1707. matrix.copy( this );
  1708. matrix.elements[0] /= scale.x;
  1709. matrix.elements[1] /= scale.x;
  1710. matrix.elements[2] /= scale.x;
  1711. matrix.elements[4] /= scale.y;
  1712. matrix.elements[5] /= scale.y;
  1713. matrix.elements[6] /= scale.y;
  1714. matrix.elements[8] /= scale.z;
  1715. matrix.elements[9] /= scale.z;
  1716. matrix.elements[10] /= scale.z;
  1717. rotation.setFromRotationMatrix( matrix );
  1718. return [ translation, rotation, scale ];
  1719. },
  1720. extractPosition: function ( m ) {
  1721. var te = this.elements;
  1722. var me = m.elements;
  1723. te[12] = me[12];
  1724. te[13] = me[13];
  1725. te[14] = me[14];
  1726. return this;
  1727. },
  1728. extractRotation: function ( m ) {
  1729. var te = this.elements;
  1730. var me = m.elements;
  1731. var vector = THREE.Matrix4.__v1;
  1732. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1733. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1734. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1735. te[0] = me[0] * scaleX;
  1736. te[1] = me[1] * scaleX;
  1737. te[2] = me[2] * scaleX;
  1738. te[4] = me[4] * scaleY;
  1739. te[5] = me[5] * scaleY;
  1740. te[6] = me[6] * scaleY;
  1741. te[8] = me[8] * scaleZ;
  1742. te[9] = me[9] * scaleZ;
  1743. te[10] = me[10] * scaleZ;
  1744. return this;
  1745. },
  1746. //
  1747. translate: function ( v ) {
  1748. var te = this.elements;
  1749. var x = v.x, y = v.y, z = v.z;
  1750. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1751. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1752. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1753. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1754. return this;
  1755. },
  1756. rotateX: function ( angle ) {
  1757. var te = this.elements;
  1758. var m12 = te[4];
  1759. var m22 = te[5];
  1760. var m32 = te[6];
  1761. var m42 = te[7];
  1762. var m13 = te[8];
  1763. var m23 = te[9];
  1764. var m33 = te[10];
  1765. var m43 = te[11];
  1766. var c = Math.cos( angle );
  1767. var s = Math.sin( angle );
  1768. te[4] = c * m12 + s * m13;
  1769. te[5] = c * m22 + s * m23;
  1770. te[6] = c * m32 + s * m33;
  1771. te[7] = c * m42 + s * m43;
  1772. te[8] = c * m13 - s * m12;
  1773. te[9] = c * m23 - s * m22;
  1774. te[10] = c * m33 - s * m32;
  1775. te[11] = c * m43 - s * m42;
  1776. return this;
  1777. },
  1778. rotateY: function ( angle ) {
  1779. var te = this.elements;
  1780. var m11 = te[0];
  1781. var m21 = te[1];
  1782. var m31 = te[2];
  1783. var m41 = te[3];
  1784. var m13 = te[8];
  1785. var m23 = te[9];
  1786. var m33 = te[10];
  1787. var m43 = te[11];
  1788. var c = Math.cos( angle );
  1789. var s = Math.sin( angle );
  1790. te[0] = c * m11 - s * m13;
  1791. te[1] = c * m21 - s * m23;
  1792. te[2] = c * m31 - s * m33;
  1793. te[3] = c * m41 - s * m43;
  1794. te[8] = c * m13 + s * m11;
  1795. te[9] = c * m23 + s * m21;
  1796. te[10] = c * m33 + s * m31;
  1797. te[11] = c * m43 + s * m41;
  1798. return this;
  1799. },
  1800. rotateZ: function ( angle ) {
  1801. var te = this.elements;
  1802. var m11 = te[0];
  1803. var m21 = te[1];
  1804. var m31 = te[2];
  1805. var m41 = te[3];
  1806. var m12 = te[4];
  1807. var m22 = te[5];
  1808. var m32 = te[6];
  1809. var m42 = te[7];
  1810. var c = Math.cos( angle );
  1811. var s = Math.sin( angle );
  1812. te[0] = c * m11 + s * m12;
  1813. te[1] = c * m21 + s * m22;
  1814. te[2] = c * m31 + s * m32;
  1815. te[3] = c * m41 + s * m42;
  1816. te[4] = c * m12 - s * m11;
  1817. te[5] = c * m22 - s * m21;
  1818. te[6] = c * m32 - s * m31;
  1819. te[7] = c * m42 - s * m41;
  1820. return this;
  1821. },
  1822. rotateByAxis: function ( axis, angle ) {
  1823. var te = this.elements;
  1824. // optimize by checking axis
  1825. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1826. return this.rotateX( angle );
  1827. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1828. return this.rotateY( angle );
  1829. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1830. return this.rotateZ( angle );
  1831. }
  1832. var x = axis.x, y = axis.y, z = axis.z;
  1833. var n = Math.sqrt(x * x + y * y + z * z);
  1834. x /= n;
  1835. y /= n;
  1836. z /= n;
  1837. var xx = x * x, yy = y * y, zz = z * z;
  1838. var c = Math.cos( angle );
  1839. var s = Math.sin( angle );
  1840. var oneMinusCosine = 1 - c;
  1841. var xy = x * y * oneMinusCosine;
  1842. var xz = x * z * oneMinusCosine;
  1843. var yz = y * z * oneMinusCosine;
  1844. var xs = x * s;
  1845. var ys = y * s;
  1846. var zs = z * s;
  1847. var r11 = xx + (1 - xx) * c;
  1848. var r21 = xy + zs;
  1849. var r31 = xz - ys;
  1850. var r12 = xy - zs;
  1851. var r22 = yy + (1 - yy) * c;
  1852. var r32 = yz + xs;
  1853. var r13 = xz + ys;
  1854. var r23 = yz - xs;
  1855. var r33 = zz + (1 - zz) * c;
  1856. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1857. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1858. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1859. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1860. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1861. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1862. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1863. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1864. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1865. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1866. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1867. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1868. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1869. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1870. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1871. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1872. return this;
  1873. },
  1874. scale: function ( v ) {
  1875. var te = this.elements;
  1876. var x = v.x, y = v.y, z = v.z;
  1877. te[0] *= x; te[4] *= y; te[8] *= z;
  1878. te[1] *= x; te[5] *= y; te[9] *= z;
  1879. te[2] *= x; te[6] *= y; te[10] *= z;
  1880. te[3] *= x; te[7] *= y; te[11] *= z;
  1881. return this;
  1882. },
  1883. getMaxScaleOnAxis: function () {
  1884. var te = this.elements;
  1885. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  1886. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  1887. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  1888. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  1889. },
  1890. //
  1891. makeTranslation: function ( x, y, z ) {
  1892. this.set(
  1893. 1, 0, 0, x,
  1894. 0, 1, 0, y,
  1895. 0, 0, 1, z,
  1896. 0, 0, 0, 1
  1897. );
  1898. return this;
  1899. },
  1900. makeRotationX: function ( theta ) {
  1901. var c = Math.cos( theta ), s = Math.sin( theta );
  1902. this.set(
  1903. 1, 0, 0, 0,
  1904. 0, c, -s, 0,
  1905. 0, s, c, 0,
  1906. 0, 0, 0, 1
  1907. );
  1908. return this;
  1909. },
  1910. makeRotationY: function ( theta ) {
  1911. var c = Math.cos( theta ), s = Math.sin( theta );
  1912. this.set(
  1913. c, 0, s, 0,
  1914. 0, 1, 0, 0,
  1915. -s, 0, c, 0,
  1916. 0, 0, 0, 1
  1917. );
  1918. return this;
  1919. },
  1920. makeRotationZ: function ( theta ) {
  1921. var c = Math.cos( theta ), s = Math.sin( theta );
  1922. this.set(
  1923. c, -s, 0, 0,
  1924. s, c, 0, 0,
  1925. 0, 0, 1, 0,
  1926. 0, 0, 0, 1
  1927. );
  1928. return this;
  1929. },
  1930. makeRotationAxis: function ( axis, angle ) {
  1931. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1932. var c = Math.cos( angle );
  1933. var s = Math.sin( angle );
  1934. var t = 1 - c;
  1935. var x = axis.x, y = axis.y, z = axis.z;
  1936. var tx = t * x, ty = t * y;
  1937. this.set(
  1938. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1939. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1940. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1941. 0, 0, 0, 1
  1942. );
  1943. return this;
  1944. },
  1945. makeScale: function ( x, y, z ) {
  1946. this.set(
  1947. x, 0, 0, 0,
  1948. 0, y, 0, 0,
  1949. 0, 0, z, 0,
  1950. 0, 0, 0, 1
  1951. );
  1952. return this;
  1953. },
  1954. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1955. var te = this.elements;
  1956. var x = 2 * near / ( right - left );
  1957. var y = 2 * near / ( top - bottom );
  1958. var a = ( right + left ) / ( right - left );
  1959. var b = ( top + bottom ) / ( top - bottom );
  1960. var c = - ( far + near ) / ( far - near );
  1961. var d = - 2 * far * near / ( far - near );
  1962. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1963. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1964. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1965. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1966. return this;
  1967. },
  1968. makePerspective: function ( fov, aspect, near, far ) {
  1969. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1970. var ymin = - ymax;
  1971. var xmin = ymin * aspect;
  1972. var xmax = ymax * aspect;
  1973. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1974. },
  1975. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1976. var te = this.elements;
  1977. var w = right - left;
  1978. var h = top - bottom;
  1979. var p = far - near;
  1980. var x = ( right + left ) / w;
  1981. var y = ( top + bottom ) / h;
  1982. var z = ( far + near ) / p;
  1983. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1984. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1985. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1986. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1987. return this;
  1988. },
  1989. clone: function () {
  1990. var te = this.elements;
  1991. return new THREE.Matrix4(
  1992. te[0], te[4], te[8], te[12],
  1993. te[1], te[5], te[9], te[13],
  1994. te[2], te[6], te[10], te[14],
  1995. te[3], te[7], te[11], te[15]
  1996. );
  1997. }
  1998. };
  1999. THREE.Matrix4.__v1 = new THREE.Vector3();
  2000. THREE.Matrix4.__v2 = new THREE.Vector3();
  2001. THREE.Matrix4.__v3 = new THREE.Vector3();
  2002. THREE.Matrix4.__m1 = new THREE.Matrix4();
  2003. THREE.Matrix4.__m2 = new THREE.Matrix4();
  2004. /**
  2005. * @author mrdoob / http://mrdoob.com/
  2006. * @author mikael emtinger / http://gomo.se/
  2007. * @author alteredq / http://alteredqualia.com/
  2008. */
  2009. THREE.Object3D = function () {
  2010. this.id = THREE.Object3DCount ++;
  2011. this.name = '';
  2012. this.properties = {};
  2013. this.parent = undefined;
  2014. this.children = [];
  2015. this.up = new THREE.Vector3( 0, 1, 0 );
  2016. this.position = new THREE.Vector3();
  2017. this.rotation = new THREE.Vector3();
  2018. this.eulerOrder = 'XYZ';
  2019. this.scale = new THREE.Vector3( 1, 1, 1 );
  2020. this.renderDepth = null;
  2021. this.rotationAutoUpdate = true;
  2022. this.matrix = new THREE.Matrix4();
  2023. this.matrixWorld = new THREE.Matrix4();
  2024. this.matrixRotationWorld = new THREE.Matrix4();
  2025. this.matrixAutoUpdate = true;
  2026. this.matrixWorldNeedsUpdate = true;
  2027. this.quaternion = new THREE.Quaternion();
  2028. this.useQuaternion = false;
  2029. this.boundRadius = 0.0;
  2030. this.boundRadiusScale = 1.0;
  2031. this.visible = true;
  2032. this.castShadow = false;
  2033. this.receiveShadow = false;
  2034. this.frustumCulled = true;
  2035. this._vector = new THREE.Vector3();
  2036. };
  2037. THREE.Object3D.prototype = {
  2038. constructor: THREE.Object3D,
  2039. applyMatrix: function ( matrix ) {
  2040. this.matrix.multiply( matrix, this.matrix );
  2041. this.scale.getScaleFromMatrix( this.matrix );
  2042. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2043. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2044. this.position.getPositionFromMatrix( this.matrix );
  2045. },
  2046. translate: function ( distance, axis ) {
  2047. this.matrix.rotateAxis( axis );
  2048. this.position.addSelf( axis.multiplyScalar( distance ) );
  2049. },
  2050. translateX: function ( distance ) {
  2051. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2052. },
  2053. translateY: function ( distance ) {
  2054. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2055. },
  2056. translateZ: function ( distance ) {
  2057. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2058. },
  2059. lookAt: function ( vector ) {
  2060. // TODO: Add hierarchy support.
  2061. this.matrix.lookAt( vector, this.position, this.up );
  2062. if ( this.rotationAutoUpdate ) {
  2063. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2064. }
  2065. },
  2066. add: function ( object ) {
  2067. if ( object === this ) {
  2068. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2069. return;
  2070. }
  2071. if ( object instanceof THREE.Object3D ) {
  2072. if ( object.parent !== undefined ) {
  2073. object.parent.remove( object );
  2074. }
  2075. object.parent = this;
  2076. this.children.push( object );
  2077. // add to scene
  2078. var scene = this;
  2079. while ( scene.parent !== undefined ) {
  2080. scene = scene.parent;
  2081. }
  2082. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2083. scene.__addObject( object );
  2084. }
  2085. }
  2086. },
  2087. remove: function ( object ) {
  2088. var index = this.children.indexOf( object );
  2089. if ( index !== - 1 ) {
  2090. object.parent = undefined;
  2091. this.children.splice( index, 1 );
  2092. // remove from scene
  2093. var scene = this;
  2094. while ( scene.parent !== undefined ) {
  2095. scene = scene.parent;
  2096. }
  2097. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2098. scene.__removeObject( object );
  2099. }
  2100. }
  2101. },
  2102. getChildByName: function ( name, recursive ) {
  2103. var c, cl, child;
  2104. for ( c = 0, cl = this.children.length; c < cl; c ++ ) {
  2105. child = this.children[ c ];
  2106. if ( child.name === name ) {
  2107. return child;
  2108. }
  2109. if ( recursive ) {
  2110. child = child.getChildByName( name, recursive );
  2111. if ( child !== undefined ) {
  2112. return child;
  2113. }
  2114. }
  2115. }
  2116. return undefined;
  2117. },
  2118. updateMatrix: function () {
  2119. this.matrix.setPosition( this.position );
  2120. if ( this.useQuaternion === true ) {
  2121. this.matrix.setRotationFromQuaternion( this.quaternion );
  2122. } else {
  2123. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2124. }
  2125. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2126. this.matrix.scale( this.scale );
  2127. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2128. }
  2129. this.matrixWorldNeedsUpdate = true;
  2130. },
  2131. updateMatrixWorld: function ( force ) {
  2132. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2133. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2134. if ( this.parent !== undefined ) {
  2135. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2136. } else {
  2137. this.matrixWorld.copy( this.matrix );
  2138. }
  2139. this.matrixWorldNeedsUpdate = false;
  2140. force = true;
  2141. }
  2142. // update children
  2143. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2144. this.children[ i ].updateMatrixWorld( force );
  2145. }
  2146. },
  2147. worldToLocal: function ( vector ) {
  2148. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2149. },
  2150. localToWorld: function ( vector ) {
  2151. return this.matrixWorld.multiplyVector3( vector );
  2152. },
  2153. clone: function () {
  2154. // TODO
  2155. }
  2156. };
  2157. THREE.Object3D.__m1 = new THREE.Matrix4();
  2158. THREE.Object3DCount = 0;
  2159. /**
  2160. * @author mrdoob / http://mrdoob.com/
  2161. * @author supereggbert / http://www.paulbrunt.co.uk/
  2162. * @author julianwa / https://github.com/julianwa
  2163. */
  2164. THREE.Projector = function() {
  2165. var _object, _objectCount, _objectPool = [],
  2166. _vertex, _vertexCount, _vertexPool = [],
  2167. _face, _face3Count, _face3Pool = [], _face4Count, _face4Pool = [],
  2168. _line, _lineCount, _linePool = [],
  2169. _particle, _particleCount, _particlePool = [],
  2170. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  2171. _vector3 = new THREE.Vector3(),
  2172. _vector4 = new THREE.Vector4(),
  2173. _viewProjectionMatrix = new THREE.Matrix4(),
  2174. _modelViewProjectionMatrix = new THREE.Matrix4(),
  2175. _frustum = new THREE.Frustum(),
  2176. _clippedVertex1PositionScreen = new THREE.Vector4(),
  2177. _clippedVertex2PositionScreen = new THREE.Vector4(),
  2178. _face3VertexNormals;
  2179. this.projectVector = function ( vector, camera ) {
  2180. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2181. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2182. _viewProjectionMatrix.multiplyVector3( vector );
  2183. return vector;
  2184. };
  2185. this.unprojectVector = function ( vector, camera ) {
  2186. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  2187. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  2188. _viewProjectionMatrix.multiplyVector3( vector );
  2189. return vector;
  2190. };
  2191. this.pickingRay = function ( vector, camera ) {
  2192. var end, ray, t;
  2193. // set two vectors with opposing z values
  2194. vector.z = -1.0;
  2195. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  2196. this.unprojectVector( vector, camera );
  2197. this.unprojectVector( end, camera );
  2198. // find direction from vector to end
  2199. end.subSelf( vector ).normalize();
  2200. return new THREE.Ray( vector, end );
  2201. };
  2202. function projectGraph( root, sort ) {
  2203. _objectCount = 0;
  2204. _renderData.objects.length = 0;
  2205. _renderData.sprites.length = 0;
  2206. _renderData.lights.length = 0;
  2207. var projectObject = function ( object ) {
  2208. if ( object.visible === false ) return;
  2209. if ( ( object instanceof THREE.Mesh || object instanceof THREE.Line ) &&
  2210. ( object.frustumCulled === false || _frustum.contains( object ) === true ) ) {
  2211. _vector3.copy( object.matrixWorld.getPosition() );
  2212. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2213. _object = getNextObjectInPool();
  2214. _object.object = object;
  2215. _object.z = _vector3.z;
  2216. _renderData.objects.push( _object );
  2217. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  2218. _vector3.copy( object.matrixWorld.getPosition() );
  2219. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2220. _object = getNextObjectInPool();
  2221. _object.object = object;
  2222. _object.z = _vector3.z;
  2223. _renderData.sprites.push( _object );
  2224. } else if ( object instanceof THREE.Light ) {
  2225. _renderData.lights.push( object );
  2226. }
  2227. for ( var c = 0, cl = object.children.length; c < cl; c ++ ) {
  2228. projectObject( object.children[ c ] );
  2229. }
  2230. };
  2231. projectObject( root );
  2232. if ( sort === true ) _renderData.objects.sort( painterSort );
  2233. return _renderData;
  2234. };
  2235. this.projectScene = function ( scene, camera, sort ) {
  2236. var near = camera.near, far = camera.far, visible = false,
  2237. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  2238. modelMatrix, rotationMatrix,
  2239. geometry, geometryMaterials, vertices, vertex, vertexPositionScreen,
  2240. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  2241. v1, v2, v3, v4, isFaceMaterial, material, side;
  2242. _face3Count = 0;
  2243. _face4Count = 0;
  2244. _lineCount = 0;
  2245. _particleCount = 0;
  2246. _renderData.elements.length = 0;
  2247. scene.updateMatrixWorld();
  2248. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2249. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2250. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2251. _frustum.setFromMatrix( _viewProjectionMatrix );
  2252. _renderData = projectGraph( scene, false );
  2253. for ( o = 0, ol = _renderData.objects.length; o < ol; o++ ) {
  2254. object = _renderData.objects[ o ].object;
  2255. modelMatrix = object.matrixWorld;
  2256. _vertexCount = 0;
  2257. if ( object instanceof THREE.Mesh ) {
  2258. geometry = object.geometry;
  2259. geometryMaterials = object.geometry.materials;
  2260. vertices = geometry.vertices;
  2261. faces = geometry.faces;
  2262. faceVertexUvs = geometry.faceVertexUvs;
  2263. rotationMatrix = object.matrixRotationWorld.extractRotation( modelMatrix );
  2264. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2265. side = object.material.side;
  2266. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  2267. _vertex = getNextVertexInPool();
  2268. _vertex.positionWorld.copy( vertices[ v ] );
  2269. modelMatrix.multiplyVector3( _vertex.positionWorld );
  2270. _vertex.positionScreen.copy( _vertex.positionWorld );
  2271. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  2272. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  2273. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  2274. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  2275. }
  2276. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  2277. face = faces[ f ];
  2278. material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  2279. if ( material === undefined ) continue;
  2280. side = material.side;
  2281. if ( face instanceof THREE.Face3 ) {
  2282. v1 = _vertexPool[ face.a ];
  2283. v2 = _vertexPool[ face.b ];
  2284. v3 = _vertexPool[ face.c ];
  2285. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  2286. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2287. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  2288. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2289. _face = getNextFace3InPool();
  2290. _face.v1.copy( v1 );
  2291. _face.v2.copy( v2 );
  2292. _face.v3.copy( v3 );
  2293. } else {
  2294. continue;
  2295. }
  2296. } else {
  2297. continue;
  2298. }
  2299. } else if ( face instanceof THREE.Face4 ) {
  2300. v1 = _vertexPool[ face.a ];
  2301. v2 = _vertexPool[ face.b ];
  2302. v3 = _vertexPool[ face.c ];
  2303. v4 = _vertexPool[ face.d ];
  2304. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  2305. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2306. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  2307. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  2308. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  2309. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2310. _face = getNextFace4InPool();
  2311. _face.v1.copy( v1 );
  2312. _face.v2.copy( v2 );
  2313. _face.v3.copy( v3 );
  2314. _face.v4.copy( v4 );
  2315. } else {
  2316. continue;
  2317. }
  2318. } else {
  2319. continue;
  2320. }
  2321. }
  2322. _face.normalWorld.copy( face.normal );
  2323. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  2324. rotationMatrix.multiplyVector3( _face.normalWorld );
  2325. _face.centroidWorld.copy( face.centroid );
  2326. modelMatrix.multiplyVector3( _face.centroidWorld );
  2327. _face.centroidScreen.copy( _face.centroidWorld );
  2328. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  2329. faceVertexNormals = face.vertexNormals;
  2330. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  2331. normal = _face.vertexNormalsWorld[ n ];
  2332. normal.copy( faceVertexNormals[ n ] );
  2333. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  2334. rotationMatrix.multiplyVector3( normal );
  2335. }
  2336. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  2337. uvs = faceVertexUvs[ c ][ f ];
  2338. if ( uvs === undefined ) continue;
  2339. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2340. _face.uvs[ c ][ u ] = uvs[ u ];
  2341. }
  2342. }
  2343. _face.material = material;
  2344. _face.z = _face.centroidScreen.z;
  2345. _renderData.elements.push( _face );
  2346. }
  2347. } else if ( object instanceof THREE.Line ) {
  2348. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  2349. vertices = object.geometry.vertices;
  2350. v1 = getNextVertexInPool();
  2351. v1.positionScreen.copy( vertices[ 0 ] );
  2352. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2353. // Handle LineStrip and LinePieces
  2354. var step = object.type === THREE.LinePieces ? 2 : 1;
  2355. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2356. v1 = getNextVertexInPool();
  2357. v1.positionScreen.copy( vertices[ v ] );
  2358. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2359. if ( ( v + 1 ) % step > 0 ) continue;
  2360. v2 = _vertexPool[ _vertexCount - 2 ];
  2361. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2362. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2363. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  2364. // Perform the perspective divide
  2365. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2366. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2367. _line = getNextLineInPool();
  2368. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2369. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2370. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2371. _line.material = object.material;
  2372. _renderData.elements.push( _line );
  2373. }
  2374. }
  2375. }
  2376. }
  2377. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2378. object = _renderData.sprites[ o ].object;
  2379. modelMatrix = object.matrixWorld;
  2380. if ( object instanceof THREE.Particle ) {
  2381. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  2382. _viewProjectionMatrix.multiplyVector4( _vector4 );
  2383. _vector4.z /= _vector4.w;
  2384. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2385. _particle = getNextParticleInPool();
  2386. _particle.object = object;
  2387. _particle.x = _vector4.x / _vector4.w;
  2388. _particle.y = _vector4.y / _vector4.w;
  2389. _particle.z = _vector4.z;
  2390. _particle.rotation = object.rotation.z;
  2391. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2392. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2393. _particle.material = object.material;
  2394. _renderData.elements.push( _particle );
  2395. }
  2396. }
  2397. }
  2398. sort && _renderData.elements.sort( painterSort );
  2399. return _renderData;
  2400. };
  2401. // Pools
  2402. function getNextObjectInPool() {
  2403. var object;
  2404. if ( _objectCount === _objectPool.length ) {
  2405. object = new THREE.RenderableObject();
  2406. _objectPool.push( object );
  2407. } else {
  2408. object = _objectPool[ _objectCount ];
  2409. }
  2410. _objectCount ++;
  2411. return object;
  2412. }
  2413. function getNextVertexInPool() {
  2414. var vertex;
  2415. if ( _vertexCount === _vertexPool.length ) {
  2416. vertex = new THREE.RenderableVertex();
  2417. _vertexPool.push( vertex );
  2418. } else {
  2419. vertex = _vertexPool[ _vertexCount ];
  2420. }
  2421. _vertexCount ++;
  2422. return vertex;
  2423. }
  2424. function getNextFace3InPool() {
  2425. var face;
  2426. if ( _face3Count === _face3Pool.length ) {
  2427. face = new THREE.RenderableFace3();
  2428. _face3Pool.push( face );
  2429. } else {
  2430. face = _face3Pool[ _face3Count ];
  2431. }
  2432. _face3Count ++;
  2433. return face;
  2434. }
  2435. function getNextFace4InPool() {
  2436. var face;
  2437. if ( _face4Count === _face4Pool.length ) {
  2438. face = new THREE.RenderableFace4();
  2439. _face4Pool.push( face );
  2440. } else {
  2441. face = _face4Pool[ _face4Count ];
  2442. }
  2443. _face4Count ++;
  2444. return face;
  2445. }
  2446. function getNextLineInPool() {
  2447. var line;
  2448. if ( _lineCount === _linePool.length ) {
  2449. line = new THREE.RenderableLine();
  2450. _linePool.push( line );
  2451. } else {
  2452. line = _linePool[ _lineCount ];
  2453. }
  2454. _lineCount ++;
  2455. return line;
  2456. }
  2457. function getNextParticleInPool() {
  2458. var particle;
  2459. if ( _particleCount === _particlePool.length ) {
  2460. particle = new THREE.RenderableParticle();
  2461. _particlePool.push( particle );
  2462. } else {
  2463. particle = _particlePool[ _particleCount ];
  2464. }
  2465. _particleCount ++;
  2466. return particle;
  2467. }
  2468. //
  2469. function painterSort( a, b ) {
  2470. return b.z - a.z;
  2471. }
  2472. function clipLine( s1, s2 ) {
  2473. var alpha1 = 0, alpha2 = 1,
  2474. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2475. // Z = -1 and Z = +1, respectively.
  2476. bc1near = s1.z + s1.w,
  2477. bc2near = s2.z + s2.w,
  2478. bc1far = - s1.z + s1.w,
  2479. bc2far = - s2.z + s2.w;
  2480. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2481. // Both vertices lie entirely within all clip planes.
  2482. return true;
  2483. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2484. // Both vertices lie entirely outside one of the clip planes.
  2485. return false;
  2486. } else {
  2487. // The line segment spans at least one clip plane.
  2488. if ( bc1near < 0 ) {
  2489. // v1 lies outside the near plane, v2 inside
  2490. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2491. } else if ( bc2near < 0 ) {
  2492. // v2 lies outside the near plane, v1 inside
  2493. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2494. }
  2495. if ( bc1far < 0 ) {
  2496. // v1 lies outside the far plane, v2 inside
  2497. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2498. } else if ( bc2far < 0 ) {
  2499. // v2 lies outside the far plane, v2 inside
  2500. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2501. }
  2502. if ( alpha2 < alpha1 ) {
  2503. // The line segment spans two boundaries, but is outside both of them.
  2504. // (This can't happen when we're only clipping against just near/far but good
  2505. // to leave the check here for future usage if other clip planes are added.)
  2506. return false;
  2507. } else {
  2508. // Update the s1 and s2 vertices to match the clipped line segment.
  2509. s1.lerpSelf( s2, alpha1 );
  2510. s2.lerpSelf( s1, 1 - alpha2 );
  2511. return true;
  2512. }
  2513. }
  2514. }
  2515. };
  2516. /**
  2517. * @author mikael emtinger / http://gomo.se/
  2518. * @author alteredq / http://alteredqualia.com/
  2519. * @author WestLangley / http://github.com/WestLangley
  2520. */
  2521. THREE.Quaternion = function( x, y, z, w ) {
  2522. this.x = x || 0;
  2523. this.y = y || 0;
  2524. this.z = z || 0;
  2525. this.w = ( w !== undefined ) ? w : 1;
  2526. };
  2527. THREE.Quaternion.prototype = {
  2528. constructor: THREE.Quaternion,
  2529. set: function ( x, y, z, w ) {
  2530. this.x = x;
  2531. this.y = y;
  2532. this.z = z;
  2533. this.w = w;
  2534. return this;
  2535. },
  2536. copy: function ( q ) {
  2537. this.x = q.x;
  2538. this.y = q.y;
  2539. this.z = q.z;
  2540. this.w = q.w;
  2541. return this;
  2542. },
  2543. setFromEuler: function ( v, order ) {
  2544. // http://www.mathworks.com/matlabcentral/fileexchange/
  2545. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2546. // content/SpinCalc.m
  2547. var c1 = Math.cos( v.x / 2 );
  2548. var c2 = Math.cos( v.y / 2 );
  2549. var c3 = Math.cos( v.z / 2 );
  2550. var s1 = Math.sin( v.x / 2 );
  2551. var s2 = Math.sin( v.y / 2 );
  2552. var s3 = Math.sin( v.z / 2 );
  2553. if ( order === undefined || order === 'XYZ' ) {
  2554. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2555. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2556. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2557. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2558. } else if ( order === 'YXZ' ) {
  2559. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2560. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2561. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2562. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2563. } else if ( order === 'ZXY' ) {
  2564. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2565. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2566. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2567. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2568. } else if ( order === 'ZYX' ) {
  2569. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2570. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2571. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2572. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2573. } else if ( order === 'YZX' ) {
  2574. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2575. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2576. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2577. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2578. } else if ( order === 'XZY' ) {
  2579. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2580. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2581. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2582. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2583. }
  2584. return this;
  2585. },
  2586. setFromAxisAngle: function ( axis, angle ) {
  2587. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2588. // axis have to be normalized
  2589. var halfAngle = angle / 2,
  2590. s = Math.sin( halfAngle );
  2591. this.x = axis.x * s;
  2592. this.y = axis.y * s;
  2593. this.z = axis.z * s;
  2594. this.w = Math.cos( halfAngle );
  2595. return this;
  2596. },
  2597. setFromRotationMatrix: function ( m ) {
  2598. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2599. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2600. var te = m.elements,
  2601. m11 = te[0], m12 = te[4], m13 = te[8],
  2602. m21 = te[1], m22 = te[5], m23 = te[9],
  2603. m31 = te[2], m32 = te[6], m33 = te[10],
  2604. trace = m11 + m22 + m33,
  2605. s;
  2606. if( trace > 0 ) {
  2607. s = 0.5 / Math.sqrt( trace + 1.0 );
  2608. this.w = 0.25 / s;
  2609. this.x = ( m32 - m23 ) * s;
  2610. this.y = ( m13 - m31 ) * s;
  2611. this.z = ( m21 - m12 ) * s;
  2612. } else if ( m11 > m22 && m11 > m33 ) {
  2613. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2614. this.w = (m32 - m23 ) / s;
  2615. this.x = 0.25 * s;
  2616. this.y = (m12 + m21 ) / s;
  2617. this.z = (m13 + m31 ) / s;
  2618. } else if (m22 > m33) {
  2619. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2620. this.w = (m13 - m31 ) / s;
  2621. this.x = (m12 + m21 ) / s;
  2622. this.y = 0.25 * s;
  2623. this.z = (m23 + m32 ) / s;
  2624. } else {
  2625. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2626. this.w = ( m21 - m12 ) / s;
  2627. this.x = ( m13 + m31 ) / s;
  2628. this.y = ( m23 + m32 ) / s;
  2629. this.z = 0.25 * s;
  2630. }
  2631. return this;
  2632. },
  2633. calculateW : function () {
  2634. this.w = - Math.sqrt( Math.abs( 1.0 - this.x * this.x - this.y * this.y - this.z * this.z ) );
  2635. return this;
  2636. },
  2637. inverse: function () {
  2638. this.x *= -1;
  2639. this.y *= -1;
  2640. this.z *= -1;
  2641. return this;
  2642. },
  2643. length: function () {
  2644. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2645. },
  2646. normalize: function () {
  2647. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2648. if ( l === 0 ) {
  2649. this.x = 0;
  2650. this.y = 0;
  2651. this.z = 0;
  2652. this.w = 0;
  2653. } else {
  2654. l = 1 / l;
  2655. this.x = this.x * l;
  2656. this.y = this.y * l;
  2657. this.z = this.z * l;
  2658. this.w = this.w * l;
  2659. }
  2660. return this;
  2661. },
  2662. multiply: function ( a, b ) {
  2663. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2664. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2665. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2666. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2667. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2668. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2669. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2670. return this;
  2671. },
  2672. multiplySelf: function ( b ) {
  2673. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2674. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2675. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2676. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2677. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2678. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2679. return this;
  2680. },
  2681. multiplyVector3: function ( vector, dest ) {
  2682. if ( !dest ) { dest = vector; }
  2683. var x = vector.x, y = vector.y, z = vector.z,
  2684. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2685. // calculate quat * vector
  2686. var ix = qw * x + qy * z - qz * y,
  2687. iy = qw * y + qz * x - qx * z,
  2688. iz = qw * z + qx * y - qy * x,
  2689. iw = -qx * x - qy * y - qz * z;
  2690. // calculate result * inverse quat
  2691. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2692. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2693. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2694. return dest;
  2695. },
  2696. slerpSelf: function ( qb, t ) {
  2697. var x = this.x, y = this.y, z = this.z, w = this.w;
  2698. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2699. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2700. if ( cosHalfTheta < 0 ) {
  2701. this.w = -qb.w;
  2702. this.x = -qb.x;
  2703. this.y = -qb.y;
  2704. this.z = -qb.z;
  2705. cosHalfTheta = -cosHalfTheta;
  2706. } else {
  2707. this.copy( qb );
  2708. }
  2709. if ( cosHalfTheta >= 1.0 ) {
  2710. this.w = w;
  2711. this.x = x;
  2712. this.y = y;
  2713. this.z = z;
  2714. return this;
  2715. }
  2716. var halfTheta = Math.acos( cosHalfTheta );
  2717. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2718. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2719. this.w = 0.5 * ( w + this.w );
  2720. this.x = 0.5 * ( x + this.x );
  2721. this.y = 0.5 * ( y + this.y );
  2722. this.z = 0.5 * ( z + this.z );
  2723. return this;
  2724. }
  2725. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2726. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2727. this.w = ( w * ratioA + this.w * ratioB );
  2728. this.x = ( x * ratioA + this.x * ratioB );
  2729. this.y = ( y * ratioA + this.y * ratioB );
  2730. this.z = ( z * ratioA + this.z * ratioB );
  2731. return this;
  2732. },
  2733. clone: function () {
  2734. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2735. }
  2736. }
  2737. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2738. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2739. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2740. if ( cosHalfTheta < 0 ) {
  2741. qm.w = -qb.w;
  2742. qm.x = -qb.x;
  2743. qm.y = -qb.y;
  2744. qm.z = -qb.z;
  2745. cosHalfTheta = -cosHalfTheta;
  2746. } else {
  2747. qm.copy( qb );
  2748. }
  2749. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2750. qm.w = qa.w;
  2751. qm.x = qa.x;
  2752. qm.y = qa.y;
  2753. qm.z = qa.z;
  2754. return qm;
  2755. }
  2756. var halfTheta = Math.acos( cosHalfTheta );
  2757. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2758. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2759. qm.w = 0.5 * ( qa.w + qm.w );
  2760. qm.x = 0.5 * ( qa.x + qm.x );
  2761. qm.y = 0.5 * ( qa.y + qm.y );
  2762. qm.z = 0.5 * ( qa.z + qm.z );
  2763. return qm;
  2764. }
  2765. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2766. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2767. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2768. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2769. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2770. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2771. return qm;
  2772. }
  2773. /**
  2774. * @author mrdoob / http://mrdoob.com/
  2775. */
  2776. THREE.Vertex = function ( v ) {
  2777. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  2778. return v;
  2779. };
  2780. /**
  2781. * @author mrdoob / http://mrdoob.com/
  2782. * @author alteredq / http://alteredqualia.com/
  2783. */
  2784. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2785. this.a = a;
  2786. this.b = b;
  2787. this.c = c;
  2788. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2789. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2790. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2791. this.vertexColors = color instanceof Array ? color : [];
  2792. this.vertexTangents = [];
  2793. this.materialIndex = materialIndex;
  2794. this.centroid = new THREE.Vector3();
  2795. };
  2796. THREE.Face3.prototype = {
  2797. constructor: THREE.Face3,
  2798. clone: function () {
  2799. var face = new THREE.Face3( this.a, this.b, this.c );
  2800. face.normal.copy( this.normal );
  2801. face.color.copy( this.color );
  2802. face.centroid.copy( this.centroid );
  2803. face.materialIndex = this.materialIndex;
  2804. var i, il;
  2805. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2806. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2807. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2808. return face;
  2809. }
  2810. };
  2811. /**
  2812. * @author mrdoob / http://mrdoob.com/
  2813. * @author alteredq / http://alteredqualia.com/
  2814. */
  2815. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2816. this.a = a;
  2817. this.b = b;
  2818. this.c = c;
  2819. this.d = d;
  2820. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2821. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2822. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2823. this.vertexColors = color instanceof Array ? color : [];
  2824. this.vertexTangents = [];
  2825. this.materialIndex = materialIndex;
  2826. this.centroid = new THREE.Vector3();
  2827. };
  2828. THREE.Face4.prototype = {
  2829. constructor: THREE.Face4,
  2830. clone: function () {
  2831. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  2832. face.normal.copy( this.normal );
  2833. face.color.copy( this.color );
  2834. face.centroid.copy( this.centroid );
  2835. face.materialIndex = this.materialIndex;
  2836. var i, il;
  2837. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2838. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2839. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2840. return face;
  2841. }
  2842. };
  2843. /**
  2844. * @author mrdoob / http://mrdoob.com/
  2845. */
  2846. THREE.UV = function ( u, v ) {
  2847. this.u = u || 0;
  2848. this.v = v || 0;
  2849. };
  2850. THREE.UV.prototype = {
  2851. constructor: THREE.UV,
  2852. set: function ( u, v ) {
  2853. this.u = u;
  2854. this.v = v;
  2855. return this;
  2856. },
  2857. copy: function ( uv ) {
  2858. this.u = uv.u;
  2859. this.v = uv.v;
  2860. return this;
  2861. },
  2862. lerpSelf: function ( uv, alpha ) {
  2863. this.u += ( uv.u - this.u ) * alpha;
  2864. this.v += ( uv.v - this.v ) * alpha;
  2865. return this;
  2866. },
  2867. clone: function () {
  2868. return new THREE.UV( this.u, this.v );
  2869. }
  2870. };
  2871. /**
  2872. * @author mrdoob / http://mrdoob.com/
  2873. * @author kile / http://kile.stravaganza.org/
  2874. * @author alteredq / http://alteredqualia.com/
  2875. * @author mikael emtinger / http://gomo.se/
  2876. * @author zz85 / http://www.lab4games.net/zz85/blog
  2877. */
  2878. THREE.Geometry = function () {
  2879. this.id = THREE.GeometryCount ++;
  2880. this.name = '';
  2881. this.vertices = [];
  2882. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  2883. this.materials = [];
  2884. this.faces = [];
  2885. this.faceUvs = [[]];
  2886. this.faceVertexUvs = [[]];
  2887. this.morphTargets = [];
  2888. this.morphColors = [];
  2889. this.morphNormals = [];
  2890. this.skinWeights = [];
  2891. this.skinIndices = [];
  2892. this.boundingBox = null;
  2893. this.boundingSphere = null;
  2894. this.hasTangents = false;
  2895. this.dynamic = true; // the intermediate typearrays will be deleted when set to false
  2896. };
  2897. THREE.Geometry.prototype = {
  2898. constructor : THREE.Geometry,
  2899. applyMatrix: function ( matrix ) {
  2900. var matrixRotation = new THREE.Matrix4();
  2901. matrixRotation.extractRotation( matrix );
  2902. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  2903. var vertex = this.vertices[ i ];
  2904. matrix.multiplyVector3( vertex );
  2905. }
  2906. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  2907. var face = this.faces[ i ];
  2908. matrixRotation.multiplyVector3( face.normal );
  2909. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  2910. matrixRotation.multiplyVector3( face.vertexNormals[ j ] );
  2911. }
  2912. matrix.multiplyVector3( face.centroid );
  2913. }
  2914. },
  2915. computeCentroids: function () {
  2916. var f, fl, face;
  2917. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2918. face = this.faces[ f ];
  2919. face.centroid.set( 0, 0, 0 );
  2920. if ( face instanceof THREE.Face3 ) {
  2921. face.centroid.addSelf( this.vertices[ face.a ] );
  2922. face.centroid.addSelf( this.vertices[ face.b ] );
  2923. face.centroid.addSelf( this.vertices[ face.c ] );
  2924. face.centroid.divideScalar( 3 );
  2925. } else if ( face instanceof THREE.Face4 ) {
  2926. face.centroid.addSelf( this.vertices[ face.a ] );
  2927. face.centroid.addSelf( this.vertices[ face.b ] );
  2928. face.centroid.addSelf( this.vertices[ face.c ] );
  2929. face.centroid.addSelf( this.vertices[ face.d ] );
  2930. face.centroid.divideScalar( 4 );
  2931. }
  2932. }
  2933. },
  2934. computeFaceNormals: function () {
  2935. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  2936. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  2937. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2938. face = this.faces[ f ];
  2939. vA = this.vertices[ face.a ];
  2940. vB = this.vertices[ face.b ];
  2941. vC = this.vertices[ face.c ];
  2942. cb.sub( vC, vB );
  2943. ab.sub( vA, vB );
  2944. cb.crossSelf( ab );
  2945. if ( !cb.isZero() ) {
  2946. cb.normalize();
  2947. }
  2948. face.normal.copy( cb );
  2949. }
  2950. },
  2951. computeVertexNormals: function () {
  2952. var v, vl, f, fl, face, vertices;
  2953. // create internal buffers for reuse when calling this method repeatedly
  2954. // (otherwise memory allocation / deallocation every frame is big resource hog)
  2955. if ( this.__tmpVertices === undefined ) {
  2956. this.__tmpVertices = new Array( this.vertices.length );
  2957. vertices = this.__tmpVertices;
  2958. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2959. vertices[ v ] = new THREE.Vector3();
  2960. }
  2961. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2962. face = this.faces[ f ];
  2963. if ( face instanceof THREE.Face3 ) {
  2964. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2965. } else if ( face instanceof THREE.Face4 ) {
  2966. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2967. }
  2968. }
  2969. } else {
  2970. vertices = this.__tmpVertices;
  2971. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2972. vertices[ v ].set( 0, 0, 0 );
  2973. }
  2974. }
  2975. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2976. face = this.faces[ f ];
  2977. if ( face instanceof THREE.Face3 ) {
  2978. vertices[ face.a ].addSelf( face.normal );
  2979. vertices[ face.b ].addSelf( face.normal );
  2980. vertices[ face.c ].addSelf( face.normal );
  2981. } else if ( face instanceof THREE.Face4 ) {
  2982. vertices[ face.a ].addSelf( face.normal );
  2983. vertices[ face.b ].addSelf( face.normal );
  2984. vertices[ face.c ].addSelf( face.normal );
  2985. vertices[ face.d ].addSelf( face.normal );
  2986. }
  2987. }
  2988. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2989. vertices[ v ].normalize();
  2990. }
  2991. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2992. face = this.faces[ f ];
  2993. if ( face instanceof THREE.Face3 ) {
  2994. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  2995. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  2996. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  2997. } else if ( face instanceof THREE.Face4 ) {
  2998. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  2999. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3000. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3001. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3002. }
  3003. }
  3004. },
  3005. computeMorphNormals: function () {
  3006. var i, il, f, fl, face;
  3007. // save original normals
  3008. // - create temp variables on first access
  3009. // otherwise just copy (for faster repeated calls)
  3010. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3011. face = this.faces[ f ];
  3012. if ( ! face.__originalFaceNormal ) {
  3013. face.__originalFaceNormal = face.normal.clone();
  3014. } else {
  3015. face.__originalFaceNormal.copy( face.normal );
  3016. }
  3017. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3018. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3019. if ( ! face.__originalVertexNormals[ i ] ) {
  3020. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3021. } else {
  3022. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3023. }
  3024. }
  3025. }
  3026. // use temp geometry to compute face and vertex normals for each morph
  3027. var tmpGeo = new THREE.Geometry();
  3028. tmpGeo.faces = this.faces;
  3029. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3030. // create on first access
  3031. if ( ! this.morphNormals[ i ] ) {
  3032. this.morphNormals[ i ] = {};
  3033. this.morphNormals[ i ].faceNormals = [];
  3034. this.morphNormals[ i ].vertexNormals = [];
  3035. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3036. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3037. var faceNormal, vertexNormals;
  3038. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3039. face = this.faces[ f ];
  3040. faceNormal = new THREE.Vector3();
  3041. if ( face instanceof THREE.Face3 ) {
  3042. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3043. } else {
  3044. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3045. }
  3046. dstNormalsFace.push( faceNormal );
  3047. dstNormalsVertex.push( vertexNormals );
  3048. }
  3049. }
  3050. var morphNormals = this.morphNormals[ i ];
  3051. // set vertices to morph target
  3052. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3053. // compute morph normals
  3054. tmpGeo.computeFaceNormals();
  3055. tmpGeo.computeVertexNormals();
  3056. // store morph normals
  3057. var faceNormal, vertexNormals;
  3058. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3059. face = this.faces[ f ];
  3060. faceNormal = morphNormals.faceNormals[ f ];
  3061. vertexNormals = morphNormals.vertexNormals[ f ];
  3062. faceNormal.copy( face.normal );
  3063. if ( face instanceof THREE.Face3 ) {
  3064. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3065. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3066. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3067. } else {
  3068. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3069. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3070. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3071. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3072. }
  3073. }
  3074. }
  3075. // restore original normals
  3076. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3077. face = this.faces[ f ];
  3078. face.normal = face.__originalFaceNormal;
  3079. face.vertexNormals = face.__originalVertexNormals;
  3080. }
  3081. },
  3082. computeTangents: function () {
  3083. // based on http://www.terathon.com/code/tangent.html
  3084. // tangents go to vertices
  3085. var f, fl, v, vl, i, il, vertexIndex,
  3086. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3087. x1, x2, y1, y2, z1, z2,
  3088. s1, s2, t1, t2, r, t, test,
  3089. tan1 = [], tan2 = [],
  3090. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3091. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3092. n = new THREE.Vector3(), w;
  3093. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3094. tan1[ v ] = new THREE.Vector3();
  3095. tan2[ v ] = new THREE.Vector3();
  3096. }
  3097. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  3098. vA = context.vertices[ a ];
  3099. vB = context.vertices[ b ];
  3100. vC = context.vertices[ c ];
  3101. uvA = uv[ ua ];
  3102. uvB = uv[ ub ];
  3103. uvC = uv[ uc ];
  3104. x1 = vB.x - vA.x;
  3105. x2 = vC.x - vA.x;
  3106. y1 = vB.y - vA.y;
  3107. y2 = vC.y - vA.y;
  3108. z1 = vB.z - vA.z;
  3109. z2 = vC.z - vA.z;
  3110. s1 = uvB.u - uvA.u;
  3111. s2 = uvC.u - uvA.u;
  3112. t1 = uvB.v - uvA.v;
  3113. t2 = uvC.v - uvA.v;
  3114. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3115. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  3116. ( t2 * y1 - t1 * y2 ) * r,
  3117. ( t2 * z1 - t1 * z2 ) * r );
  3118. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  3119. ( s1 * y2 - s2 * y1 ) * r,
  3120. ( s1 * z2 - s2 * z1 ) * r );
  3121. tan1[ a ].addSelf( sdir );
  3122. tan1[ b ].addSelf( sdir );
  3123. tan1[ c ].addSelf( sdir );
  3124. tan2[ a ].addSelf( tdir );
  3125. tan2[ b ].addSelf( tdir );
  3126. tan2[ c ].addSelf( tdir );
  3127. }
  3128. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3129. face = this.faces[ f ];
  3130. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  3131. if ( face instanceof THREE.Face3 ) {
  3132. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  3133. } else if ( face instanceof THREE.Face4 ) {
  3134. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  3135. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  3136. }
  3137. }
  3138. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  3139. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3140. face = this.faces[ f ];
  3141. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  3142. n.copy( face.vertexNormals[ i ] );
  3143. vertexIndex = face[ faceIndex[ i ] ];
  3144. t = tan1[ vertexIndex ];
  3145. // Gram-Schmidt orthogonalize
  3146. tmp.copy( t );
  3147. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3148. // Calculate handedness
  3149. tmp2.cross( face.vertexNormals[ i ], t );
  3150. test = tmp2.dot( tan2[ vertexIndex ] );
  3151. w = (test < 0.0) ? -1.0 : 1.0;
  3152. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  3153. }
  3154. }
  3155. this.hasTangents = true;
  3156. },
  3157. computeBoundingBox: function () {
  3158. if ( ! this.boundingBox ) {
  3159. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  3160. }
  3161. if ( this.vertices.length > 0 ) {
  3162. var position, firstPosition = this.vertices[ 0 ];
  3163. this.boundingBox.min.copy( firstPosition );
  3164. this.boundingBox.max.copy( firstPosition );
  3165. var min = this.boundingBox.min,
  3166. max = this.boundingBox.max;
  3167. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  3168. position = this.vertices[ v ];
  3169. if ( position.x < min.x ) {
  3170. min.x = position.x;
  3171. } else if ( position.x > max.x ) {
  3172. max.x = position.x;
  3173. }
  3174. if ( position.y < min.y ) {
  3175. min.y = position.y;
  3176. } else if ( position.y > max.y ) {
  3177. max.y = position.y;
  3178. }
  3179. if ( position.z < min.z ) {
  3180. min.z = position.z;
  3181. } else if ( position.z > max.z ) {
  3182. max.z = position.z;
  3183. }
  3184. }
  3185. } else {
  3186. this.boundingBox.min.set( 0, 0, 0 );
  3187. this.boundingBox.max.set( 0, 0, 0 );
  3188. }
  3189. },
  3190. computeBoundingSphere: function () {
  3191. var maxRadiusSq = 0;
  3192. if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
  3193. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  3194. var radiusSq = this.vertices[ i ].lengthSq();
  3195. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3196. }
  3197. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3198. },
  3199. /*
  3200. * Checks for duplicate vertices with hashmap.
  3201. * Duplicated vertices are removed
  3202. * and faces' vertices are updated.
  3203. */
  3204. mergeVertices: function () {
  3205. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  3206. var unique = [], changes = [];
  3207. var v, key;
  3208. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  3209. var precision = Math.pow( 10, precisionPoints );
  3210. var i,il, face;
  3211. var abcd = 'abcd', o, k, j, jl, u;
  3212. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  3213. v = this.vertices[ i ];
  3214. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  3215. if ( verticesMap[ key ] === undefined ) {
  3216. verticesMap[ key ] = i;
  3217. unique.push( this.vertices[ i ] );
  3218. changes[ i ] = unique.length - 1;
  3219. } else {
  3220. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3221. changes[ i ] = changes[ verticesMap[ key ] ];
  3222. }
  3223. };
  3224. // Start to patch face indices
  3225. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  3226. face = this.faces[ i ];
  3227. if ( face instanceof THREE.Face3 ) {
  3228. face.a = changes[ face.a ];
  3229. face.b = changes[ face.b ];
  3230. face.c = changes[ face.c ];
  3231. } else if ( face instanceof THREE.Face4 ) {
  3232. face.a = changes[ face.a ];
  3233. face.b = changes[ face.b ];
  3234. face.c = changes[ face.c ];
  3235. face.d = changes[ face.d ];
  3236. // check dups in (a, b, c, d) and convert to -> face3
  3237. o = [ face.a, face.b, face.c, face.d ];
  3238. for ( k = 3; k > 0; k -- ) {
  3239. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  3240. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  3241. o.splice( k, 1 );
  3242. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  3243. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  3244. u = this.faceVertexUvs[ j ][ i ];
  3245. if ( u ) u.splice( k, 1 );
  3246. }
  3247. this.faces[ i ].vertexColors = face.vertexColors;
  3248. break;
  3249. }
  3250. }
  3251. }
  3252. }
  3253. // Use unique set of vertices
  3254. var diff = this.vertices.length - unique.length;
  3255. this.vertices = unique;
  3256. return diff;
  3257. },
  3258. clone: function () {
  3259. // TODO
  3260. }
  3261. };
  3262. THREE.GeometryCount = 0;
  3263. /**
  3264. * @author alteredq / http://alteredqualia.com/
  3265. */
  3266. THREE.BufferGeometry = function () {
  3267. this.id = THREE.GeometryCount ++;
  3268. // attributes
  3269. this.attributes = {};
  3270. // attributes typed arrays are kept only if dynamic flag is set
  3271. this.dynamic = false;
  3272. // boundings
  3273. this.boundingBox = null;
  3274. this.boundingSphere = null;
  3275. this.hasTangents = false;
  3276. // for compatibility
  3277. this.morphTargets = [];
  3278. };
  3279. THREE.BufferGeometry.prototype = {
  3280. constructor : THREE.BufferGeometry,
  3281. applyMatrix: function ( matrix ) {
  3282. var positionArray;
  3283. var normalArray;
  3284. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  3285. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  3286. if ( positionArray !== undefined ) {
  3287. matrix.multiplyVector3Array( positionArray );
  3288. this.verticesNeedUpdate = true;
  3289. }
  3290. if ( normalArray !== undefined ) {
  3291. var matrixRotation = new THREE.Matrix4();
  3292. matrixRotation.extractRotation( matrix );
  3293. matrixRotation.multiplyVector3Array( normalArray );
  3294. this.normalsNeedUpdate = true;
  3295. }
  3296. },
  3297. computeBoundingBox: function () {
  3298. if ( ! this.boundingBox ) {
  3299. this.boundingBox = {
  3300. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  3301. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  3302. };
  3303. }
  3304. var positions = this.attributes[ "position" ].array;
  3305. if ( positions ) {
  3306. var bb = this.boundingBox;
  3307. var x, y, z;
  3308. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3309. x = positions[ i ];
  3310. y = positions[ i + 1 ];
  3311. z = positions[ i + 2 ];
  3312. // bounding box
  3313. if ( x < bb.min.x ) {
  3314. bb.min.x = x;
  3315. } else if ( x > bb.max.x ) {
  3316. bb.max.x = x;
  3317. }
  3318. if ( y < bb.min.y ) {
  3319. bb.min.y = y;
  3320. } else if ( y > bb.max.y ) {
  3321. bb.max.y = y;
  3322. }
  3323. if ( z < bb.min.z ) {
  3324. bb.min.z = z;
  3325. } else if ( z > bb.max.z ) {
  3326. bb.max.z = z;
  3327. }
  3328. }
  3329. }
  3330. if ( positions === undefined || positions.length === 0 ) {
  3331. this.boundingBox.min.set( 0, 0, 0 );
  3332. this.boundingBox.max.set( 0, 0, 0 );
  3333. }
  3334. },
  3335. computeBoundingSphere: function () {
  3336. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  3337. var positions = this.attributes[ "position" ].array;
  3338. if ( positions ) {
  3339. var radiusSq, maxRadiusSq = 0;
  3340. var x, y, z;
  3341. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3342. x = positions[ i ];
  3343. y = positions[ i + 1 ];
  3344. z = positions[ i + 2 ];
  3345. radiusSq = x * x + y * y + z * z;
  3346. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3347. }
  3348. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3349. }
  3350. },
  3351. computeVertexNormals: function () {
  3352. if ( this.attributes[ "position" ] && this.attributes[ "index" ] ) {
  3353. var i, il;
  3354. var j, jl;
  3355. var nVertexElements = this.attributes[ "position" ].array.length;
  3356. if ( this.attributes[ "normal" ] === undefined ) {
  3357. this.attributes[ "normal" ] = {
  3358. itemSize: 3,
  3359. array: new Float32Array( nVertexElements ),
  3360. numItems: nVertexElements
  3361. };
  3362. } else {
  3363. // reset existing normals to zero
  3364. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  3365. this.attributes[ "normal" ].array[ i ] = 0;
  3366. }
  3367. }
  3368. var offsets = this.offsets;
  3369. var indices = this.attributes[ "index" ].array;
  3370. var positions = this.attributes[ "position" ].array;
  3371. var normals = this.attributes[ "normal" ].array;
  3372. var vA, vB, vC, x, y, z,
  3373. pA = new THREE.Vector3(),
  3374. pB = new THREE.Vector3(),
  3375. pC = new THREE.Vector3(),
  3376. cb = new THREE.Vector3(),
  3377. ab = new THREE.Vector3();
  3378. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3379. var start = offsets[ j ].start;
  3380. var count = offsets[ j ].count;
  3381. var index = offsets[ j ].index;
  3382. for ( i = start, il = start + count; i < il; i += 3 ) {
  3383. vA = index + indices[ i ];
  3384. vB = index + indices[ i + 1 ];
  3385. vC = index + indices[ i + 2 ];
  3386. x = positions[ vA * 3 ];
  3387. y = positions[ vA * 3 + 1 ];
  3388. z = positions[ vA * 3 + 2 ];
  3389. pA.set( x, y, z );
  3390. x = positions[ vB * 3 ];
  3391. y = positions[ vB * 3 + 1 ];
  3392. z = positions[ vB * 3 + 2 ];
  3393. pB.set( x, y, z );
  3394. x = positions[ vC * 3 ];
  3395. y = positions[ vC * 3 + 1 ];
  3396. z = positions[ vC * 3 + 2 ];
  3397. pC.set( x, y, z );
  3398. cb.sub( pC, pB );
  3399. ab.sub( pA, pB );
  3400. cb.crossSelf( ab );
  3401. normals[ vA * 3 ] += cb.x;
  3402. normals[ vA * 3 + 1 ] += cb.y;
  3403. normals[ vA * 3 + 2 ] += cb.z;
  3404. normals[ vB * 3 ] += cb.x;
  3405. normals[ vB * 3 + 1 ] += cb.y;
  3406. normals[ vB * 3 + 2 ] += cb.z;
  3407. normals[ vC * 3 ] += cb.x;
  3408. normals[ vC * 3 + 1 ] += cb.y;
  3409. normals[ vC * 3 + 2 ] += cb.z;
  3410. }
  3411. }
  3412. // normalize normals
  3413. for ( i = 0, il = normals.length; i < il; i += 3 ) {
  3414. x = normals[ i ];
  3415. y = normals[ i + 1 ];
  3416. z = normals[ i + 2 ];
  3417. var n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  3418. normals[ i ] *= n;
  3419. normals[ i + 1 ] *= n;
  3420. normals[ i + 2 ] *= n;
  3421. }
  3422. this.normalsNeedUpdate = true;
  3423. }
  3424. },
  3425. computeTangents: function () {
  3426. // based on http://www.terathon.com/code/tangent.html
  3427. // (per vertex tangents)
  3428. if ( this.attributes[ "index" ] === undefined ||
  3429. this.attributes[ "position" ] === undefined ||
  3430. this.attributes[ "normal" ] === undefined ||
  3431. this.attributes[ "uv" ] === undefined ) {
  3432. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  3433. return;
  3434. }
  3435. var indices = this.attributes[ "index" ].array;
  3436. var positions = this.attributes[ "position" ].array;
  3437. var normals = this.attributes[ "normal" ].array;
  3438. var uvs = this.attributes[ "uv" ].array;
  3439. var nVertices = positions.length / 3;
  3440. if ( this.attributes[ "tangent" ] === undefined ) {
  3441. var nTangentElements = 4 * nVertices;
  3442. this.attributes[ "tangent" ] = {
  3443. itemSize: 4,
  3444. array: new Float32Array( nTangentElements ),
  3445. numItems: nTangentElements
  3446. };
  3447. }
  3448. var tangents = this.attributes[ "tangent" ].array;
  3449. var tan1 = [], tan2 = [];
  3450. for ( var k = 0; k < nVertices; k ++ ) {
  3451. tan1[ k ] = new THREE.Vector3();
  3452. tan2[ k ] = new THREE.Vector3();
  3453. }
  3454. var xA, yA, zA,
  3455. xB, yB, zB,
  3456. xC, yC, zC,
  3457. uA, vA,
  3458. uB, vB,
  3459. uC, vC,
  3460. x1, x2, y1, y2, z1, z2,
  3461. s1, s2, t1, t2, r;
  3462. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  3463. function handleTriangle( a, b, c ) {
  3464. xA = positions[ a * 3 ];
  3465. yA = positions[ a * 3 + 1 ];
  3466. zA = positions[ a * 3 + 2 ];
  3467. xB = positions[ b * 3 ];
  3468. yB = positions[ b * 3 + 1 ];
  3469. zB = positions[ b * 3 + 2 ];
  3470. xC = positions[ c * 3 ];
  3471. yC = positions[ c * 3 + 1 ];
  3472. zC = positions[ c * 3 + 2 ];
  3473. uA = uvs[ a * 2 ];
  3474. vA = uvs[ a * 2 + 1 ];
  3475. uB = uvs[ b * 2 ];
  3476. vB = uvs[ b * 2 + 1 ];
  3477. uC = uvs[ c * 2 ];
  3478. vC = uvs[ c * 2 + 1 ];
  3479. x1 = xB - xA;
  3480. x2 = xC - xA;
  3481. y1 = yB - yA;
  3482. y2 = yC - yA;
  3483. z1 = zB - zA;
  3484. z2 = zC - zA;
  3485. s1 = uB - uA;
  3486. s2 = uC - uA;
  3487. t1 = vB - vA;
  3488. t2 = vC - vA;
  3489. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3490. sdir.set(
  3491. ( t2 * x1 - t1 * x2 ) * r,
  3492. ( t2 * y1 - t1 * y2 ) * r,
  3493. ( t2 * z1 - t1 * z2 ) * r
  3494. );
  3495. tdir.set(
  3496. ( s1 * x2 - s2 * x1 ) * r,
  3497. ( s1 * y2 - s2 * y1 ) * r,
  3498. ( s1 * z2 - s2 * z1 ) * r
  3499. );
  3500. tan1[ a ].addSelf( sdir );
  3501. tan1[ b ].addSelf( sdir );
  3502. tan1[ c ].addSelf( sdir );
  3503. tan2[ a ].addSelf( tdir );
  3504. tan2[ b ].addSelf( tdir );
  3505. tan2[ c ].addSelf( tdir );
  3506. }
  3507. var i, il;
  3508. var j, jl;
  3509. var iA, iB, iC;
  3510. var offsets = this.offsets;
  3511. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3512. var start = offsets[ j ].start;
  3513. var count = offsets[ j ].count;
  3514. var index = offsets[ j ].index;
  3515. for ( i = start, il = start + count; i < il; i += 3 ) {
  3516. iA = index + indices[ i ];
  3517. iB = index + indices[ i + 1 ];
  3518. iC = index + indices[ i + 2 ];
  3519. handleTriangle( iA, iB, iC );
  3520. }
  3521. }
  3522. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  3523. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  3524. var w, t, test;
  3525. var nx, ny, nz;
  3526. function handleVertex( v ) {
  3527. n.x = normals[ v * 3 ];
  3528. n.y = normals[ v * 3 + 1 ];
  3529. n.z = normals[ v * 3 + 2 ];
  3530. n2.copy( n );
  3531. t = tan1[ v ];
  3532. // Gram-Schmidt orthogonalize
  3533. tmp.copy( t );
  3534. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3535. // Calculate handedness
  3536. tmp2.cross( n2, t );
  3537. test = tmp2.dot( tan2[ v ] );
  3538. w = ( test < 0.0 ) ? -1.0 : 1.0;
  3539. tangents[ v * 4 ] = tmp.x;
  3540. tangents[ v * 4 + 1 ] = tmp.y;
  3541. tangents[ v * 4 + 2 ] = tmp.z;
  3542. tangents[ v * 4 + 3 ] = w;
  3543. }
  3544. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3545. var start = offsets[ j ].start;
  3546. var count = offsets[ j ].count;
  3547. var index = offsets[ j ].index;
  3548. for ( i = start, il = start + count; i < il; i += 3 ) {
  3549. iA = index + indices[ i ];
  3550. iB = index + indices[ i + 1 ];
  3551. iC = index + indices[ i + 2 ];
  3552. handleVertex( iA );
  3553. handleVertex( iB );
  3554. handleVertex( iC );
  3555. }
  3556. }
  3557. this.hasTangents = true;
  3558. this.tangentsNeedUpdate = true;
  3559. }
  3560. };
  3561. /**
  3562. * Spline from Tween.js, slightly optimized (and trashed)
  3563. * http://sole.github.com/tween.js/examples/05_spline.html
  3564. *
  3565. * @author mrdoob / http://mrdoob.com/
  3566. * @author alteredq / http://alteredqualia.com/
  3567. */
  3568. THREE.Spline = function ( points ) {
  3569. this.points = points;
  3570. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3571. point, intPoint, weight, w2, w3,
  3572. pa, pb, pc, pd;
  3573. this.initFromArray = function( a ) {
  3574. this.points = [];
  3575. for ( var i = 0; i < a.length; i++ ) {
  3576. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3577. }
  3578. };
  3579. this.getPoint = function ( k ) {
  3580. point = ( this.points.length - 1 ) * k;
  3581. intPoint = Math.floor( point );
  3582. weight = point - intPoint;
  3583. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3584. c[ 1 ] = intPoint;
  3585. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3586. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3587. pa = this.points[ c[ 0 ] ];
  3588. pb = this.points[ c[ 1 ] ];
  3589. pc = this.points[ c[ 2 ] ];
  3590. pd = this.points[ c[ 3 ] ];
  3591. w2 = weight * weight;
  3592. w3 = weight * w2;
  3593. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3594. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3595. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3596. return v3;
  3597. };
  3598. this.getControlPointsArray = function () {
  3599. var i, p, l = this.points.length,
  3600. coords = [];
  3601. for ( i = 0; i < l; i ++ ) {
  3602. p = this.points[ i ];
  3603. coords[ i ] = [ p.x, p.y, p.z ];
  3604. }
  3605. return coords;
  3606. };
  3607. // approximate length by summing linear segments
  3608. this.getLength = function ( nSubDivisions ) {
  3609. var i, index, nSamples, position,
  3610. point = 0, intPoint = 0, oldIntPoint = 0,
  3611. oldPosition = new THREE.Vector3(),
  3612. tmpVec = new THREE.Vector3(),
  3613. chunkLengths = [],
  3614. totalLength = 0;
  3615. // first point has 0 length
  3616. chunkLengths[ 0 ] = 0;
  3617. if ( !nSubDivisions ) nSubDivisions = 100;
  3618. nSamples = this.points.length * nSubDivisions;
  3619. oldPosition.copy( this.points[ 0 ] );
  3620. for ( i = 1; i < nSamples; i ++ ) {
  3621. index = i / nSamples;
  3622. position = this.getPoint( index );
  3623. tmpVec.copy( position );
  3624. totalLength += tmpVec.distanceTo( oldPosition );
  3625. oldPosition.copy( position );
  3626. point = ( this.points.length - 1 ) * index;
  3627. intPoint = Math.floor( point );
  3628. if ( intPoint != oldIntPoint ) {
  3629. chunkLengths[ intPoint ] = totalLength;
  3630. oldIntPoint = intPoint;
  3631. }
  3632. }
  3633. // last point ends with total length
  3634. chunkLengths[ chunkLengths.length ] = totalLength;
  3635. return { chunks: chunkLengths, total: totalLength };
  3636. };
  3637. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3638. var i, j,
  3639. index, indexCurrent, indexNext,
  3640. linearDistance, realDistance,
  3641. sampling, position,
  3642. newpoints = [],
  3643. tmpVec = new THREE.Vector3(),
  3644. sl = this.getLength();
  3645. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3646. for ( i = 1; i < this.points.length; i++ ) {
  3647. //tmpVec.copy( this.points[ i - 1 ] );
  3648. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3649. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3650. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3651. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3652. indexNext = i / ( this.points.length - 1 );
  3653. for ( j = 1; j < sampling - 1; j++ ) {
  3654. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3655. position = this.getPoint( index );
  3656. newpoints.push( tmpVec.copy( position ).clone() );
  3657. }
  3658. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3659. }
  3660. this.points = newpoints;
  3661. };
  3662. // Catmull-Rom
  3663. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3664. var v0 = ( p2 - p0 ) * 0.5,
  3665. v1 = ( p3 - p1 ) * 0.5;
  3666. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3667. };
  3668. };
  3669. /**
  3670. * @author mrdoob / http://mrdoob.com/
  3671. * @author mikael emtinger / http://gomo.se/
  3672. */
  3673. THREE.Camera = function () {
  3674. THREE.Object3D.call( this );
  3675. this.matrixWorldInverse = new THREE.Matrix4();
  3676. this.projectionMatrix = new THREE.Matrix4();
  3677. this.projectionMatrixInverse = new THREE.Matrix4();
  3678. };
  3679. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  3680. THREE.Camera.prototype.lookAt = function ( vector ) {
  3681. // TODO: Add hierarchy support.
  3682. this.matrix.lookAt( this.position, vector, this.up );
  3683. if ( this.rotationAutoUpdate === true ) {
  3684. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3685. }
  3686. };
  3687. /**
  3688. * @author alteredq / http://alteredqualia.com/
  3689. */
  3690. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  3691. THREE.Camera.call( this );
  3692. this.left = left;
  3693. this.right = right;
  3694. this.top = top;
  3695. this.bottom = bottom;
  3696. this.near = ( near !== undefined ) ? near : 0.1;
  3697. this.far = ( far !== undefined ) ? far : 2000;
  3698. this.updateProjectionMatrix();
  3699. };
  3700. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  3701. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  3702. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  3703. };
  3704. /**
  3705. * @author mrdoob / http://mrdoob.com/
  3706. * @author greggman / http://games.greggman.com/
  3707. * @author zz85 / http://www.lab4games.net/zz85/blog
  3708. */
  3709. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  3710. THREE.Camera.call( this );
  3711. this.fov = fov !== undefined ? fov : 50;
  3712. this.aspect = aspect !== undefined ? aspect : 1;
  3713. this.near = near !== undefined ? near : 0.1;
  3714. this.far = far !== undefined ? far : 2000;
  3715. this.updateProjectionMatrix();
  3716. };
  3717. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  3718. /**
  3719. * Uses Focal Length (in mm) to estimate and set FOV
  3720. * 35mm (fullframe) camera is used if frame size is not specified;
  3721. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  3722. */
  3723. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  3724. frameHeight = frameHeight !== undefined ? frameHeight : 24;
  3725. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  3726. this.updateProjectionMatrix();
  3727. }
  3728. /**
  3729. * Sets an offset in a larger frustum. This is useful for multi-window or
  3730. * multi-monitor/multi-machine setups.
  3731. *
  3732. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  3733. * the monitors are in grid like this
  3734. *
  3735. * +---+---+---+
  3736. * | A | B | C |
  3737. * +---+---+---+
  3738. * | D | E | F |
  3739. * +---+---+---+
  3740. *
  3741. * then for each monitor you would call it like this
  3742. *
  3743. * var w = 1920;
  3744. * var h = 1080;
  3745. * var fullWidth = w * 3;
  3746. * var fullHeight = h * 2;
  3747. *
  3748. * --A--
  3749. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  3750. * --B--
  3751. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  3752. * --C--
  3753. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  3754. * --D--
  3755. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  3756. * --E--
  3757. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  3758. * --F--
  3759. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  3760. *
  3761. * Note there is no reason monitors have to be the same size or in a grid.
  3762. */
  3763. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  3764. this.fullWidth = fullWidth;
  3765. this.fullHeight = fullHeight;
  3766. this.x = x;
  3767. this.y = y;
  3768. this.width = width;
  3769. this.height = height;
  3770. this.updateProjectionMatrix();
  3771. };
  3772. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  3773. if ( this.fullWidth ) {
  3774. var aspect = this.fullWidth / this.fullHeight;
  3775. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  3776. var bottom = -top;
  3777. var left = aspect * bottom;
  3778. var right = aspect * top;
  3779. var width = Math.abs( right - left );
  3780. var height = Math.abs( top - bottom );
  3781. this.projectionMatrix.makeFrustum(
  3782. left + this.x * width / this.fullWidth,
  3783. left + ( this.x + this.width ) * width / this.fullWidth,
  3784. top - ( this.y + this.height ) * height / this.fullHeight,
  3785. top - this.y * height / this.fullHeight,
  3786. this.near,
  3787. this.far
  3788. );
  3789. } else {
  3790. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  3791. }
  3792. };
  3793. /**
  3794. * @author mrdoob / http://mrdoob.com/
  3795. * @author alteredq / http://alteredqualia.com/
  3796. */
  3797. THREE.Light = function ( hex ) {
  3798. THREE.Object3D.call( this );
  3799. this.color = new THREE.Color( hex );
  3800. };
  3801. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  3802. /**
  3803. * @author mrdoob / http://mrdoob.com/
  3804. */
  3805. THREE.AmbientLight = function ( hex ) {
  3806. THREE.Light.call( this, hex );
  3807. };
  3808. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  3809. /**
  3810. * @author mrdoob / http://mrdoob.com/
  3811. * @author alteredq / http://alteredqualia.com/
  3812. */
  3813. THREE.DirectionalLight = function ( hex, intensity, distance ) {
  3814. THREE.Light.call( this, hex );
  3815. this.position = new THREE.Vector3( 0, 1, 0 );
  3816. this.target = new THREE.Object3D();
  3817. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3818. this.distance = ( distance !== undefined ) ? distance : 0;
  3819. this.castShadow = false;
  3820. this.onlyShadow = false;
  3821. //
  3822. this.shadowCameraNear = 50;
  3823. this.shadowCameraFar = 5000;
  3824. this.shadowCameraLeft = -500;
  3825. this.shadowCameraRight = 500;
  3826. this.shadowCameraTop = 500;
  3827. this.shadowCameraBottom = -500;
  3828. this.shadowCameraVisible = false;
  3829. this.shadowBias = 0;
  3830. this.shadowDarkness = 0.5;
  3831. this.shadowMapWidth = 512;
  3832. this.shadowMapHeight = 512;
  3833. //
  3834. this.shadowCascade = false;
  3835. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  3836. this.shadowCascadeCount = 2;
  3837. this.shadowCascadeBias = [ 0, 0, 0 ];
  3838. this.shadowCascadeWidth = [ 512, 512, 512 ];
  3839. this.shadowCascadeHeight = [ 512, 512, 512 ];
  3840. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  3841. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  3842. this.shadowCascadeArray = [];
  3843. //
  3844. this.shadowMap = null;
  3845. this.shadowMapSize = null;
  3846. this.shadowCamera = null;
  3847. this.shadowMatrix = null;
  3848. };
  3849. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  3850. /**
  3851. * @author mrdoob / http://mrdoob.com/
  3852. */
  3853. THREE.PointLight = function ( hex, intensity, distance ) {
  3854. THREE.Light.call( this, hex );
  3855. this.position = new THREE.Vector3( 0, 0, 0 );
  3856. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3857. this.distance = ( distance !== undefined ) ? distance : 0;
  3858. };
  3859. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  3860. /**
  3861. * @author alteredq / http://alteredqualia.com/
  3862. */
  3863. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  3864. THREE.Light.call( this, hex );
  3865. this.position = new THREE.Vector3( 0, 1, 0 );
  3866. this.target = new THREE.Object3D();
  3867. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3868. this.distance = ( distance !== undefined ) ? distance : 0;
  3869. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  3870. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  3871. this.castShadow = false;
  3872. this.onlyShadow = false;
  3873. //
  3874. this.shadowCameraNear = 50;
  3875. this.shadowCameraFar = 5000;
  3876. this.shadowCameraFov = 50;
  3877. this.shadowCameraVisible = false;
  3878. this.shadowBias = 0;
  3879. this.shadowDarkness = 0.5;
  3880. this.shadowMapWidth = 512;
  3881. this.shadowMapHeight = 512;
  3882. //
  3883. this.shadowMap = null;
  3884. this.shadowMapSize = null;
  3885. this.shadowCamera = null;
  3886. this.shadowMatrix = null;
  3887. };
  3888. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  3889. /**
  3890. * @author alteredq / http://alteredqualia.com/
  3891. */
  3892. THREE.Loader = function ( showStatus ) {
  3893. this.showStatus = showStatus;
  3894. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  3895. this.onLoadStart = function () {};
  3896. this.onLoadProgress = function () {};
  3897. this.onLoadComplete = function () {};
  3898. };
  3899. THREE.Loader.prototype = {
  3900. constructor: THREE.Loader,
  3901. crossOrigin: 'anonymous',
  3902. addStatusElement: function () {
  3903. var e = document.createElement( "div" );
  3904. e.style.position = "absolute";
  3905. e.style.right = "0px";
  3906. e.style.top = "0px";
  3907. e.style.fontSize = "0.8em";
  3908. e.style.textAlign = "left";
  3909. e.style.background = "rgba(0,0,0,0.25)";
  3910. e.style.color = "#fff";
  3911. e.style.width = "120px";
  3912. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  3913. e.style.zIndex = 1000;
  3914. e.innerHTML = "Loading ...";
  3915. return e;
  3916. },
  3917. updateProgress: function ( progress ) {
  3918. var message = "Loaded ";
  3919. if ( progress.total ) {
  3920. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  3921. } else {
  3922. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  3923. }
  3924. this.statusDomElement.innerHTML = message;
  3925. },
  3926. extractUrlBase: function ( url ) {
  3927. var parts = url.split( '/' );
  3928. parts.pop();
  3929. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  3930. },
  3931. initMaterials: function ( scope, materials, texturePath ) {
  3932. scope.materials = [];
  3933. for ( var i = 0; i < materials.length; ++ i ) {
  3934. scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  3935. }
  3936. },
  3937. hasNormals: function ( scope ) {
  3938. var m, i, il = scope.materials.length;
  3939. for( i = 0; i < il; i ++ ) {
  3940. m = scope.materials[ i ];
  3941. if ( m instanceof THREE.ShaderMaterial ) return true;
  3942. }
  3943. return false;
  3944. },
  3945. createMaterial: function ( m, texturePath ) {
  3946. var _this = this;
  3947. function is_pow2( n ) {
  3948. var l = Math.log( n ) / Math.LN2;
  3949. return Math.floor( l ) == l;
  3950. }
  3951. function nearest_pow2( n ) {
  3952. var l = Math.log( n ) / Math.LN2;
  3953. return Math.pow( 2, Math.round( l ) );
  3954. }
  3955. function load_image( where, url ) {
  3956. var image = new Image();
  3957. image.onload = function () {
  3958. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  3959. var width = nearest_pow2( this.width );
  3960. var height = nearest_pow2( this.height );
  3961. where.image.width = width;
  3962. where.image.height = height;
  3963. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  3964. } else {
  3965. where.image = this;
  3966. }
  3967. where.needsUpdate = true;
  3968. };
  3969. image.crossOrigin = _this.crossOrigin;
  3970. image.src = url;
  3971. }
  3972. function create_texture( where, name, sourceFile, repeat, offset, wrap ) {
  3973. var texture = document.createElement( 'canvas' );
  3974. where[ name ] = new THREE.Texture( texture );
  3975. where[ name ].sourceFile = sourceFile;
  3976. if( repeat ) {
  3977. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  3978. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  3979. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  3980. }
  3981. if ( offset ) {
  3982. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  3983. }
  3984. if ( wrap ) {
  3985. var wrapMap = {
  3986. "repeat": THREE.RepeatWrapping,
  3987. "mirror": THREE.MirroredRepeatWrapping
  3988. }
  3989. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  3990. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  3991. }
  3992. load_image( where[ name ], texturePath + "/" + sourceFile );
  3993. }
  3994. function rgb2hex( rgb ) {
  3995. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  3996. }
  3997. // defaults
  3998. var mtype = "MeshLambertMaterial";
  3999. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4000. // parameters from model file
  4001. if ( m.shading ) {
  4002. var shading = m.shading.toLowerCase();
  4003. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4004. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4005. }
  4006. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4007. mpars.blending = THREE[ m.blending ];
  4008. }
  4009. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4010. mpars.transparent = m.transparent;
  4011. }
  4012. if ( m.depthTest !== undefined ) {
  4013. mpars.depthTest = m.depthTest;
  4014. }
  4015. if ( m.depthWrite !== undefined ) {
  4016. mpars.depthWrite = m.depthWrite;
  4017. }
  4018. if ( m.visible !== undefined ) {
  4019. mpars.visible = m.visible;
  4020. }
  4021. if ( m.flipSided !== undefined ) {
  4022. mpars.side = THREE.BackSide;
  4023. }
  4024. if ( m.doubleSided !== undefined ) {
  4025. mpars.side = THREE.DoubleSide;
  4026. }
  4027. if ( m.wireframe !== undefined ) {
  4028. mpars.wireframe = m.wireframe;
  4029. }
  4030. if ( m.vertexColors !== undefined ) {
  4031. if ( m.vertexColors == "face" ) {
  4032. mpars.vertexColors = THREE.FaceColors;
  4033. } else if ( m.vertexColors ) {
  4034. mpars.vertexColors = THREE.VertexColors;
  4035. }
  4036. }
  4037. // colors
  4038. if ( m.colorDiffuse ) {
  4039. mpars.color = rgb2hex( m.colorDiffuse );
  4040. } else if ( m.DbgColor ) {
  4041. mpars.color = m.DbgColor;
  4042. }
  4043. if ( m.colorSpecular ) {
  4044. mpars.specular = rgb2hex( m.colorSpecular );
  4045. }
  4046. if ( m.colorAmbient ) {
  4047. mpars.ambient = rgb2hex( m.colorAmbient );
  4048. }
  4049. // modifiers
  4050. if ( m.transparency ) {
  4051. mpars.opacity = m.transparency;
  4052. }
  4053. if ( m.specularCoef ) {
  4054. mpars.shininess = m.specularCoef;
  4055. }
  4056. // textures
  4057. if ( m.mapDiffuse && texturePath ) {
  4058. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  4059. }
  4060. if ( m.mapLight && texturePath ) {
  4061. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  4062. }
  4063. if ( m.mapBump && texturePath ) {
  4064. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap );
  4065. }
  4066. if ( m.mapNormal && texturePath ) {
  4067. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  4068. }
  4069. if ( m.mapSpecular && texturePath ) {
  4070. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  4071. }
  4072. // special case for normal mapped material
  4073. if ( m.mapNormal ) {
  4074. var shader = THREE.ShaderUtils.lib[ "normal" ];
  4075. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  4076. uniforms[ "tNormal" ].texture = mpars.normalMap;
  4077. if ( m.mapNormalFactor ) {
  4078. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  4079. }
  4080. if ( mpars.map ) {
  4081. uniforms[ "tDiffuse" ].texture = mpars.map;
  4082. uniforms[ "enableDiffuse" ].value = true;
  4083. }
  4084. if ( mpars.specularMap ) {
  4085. uniforms[ "tSpecular" ].texture = mpars.specularMap;
  4086. uniforms[ "enableSpecular" ].value = true;
  4087. }
  4088. if ( mpars.lightMap ) {
  4089. uniforms[ "tAO" ].texture = mpars.lightMap;
  4090. uniforms[ "enableAO" ].value = true;
  4091. }
  4092. // for the moment don't handle displacement texture
  4093. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  4094. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  4095. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  4096. uniforms[ "uShininess" ].value = mpars.shininess;
  4097. if ( mpars.opacity !== undefined ) {
  4098. uniforms[ "uOpacity" ].value = mpars.opacity;
  4099. }
  4100. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  4101. var material = new THREE.ShaderMaterial( parameters );
  4102. } else {
  4103. var material = new THREE[ mtype ]( mpars );
  4104. }
  4105. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  4106. return material;
  4107. }
  4108. };
  4109. /**
  4110. * @author alteredq / http://alteredqualia.com/
  4111. */
  4112. THREE.BinaryLoader = function ( showStatus ) {
  4113. THREE.Loader.call( this, showStatus );
  4114. };
  4115. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  4116. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  4117. // - binary models consist of two files: JS and BIN
  4118. // - parameters
  4119. // - url (required)
  4120. // - callback (required)
  4121. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  4122. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  4123. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  4124. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4125. binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
  4126. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  4127. this.onLoadStart();
  4128. // #1 load JS part via web worker
  4129. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  4130. };
  4131. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  4132. var xhr = new XMLHttpRequest();
  4133. xhr.onreadystatechange = function () {
  4134. if ( xhr.readyState == 4 ) {
  4135. if ( xhr.status == 200 || xhr.status == 0 ) {
  4136. var json = JSON.parse( xhr.responseText );
  4137. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  4138. } else {
  4139. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4140. }
  4141. }
  4142. };
  4143. xhr.open( "GET", url, true );
  4144. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  4145. xhr.setRequestHeader( "Content-Type", "text/plain" );
  4146. xhr.send( null );
  4147. };
  4148. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  4149. var xhr = new XMLHttpRequest(),
  4150. url = binaryPath + "/" + json.buffers;
  4151. var length = 0;
  4152. xhr.onreadystatechange = function () {
  4153. if ( xhr.readyState == 4 ) {
  4154. if ( xhr.status == 200 || xhr.status == 0 ) {
  4155. var buffer = xhr.response;
  4156. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  4157. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  4158. } else {
  4159. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4160. }
  4161. } else if ( xhr.readyState == 3 ) {
  4162. if ( callbackProgress ) {
  4163. if ( length == 0 ) {
  4164. length = xhr.getResponseHeader( "Content-Length" );
  4165. }
  4166. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4167. }
  4168. } else if ( xhr.readyState == 2 ) {
  4169. length = xhr.getResponseHeader( "Content-Length" );
  4170. }
  4171. };
  4172. xhr.open( "GET", url, true );
  4173. xhr.responseType = "arraybuffer";
  4174. xhr.send( null );
  4175. };
  4176. // Binary AJAX parser
  4177. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
  4178. var Model = function ( texturePath ) {
  4179. var scope = this,
  4180. currentOffset = 0,
  4181. md,
  4182. normals = [],
  4183. uvs = [],
  4184. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  4185. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  4186. tri_size, quad_size,
  4187. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  4188. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  4189. THREE.Geometry.call( this );
  4190. THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
  4191. md = parseMetaData( data, currentOffset );
  4192. currentOffset += md.header_bytes;
  4193. /*
  4194. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4195. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  4196. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4197. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4198. */
  4199. // buffers sizes
  4200. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  4201. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  4202. len_tri_flat = md.ntri_flat * ( tri_size );
  4203. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  4204. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  4205. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  4206. len_quad_flat = md.nquad_flat * ( quad_size );
  4207. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  4208. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  4209. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  4210. // read buffers
  4211. currentOffset += init_vertices( currentOffset );
  4212. currentOffset += init_normals( currentOffset );
  4213. currentOffset += handlePadding( md.nnormals * 3 );
  4214. currentOffset += init_uvs( currentOffset );
  4215. start_tri_flat = currentOffset;
  4216. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  4217. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  4218. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  4219. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  4220. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  4221. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  4222. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  4223. // have to first process faces with uvs
  4224. // so that face and uv indices match
  4225. init_triangles_flat_uv( start_tri_flat_uv );
  4226. init_triangles_smooth_uv( start_tri_smooth_uv );
  4227. init_quads_flat_uv( start_quad_flat_uv );
  4228. init_quads_smooth_uv( start_quad_smooth_uv );
  4229. // now we can process untextured faces
  4230. init_triangles_flat( start_tri_flat );
  4231. init_triangles_smooth( start_tri_smooth );
  4232. init_quads_flat( start_quad_flat );
  4233. init_quads_smooth( start_quad_smooth );
  4234. this.computeCentroids();
  4235. this.computeFaceNormals();
  4236. if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
  4237. function handlePadding( n ) {
  4238. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  4239. };
  4240. function parseMetaData( data, offset ) {
  4241. var metaData = {
  4242. 'signature' :parseString( data, offset, 12 ),
  4243. 'header_bytes' :parseUChar8( data, offset + 12 ),
  4244. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  4245. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  4246. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  4247. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  4248. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  4249. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  4250. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  4251. 'nvertices' :parseUInt32( data, offset + 20 ),
  4252. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  4253. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  4254. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  4255. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  4256. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  4257. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  4258. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  4259. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  4260. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  4261. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  4262. };
  4263. /*
  4264. console.log( "signature: " + metaData.signature );
  4265. console.log( "header_bytes: " + metaData.header_bytes );
  4266. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  4267. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  4268. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  4269. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  4270. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  4271. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  4272. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  4273. console.log( "nvertices: " + metaData.nvertices );
  4274. console.log( "nnormals: " + metaData.nnormals );
  4275. console.log( "nuvs: " + metaData.nuvs );
  4276. console.log( "ntri_flat: " + metaData.ntri_flat );
  4277. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  4278. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  4279. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  4280. console.log( "nquad_flat: " + metaData.nquad_flat );
  4281. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  4282. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  4283. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  4284. var total = metaData.header_bytes
  4285. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  4286. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  4287. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  4288. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  4289. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  4290. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  4291. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  4292. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  4293. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  4294. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  4295. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  4296. console.log( "total bytes: " + total );
  4297. */
  4298. return metaData;
  4299. };
  4300. function parseString( data, offset, length ) {
  4301. var charArray = new Uint8Array( data, offset, length );
  4302. var text = "";
  4303. for ( var i = 0; i < length; i ++ ) {
  4304. text += String.fromCharCode( charArray[ offset + i ] );
  4305. }
  4306. return text;
  4307. };
  4308. function parseUChar8( data, offset ) {
  4309. var charArray = new Uint8Array( data, offset, 1 );
  4310. return charArray[ 0 ];
  4311. };
  4312. function parseUInt32( data, offset ) {
  4313. var intArray = new Uint32Array( data, offset, 1 );
  4314. return intArray[ 0 ];
  4315. };
  4316. function init_vertices( start ) {
  4317. var nElements = md.nvertices;
  4318. var coordArray = new Float32Array( data, start, nElements * 3 );
  4319. var i, x, y, z;
  4320. for( i = 0; i < nElements; i ++ ) {
  4321. x = coordArray[ i * 3 ];
  4322. y = coordArray[ i * 3 + 1 ];
  4323. z = coordArray[ i * 3 + 2 ];
  4324. vertex( scope, x, y, z );
  4325. }
  4326. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  4327. };
  4328. function init_normals( start ) {
  4329. var nElements = md.nnormals;
  4330. if ( nElements ) {
  4331. var normalArray = new Int8Array( data, start, nElements * 3 );
  4332. var i, x, y, z;
  4333. for( i = 0; i < nElements; i ++ ) {
  4334. x = normalArray[ i * 3 ];
  4335. y = normalArray[ i * 3 + 1 ];
  4336. z = normalArray[ i * 3 + 2 ];
  4337. normals.push( x/127, y/127, z/127 );
  4338. }
  4339. }
  4340. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  4341. };
  4342. function init_uvs( start ) {
  4343. var nElements = md.nuvs;
  4344. if ( nElements ) {
  4345. var uvArray = new Float32Array( data, start, nElements * 2 );
  4346. var i, u, v;
  4347. for( i = 0; i < nElements; i ++ ) {
  4348. u = uvArray[ i * 2 ];
  4349. v = uvArray[ i * 2 + 1 ];
  4350. uvs.push( u, v );
  4351. }
  4352. }
  4353. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  4354. };
  4355. function init_uvs3( nElements, offset ) {
  4356. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  4357. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  4358. for( i = 0; i < nElements; i ++ ) {
  4359. uva = uvIndexBuffer[ i * 3 ];
  4360. uvb = uvIndexBuffer[ i * 3 + 1 ];
  4361. uvc = uvIndexBuffer[ i * 3 + 2 ];
  4362. u1 = uvs[ uva*2 ];
  4363. v1 = uvs[ uva*2 + 1 ];
  4364. u2 = uvs[ uvb*2 ];
  4365. v2 = uvs[ uvb*2 + 1 ];
  4366. u3 = uvs[ uvc*2 ];
  4367. v3 = uvs[ uvc*2 + 1 ];
  4368. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  4369. }
  4370. };
  4371. function init_uvs4( nElements, offset ) {
  4372. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  4373. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  4374. for( i = 0; i < nElements; i ++ ) {
  4375. uva = uvIndexBuffer[ i * 4 ];
  4376. uvb = uvIndexBuffer[ i * 4 + 1 ];
  4377. uvc = uvIndexBuffer[ i * 4 + 2 ];
  4378. uvd = uvIndexBuffer[ i * 4 + 3 ];
  4379. u1 = uvs[ uva*2 ];
  4380. v1 = uvs[ uva*2 + 1 ];
  4381. u2 = uvs[ uvb*2 ];
  4382. v2 = uvs[ uvb*2 + 1 ];
  4383. u3 = uvs[ uvc*2 ];
  4384. v3 = uvs[ uvc*2 + 1 ];
  4385. u4 = uvs[ uvd*2 ];
  4386. v4 = uvs[ uvd*2 + 1 ];
  4387. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  4388. }
  4389. };
  4390. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  4391. var i, a, b, c, m;
  4392. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4393. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4394. for( i = 0; i < nElements; i ++ ) {
  4395. a = vertexIndexBuffer[ i * 3 ];
  4396. b = vertexIndexBuffer[ i * 3 + 1 ];
  4397. c = vertexIndexBuffer[ i * 3 + 2 ];
  4398. m = materialIndexBuffer[ i ];
  4399. f3( scope, a, b, c, m );
  4400. }
  4401. };
  4402. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  4403. var i, a, b, c, d, m;
  4404. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4405. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4406. for( i = 0; i < nElements; i ++ ) {
  4407. a = vertexIndexBuffer[ i * 4 ];
  4408. b = vertexIndexBuffer[ i * 4 + 1 ];
  4409. c = vertexIndexBuffer[ i * 4 + 2 ];
  4410. d = vertexIndexBuffer[ i * 4 + 3 ];
  4411. m = materialIndexBuffer[ i ];
  4412. f4( scope, a, b, c, d, m );
  4413. }
  4414. };
  4415. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4416. var i, a, b, c, m;
  4417. var na, nb, nc;
  4418. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4419. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  4420. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4421. for( i = 0; i < nElements; i ++ ) {
  4422. a = vertexIndexBuffer[ i * 3 ];
  4423. b = vertexIndexBuffer[ i * 3 + 1 ];
  4424. c = vertexIndexBuffer[ i * 3 + 2 ];
  4425. na = normalIndexBuffer[ i * 3 ];
  4426. nb = normalIndexBuffer[ i * 3 + 1 ];
  4427. nc = normalIndexBuffer[ i * 3 + 2 ];
  4428. m = materialIndexBuffer[ i ];
  4429. f3n( scope, normals, a, b, c, m, na, nb, nc );
  4430. }
  4431. };
  4432. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4433. var i, a, b, c, d, m;
  4434. var na, nb, nc, nd;
  4435. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4436. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  4437. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4438. for( i = 0; i < nElements; i ++ ) {
  4439. a = vertexIndexBuffer[ i * 4 ];
  4440. b = vertexIndexBuffer[ i * 4 + 1 ];
  4441. c = vertexIndexBuffer[ i * 4 + 2 ];
  4442. d = vertexIndexBuffer[ i * 4 + 3 ];
  4443. na = normalIndexBuffer[ i * 4 ];
  4444. nb = normalIndexBuffer[ i * 4 + 1 ];
  4445. nc = normalIndexBuffer[ i * 4 + 2 ];
  4446. nd = normalIndexBuffer[ i * 4 + 3 ];
  4447. m = materialIndexBuffer[ i ];
  4448. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  4449. }
  4450. };
  4451. function init_triangles_flat( start ) {
  4452. var nElements = md.ntri_flat;
  4453. if ( nElements ) {
  4454. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4455. init_faces3_flat( nElements, start, offsetMaterials );
  4456. }
  4457. };
  4458. function init_triangles_flat_uv( start ) {
  4459. var nElements = md.ntri_flat_uv;
  4460. if ( nElements ) {
  4461. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4462. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4463. init_faces3_flat( nElements, start, offsetMaterials );
  4464. init_uvs3( nElements, offsetUvs );
  4465. }
  4466. };
  4467. function init_triangles_smooth( start ) {
  4468. var nElements = md.ntri_smooth;
  4469. if ( nElements ) {
  4470. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4471. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4472. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4473. }
  4474. };
  4475. function init_triangles_smooth_uv( start ) {
  4476. var nElements = md.ntri_smooth_uv;
  4477. if ( nElements ) {
  4478. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4479. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4480. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4481. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4482. init_uvs3( nElements, offsetUvs );
  4483. }
  4484. };
  4485. function init_quads_flat( start ) {
  4486. var nElements = md.nquad_flat;
  4487. if ( nElements ) {
  4488. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4489. init_faces4_flat( nElements, start, offsetMaterials );
  4490. }
  4491. };
  4492. function init_quads_flat_uv( start ) {
  4493. var nElements = md.nquad_flat_uv;
  4494. if ( nElements ) {
  4495. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4496. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4497. init_faces4_flat( nElements, start, offsetMaterials );
  4498. init_uvs4( nElements, offsetUvs );
  4499. }
  4500. };
  4501. function init_quads_smooth( start ) {
  4502. var nElements = md.nquad_smooth;
  4503. if ( nElements ) {
  4504. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4505. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4506. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4507. }
  4508. };
  4509. function init_quads_smooth_uv( start ) {
  4510. var nElements = md.nquad_smooth_uv;
  4511. if ( nElements ) {
  4512. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4513. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4514. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4515. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4516. init_uvs4( nElements, offsetUvs );
  4517. }
  4518. };
  4519. };
  4520. function vertex ( scope, x, y, z ) {
  4521. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  4522. };
  4523. function f3 ( scope, a, b, c, mi ) {
  4524. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  4525. };
  4526. function f4 ( scope, a, b, c, d, mi ) {
  4527. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  4528. };
  4529. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  4530. var nax = normals[ na*3 ],
  4531. nay = normals[ na*3 + 1 ],
  4532. naz = normals[ na*3 + 2 ],
  4533. nbx = normals[ nb*3 ],
  4534. nby = normals[ nb*3 + 1 ],
  4535. nbz = normals[ nb*3 + 2 ],
  4536. ncx = normals[ nc*3 ],
  4537. ncy = normals[ nc*3 + 1 ],
  4538. ncz = normals[ nc*3 + 2 ];
  4539. scope.faces.push( new THREE.Face3( a, b, c,
  4540. [new THREE.Vector3( nax, nay, naz ),
  4541. new THREE.Vector3( nbx, nby, nbz ),
  4542. new THREE.Vector3( ncx, ncy, ncz )],
  4543. null,
  4544. mi ) );
  4545. };
  4546. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  4547. var nax = normals[ na*3 ],
  4548. nay = normals[ na*3 + 1 ],
  4549. naz = normals[ na*3 + 2 ],
  4550. nbx = normals[ nb*3 ],
  4551. nby = normals[ nb*3 + 1 ],
  4552. nbz = normals[ nb*3 + 2 ],
  4553. ncx = normals[ nc*3 ],
  4554. ncy = normals[ nc*3 + 1 ],
  4555. ncz = normals[ nc*3 + 2 ],
  4556. ndx = normals[ nd*3 ],
  4557. ndy = normals[ nd*3 + 1 ],
  4558. ndz = normals[ nd*3 + 2 ];
  4559. scope.faces.push( new THREE.Face4( a, b, c, d,
  4560. [new THREE.Vector3( nax, nay, naz ),
  4561. new THREE.Vector3( nbx, nby, nbz ),
  4562. new THREE.Vector3( ncx, ncy, ncz ),
  4563. new THREE.Vector3( ndx, ndy, ndz )],
  4564. null,
  4565. mi ) );
  4566. };
  4567. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  4568. var uv = [];
  4569. uv.push( new THREE.UV( u1, v1 ) );
  4570. uv.push( new THREE.UV( u2, v2 ) );
  4571. uv.push( new THREE.UV( u3, v3 ) );
  4572. where.push( uv );
  4573. };
  4574. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  4575. var uv = [];
  4576. uv.push( new THREE.UV( u1, v1 ) );
  4577. uv.push( new THREE.UV( u2, v2 ) );
  4578. uv.push( new THREE.UV( u3, v3 ) );
  4579. uv.push( new THREE.UV( u4, v4 ) );
  4580. where.push( uv );
  4581. };
  4582. Model.prototype = Object.create( THREE.Geometry.prototype );
  4583. callback( new Model( texturePath ) );
  4584. };
  4585. /**
  4586. * @author mrdoob / http://mrdoob.com/
  4587. */
  4588. THREE.ImageLoader = function () {
  4589. THREE.EventTarget.call( this );
  4590. this.crossOrigin = null;
  4591. };
  4592. THREE.ImageLoader.prototype = {
  4593. constructor: THREE.ImageLoader,
  4594. load: function ( url, image ) {
  4595. var scope = this;
  4596. if ( image === undefined ) image = new Image();
  4597. image.addEventListener( 'load', function () {
  4598. scope.dispatchEvent( { type: 'load', content: image } );
  4599. }, false );
  4600. image.addEventListener( 'error', function () {
  4601. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4602. }, false );
  4603. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  4604. image.src = url;
  4605. }
  4606. }
  4607. /**
  4608. * @author mrdoob / http://mrdoob.com/
  4609. * @author alteredq / http://alteredqualia.com/
  4610. */
  4611. THREE.JSONLoader = function ( showStatus ) {
  4612. THREE.Loader.call( this, showStatus );
  4613. };
  4614. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  4615. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  4616. var scope = this;
  4617. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4618. this.onLoadStart();
  4619. this.loadAjaxJSON( this, url, callback, texturePath );
  4620. };
  4621. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  4622. var xhr = new XMLHttpRequest();
  4623. var length = 0;
  4624. xhr.onreadystatechange = function () {
  4625. if ( xhr.readyState === xhr.DONE ) {
  4626. if ( xhr.status === 200 || xhr.status === 0 ) {
  4627. if ( xhr.responseText ) {
  4628. var json = JSON.parse( xhr.responseText );
  4629. context.createModel( json, callback, texturePath );
  4630. } else {
  4631. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  4632. }
  4633. // in context of more complex asset initialization
  4634. // do not block on single failed file
  4635. // maybe should go even one more level up
  4636. context.onLoadComplete();
  4637. } else {
  4638. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4639. }
  4640. } else if ( xhr.readyState === xhr.LOADING ) {
  4641. if ( callbackProgress ) {
  4642. if ( length === 0 ) {
  4643. length = xhr.getResponseHeader( "Content-Length" );
  4644. }
  4645. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4646. }
  4647. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  4648. length = xhr.getResponseHeader( "Content-Length" );
  4649. }
  4650. };
  4651. xhr.open( "GET", url, true );
  4652. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  4653. xhr.setRequestHeader( "Content-Type", "text/plain" );
  4654. xhr.send( null );
  4655. };
  4656. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  4657. var scope = this,
  4658. geometry = new THREE.Geometry(),
  4659. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  4660. this.initMaterials( geometry, json.materials, texturePath );
  4661. parseModel( scale );
  4662. parseSkin();
  4663. parseMorphing( scale );
  4664. geometry.computeCentroids();
  4665. geometry.computeFaceNormals();
  4666. if ( this.hasNormals( geometry ) ) geometry.computeTangents();
  4667. function parseModel( scale ) {
  4668. function isBitSet( value, position ) {
  4669. return value & ( 1 << position );
  4670. }
  4671. var i, j, fi,
  4672. offset, zLength, nVertices,
  4673. colorIndex, normalIndex, uvIndex, materialIndex,
  4674. type,
  4675. isQuad,
  4676. hasMaterial,
  4677. hasFaceUv, hasFaceVertexUv,
  4678. hasFaceNormal, hasFaceVertexNormal,
  4679. hasFaceColor, hasFaceVertexColor,
  4680. vertex, face, color, normal,
  4681. uvLayer, uvs, u, v,
  4682. faces = json.faces,
  4683. vertices = json.vertices,
  4684. normals = json.normals,
  4685. colors = json.colors,
  4686. nUvLayers = 0;
  4687. // disregard empty arrays
  4688. for ( i = 0; i < json.uvs.length; i++ ) {
  4689. if ( json.uvs[ i ].length ) nUvLayers ++;
  4690. }
  4691. for ( i = 0; i < nUvLayers; i++ ) {
  4692. geometry.faceUvs[ i ] = [];
  4693. geometry.faceVertexUvs[ i ] = [];
  4694. }
  4695. offset = 0;
  4696. zLength = vertices.length;
  4697. while ( offset < zLength ) {
  4698. vertex = new THREE.Vector3();
  4699. vertex.x = vertices[ offset ++ ] * scale;
  4700. vertex.y = vertices[ offset ++ ] * scale;
  4701. vertex.z = vertices[ offset ++ ] * scale;
  4702. geometry.vertices.push( vertex );
  4703. }
  4704. offset = 0;
  4705. zLength = faces.length;
  4706. while ( offset < zLength ) {
  4707. type = faces[ offset ++ ];
  4708. isQuad = isBitSet( type, 0 );
  4709. hasMaterial = isBitSet( type, 1 );
  4710. hasFaceUv = isBitSet( type, 2 );
  4711. hasFaceVertexUv = isBitSet( type, 3 );
  4712. hasFaceNormal = isBitSet( type, 4 );
  4713. hasFaceVertexNormal = isBitSet( type, 5 );
  4714. hasFaceColor = isBitSet( type, 6 );
  4715. hasFaceVertexColor = isBitSet( type, 7 );
  4716. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  4717. if ( isQuad ) {
  4718. face = new THREE.Face4();
  4719. face.a = faces[ offset ++ ];
  4720. face.b = faces[ offset ++ ];
  4721. face.c = faces[ offset ++ ];
  4722. face.d = faces[ offset ++ ];
  4723. nVertices = 4;
  4724. } else {
  4725. face = new THREE.Face3();
  4726. face.a = faces[ offset ++ ];
  4727. face.b = faces[ offset ++ ];
  4728. face.c = faces[ offset ++ ];
  4729. nVertices = 3;
  4730. }
  4731. if ( hasMaterial ) {
  4732. materialIndex = faces[ offset ++ ];
  4733. face.materialIndex = materialIndex;
  4734. }
  4735. // to get face <=> uv index correspondence
  4736. fi = geometry.faces.length;
  4737. if ( hasFaceUv ) {
  4738. for ( i = 0; i < nUvLayers; i++ ) {
  4739. uvLayer = json.uvs[ i ];
  4740. uvIndex = faces[ offset ++ ];
  4741. u = uvLayer[ uvIndex * 2 ];
  4742. v = uvLayer[ uvIndex * 2 + 1 ];
  4743. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  4744. }
  4745. }
  4746. if ( hasFaceVertexUv ) {
  4747. for ( i = 0; i < nUvLayers; i++ ) {
  4748. uvLayer = json.uvs[ i ];
  4749. uvs = [];
  4750. for ( j = 0; j < nVertices; j ++ ) {
  4751. uvIndex = faces[ offset ++ ];
  4752. u = uvLayer[ uvIndex * 2 ];
  4753. v = uvLayer[ uvIndex * 2 + 1 ];
  4754. uvs[ j ] = new THREE.UV( u, v );
  4755. }
  4756. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  4757. }
  4758. }
  4759. if ( hasFaceNormal ) {
  4760. normalIndex = faces[ offset ++ ] * 3;
  4761. normal = new THREE.Vector3();
  4762. normal.x = normals[ normalIndex ++ ];
  4763. normal.y = normals[ normalIndex ++ ];
  4764. normal.z = normals[ normalIndex ];
  4765. face.normal = normal;
  4766. }
  4767. if ( hasFaceVertexNormal ) {
  4768. for ( i = 0; i < nVertices; i++ ) {
  4769. normalIndex = faces[ offset ++ ] * 3;
  4770. normal = new THREE.Vector3();
  4771. normal.x = normals[ normalIndex ++ ];
  4772. normal.y = normals[ normalIndex ++ ];
  4773. normal.z = normals[ normalIndex ];
  4774. face.vertexNormals.push( normal );
  4775. }
  4776. }
  4777. if ( hasFaceColor ) {
  4778. colorIndex = faces[ offset ++ ];
  4779. color = new THREE.Color( colors[ colorIndex ] );
  4780. face.color = color;
  4781. }
  4782. if ( hasFaceVertexColor ) {
  4783. for ( i = 0; i < nVertices; i++ ) {
  4784. colorIndex = faces[ offset ++ ];
  4785. color = new THREE.Color( colors[ colorIndex ] );
  4786. face.vertexColors.push( color );
  4787. }
  4788. }
  4789. geometry.faces.push( face );
  4790. }
  4791. };
  4792. function parseSkin() {
  4793. var i, l, x, y, z, w, a, b, c, d;
  4794. if ( json.skinWeights ) {
  4795. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  4796. x = json.skinWeights[ i ];
  4797. y = json.skinWeights[ i + 1 ];
  4798. z = 0;
  4799. w = 0;
  4800. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  4801. }
  4802. }
  4803. if ( json.skinIndices ) {
  4804. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  4805. a = json.skinIndices[ i ];
  4806. b = json.skinIndices[ i + 1 ];
  4807. c = 0;
  4808. d = 0;
  4809. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  4810. }
  4811. }
  4812. geometry.bones = json.bones;
  4813. geometry.animation = json.animation;
  4814. };
  4815. function parseMorphing( scale ) {
  4816. if ( json.morphTargets !== undefined ) {
  4817. var i, l, v, vl, dstVertices, srcVertices;
  4818. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  4819. geometry.morphTargets[ i ] = {};
  4820. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  4821. geometry.morphTargets[ i ].vertices = [];
  4822. dstVertices = geometry.morphTargets[ i ].vertices;
  4823. srcVertices = json.morphTargets [ i ].vertices;
  4824. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  4825. var vertex = new THREE.Vector3();
  4826. vertex.x = srcVertices[ v ] * scale;
  4827. vertex.y = srcVertices[ v + 1 ] * scale;
  4828. vertex.z = srcVertices[ v + 2 ] * scale;
  4829. dstVertices.push( vertex );
  4830. }
  4831. }
  4832. }
  4833. if ( json.morphColors !== undefined ) {
  4834. var i, l, c, cl, dstColors, srcColors, color;
  4835. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  4836. geometry.morphColors[ i ] = {};
  4837. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  4838. geometry.morphColors[ i ].colors = [];
  4839. dstColors = geometry.morphColors[ i ].colors;
  4840. srcColors = json.morphColors [ i ].colors;
  4841. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  4842. color = new THREE.Color( 0xffaa00 );
  4843. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  4844. dstColors.push( color );
  4845. }
  4846. }
  4847. }
  4848. };
  4849. callback( geometry );
  4850. };
  4851. /**
  4852. * @author mrdoob / http://mrdoob.com/
  4853. * @author alteredq / http://alteredqualia.com/
  4854. */
  4855. THREE.GeometryLoader = function () {
  4856. THREE.EventTarget.call( this );
  4857. this.crossOrigin = null;
  4858. this.path = null;
  4859. };
  4860. THREE.GeometryLoader.prototype = {
  4861. constructor: THREE.GeometryLoader,
  4862. load: function ( url ) {
  4863. var scope = this;
  4864. var geometry = null;
  4865. if ( scope.path === null ) {
  4866. var parts = url.split( '/' ); parts.pop();
  4867. scope.path = ( parts.length < 1 ? '.' : parts.join( '/' ) );
  4868. }
  4869. //
  4870. var xhr = new XMLHttpRequest();
  4871. xhr.addEventListener( 'load', function ( event ) {
  4872. if ( event.target.responseText ) {
  4873. geometry = scope.parse( JSON.parse( event.target.responseText ), monitor );
  4874. } else {
  4875. scope.dispatchEvent( { type: 'error', message: 'Invalid file [' + url + ']' } );
  4876. }
  4877. }, false );
  4878. xhr.addEventListener( 'error', function () {
  4879. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4880. }, false );
  4881. xhr.open( 'GET', url, true );
  4882. xhr.send( null );
  4883. //
  4884. var monitor = new THREE.LoadingMonitor();
  4885. monitor.addEventListener( 'load', function ( event ) {
  4886. scope.dispatchEvent( { type: 'load', content: geometry } );
  4887. } );
  4888. monitor.add( xhr );
  4889. },
  4890. parse: function ( data, monitor ) {
  4891. var scope = this;
  4892. var geometry = new THREE.Geometry();
  4893. var scale = ( data.scale !== undefined ) ? 1 / data.scale : 1;
  4894. // materials
  4895. if ( data.materials ) {
  4896. geometry.materials = [];
  4897. for ( var i = 0; i < data.materials.length; ++ i ) {
  4898. var m = data.materials[ i ];
  4899. function isPow2( n ) {
  4900. var l = Math.log( n ) / Math.LN2;
  4901. return Math.floor( l ) == l;
  4902. }
  4903. function nearestPow2( n ) {
  4904. var l = Math.log( n ) / Math.LN2;
  4905. return Math.pow( 2, Math.round( l ) );
  4906. }
  4907. function createTexture( where, name, sourceFile, repeat, offset, wrap ) {
  4908. where[ name ] = new THREE.Texture();
  4909. where[ name ].sourceFile = sourceFile;
  4910. if ( repeat ) {
  4911. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4912. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4913. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4914. }
  4915. if ( offset ) {
  4916. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4917. }
  4918. if ( wrap ) {
  4919. var wrapMap = {
  4920. "repeat": THREE.RepeatWrapping,
  4921. "mirror": THREE.MirroredRepeatWrapping
  4922. }
  4923. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4924. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4925. }
  4926. // load image
  4927. var texture = where[ name ];
  4928. var loader = new THREE.ImageLoader();
  4929. loader.addEventListener( 'load', function ( event ) {
  4930. var image = event.content;
  4931. if ( !isPow2( image.width ) || !isPow2( image.height ) ) {
  4932. var width = nearestPow2( image.width );
  4933. var height = nearestPow2( image.height );
  4934. texture.image = document.createElement( 'canvas' );
  4935. texture.image.width = width;
  4936. texture.image.height = height;
  4937. texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
  4938. } else {
  4939. texture.image = image;
  4940. }
  4941. texture.needsUpdate = true;
  4942. } );
  4943. loader.crossOrigin = scope.crossOrigin;
  4944. loader.load( scope.path + '/' + sourceFile );
  4945. if ( monitor ) monitor.add( loader );
  4946. }
  4947. function rgb2hex( rgb ) {
  4948. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4949. }
  4950. // defaults
  4951. var mtype = "MeshLambertMaterial";
  4952. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4953. // parameters from model file
  4954. if ( m.shading ) {
  4955. var shading = m.shading.toLowerCase();
  4956. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4957. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4958. }
  4959. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4960. mpars.blending = THREE[ m.blending ];
  4961. }
  4962. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4963. mpars.transparent = m.transparent;
  4964. }
  4965. if ( m.depthTest !== undefined ) {
  4966. mpars.depthTest = m.depthTest;
  4967. }
  4968. if ( m.depthWrite !== undefined ) {
  4969. mpars.depthWrite = m.depthWrite;
  4970. }
  4971. if ( m.vertexColors !== undefined ) {
  4972. if ( m.vertexColors == "face" ) {
  4973. mpars.vertexColors = THREE.FaceColors;
  4974. } else if ( m.vertexColors ) {
  4975. mpars.vertexColors = THREE.VertexColors;
  4976. }
  4977. }
  4978. // colors
  4979. if ( m.colorDiffuse ) {
  4980. mpars.color = rgb2hex( m.colorDiffuse );
  4981. } else if ( m.DbgColor ) {
  4982. mpars.color = m.DbgColor;
  4983. }
  4984. if ( m.colorSpecular ) {
  4985. mpars.specular = rgb2hex( m.colorSpecular );
  4986. }
  4987. if ( m.colorAmbient ) {
  4988. mpars.ambient = rgb2hex( m.colorAmbient );
  4989. }
  4990. // modifiers
  4991. if ( m.transparency ) {
  4992. mpars.opacity = m.transparency;
  4993. }
  4994. if ( m.specularCoef ) {
  4995. mpars.shininess = m.specularCoef;
  4996. }
  4997. if ( m.visible !== undefined ) {
  4998. mpars.visible = m.visible;
  4999. }
  5000. if ( m.flipSided !== undefined ) {
  5001. mpars.side = THREE.BackSide;
  5002. }
  5003. if ( m.doubleSided !== undefined ) {
  5004. mpars.side = THREE.DoubleSide;
  5005. }
  5006. if ( m.wireframe !== undefined ) {
  5007. mpars.wireframe = m.wireframe;
  5008. }
  5009. // textures
  5010. if ( m.mapDiffuse ) {
  5011. createTexture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  5012. }
  5013. if ( m.mapLight ) {
  5014. createTexture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  5015. }
  5016. if ( m.mapBump ) {
  5017. createTexture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap );
  5018. }
  5019. if ( m.mapNormal ) {
  5020. createTexture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  5021. }
  5022. if ( m.mapSpecular ) {
  5023. createTexture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  5024. }
  5025. // special case for normal mapped material
  5026. if ( m.mapNormal ) {
  5027. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5028. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5029. uniforms[ "tNormal" ].texture = mpars.normalMap;
  5030. if ( m.mapNormalFactor ) {
  5031. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  5032. }
  5033. if ( mpars.map ) {
  5034. uniforms[ "tDiffuse" ].texture = mpars.map;
  5035. uniforms[ "enableDiffuse" ].value = true;
  5036. }
  5037. if ( mpars.specularMap ) {
  5038. uniforms[ "tSpecular" ].texture = mpars.specularMap;
  5039. uniforms[ "enableSpecular" ].value = true;
  5040. }
  5041. if ( mpars.lightMap ) {
  5042. uniforms[ "tAO" ].texture = mpars.lightMap;
  5043. uniforms[ "enableAO" ].value = true;
  5044. }
  5045. // for the moment don't handle displacement texture
  5046. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5047. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5048. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5049. uniforms[ "uShininess" ].value = mpars.shininess;
  5050. if ( mpars.opacity !== undefined ) {
  5051. uniforms[ "uOpacity" ].value = mpars.opacity;
  5052. }
  5053. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5054. var material = new THREE.ShaderMaterial( parameters );
  5055. } else {
  5056. var material = new THREE[ mtype ]( mpars );
  5057. }
  5058. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5059. geometry.materials[ i ] = material;
  5060. }
  5061. }
  5062. // geometry
  5063. function isBitSet( value, position ) {
  5064. return value & ( 1 << position );
  5065. }
  5066. var faces = data.faces;
  5067. var vertices = data.vertices;
  5068. var normals = data.normals;
  5069. var colors = data.colors;
  5070. var nUvLayers = 0;
  5071. // disregard empty arrays
  5072. if ( data.uvs ) {
  5073. for ( var i = 0; i < data.uvs.length; i ++ ) {
  5074. if ( data.uvs[ i ].length ) nUvLayers ++;
  5075. }
  5076. }
  5077. for ( var i = 0; i < nUvLayers; i ++ ) {
  5078. geometry.faceUvs[ i ] = [];
  5079. geometry.faceVertexUvs[ i ] = [];
  5080. }
  5081. var offset = 0;
  5082. var zLength = vertices.length;
  5083. while ( offset < zLength ) {
  5084. var vertex = new THREE.Vector3();
  5085. vertex.x = vertices[ offset ++ ] * scale;
  5086. vertex.y = vertices[ offset ++ ] * scale;
  5087. vertex.z = vertices[ offset ++ ] * scale;
  5088. geometry.vertices.push( vertex );
  5089. }
  5090. offset = 0;
  5091. zLength = faces.length;
  5092. while ( offset < zLength ) {
  5093. var type = faces[ offset ++ ];
  5094. var isQuad = isBitSet( type, 0 );
  5095. var hasMaterial = isBitSet( type, 1 );
  5096. var hasFaceUv = isBitSet( type, 2 );
  5097. var hasFaceVertexUv = isBitSet( type, 3 );
  5098. var hasFaceNormal = isBitSet( type, 4 );
  5099. var hasFaceVertexNormal = isBitSet( type, 5 );
  5100. var hasFaceColor = isBitSet( type, 6 );
  5101. var hasFaceVertexColor = isBitSet( type, 7 );
  5102. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5103. if ( isQuad ) {
  5104. var face = new THREE.Face4();
  5105. face.a = faces[ offset ++ ];
  5106. face.b = faces[ offset ++ ];
  5107. face.c = faces[ offset ++ ];
  5108. face.d = faces[ offset ++ ];
  5109. var nVertices = 4;
  5110. } else {
  5111. var face = new THREE.Face3();
  5112. face.a = faces[ offset ++ ];
  5113. face.b = faces[ offset ++ ];
  5114. face.c = faces[ offset ++ ];
  5115. var nVertices = 3;
  5116. }
  5117. if ( hasMaterial ) {
  5118. var materialIndex = faces[ offset ++ ];
  5119. face.materialIndex = materialIndex;
  5120. }
  5121. // to get face <=> uv index correspondence
  5122. var fi = geometry.faces.length;
  5123. if ( hasFaceUv ) {
  5124. for ( var i = 0; i < nUvLayers; i ++ ) {
  5125. var uvLayer = data.uvs[ i ];
  5126. var uvIndex = faces[ offset ++ ];
  5127. var u = uvLayer[ uvIndex * 2 ];
  5128. var v = uvLayer[ uvIndex * 2 + 1 ];
  5129. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5130. }
  5131. }
  5132. if ( hasFaceVertexUv ) {
  5133. for ( var i = 0; i < nUvLayers; i ++ ) {
  5134. var uvLayer = data.uvs[ i ];
  5135. var uvs = [];
  5136. for ( var j = 0; j < nVertices; j ++ ) {
  5137. var uvIndex = faces[ offset ++ ];
  5138. var u = uvLayer[ uvIndex * 2 ];
  5139. var v = uvLayer[ uvIndex * 2 + 1 ];
  5140. uvs[ j ] = new THREE.UV( u, v );
  5141. }
  5142. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5143. }
  5144. }
  5145. if ( hasFaceNormal ) {
  5146. var normalIndex = faces[ offset ++ ] * 3;
  5147. var normal = new THREE.Vector3();
  5148. normal.x = normals[ normalIndex ++ ];
  5149. normal.y = normals[ normalIndex ++ ];
  5150. normal.z = normals[ normalIndex ];
  5151. face.normal = normal;
  5152. }
  5153. if ( hasFaceVertexNormal ) {
  5154. for ( i = 0; i < nVertices; i ++ ) {
  5155. var normalIndex = faces[ offset ++ ] * 3;
  5156. var normal = new THREE.Vector3();
  5157. normal.x = normals[ normalIndex ++ ];
  5158. normal.y = normals[ normalIndex ++ ];
  5159. normal.z = normals[ normalIndex ];
  5160. face.vertexNormals.push( normal );
  5161. }
  5162. }
  5163. if ( hasFaceColor ) {
  5164. var colorIndex = faces[ offset ++ ];
  5165. face.color = new THREE.Color( colors[ colorIndex ] );
  5166. }
  5167. if ( hasFaceVertexColor ) {
  5168. for ( var i = 0; i < nVertices; i ++ ) {
  5169. var colorIndex = faces[ offset ++ ];
  5170. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  5171. }
  5172. }
  5173. geometry.faces.push( face );
  5174. }
  5175. // skin
  5176. if ( data.skinWeights ) {
  5177. for ( var i = 0, l = data.skinWeights.length; i < l; i += 2 ) {
  5178. var x = data.skinWeights[ i ];
  5179. var y = data.skinWeights[ i + 1 ];
  5180. var z = 0;
  5181. var w = 0;
  5182. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5183. }
  5184. }
  5185. if ( data.skinIndices ) {
  5186. for ( var i = 0, l = data.skinIndices.length; i < l; i += 2 ) {
  5187. var a = data.skinIndices[ i ];
  5188. var b = data.skinIndices[ i + 1 ];
  5189. var c = 0;
  5190. var d = 0;
  5191. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5192. }
  5193. }
  5194. geometry.bones = data.bones;
  5195. geometry.animation = data.animation;
  5196. // morphing
  5197. if ( data.morphTargets ) {
  5198. for ( var i = 0, l = data.morphTargets.length; i < l; i ++ ) {
  5199. geometry.morphTargets[ i ] = {};
  5200. geometry.morphTargets[ i ].name = data.morphTargets[ i ].name;
  5201. geometry.morphTargets[ i ].vertices = [];
  5202. var dstVertices = geometry.morphTargets[ i ].vertices;
  5203. var srcVertices = data.morphTargets [ i ].vertices;
  5204. for( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5205. var vertex = new THREE.Vector3();
  5206. vertex.x = srcVertices[ v ] * scale;
  5207. vertex.y = srcVertices[ v + 1 ] * scale;
  5208. vertex.z = srcVertices[ v + 2 ] * scale;
  5209. dstVertices.push( vertex );
  5210. }
  5211. }
  5212. }
  5213. if ( data.morphColors ) {
  5214. for ( var i = 0, l = data.morphColors.length; i < l; i++ ) {
  5215. geometry.morphColors[ i ] = {};
  5216. geometry.morphColors[ i ].name = data.morphColors[ i ].name;
  5217. geometry.morphColors[ i ].colors = [];
  5218. var dstColors = geometry.morphColors[ i ].colors;
  5219. var srcColors = data.morphColors [ i ].colors;
  5220. for ( var c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5221. var color = new THREE.Color( 0xffaa00 );
  5222. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5223. dstColors.push( color );
  5224. }
  5225. }
  5226. }
  5227. geometry.computeCentroids();
  5228. geometry.computeFaceNormals();
  5229. return geometry;
  5230. }
  5231. };
  5232. /**
  5233. * @author alteredq / http://alteredqualia.com/
  5234. */
  5235. THREE.SceneLoader = function () {
  5236. this.onLoadStart = function () {};
  5237. this.onLoadProgress = function() {};
  5238. this.onLoadComplete = function () {};
  5239. this.callbackSync = function () {};
  5240. this.callbackProgress = function () {};
  5241. };
  5242. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5243. THREE.SceneLoader.prototype.load = function( url, callbackFinished ) {
  5244. var context = this;
  5245. var xhr = new XMLHttpRequest();
  5246. xhr.onreadystatechange = function () {
  5247. if ( xhr.readyState === 4 ) {
  5248. if ( xhr.status === 200 || xhr.status === 0 ) {
  5249. var json = JSON.parse( xhr.responseText );
  5250. context.createScene( json, callbackFinished, url );
  5251. } else {
  5252. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5253. }
  5254. }
  5255. };
  5256. xhr.open( "GET", url, true );
  5257. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  5258. xhr.setRequestHeader( "Content-Type", "text/plain" );
  5259. xhr.send( null );
  5260. };
  5261. THREE.SceneLoader.prototype.createScene = function ( json, callbackFinished, url ) {
  5262. var scope = this;
  5263. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5264. var dg, dm, dd, dl, dc, df, dt,
  5265. g, o, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  5266. geometry, material, camera, fog,
  5267. texture, images,
  5268. light,
  5269. data, binLoader, jsonLoader,
  5270. counter_models, counter_textures,
  5271. total_models, total_textures,
  5272. result;
  5273. data = json;
  5274. binLoader = new THREE.BinaryLoader();
  5275. jsonLoader = new THREE.JSONLoader();
  5276. counter_models = 0;
  5277. counter_textures = 0;
  5278. result = {
  5279. scene: new THREE.Scene(),
  5280. geometries: {},
  5281. materials: {},
  5282. textures: {},
  5283. objects: {},
  5284. cameras: {},
  5285. lights: {},
  5286. fogs: {},
  5287. empties: {}
  5288. };
  5289. if ( data.transform ) {
  5290. var position = data.transform.position,
  5291. rotation = data.transform.rotation,
  5292. scale = data.transform.scale;
  5293. if ( position )
  5294. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5295. if ( rotation )
  5296. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5297. if ( scale )
  5298. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5299. if ( position || rotation || scale ) {
  5300. result.scene.updateMatrix();
  5301. result.scene.updateMatrixWorld();
  5302. }
  5303. }
  5304. function get_url( source_url, url_type ) {
  5305. if ( url_type == "relativeToHTML" ) {
  5306. return source_url;
  5307. } else {
  5308. return urlBase + "/" + source_url;
  5309. }
  5310. };
  5311. // the toplevel loader function, delegates to handle_children
  5312. function handle_objects() {
  5313. handle_children( result.scene, data.objects );
  5314. }
  5315. // handle all the children from the loaded json and attach them to given parent
  5316. function handle_children( parent, children ) {
  5317. var object;
  5318. for ( dd in children ) {
  5319. // check by id if child has already been handled,
  5320. // if not, create new object
  5321. if ( result.objects[ dd ] === undefined ) {
  5322. o = children[ dd ];
  5323. if ( o.geometry !== undefined ) {
  5324. geometry = result.geometries[ o.geometry ];
  5325. // geometry already loaded
  5326. if ( geometry ) {
  5327. var hasNormals = false;
  5328. // not anymore support for multiple materials
  5329. // shouldn't really be array
  5330. material = result.materials[ o.materials[ 0 ] ];
  5331. hasNormals = material instanceof THREE.ShaderMaterial;
  5332. if ( hasNormals ) {
  5333. geometry.computeTangents();
  5334. }
  5335. p = o.position;
  5336. r = o.rotation;
  5337. q = o.quaternion;
  5338. s = o.scale;
  5339. m = o.matrix;
  5340. // turn off quaternions, for the moment
  5341. q = 0;
  5342. if ( o.materials.length == 0 ) {
  5343. material = new THREE.MeshFaceMaterial();
  5344. }
  5345. // dirty hack to handle meshes with multiple materials
  5346. // just use face materials defined in model
  5347. if ( o.materials.length > 1 ) {
  5348. material = new THREE.MeshFaceMaterial();
  5349. }
  5350. object = new THREE.Mesh( geometry, material );
  5351. object.name = dd;
  5352. if ( m ) {
  5353. object.matrixAutoUpdate = false;
  5354. object.matrix.set(
  5355. m[0], m[1], m[2], m[3],
  5356. m[4], m[5], m[6], m[7],
  5357. m[8], m[9], m[10], m[11],
  5358. m[12], m[13], m[14], m[15]
  5359. );
  5360. } else {
  5361. object.position.set( p[0], p[1], p[2] );
  5362. if ( q ) {
  5363. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5364. object.useQuaternion = true;
  5365. } else {
  5366. object.rotation.set( r[0], r[1], r[2] );
  5367. }
  5368. object.scale.set( s[0], s[1], s[2] );
  5369. }
  5370. object.visible = o.visible;
  5371. object.castShadow = o.castShadow;
  5372. object.receiveShadow = o.receiveShadow;
  5373. parent.add( object );
  5374. result.objects[ dd ] = object;
  5375. }
  5376. // pure Object3D
  5377. } else {
  5378. p = o.position;
  5379. r = o.rotation;
  5380. q = o.quaternion;
  5381. s = o.scale;
  5382. // turn off quaternions, for the moment
  5383. q = 0;
  5384. object = new THREE.Object3D();
  5385. object.name = dd;
  5386. object.position.set( p[0], p[1], p[2] );
  5387. if ( q ) {
  5388. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5389. object.useQuaternion = true;
  5390. } else {
  5391. object.rotation.set( r[0], r[1], r[2] );
  5392. }
  5393. object.scale.set( s[0], s[1], s[2] );
  5394. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  5395. parent.add( object );
  5396. result.objects[ dd ] = object;
  5397. result.empties[ dd ] = object;
  5398. }
  5399. if ( o.properties !== undefined) {
  5400. for ( var key in o.properties ) {
  5401. var value = o.properties[ key ];
  5402. object.properties[ key ] = value;
  5403. }
  5404. }
  5405. if ( o.children !== undefined ) {
  5406. handle_children( object, o.children );
  5407. }
  5408. }
  5409. }
  5410. };
  5411. function handle_mesh( geo, id ) {
  5412. result.geometries[ id ] = geo;
  5413. handle_objects();
  5414. };
  5415. function create_callback( id ) {
  5416. return function( geo ) {
  5417. handle_mesh( geo, id );
  5418. counter_models -= 1;
  5419. scope.onLoadComplete();
  5420. async_callback_gate();
  5421. }
  5422. };
  5423. function create_callback_embed( id ) {
  5424. return function( geo ) {
  5425. result.geometries[ id ] = geo;
  5426. }
  5427. };
  5428. function async_callback_gate() {
  5429. var progress = {
  5430. totalModels : total_models,
  5431. totalTextures : total_textures,
  5432. loadedModels : total_models - counter_models,
  5433. loadedTextures : total_textures - counter_textures
  5434. };
  5435. scope.callbackProgress( progress, result );
  5436. scope.onLoadProgress();
  5437. if ( counter_models === 0 && counter_textures === 0 ) {
  5438. callbackFinished( result );
  5439. }
  5440. };
  5441. var callbackTexture = function ( count ) {
  5442. counter_textures -= count;
  5443. async_callback_gate();
  5444. scope.onLoadComplete();
  5445. };
  5446. // must use this instead of just directly calling callbackTexture
  5447. // because of closure in the calling context loop
  5448. var generateTextureCallback = function ( count ) {
  5449. return function() {
  5450. callbackTexture( count );
  5451. };
  5452. };
  5453. // first go synchronous elements
  5454. // cameras
  5455. for( dc in data.cameras ) {
  5456. c = data.cameras[ dc ];
  5457. if ( c.type === "perspective" ) {
  5458. camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );
  5459. } else if ( c.type === "ortho" ) {
  5460. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  5461. }
  5462. p = c.position;
  5463. t = c.target;
  5464. u = c.up;
  5465. camera.position.set( p[0], p[1], p[2] );
  5466. camera.target = new THREE.Vector3( t[0], t[1], t[2] );
  5467. if ( u ) camera.up.set( u[0], u[1], u[2] );
  5468. result.cameras[ dc ] = camera;
  5469. }
  5470. // lights
  5471. var hex, intensity;
  5472. for ( dl in data.lights ) {
  5473. l = data.lights[ dl ];
  5474. hex = ( l.color !== undefined ) ? l.color : 0xffffff;
  5475. intensity = ( l.intensity !== undefined ) ? l.intensity : 1;
  5476. if ( l.type === "directional" ) {
  5477. p = l.direction;
  5478. light = new THREE.DirectionalLight( hex, intensity );
  5479. light.position.set( p[0], p[1], p[2] );
  5480. light.position.normalize();
  5481. } else if ( l.type === "point" ) {
  5482. p = l.position;
  5483. d = l.distance;
  5484. light = new THREE.PointLight( hex, intensity, d );
  5485. light.position.set( p[0], p[1], p[2] );
  5486. } else if ( l.type === "ambient" ) {
  5487. light = new THREE.AmbientLight( hex );
  5488. }
  5489. result.scene.add( light );
  5490. result.lights[ dl ] = light;
  5491. }
  5492. // fogs
  5493. for( df in data.fogs ) {
  5494. f = data.fogs[ df ];
  5495. if ( f.type === "linear" ) {
  5496. fog = new THREE.Fog( 0x000000, f.near, f.far );
  5497. } else if ( f.type === "exp2" ) {
  5498. fog = new THREE.FogExp2( 0x000000, f.density );
  5499. }
  5500. c = f.color;
  5501. fog.color.setRGB( c[0], c[1], c[2] );
  5502. result.fogs[ df ] = fog;
  5503. }
  5504. // defaults
  5505. if ( result.cameras && data.defaults.camera ) {
  5506. result.currentCamera = result.cameras[ data.defaults.camera ];
  5507. }
  5508. if ( result.fogs && data.defaults.fog ) {
  5509. result.scene.fog = result.fogs[ data.defaults.fog ];
  5510. }
  5511. c = data.defaults.bgcolor;
  5512. result.bgColor = new THREE.Color();
  5513. result.bgColor.setRGB( c[0], c[1], c[2] );
  5514. result.bgColorAlpha = data.defaults.bgalpha;
  5515. // now come potentially asynchronous elements
  5516. // geometries
  5517. // count how many models will be loaded asynchronously
  5518. for( dg in data.geometries ) {
  5519. g = data.geometries[ dg ];
  5520. if ( g.type == "bin_mesh" || g.type == "ascii_mesh" ) {
  5521. counter_models += 1;
  5522. scope.onLoadStart();
  5523. }
  5524. }
  5525. total_models = counter_models;
  5526. for ( dg in data.geometries ) {
  5527. g = data.geometries[ dg ];
  5528. if ( g.type === "cube" ) {
  5529. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.segmentsWidth, g.segmentsHeight, g.segmentsDepth, null, g.flipped, g.sides );
  5530. result.geometries[ dg ] = geometry;
  5531. } else if ( g.type === "plane" ) {
  5532. geometry = new THREE.PlaneGeometry( g.width, g.height, g.segmentsWidth, g.segmentsHeight );
  5533. result.geometries[ dg ] = geometry;
  5534. } else if ( g.type === "sphere" ) {
  5535. geometry = new THREE.SphereGeometry( g.radius, g.segmentsWidth, g.segmentsHeight );
  5536. result.geometries[ dg ] = geometry;
  5537. } else if ( g.type === "cylinder" ) {
  5538. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  5539. result.geometries[ dg ] = geometry;
  5540. } else if ( g.type === "torus" ) {
  5541. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  5542. result.geometries[ dg ] = geometry;
  5543. } else if ( g.type === "icosahedron" ) {
  5544. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  5545. result.geometries[ dg ] = geometry;
  5546. } else if ( g.type === "bin_mesh" ) {
  5547. binLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  5548. } else if ( g.type === "ascii_mesh" ) {
  5549. jsonLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  5550. } else if ( g.type === "embedded_mesh" ) {
  5551. var modelJson = data.embeds[ g.id ],
  5552. texture_path = "";
  5553. // pass metadata along to jsonLoader so it knows the format version
  5554. modelJson.metadata = data.metadata;
  5555. if ( modelJson ) {
  5556. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  5557. }
  5558. }
  5559. }
  5560. // textures
  5561. // count how many textures will be loaded asynchronously
  5562. for( dt in data.textures ) {
  5563. tt = data.textures[ dt ];
  5564. if( tt.url instanceof Array ) {
  5565. counter_textures += tt.url.length;
  5566. for( var n = 0; n < tt.url.length; n ++ ) {
  5567. scope.onLoadStart();
  5568. }
  5569. } else {
  5570. counter_textures += 1;
  5571. scope.onLoadStart();
  5572. }
  5573. }
  5574. total_textures = counter_textures;
  5575. for( dt in data.textures ) {
  5576. tt = data.textures[ dt ];
  5577. if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined ) {
  5578. tt.mapping = new THREE[ tt.mapping ]();
  5579. }
  5580. if( tt.url instanceof Array ) {
  5581. var count = tt.url.length;
  5582. var url_array = [];
  5583. for( var i = 0; i < count; i ++ ) {
  5584. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  5585. }
  5586. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5587. } else {
  5588. texture = THREE.ImageUtils.loadTexture( get_url( tt.url, data.urlBaseType ), tt.mapping, generateTextureCallback( 1 ) );
  5589. if ( THREE[ tt.minFilter ] !== undefined )
  5590. texture.minFilter = THREE[ tt.minFilter ];
  5591. if ( THREE[ tt.magFilter ] !== undefined )
  5592. texture.magFilter = THREE[ tt.magFilter ];
  5593. if ( tt.repeat ) {
  5594. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  5595. if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  5596. if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  5597. }
  5598. if ( tt.offset ) {
  5599. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  5600. }
  5601. // handle wrap after repeat so that default repeat can be overriden
  5602. if ( tt.wrap ) {
  5603. var wrapMap = {
  5604. "repeat" : THREE.RepeatWrapping,
  5605. "mirror" : THREE.MirroredRepeatWrapping
  5606. }
  5607. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  5608. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  5609. }
  5610. }
  5611. result.textures[ dt ] = texture;
  5612. }
  5613. // materials
  5614. for ( dm in data.materials ) {
  5615. m = data.materials[ dm ];
  5616. for ( pp in m.parameters ) {
  5617. if ( pp === "envMap" || pp === "map" || pp === "lightMap" ) {
  5618. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  5619. } else if ( pp === "shading" ) {
  5620. m.parameters[ pp ] = ( m.parameters[ pp ] == "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  5621. } else if ( pp === "blending" ) {
  5622. m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  5623. } else if ( pp === "combine" ) {
  5624. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  5625. } else if ( pp === "vertexColors" ) {
  5626. if ( m.parameters[ pp ] == "face" ) {
  5627. m.parameters[ pp ] = THREE.FaceColors;
  5628. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  5629. } else if ( m.parameters[ pp ] ) {
  5630. m.parameters[ pp ] = THREE.VertexColors;
  5631. }
  5632. }
  5633. }
  5634. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  5635. m.parameters.transparent = true;
  5636. }
  5637. if ( m.parameters.normalMap ) {
  5638. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5639. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5640. var diffuse = m.parameters.color;
  5641. var specular = m.parameters.specular;
  5642. var ambient = m.parameters.ambient;
  5643. var shininess = m.parameters.shininess;
  5644. uniforms[ "tNormal" ].texture = result.textures[ m.parameters.normalMap ];
  5645. if ( m.parameters.normalMapFactor ) {
  5646. uniforms[ "uNormalScale" ].value = m.parameters.normalMapFactor;
  5647. }
  5648. if ( m.parameters.map ) {
  5649. uniforms[ "tDiffuse" ].texture = m.parameters.map;
  5650. uniforms[ "enableDiffuse" ].value = true;
  5651. }
  5652. if ( m.parameters.lightMap ) {
  5653. uniforms[ "tAO" ].texture = m.parameters.lightMap;
  5654. uniforms[ "enableAO" ].value = true;
  5655. }
  5656. if ( m.parameters.specularMap ) {
  5657. uniforms[ "tSpecular" ].texture = result.textures[ m.parameters.specularMap ];
  5658. uniforms[ "enableSpecular" ].value = true;
  5659. }
  5660. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  5661. uniforms[ "uSpecularColor" ].value.setHex( specular );
  5662. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  5663. uniforms[ "uShininess" ].value = shininess;
  5664. if ( m.parameters.opacity ) {
  5665. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  5666. }
  5667. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5668. material = new THREE.ShaderMaterial( parameters );
  5669. } else {
  5670. material = new THREE[ m.type ]( m.parameters );
  5671. }
  5672. result.materials[ dm ] = material;
  5673. }
  5674. // objects ( synchronous init of procedural primitives )
  5675. handle_objects();
  5676. // synchronous callback
  5677. scope.callbackSync( result );
  5678. // just in case there are no async elements
  5679. async_callback_gate();
  5680. };
  5681. /**
  5682. * @author mrdoob / http://mrdoob.com/
  5683. */
  5684. THREE.TextureLoader = function () {
  5685. THREE.EventTarget.call( this );
  5686. this.crossOrigin = null;
  5687. };
  5688. THREE.TextureLoader.prototype = {
  5689. constructor: THREE.TextureLoader,
  5690. load: function ( url ) {
  5691. var scope = this;
  5692. var image = new Image();
  5693. image.addEventListener( 'load', function () {
  5694. var texture = new THREE.Texture( image );
  5695. texture.needsUpdate = true;
  5696. scope.dispatchEvent( { type: 'load', content: texture } );
  5697. }, false );
  5698. image.addEventListener( 'error', function () {
  5699. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5700. }, false );
  5701. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5702. image.src = url;
  5703. }
  5704. }
  5705. /**
  5706. * @author mrdoob / http://mrdoob.com/
  5707. * @author alteredq / http://alteredqualia.com/
  5708. */
  5709. THREE.Material = function () {
  5710. this.id = THREE.MaterialCount ++;
  5711. this.name = '';
  5712. this.side = THREE.FrontSide;
  5713. this.opacity = 1;
  5714. this.transparent = false;
  5715. this.blending = THREE.NormalBlending;
  5716. this.blendSrc = THREE.SrcAlphaFactor;
  5717. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  5718. this.blendEquation = THREE.AddEquation;
  5719. this.depthTest = true;
  5720. this.depthWrite = true;
  5721. this.polygonOffset = false;
  5722. this.polygonOffsetFactor = 0;
  5723. this.polygonOffsetUnits = 0;
  5724. this.alphaTest = 0;
  5725. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  5726. this.visible = true;
  5727. this.needsUpdate = true;
  5728. };
  5729. THREE.Material.prototype.setValues = function ( values ) {
  5730. if ( values === undefined ) return;
  5731. for ( var key in values ) {
  5732. var newValue = values[ key ];
  5733. if ( newValue === undefined ) {
  5734. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5735. continue;
  5736. }
  5737. if ( key in this ) {
  5738. var currentValue = this[ key ];
  5739. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  5740. currentValue.copy( newValue );
  5741. } else if ( currentValue instanceof THREE.Color && typeof( newValue ) === "number" ) {
  5742. currentValue.setHex( newValue );
  5743. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  5744. currentValue.copy( newValue );
  5745. } else {
  5746. this[ key ] = newValue;
  5747. }
  5748. }
  5749. }
  5750. };
  5751. THREE.Material.prototype.clone = function ( material ) {
  5752. if ( material === undefined ) material = new THREE.Material();
  5753. material.name = this.name;
  5754. material.side = this.side;
  5755. material.opacity = this.opacity;
  5756. material.transparent = this.transparent;
  5757. material.blending = this.blending;
  5758. material.blendSrc = this.blendSrc;
  5759. material.blendDst = this.blendDst;
  5760. material.blendEquation = this.blendEquation;
  5761. material.depthTest = this.depthTest;
  5762. material.depthWrite = this.depthWrite;
  5763. material.polygonOffset = this.polygonOffset;
  5764. material.polygonOffsetFactor = this.polygonOffsetFactor;
  5765. material.polygonOffsetUnits = this.polygonOffsetUnits;
  5766. material.alphaTest = this.alphaTest;
  5767. material.overdraw = this.overdraw;
  5768. material.visible = this.visible;
  5769. return material;
  5770. };
  5771. THREE.MaterialCount = 0;
  5772. /**
  5773. * @author mrdoob / http://mrdoob.com/
  5774. * @author alteredq / http://alteredqualia.com/
  5775. *
  5776. * parameters = {
  5777. * color: <hex>,
  5778. * opacity: <float>,
  5779. *
  5780. * blending: THREE.NormalBlending,
  5781. * depthTest: <bool>,
  5782. *
  5783. * linewidth: <float>,
  5784. * linecap: "round",
  5785. * linejoin: "round",
  5786. *
  5787. * vertexColors: <bool>
  5788. *
  5789. * fog: <bool>
  5790. * }
  5791. */
  5792. THREE.LineBasicMaterial = function ( parameters ) {
  5793. THREE.Material.call( this );
  5794. this.color = new THREE.Color( 0xffffff );
  5795. this.linewidth = 1;
  5796. this.linecap = 'round';
  5797. this.linejoin = 'round';
  5798. this.vertexColors = false;
  5799. this.fog = true;
  5800. this.setValues( parameters );
  5801. };
  5802. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  5803. THREE.LineBasicMaterial.prototype.clone = function () {
  5804. var material = new THREE.LineBasicMaterial();
  5805. THREE.Material.prototype.clone.call( this, material );
  5806. material.color.copy( this.color );
  5807. material.linewidth = this.linewidth;
  5808. material.linecap = this.linecap;
  5809. material.linejoin = this.linejoin;
  5810. material.vertexColors = this.vertexColors;
  5811. material.fog = this.fog;
  5812. return material;
  5813. };
  5814. /**
  5815. * @author mrdoob / http://mrdoob.com/
  5816. * @author alteredq / http://alteredqualia.com/
  5817. *
  5818. * parameters = {
  5819. * color: <hex>,
  5820. * opacity: <float>,
  5821. * map: new THREE.Texture( <Image> ),
  5822. *
  5823. * lightMap: new THREE.Texture( <Image> ),
  5824. *
  5825. * specularMap: new THREE.Texture( <Image> ),
  5826. *
  5827. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  5828. * combine: THREE.Multiply,
  5829. * reflectivity: <float>,
  5830. * refractionRatio: <float>,
  5831. *
  5832. * shading: THREE.SmoothShading,
  5833. * blending: THREE.NormalBlending,
  5834. * depthTest: <bool>,
  5835. *
  5836. * wireframe: <boolean>,
  5837. * wireframeLinewidth: <float>,
  5838. *
  5839. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  5840. *
  5841. * skinning: <bool>,
  5842. * morphTargets: <bool>,
  5843. *
  5844. * fog: <bool>
  5845. * }
  5846. */
  5847. THREE.MeshBasicMaterial = function ( parameters ) {
  5848. THREE.Material.call( this );
  5849. this.color = new THREE.Color( 0xffffff ); // emissive
  5850. this.map = null;
  5851. this.lightMap = null;
  5852. this.specularMap = null;
  5853. this.envMap = null;
  5854. this.combine = THREE.MultiplyOperation;
  5855. this.reflectivity = 1;
  5856. this.refractionRatio = 0.98;
  5857. this.fog = true;
  5858. this.shading = THREE.SmoothShading;
  5859. this.wireframe = false;
  5860. this.wireframeLinewidth = 1;
  5861. this.wireframeLinecap = 'round';
  5862. this.wireframeLinejoin = 'round';
  5863. this.vertexColors = THREE.NoColors;
  5864. this.skinning = false;
  5865. this.morphTargets = false;
  5866. this.setValues( parameters );
  5867. };
  5868. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  5869. THREE.MeshBasicMaterial.prototype.clone = function () {
  5870. var material = new THREE.MeshBasicMaterial();
  5871. THREE.Material.prototype.clone.call( this, material );
  5872. material.color.copy( this.color );
  5873. material.map = this.map;
  5874. material.lightMap = this.lightMap;
  5875. material.specularMap = this.specularMap;
  5876. material.envMap = this.envMap;
  5877. material.combine = this.combine;
  5878. material.reflectivity = this.reflectivity;
  5879. material.refractionRatio = this.refractionRatio;
  5880. material.fog = this.fog;
  5881. material.shading = this.shading;
  5882. material.wireframe = this.wireframe;
  5883. material.wireframeLinewidth = this.wireframeLinewidth;
  5884. material.wireframeLinecap = this.wireframeLinecap;
  5885. material.wireframeLinejoin = this.wireframeLinejoin;
  5886. material.vertexColors = this.vertexColors;
  5887. material.skinning = this.skinning;
  5888. material.morphTargets = this.morphTargets;
  5889. return material;
  5890. };
  5891. /**
  5892. * @author mrdoob / http://mrdoob.com/
  5893. * @author alteredq / http://alteredqualia.com/
  5894. *
  5895. * parameters = {
  5896. * color: <hex>,
  5897. * ambient: <hex>,
  5898. * emissive: <hex>,
  5899. * opacity: <float>,
  5900. *
  5901. * map: new THREE.Texture( <Image> ),
  5902. *
  5903. * lightMap: new THREE.Texture( <Image> ),
  5904. *
  5905. * specularMap: new THREE.Texture( <Image> ),
  5906. *
  5907. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  5908. * combine: THREE.Multiply,
  5909. * reflectivity: <float>,
  5910. * refractionRatio: <float>,
  5911. *
  5912. * shading: THREE.SmoothShading,
  5913. * blending: THREE.NormalBlending,
  5914. * depthTest: <bool>,
  5915. *
  5916. * wireframe: <boolean>,
  5917. * wireframeLinewidth: <float>,
  5918. *
  5919. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  5920. *
  5921. * skinning: <bool>,
  5922. * morphTargets: <bool>,
  5923. * morphNormals: <bool>,
  5924. *
  5925. * fog: <bool>
  5926. * }
  5927. */
  5928. THREE.MeshLambertMaterial = function ( parameters ) {
  5929. THREE.Material.call( this );
  5930. this.color = new THREE.Color( 0xffffff ); // diffuse
  5931. this.ambient = new THREE.Color( 0xffffff );
  5932. this.emissive = new THREE.Color( 0x000000 );
  5933. this.wrapAround = false;
  5934. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  5935. this.map = null;
  5936. this.lightMap = null;
  5937. this.specularMap = null;
  5938. this.envMap = null;
  5939. this.combine = THREE.MultiplyOperation;
  5940. this.reflectivity = 1;
  5941. this.refractionRatio = 0.98;
  5942. this.fog = true;
  5943. this.shading = THREE.SmoothShading;
  5944. this.wireframe = false;
  5945. this.wireframeLinewidth = 1;
  5946. this.wireframeLinecap = 'round';
  5947. this.wireframeLinejoin = 'round';
  5948. this.vertexColors = THREE.NoColors;
  5949. this.skinning = false;
  5950. this.morphTargets = false;
  5951. this.morphNormals = false;
  5952. this.setValues( parameters );
  5953. };
  5954. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  5955. THREE.MeshLambertMaterial.prototype.clone = function () {
  5956. var material = new THREE.MeshLambertMaterial();
  5957. THREE.Material.prototype.clone.call( this, material );
  5958. material.color.copy( this.color );
  5959. material.ambient.copy( this.ambient );
  5960. material.emissive.copy( this.emissive );
  5961. material.wrapAround = this.wrapAround;
  5962. material.wrapRGB.copy( this.wrapRGB );
  5963. material.map = this.map;
  5964. material.lightMap = this.lightMap;
  5965. material.specularMap = this.specularMap;
  5966. material.envMap = this.envMap;
  5967. material.combine = this.combine;
  5968. material.reflectivity = this.reflectivity;
  5969. material.refractionRatio = this.refractionRatio;
  5970. material.fog = this.fog;
  5971. material.shading = this.shading;
  5972. material.wireframe = this.wireframe;
  5973. material.wireframeLinewidth = this.wireframeLinewidth;
  5974. material.wireframeLinecap = this.wireframeLinecap;
  5975. material.wireframeLinejoin = this.wireframeLinejoin;
  5976. material.vertexColors = this.vertexColors;
  5977. material.skinning = this.skinning;
  5978. material.morphTargets = this.morphTargets;
  5979. material.morphNormals = this.morphNormals;
  5980. return material;
  5981. };
  5982. /**
  5983. * @author mrdoob / http://mrdoob.com/
  5984. * @author alteredq / http://alteredqualia.com/
  5985. *
  5986. * parameters = {
  5987. * color: <hex>,
  5988. * ambient: <hex>,
  5989. * emissive: <hex>,
  5990. * specular: <hex>,
  5991. * shininess: <float>,
  5992. * opacity: <float>,
  5993. *
  5994. * map: new THREE.Texture( <Image> ),
  5995. *
  5996. * lightMap: new THREE.Texture( <Image> ),
  5997. *
  5998. * bumpMap: new THREE.Texture( <Image> ),
  5999. * bumpScale: <float>,
  6000. *
  6001. * specularMap: new THREE.Texture( <Image> ),
  6002. *
  6003. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6004. * combine: THREE.Multiply,
  6005. * reflectivity: <float>,
  6006. * refractionRatio: <float>,
  6007. *
  6008. * shading: THREE.SmoothShading,
  6009. * blending: THREE.NormalBlending,
  6010. * depthTest: <bool>,
  6011. *
  6012. * wireframe: <boolean>,
  6013. * wireframeLinewidth: <float>,
  6014. *
  6015. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6016. *
  6017. * skinning: <bool>,
  6018. * morphTargets: <bool>,
  6019. * morphNormals: <bool>,
  6020. *
  6021. * fog: <bool>
  6022. * }
  6023. */
  6024. THREE.MeshPhongMaterial = function ( parameters ) {
  6025. THREE.Material.call( this );
  6026. this.color = new THREE.Color( 0xffffff ); // diffuse
  6027. this.ambient = new THREE.Color( 0xffffff );
  6028. this.emissive = new THREE.Color( 0x000000 );
  6029. this.specular = new THREE.Color( 0x111111 );
  6030. this.shininess = 30;
  6031. this.metal = false;
  6032. this.perPixel = false;
  6033. this.wrapAround = false;
  6034. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6035. this.map = null;
  6036. this.lightMap = null;
  6037. this.bumpMap = null;
  6038. this.bumpScale = 1;
  6039. this.specularMap = null;
  6040. this.envMap = null;
  6041. this.combine = THREE.MultiplyOperation;
  6042. this.reflectivity = 1;
  6043. this.refractionRatio = 0.98;
  6044. this.fog = true;
  6045. this.shading = THREE.SmoothShading;
  6046. this.wireframe = false;
  6047. this.wireframeLinewidth = 1;
  6048. this.wireframeLinecap = 'round';
  6049. this.wireframeLinejoin = 'round';
  6050. this.vertexColors = THREE.NoColors;
  6051. this.skinning = false;
  6052. this.morphTargets = false;
  6053. this.morphNormals = false;
  6054. this.setValues( parameters );
  6055. };
  6056. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6057. THREE.MeshPhongMaterial.prototype.clone = function () {
  6058. var material = new THREE.MeshPhongMaterial();
  6059. THREE.Material.prototype.clone.call( this, material );
  6060. material.color.copy( this.color );
  6061. material.ambient.copy( this.ambient );
  6062. material.emissive.copy( this.emissive );
  6063. material.specular.copy( this.specular );
  6064. material.shininess = this.shininess;
  6065. material.metal = this.metal;
  6066. material.perPixel = this.perPixel;
  6067. material.wrapAround = this.wrapAround;
  6068. material.wrapRGB.copy( this.wrapRGB );
  6069. material.map = this.map;
  6070. material.lightMap = this.lightMap;
  6071. material.bumpMap = this.bumpMap;
  6072. material.bumpScale= this.bumpScale;
  6073. material.specularMap = this.specularMap;
  6074. material.envMap = this.envMap;
  6075. material.combine = this.combine;
  6076. material.reflectivity = this.reflectivity;
  6077. material.refractionRatio = this.refractionRatio;
  6078. material.fog = this.fog;
  6079. material.shading = this.shading;
  6080. material.wireframe = this.wireframe;
  6081. material.wireframeLinewidth = this.wireframeLinewidth;
  6082. material.wireframeLinecap = this.wireframeLinecap;
  6083. material.wireframeLinejoin = this.wireframeLinejoin;
  6084. material.vertexColors = this.vertexColors;
  6085. material.skinning = this.skinning;
  6086. material.morphTargets = this.morphTargets;
  6087. material.morphNormals = this.morphNormals;
  6088. return material;
  6089. };
  6090. /**
  6091. * @author mrdoob / http://mrdoob.com/
  6092. * @author alteredq / http://alteredqualia.com/
  6093. *
  6094. * parameters = {
  6095. * opacity: <float>,
  6096. * blending: THREE.NormalBlending,
  6097. * depthTest: <bool>,
  6098. * wireframe: <boolean>,
  6099. * wireframeLinewidth: <float>
  6100. * }
  6101. */
  6102. THREE.MeshDepthMaterial = function ( parameters ) {
  6103. THREE.Material.call( this );
  6104. this.wireframe = false;
  6105. this.wireframeLinewidth = 1;
  6106. this.setValues( parameters );
  6107. };
  6108. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6109. THREE.MeshDepthMaterial.prototype.clone = function () {
  6110. var material = new THREE.LineBasicMaterial();
  6111. THREE.Material.prototype.clone.call( this, material );
  6112. material.wireframe = this.wireframe;
  6113. material.wireframeLinewidth = this.wireframeLinewidth;
  6114. return material;
  6115. };
  6116. /**
  6117. * @author mrdoob / http://mrdoob.com/
  6118. *
  6119. * parameters = {
  6120. * opacity: <float>,
  6121. * shading: THREE.FlatShading,
  6122. * blending: THREE.NormalBlending,
  6123. * depthTest: <bool>,
  6124. * wireframe: <boolean>,
  6125. * wireframeLinewidth: <float>
  6126. * }
  6127. */
  6128. THREE.MeshNormalMaterial = function ( parameters ) {
  6129. THREE.Material.call( this, parameters );
  6130. this.shading = THREE.FlatShading;
  6131. this.wireframe = false;
  6132. this.wireframeLinewidth = 1;
  6133. this.setValues( parameters );
  6134. };
  6135. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6136. THREE.MeshNormalMaterial.prototype.clone = function () {
  6137. var material = new THREE.MeshNormalMaterial();
  6138. THREE.Material.prototype.clone.call( this, material );
  6139. material.shading = this.shading;
  6140. material.wireframe = this.wireframe;
  6141. material.wireframeLinewidth = this.wireframeLinewidth;
  6142. return material;
  6143. };
  6144. /**
  6145. * @author mrdoob / http://mrdoob.com/
  6146. */
  6147. THREE.MeshFaceMaterial = function () {};
  6148. THREE.MeshFaceMaterial.prototype.clone = function () {
  6149. return new THREE.MeshFaceMaterial();
  6150. };
  6151. /**
  6152. * @author mrdoob / http://mrdoob.com/
  6153. * @author alteredq / http://alteredqualia.com/
  6154. *
  6155. * parameters = {
  6156. * color: <hex>,
  6157. * opacity: <float>,
  6158. * map: new THREE.Texture( <Image> ),
  6159. *
  6160. * size: <float>,
  6161. *
  6162. * blending: THREE.NormalBlending,
  6163. * depthTest: <bool>,
  6164. *
  6165. * vertexColors: <bool>,
  6166. *
  6167. * fog: <bool>
  6168. * }
  6169. */
  6170. THREE.ParticleBasicMaterial = function ( parameters ) {
  6171. THREE.Material.call( this );
  6172. this.color = new THREE.Color( 0xffffff );
  6173. this.map = null;
  6174. this.size = 1;
  6175. this.sizeAttenuation = true;
  6176. this.vertexColors = false;
  6177. this.fog = true;
  6178. this.setValues( parameters );
  6179. };
  6180. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6181. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6182. var material = new THREE.ParticleBasicMaterial();
  6183. THREE.Material.prototype.clone.call( this, material );
  6184. material.color.copy( this.color );
  6185. material.map = this.map;
  6186. material.size = this.size;
  6187. material.sizeAttenuation = this.sizeAttenuation;
  6188. material.vertexColors = this.vertexColors;
  6189. material.fog = this.fog;
  6190. return material;
  6191. };
  6192. /**
  6193. * @author mrdoob / http://mrdoob.com/
  6194. *
  6195. * parameters = {
  6196. * color: <hex>,
  6197. * program: <function>,
  6198. * opacity: <float>,
  6199. * blending: THREE.NormalBlending
  6200. * }
  6201. */
  6202. THREE.ParticleCanvasMaterial = function ( parameters ) {
  6203. THREE.Material.call( this );
  6204. this.color = new THREE.Color( 0xffffff );
  6205. this.program = function ( context, color ) {};
  6206. this.setValues( parameters );
  6207. };
  6208. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  6209. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  6210. var material = new THREE.ParticleCanvasMaterial();
  6211. THREE.Material.prototype.clone.call( this, material );
  6212. material.color.copy( this.color );
  6213. material.program = this.program;
  6214. return material;
  6215. };
  6216. /**
  6217. * @author mrdoob / http://mrdoob.com/
  6218. */
  6219. THREE.ParticleDOMMaterial = function ( domElement ) {
  6220. this.domElement = domElement;
  6221. };
  6222. THREE.ParticleDOMMaterial.prototype.clone = function(){
  6223. return new THREE.ParticleDOMMaterial( this.domElement );
  6224. };
  6225. /**
  6226. * @author alteredq / http://alteredqualia.com/
  6227. *
  6228. * parameters = {
  6229. * fragmentShader: <string>,
  6230. * vertexShader: <string>,
  6231. *
  6232. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  6233. *
  6234. * shading: THREE.SmoothShading,
  6235. * blending: THREE.NormalBlending,
  6236. * depthTest: <bool>,
  6237. *
  6238. * wireframe: <boolean>,
  6239. * wireframeLinewidth: <float>,
  6240. *
  6241. * lights: <bool>,
  6242. *
  6243. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6244. *
  6245. * skinning: <bool>,
  6246. * morphTargets: <bool>,
  6247. * morphNormals: <bool>,
  6248. *
  6249. * fog: <bool>
  6250. * }
  6251. */
  6252. THREE.ShaderMaterial = function ( parameters ) {
  6253. THREE.Material.call( this );
  6254. this.fragmentShader = "void main() {}";
  6255. this.vertexShader = "void main() {}";
  6256. this.uniforms = {};
  6257. this.attributes = null;
  6258. this.shading = THREE.SmoothShading;
  6259. this.wireframe = false;
  6260. this.wireframeLinewidth = 1;
  6261. this.fog = false; // set to use scene fog
  6262. this.lights = false; // set to use scene lights
  6263. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  6264. this.skinning = false; // set to use skinning attribute streams
  6265. this.morphTargets = false; // set to use morph targets
  6266. this.morphNormals = false; // set to use morph normals
  6267. this.setValues( parameters );
  6268. };
  6269. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  6270. THREE.ShaderMaterial.prototype.clone = function () {
  6271. var material = new THREE.ShaderMaterial();
  6272. THREE.Material.prototype.clone.call( this, material );
  6273. material.fragmentShader = this.fragmentShader;
  6274. material.vertexShader = this.vertexShader;
  6275. material.uniforms = this.uniforms;
  6276. material.attributes = this.attributes;
  6277. material.shading = this.shading;
  6278. material.wireframe = this.wireframe;
  6279. material.wireframeLinewidth = this.wireframeLinewidth;
  6280. material.fog = this.fog;
  6281. material.lights = this.lights;
  6282. material.vertexColors = this.vertexColors;
  6283. material.skinning = this.skinning;
  6284. material.morphTargets = this.morphTargets;
  6285. material.morphNormals = this.morphNormals;
  6286. return material;
  6287. };
  6288. /**
  6289. * @author mrdoob / http://mrdoob.com/
  6290. * @author alteredq / http://alteredqualia.com/
  6291. * @author szimek / https://github.com/szimek/
  6292. */
  6293. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  6294. this.id = THREE.TextureCount ++;
  6295. this.image = image;
  6296. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  6297. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  6298. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  6299. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  6300. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  6301. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6302. this.format = format !== undefined ? format : THREE.RGBAFormat;
  6303. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  6304. this.offset = new THREE.Vector2( 0, 0 );
  6305. this.repeat = new THREE.Vector2( 1, 1 );
  6306. this.generateMipmaps = true;
  6307. this.premultiplyAlpha = false;
  6308. this.flipY = true;
  6309. this.needsUpdate = false;
  6310. this.onUpdate = null;
  6311. };
  6312. THREE.Texture.prototype = {
  6313. constructor: THREE.Texture,
  6314. clone: function () {
  6315. var clonedTexture = new THREE.Texture( this.image, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter, this.format, this.type, this.anisotropy );
  6316. clonedTexture.offset.copy( this.offset );
  6317. clonedTexture.repeat.copy( this.repeat );
  6318. clonedTexture.generateMipmaps = this.generateMipmaps;
  6319. clonedTexture.premultiplyAlpha = this.premultiplyAlpha;
  6320. clonedTexture.flipY = this.flipY;
  6321. return clonedTexture;
  6322. }
  6323. };
  6324. THREE.TextureCount = 0;
  6325. /**
  6326. * @author alteredq / http://alteredqualia.com/
  6327. */
  6328. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6329. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6330. this.image = { data: data, width: width, height: height };
  6331. };
  6332. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  6333. THREE.DataTexture.prototype.clone = function () {
  6334. 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 );
  6335. clonedTexture.offset.copy( this.offset );
  6336. clonedTexture.repeat.copy( this.repeat );
  6337. return clonedTexture;
  6338. };
  6339. /**
  6340. * @author mrdoob / http://mrdoob.com/
  6341. */
  6342. THREE.Particle = function ( material ) {
  6343. THREE.Object3D.call( this );
  6344. this.material = material;
  6345. };
  6346. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  6347. /**
  6348. * @author alteredq / http://alteredqualia.com/
  6349. */
  6350. THREE.ParticleSystem = function ( geometry, material ) {
  6351. THREE.Object3D.call( this );
  6352. this.geometry = geometry;
  6353. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  6354. this.sortParticles = false;
  6355. if ( this.geometry ) {
  6356. // calc bound radius
  6357. if( !this.geometry.boundingSphere ) {
  6358. this.geometry.computeBoundingSphere();
  6359. }
  6360. this.boundRadius = geometry.boundingSphere.radius;
  6361. }
  6362. this.frustumCulled = false;
  6363. };
  6364. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  6365. /**
  6366. * @author mrdoob / http://mrdoob.com/
  6367. */
  6368. THREE.Line = function ( geometry, material, type ) {
  6369. THREE.Object3D.call( this );
  6370. this.geometry = geometry;
  6371. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6372. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  6373. if ( this.geometry ) {
  6374. if ( ! this.geometry.boundingSphere ) {
  6375. this.geometry.computeBoundingSphere();
  6376. }
  6377. }
  6378. };
  6379. THREE.LineStrip = 0;
  6380. THREE.LinePieces = 1;
  6381. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  6382. /**
  6383. * @author mrdoob / http://mrdoob.com/
  6384. * @author alteredq / http://alteredqualia.com/
  6385. * @author mikael emtinger / http://gomo.se/
  6386. */
  6387. THREE.Mesh = function ( geometry, material ) {
  6388. THREE.Object3D.call( this );
  6389. this.geometry = geometry;
  6390. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  6391. if ( this.geometry ) {
  6392. // calc bound radius
  6393. if ( ! this.geometry.boundingSphere ) {
  6394. this.geometry.computeBoundingSphere();
  6395. }
  6396. this.boundRadius = geometry.boundingSphere.radius;
  6397. // setup morph targets
  6398. if( this.geometry.morphTargets.length ) {
  6399. this.morphTargetBase = -1;
  6400. this.morphTargetForcedOrder = [];
  6401. this.morphTargetInfluences = [];
  6402. this.morphTargetDictionary = {};
  6403. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  6404. this.morphTargetInfluences.push( 0 );
  6405. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  6406. }
  6407. }
  6408. }
  6409. }
  6410. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  6411. /*
  6412. * Get Morph Target Index by Name
  6413. */
  6414. THREE.Mesh.prototype.getMorphTargetIndexByName = function( name ) {
  6415. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  6416. return this.morphTargetDictionary[ name ];
  6417. }
  6418. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  6419. return 0;
  6420. }
  6421. /**
  6422. * @author mikael emtinger / http://gomo.se/
  6423. * @author alteredq / http://alteredqualia.com/
  6424. */
  6425. THREE.Bone = function( belongsToSkin ) {
  6426. THREE.Object3D.call( this );
  6427. this.skin = belongsToSkin;
  6428. this.skinMatrix = new THREE.Matrix4();
  6429. };
  6430. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  6431. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  6432. // update local
  6433. if ( this.matrixAutoUpdate ) {
  6434. forceUpdate |= this.updateMatrix();
  6435. }
  6436. // update skin matrix
  6437. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  6438. if( parentSkinMatrix ) {
  6439. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  6440. } else {
  6441. this.skinMatrix.copy( this.matrix );
  6442. }
  6443. this.matrixWorldNeedsUpdate = false;
  6444. forceUpdate = true;
  6445. }
  6446. // update children
  6447. var child, i, l = this.children.length;
  6448. for ( i = 0; i < l; i ++ ) {
  6449. this.children[ i ].update( this.skinMatrix, forceUpdate );
  6450. }
  6451. };
  6452. /**
  6453. * @author mikael emtinger / http://gomo.se/
  6454. * @author alteredq / http://alteredqualia.com/
  6455. */
  6456. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  6457. THREE.Mesh.call( this, geometry, material );
  6458. //
  6459. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  6460. // init bones
  6461. this.identityMatrix = new THREE.Matrix4();
  6462. this.bones = [];
  6463. this.boneMatrices = [];
  6464. var b, bone, gbone, p, q, s;
  6465. if ( this.geometry.bones !== undefined ) {
  6466. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  6467. gbone = this.geometry.bones[ b ];
  6468. p = gbone.pos;
  6469. q = gbone.rotq;
  6470. s = gbone.scl;
  6471. bone = this.addBone();
  6472. bone.name = gbone.name;
  6473. bone.position.set( p[0], p[1], p[2] );
  6474. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  6475. bone.useQuaternion = true;
  6476. if ( s !== undefined ) {
  6477. bone.scale.set( s[0], s[1], s[2] );
  6478. } else {
  6479. bone.scale.set( 1, 1, 1 );
  6480. }
  6481. }
  6482. for ( b = 0; b < this.bones.length; b ++ ) {
  6483. gbone = this.geometry.bones[ b ];
  6484. bone = this.bones[ b ];
  6485. if ( gbone.parent === -1 ) {
  6486. this.add( bone );
  6487. } else {
  6488. this.bones[ gbone.parent ].add( bone );
  6489. }
  6490. }
  6491. //
  6492. var nBones = this.bones.length;
  6493. if ( this.useVertexTexture ) {
  6494. // layout (1 matrix = 4 pixels)
  6495. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  6496. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  6497. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  6498. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  6499. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  6500. var size;
  6501. if ( nBones > 256 )
  6502. size = 64;
  6503. else if ( nBones > 64 )
  6504. size = 32;
  6505. else if ( nBones > 16 )
  6506. size = 16;
  6507. else
  6508. size = 8;
  6509. this.boneTextureWidth = size;
  6510. this.boneTextureHeight = size;
  6511. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  6512. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  6513. this.boneTexture.minFilter = THREE.NearestFilter;
  6514. this.boneTexture.magFilter = THREE.NearestFilter;
  6515. this.boneTexture.generateMipmaps = false;
  6516. this.boneTexture.flipY = false;
  6517. } else {
  6518. this.boneMatrices = new Float32Array( 16 * nBones );
  6519. }
  6520. this.pose();
  6521. }
  6522. };
  6523. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  6524. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  6525. if ( bone === undefined ) {
  6526. bone = new THREE.Bone( this );
  6527. }
  6528. this.bones.push( bone );
  6529. return bone;
  6530. };
  6531. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  6532. this.matrixAutoUpdate && this.updateMatrix();
  6533. // update matrixWorld
  6534. if ( this.matrixWorldNeedsUpdate || force ) {
  6535. if ( this.parent ) {
  6536. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  6537. } else {
  6538. this.matrixWorld.copy( this.matrix );
  6539. }
  6540. this.matrixWorldNeedsUpdate = false;
  6541. force = true;
  6542. }
  6543. // update children
  6544. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6545. var child = this.children[ i ];
  6546. if ( child instanceof THREE.Bone ) {
  6547. child.update( this.identityMatrix, false );
  6548. } else {
  6549. child.updateMatrixWorld( true );
  6550. }
  6551. }
  6552. // flatten bone matrices to array
  6553. var b, bl = this.bones.length,
  6554. ba = this.bones,
  6555. bm = this.boneMatrices;
  6556. for ( b = 0; b < bl; b ++ ) {
  6557. ba[ b ].skinMatrix.flattenToArrayOffset( bm, b * 16 );
  6558. }
  6559. if ( this.useVertexTexture ) {
  6560. this.boneTexture.needsUpdate = true;
  6561. }
  6562. };
  6563. /*
  6564. * Pose
  6565. */
  6566. THREE.SkinnedMesh.prototype.pose = function() {
  6567. this.updateMatrixWorld( true );
  6568. var bim, bone, boneInverses = [];
  6569. for ( var b = 0; b < this.bones.length; b ++ ) {
  6570. bone = this.bones[ b ];
  6571. var inverseMatrix = new THREE.Matrix4();
  6572. inverseMatrix.getInverse( bone.skinMatrix );
  6573. boneInverses.push( inverseMatrix );
  6574. bone.skinMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  6575. }
  6576. // project vertices to local
  6577. if ( this.geometry.skinVerticesA === undefined ) {
  6578. this.geometry.skinVerticesA = [];
  6579. this.geometry.skinVerticesB = [];
  6580. var orgVertex, vertex;
  6581. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  6582. orgVertex = this.geometry.vertices[ i ];
  6583. var indexA = this.geometry.skinIndices[ i ].x;
  6584. var indexB = this.geometry.skinIndices[ i ].y;
  6585. vertex = new THREE.Vector3( orgVertex.x, orgVertex.y, orgVertex.z );
  6586. this.geometry.skinVerticesA.push( boneInverses[ indexA ].multiplyVector3( vertex ) );
  6587. vertex = new THREE.Vector3( orgVertex.x, orgVertex.y, orgVertex.z );
  6588. this.geometry.skinVerticesB.push( boneInverses[ indexB ].multiplyVector3( vertex ) );
  6589. // todo: add more influences
  6590. // normalize weights
  6591. if ( this.geometry.skinWeights[ i ].x + this.geometry.skinWeights[ i ].y !== 1 ) {
  6592. var len = ( 1.0 - ( this.geometry.skinWeights[ i ].x + this.geometry.skinWeights[ i ].y ) ) * 0.5;
  6593. this.geometry.skinWeights[ i ].x += len;
  6594. this.geometry.skinWeights[ i ].y += len;
  6595. }
  6596. }
  6597. }
  6598. };
  6599. /**
  6600. * @author alteredq / http://alteredqualia.com/
  6601. */
  6602. THREE.MorphAnimMesh = function ( geometry, material ) {
  6603. THREE.Mesh.call( this, geometry, material );
  6604. // API
  6605. this.duration = 1000; // milliseconds
  6606. this.mirroredLoop = false;
  6607. this.time = 0;
  6608. // internals
  6609. this.lastKeyframe = 0;
  6610. this.currentKeyframe = 0;
  6611. this.direction = 1;
  6612. this.directionBackwards = false;
  6613. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  6614. };
  6615. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  6616. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  6617. this.startKeyframe = start;
  6618. this.endKeyframe = end;
  6619. this.length = this.endKeyframe - this.startKeyframe + 1;
  6620. };
  6621. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  6622. this.direction = 1;
  6623. this.directionBackwards = false;
  6624. };
  6625. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  6626. this.direction = -1;
  6627. this.directionBackwards = true;
  6628. };
  6629. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  6630. var geometry = this.geometry;
  6631. if ( ! geometry.animations ) geometry.animations = {};
  6632. var firstAnimation, animations = geometry.animations;
  6633. var pattern = /([a-z]+)(\d+)/;
  6634. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  6635. var morph = geometry.morphTargets[ i ];
  6636. var parts = morph.name.match( pattern );
  6637. if ( parts && parts.length > 1 ) {
  6638. var label = parts[ 1 ];
  6639. var num = parts[ 2 ];
  6640. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  6641. var animation = animations[ label ];
  6642. if ( i < animation.start ) animation.start = i;
  6643. if ( i > animation.end ) animation.end = i;
  6644. if ( ! firstAnimation ) firstAnimation = label;
  6645. }
  6646. }
  6647. geometry.firstAnimation = firstAnimation;
  6648. };
  6649. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  6650. if ( ! this.geometry.animations ) this.geometry.animations = {};
  6651. this.geometry.animations[ label ] = { start: start, end: end };
  6652. };
  6653. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  6654. var animation = this.geometry.animations[ label ];
  6655. if ( animation ) {
  6656. this.setFrameRange( animation.start, animation.end );
  6657. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  6658. this.time = 0;
  6659. } else {
  6660. console.warn( "animation[" + label + "] undefined" );
  6661. }
  6662. };
  6663. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  6664. var frameTime = this.duration / this.length;
  6665. this.time += this.direction * delta;
  6666. if ( this.mirroredLoop ) {
  6667. if ( this.time > this.duration || this.time < 0 ) {
  6668. this.direction *= -1;
  6669. if ( this.time > this.duration ) {
  6670. this.time = this.duration;
  6671. this.directionBackwards = true;
  6672. }
  6673. if ( this.time < 0 ) {
  6674. this.time = 0;
  6675. this.directionBackwards = false;
  6676. }
  6677. }
  6678. } else {
  6679. this.time = this.time % this.duration;
  6680. if ( this.time < 0 ) this.time += this.duration;
  6681. }
  6682. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  6683. if ( keyframe !== this.currentKeyframe ) {
  6684. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  6685. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  6686. this.morphTargetInfluences[ keyframe ] = 0;
  6687. this.lastKeyframe = this.currentKeyframe;
  6688. this.currentKeyframe = keyframe;
  6689. }
  6690. var mix = ( this.time % frameTime ) / frameTime;
  6691. if ( this.directionBackwards ) {
  6692. mix = 1 - mix;
  6693. }
  6694. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  6695. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  6696. };
  6697. /**
  6698. * @author alteredq / http://alteredqualia.com/
  6699. */
  6700. THREE.Ribbon = function ( geometry, material ) {
  6701. THREE.Object3D.call( this );
  6702. this.geometry = geometry;
  6703. this.material = material;
  6704. };
  6705. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  6706. /**
  6707. * @author mikael emtinger / http://gomo.se/
  6708. * @author alteredq / http://alteredqualia.com/
  6709. * @author mrdoob / http://mrdoob.com/
  6710. */
  6711. THREE.LOD = function () {
  6712. THREE.Object3D.call( this );
  6713. this.LODs = [];
  6714. };
  6715. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  6716. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  6717. if ( visibleAtDistance === undefined ) {
  6718. visibleAtDistance = 0;
  6719. }
  6720. visibleAtDistance = Math.abs( visibleAtDistance );
  6721. for ( var l = 0; l < this.LODs.length; l ++ ) {
  6722. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  6723. break;
  6724. }
  6725. }
  6726. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  6727. this.add( object3D );
  6728. };
  6729. THREE.LOD.prototype.update = function ( camera ) {
  6730. if ( this.LODs.length > 1 ) {
  6731. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  6732. var inverse = camera.matrixWorldInverse;
  6733. 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] );
  6734. this.LODs[ 0 ].object3D.visible = true;
  6735. for ( var l = 1; l < this.LODs.length; l ++ ) {
  6736. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  6737. this.LODs[ l - 1 ].object3D.visible = false;
  6738. this.LODs[ l ].object3D.visible = true;
  6739. } else {
  6740. break;
  6741. }
  6742. }
  6743. for( ; l < this.LODs.length; l ++ ) {
  6744. this.LODs[ l ].object3D.visible = false;
  6745. }
  6746. }
  6747. };
  6748. /**
  6749. * @author mikael emtinger / http://gomo.se/
  6750. */
  6751. THREE.Sprite = function ( parameters ) {
  6752. THREE.Object3D.call( this );
  6753. this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  6754. this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();
  6755. this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;
  6756. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  6757. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  6758. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  6759. this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
  6760. this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
  6761. this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
  6762. this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
  6763. this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center;
  6764. this.rotation3d = this.rotation;
  6765. this.rotation = 0;
  6766. this.opacity = 1;
  6767. this.uvOffset = new THREE.Vector2( 0, 0 );
  6768. this.uvScale = new THREE.Vector2( 1, 1 );
  6769. };
  6770. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  6771. /*
  6772. * Custom update matrix
  6773. */
  6774. THREE.Sprite.prototype.updateMatrix = function () {
  6775. this.matrix.setPosition( this.position );
  6776. this.rotation3d.set( 0, 0, this.rotation );
  6777. this.matrix.setRotationFromEuler( this.rotation3d );
  6778. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  6779. this.matrix.scale( this.scale );
  6780. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  6781. }
  6782. this.matrixWorldNeedsUpdate = true;
  6783. };
  6784. /*
  6785. * Alignment
  6786. */
  6787. THREE.SpriteAlignment = {};
  6788. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  6789. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  6790. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  6791. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  6792. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  6793. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  6794. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  6795. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  6796. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  6797. /**
  6798. * @author mrdoob / http://mrdoob.com/
  6799. */
  6800. THREE.Scene = function () {
  6801. THREE.Object3D.call( this );
  6802. this.fog = null;
  6803. this.overrideMaterial = null;
  6804. this.matrixAutoUpdate = false;
  6805. this.__objects = [];
  6806. this.__lights = [];
  6807. this.__objectsAdded = [];
  6808. this.__objectsRemoved = [];
  6809. };
  6810. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  6811. THREE.Scene.prototype.__addObject = function ( object ) {
  6812. if ( object instanceof THREE.Light ) {
  6813. if ( this.__lights.indexOf( object ) === - 1 ) {
  6814. this.__lights.push( object );
  6815. }
  6816. if ( object.target && object.target.parent === undefined ) {
  6817. this.add( object.target );
  6818. }
  6819. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  6820. if ( this.__objects.indexOf( object ) === - 1 ) {
  6821. this.__objects.push( object );
  6822. this.__objectsAdded.push( object );
  6823. // check if previously removed
  6824. var i = this.__objectsRemoved.indexOf( object );
  6825. if ( i !== -1 ) {
  6826. this.__objectsRemoved.splice( i, 1 );
  6827. }
  6828. }
  6829. }
  6830. for ( var c = 0; c < object.children.length; c ++ ) {
  6831. this.__addObject( object.children[ c ] );
  6832. }
  6833. };
  6834. THREE.Scene.prototype.__removeObject = function ( object ) {
  6835. if ( object instanceof THREE.Light ) {
  6836. var i = this.__lights.indexOf( object );
  6837. if ( i !== -1 ) {
  6838. this.__lights.splice( i, 1 );
  6839. }
  6840. } else if ( !( object instanceof THREE.Camera ) ) {
  6841. var i = this.__objects.indexOf( object );
  6842. if( i !== -1 ) {
  6843. this.__objects.splice( i, 1 );
  6844. this.__objectsRemoved.push( object );
  6845. // check if previously added
  6846. var ai = this.__objectsAdded.indexOf( object );
  6847. if ( ai !== -1 ) {
  6848. this.__objectsAdded.splice( ai, 1 );
  6849. }
  6850. }
  6851. }
  6852. for ( var c = 0; c < object.children.length; c ++ ) {
  6853. this.__removeObject( object.children[ c ] );
  6854. }
  6855. };
  6856. /**
  6857. * @author mrdoob / http://mrdoob.com/
  6858. * @author alteredq / http://alteredqualia.com/
  6859. */
  6860. THREE.Fog = function ( hex, near, far ) {
  6861. this.color = new THREE.Color( hex );
  6862. this.near = ( near !== undefined ) ? near : 1;
  6863. this.far = ( far !== undefined ) ? far : 1000;
  6864. };
  6865. /**
  6866. * @author mrdoob / http://mrdoob.com/
  6867. * @author alteredq / http://alteredqualia.com/
  6868. */
  6869. THREE.FogExp2 = function ( hex, density ) {
  6870. this.color = new THREE.Color( hex );
  6871. this.density = ( density !== undefined ) ? density : 0.00025;
  6872. };
  6873. /**
  6874. * @author mrdoob / http://mrdoob.com/
  6875. */
  6876. THREE.CanvasRenderer = function ( parameters ) {
  6877. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  6878. parameters = parameters || {};
  6879. var _this = this,
  6880. _renderData, _elements, _lights,
  6881. _projector = new THREE.Projector(),
  6882. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  6883. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  6884. _context = _canvas.getContext( '2d' ),
  6885. _clearColor = new THREE.Color( 0x000000 ),
  6886. _clearOpacity = 0,
  6887. _contextGlobalAlpha = 1,
  6888. _contextGlobalCompositeOperation = 0,
  6889. _contextStrokeStyle = null,
  6890. _contextFillStyle = null,
  6891. _contextLineWidth = null,
  6892. _contextLineCap = null,
  6893. _contextLineJoin = null,
  6894. _v1, _v2, _v3, _v4,
  6895. _v5 = new THREE.RenderableVertex(),
  6896. _v6 = new THREE.RenderableVertex(),
  6897. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  6898. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  6899. _color = new THREE.Color(),
  6900. _color1 = new THREE.Color(),
  6901. _color2 = new THREE.Color(),
  6902. _color3 = new THREE.Color(),
  6903. _color4 = new THREE.Color(),
  6904. _patterns = [], _imagedatas = [],
  6905. _near, _far,
  6906. _image, _uvs,
  6907. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  6908. _clipRect = new THREE.Rectangle(),
  6909. _clearRect = new THREE.Rectangle(),
  6910. _bboxRect = new THREE.Rectangle(),
  6911. _enableLighting = false,
  6912. _ambientLight = new THREE.Color(),
  6913. _directionalLights = new THREE.Color(),
  6914. _pointLights = new THREE.Color(),
  6915. _pi2 = Math.PI * 2,
  6916. _vector3 = new THREE.Vector3(), // Needed for PointLight
  6917. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  6918. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  6919. _pixelMap = document.createElement( 'canvas' );
  6920. _pixelMap.width = _pixelMap.height = 2;
  6921. _pixelMapContext = _pixelMap.getContext( '2d' );
  6922. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  6923. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  6924. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  6925. _pixelMapData = _pixelMapImage.data;
  6926. _gradientMap = document.createElement( 'canvas' );
  6927. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  6928. _gradientMapContext = _gradientMap.getContext( '2d' );
  6929. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  6930. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  6931. _gradientMapQuality --; // Fix UVs
  6932. this.domElement = _canvas;
  6933. this.autoClear = true;
  6934. this.sortObjects = true;
  6935. this.sortElements = true;
  6936. this.info = {
  6937. render: {
  6938. vertices: 0,
  6939. faces: 0
  6940. }
  6941. }
  6942. this.setSize = function ( width, height ) {
  6943. _canvasWidth = width;
  6944. _canvasHeight = height;
  6945. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  6946. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  6947. _canvas.width = _canvasWidth;
  6948. _canvas.height = _canvasHeight;
  6949. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6950. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6951. _contextGlobalAlpha = 1;
  6952. _contextGlobalCompositeOperation = 0;
  6953. _contextStrokeStyle = null;
  6954. _contextFillStyle = null;
  6955. _contextLineWidth = null;
  6956. _contextLineCap = null;
  6957. _contextLineJoin = null;
  6958. };
  6959. this.setClearColor = function ( color, opacity ) {
  6960. _clearColor.copy( color );
  6961. _clearOpacity = opacity !== undefined ? opacity : 1;
  6962. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6963. };
  6964. this.setClearColorHex = function ( hex, opacity ) {
  6965. _clearColor.setHex( hex );
  6966. _clearOpacity = opacity !== undefined ? opacity : 1;
  6967. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6968. };
  6969. this.clear = function () {
  6970. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  6971. if ( _clearRect.isEmpty() === false ) {
  6972. _clearRect.minSelf( _clipRect );
  6973. _clearRect.inflate( 2 );
  6974. if ( _clearOpacity < 1 ) {
  6975. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  6976. }
  6977. if ( _clearOpacity > 0 ) {
  6978. setBlending( THREE.NormalBlending );
  6979. setOpacity( 1 );
  6980. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  6981. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  6982. }
  6983. _clearRect.empty();
  6984. }
  6985. };
  6986. this.render = function ( scene, camera ) {
  6987. if ( camera instanceof THREE.Camera === false ) {
  6988. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  6989. return;
  6990. }
  6991. var e, el, element, material;
  6992. this.autoClear === true ? this.clear() : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  6993. _this.info.render.vertices = 0;
  6994. _this.info.render.faces = 0;
  6995. _renderData = _projector.projectScene( scene, camera, this.sortElements );
  6996. _elements = _renderData.elements;
  6997. _lights = _renderData.lights;
  6998. /* DEBUG
  6999. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7000. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  7001. */
  7002. _enableLighting = _lights.length > 0;
  7003. if ( _enableLighting === true ) {
  7004. calculateLights( _lights );
  7005. }
  7006. for ( e = 0, el = _elements.length; e < el; e++ ) {
  7007. element = _elements[ e ];
  7008. material = element.material;
  7009. if ( material === undefined || material.visible === false ) continue;
  7010. _bboxRect.empty();
  7011. if ( element instanceof THREE.RenderableParticle ) {
  7012. _v1 = element;
  7013. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7014. renderParticle( _v1, element, material, scene );
  7015. } else if ( element instanceof THREE.RenderableLine ) {
  7016. _v1 = element.v1; _v2 = element.v2;
  7017. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7018. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7019. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7020. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7021. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7022. renderLine( _v1, _v2, element, material, scene );
  7023. }
  7024. } else if ( element instanceof THREE.RenderableFace3 ) {
  7025. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7026. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7027. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7028. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7029. if ( material.overdraw === true ) {
  7030. expand( _v1.positionScreen, _v2.positionScreen );
  7031. expand( _v2.positionScreen, _v3.positionScreen );
  7032. expand( _v3.positionScreen, _v1.positionScreen );
  7033. }
  7034. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  7035. _v2.positionScreen.x, _v2.positionScreen.y,
  7036. _v3.positionScreen.x, _v3.positionScreen.y );
  7037. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7038. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7039. }
  7040. } else if ( element instanceof THREE.RenderableFace4 ) {
  7041. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7042. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7043. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7044. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7045. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7046. _v5.positionScreen.copy( _v2.positionScreen );
  7047. _v6.positionScreen.copy( _v4.positionScreen );
  7048. if ( material.overdraw === true ) {
  7049. expand( _v1.positionScreen, _v2.positionScreen );
  7050. expand( _v2.positionScreen, _v4.positionScreen );
  7051. expand( _v4.positionScreen, _v1.positionScreen );
  7052. expand( _v3.positionScreen, _v5.positionScreen );
  7053. expand( _v3.positionScreen, _v6.positionScreen );
  7054. }
  7055. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7056. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7057. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  7058. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  7059. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7060. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  7061. }
  7062. }
  7063. /* DEBUG
  7064. _context.lineWidth = 1;
  7065. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  7066. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  7067. */
  7068. _clearRect.addRectangle( _bboxRect );
  7069. }
  7070. /* DEBUG
  7071. _context.lineWidth = 1;
  7072. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  7073. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  7074. */
  7075. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  7076. //
  7077. function calculateLights( lights ) {
  7078. var l, ll, light, lightColor;
  7079. _ambientLight.setRGB( 0, 0, 0 );
  7080. _directionalLights.setRGB( 0, 0, 0 );
  7081. _pointLights.setRGB( 0, 0, 0 );
  7082. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  7083. light = lights[ l ];
  7084. lightColor = light.color;
  7085. if ( light instanceof THREE.AmbientLight ) {
  7086. _ambientLight.r += lightColor.r;
  7087. _ambientLight.g += lightColor.g;
  7088. _ambientLight.b += lightColor.b;
  7089. } else if ( light instanceof THREE.DirectionalLight ) {
  7090. // for particles
  7091. _directionalLights.r += lightColor.r;
  7092. _directionalLights.g += lightColor.g;
  7093. _directionalLights.b += lightColor.b;
  7094. } else if ( light instanceof THREE.PointLight ) {
  7095. // for particles
  7096. _pointLights.r += lightColor.r;
  7097. _pointLights.g += lightColor.g;
  7098. _pointLights.b += lightColor.b;
  7099. }
  7100. }
  7101. }
  7102. function calculateLight( lights, position, normal, color ) {
  7103. var l, ll, light, lightColor, lightPosition, amount;
  7104. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  7105. light = lights[ l ];
  7106. lightColor = light.color;
  7107. if ( light instanceof THREE.DirectionalLight ) {
  7108. lightPosition = light.matrixWorld.getPosition().normalize();
  7109. amount = normal.dot( lightPosition );
  7110. if ( amount <= 0 ) continue;
  7111. amount *= light.intensity;
  7112. color.r += lightColor.r * amount;
  7113. color.g += lightColor.g * amount;
  7114. color.b += lightColor.b * amount;
  7115. } else if ( light instanceof THREE.PointLight ) {
  7116. lightPosition = light.matrixWorld.getPosition();
  7117. amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  7118. if ( amount <= 0 ) continue;
  7119. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  7120. if ( amount == 0 ) continue;
  7121. amount *= light.intensity;
  7122. color.r += lightColor.r * amount;
  7123. color.g += lightColor.g * amount;
  7124. color.b += lightColor.b * amount;
  7125. }
  7126. }
  7127. }
  7128. function renderParticle( v1, element, material, scene ) {
  7129. setOpacity( material.opacity );
  7130. setBlending( material.blending );
  7131. var width, height, scaleX, scaleY,
  7132. bitmap, bitmapWidth, bitmapHeight;
  7133. if ( material instanceof THREE.ParticleBasicMaterial ) {
  7134. if ( material.map === null ) {
  7135. scaleX = element.object.scale.x;
  7136. scaleY = element.object.scale.y;
  7137. // TODO: Be able to disable this
  7138. scaleX *= element.scale.x * _canvasWidthHalf;
  7139. scaleY *= element.scale.y * _canvasHeightHalf;
  7140. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  7141. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7142. return;
  7143. }
  7144. setFillStyle( material.color.getContextStyle() );
  7145. _context.save();
  7146. _context.translate( v1.x, v1.y );
  7147. _context.rotate( - element.rotation );
  7148. _context.scale( scaleX, scaleY );
  7149. _context.fillRect( -1, -1, 2, 2 );
  7150. _context.restore();
  7151. } else {
  7152. bitmap = material.map.image;
  7153. bitmapWidth = bitmap.width >> 1;
  7154. bitmapHeight = bitmap.height >> 1;
  7155. scaleX = element.scale.x * _canvasWidthHalf;
  7156. scaleY = element.scale.y * _canvasHeightHalf;
  7157. width = scaleX * bitmapWidth;
  7158. height = scaleY * bitmapHeight;
  7159. // TODO: Rotations break this...
  7160. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7161. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7162. return;
  7163. }
  7164. _context.save();
  7165. _context.translate( v1.x, v1.y );
  7166. _context.rotate( - element.rotation );
  7167. _context.scale( scaleX, - scaleY );
  7168. _context.translate( - bitmapWidth, - bitmapHeight );
  7169. _context.drawImage( bitmap, 0, 0 );
  7170. _context.restore();
  7171. }
  7172. /* DEBUG
  7173. setStrokeStyle( 'rgb(255,255,0)' );
  7174. _context.beginPath();
  7175. _context.moveTo( v1.x - 10, v1.y );
  7176. _context.lineTo( v1.x + 10, v1.y );
  7177. _context.moveTo( v1.x, v1.y - 10 );
  7178. _context.lineTo( v1.x, v1.y + 10 );
  7179. _context.stroke();
  7180. */
  7181. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  7182. width = element.scale.x * _canvasWidthHalf;
  7183. height = element.scale.y * _canvasHeightHalf;
  7184. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7185. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7186. return;
  7187. }
  7188. setStrokeStyle( material.color.getContextStyle() );
  7189. setFillStyle( material.color.getContextStyle() );
  7190. _context.save();
  7191. _context.translate( v1.x, v1.y );
  7192. _context.rotate( - element.rotation );
  7193. _context.scale( width, height );
  7194. material.program( _context );
  7195. _context.restore();
  7196. }
  7197. }
  7198. function renderLine( v1, v2, element, material, scene ) {
  7199. setOpacity( material.opacity );
  7200. setBlending( material.blending );
  7201. _context.beginPath();
  7202. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  7203. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  7204. _context.closePath();
  7205. if ( material instanceof THREE.LineBasicMaterial ) {
  7206. setLineWidth( material.linewidth );
  7207. setLineCap( material.linecap );
  7208. setLineJoin( material.linejoin );
  7209. setStrokeStyle( material.color.getContextStyle() );
  7210. _context.stroke();
  7211. _bboxRect.inflate( material.linewidth * 2 );
  7212. }
  7213. }
  7214. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  7215. _this.info.render.vertices += 3;
  7216. _this.info.render.faces ++;
  7217. setOpacity( material.opacity );
  7218. setBlending( material.blending );
  7219. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7220. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7221. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7222. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  7223. if ( material instanceof THREE.MeshBasicMaterial ) {
  7224. if ( material.map !== null ) {
  7225. if ( material.map.mapping instanceof THREE.UVMapping ) {
  7226. _uvs = element.uvs[ 0 ];
  7227. 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 );
  7228. }
  7229. } else if ( material.envMap !== null ) {
  7230. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  7231. var cameraMatrix = camera.matrixWorldInverse;
  7232. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  7233. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7234. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7235. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  7236. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7237. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7238. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  7239. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7240. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7241. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  7242. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  7243. }*/
  7244. } else {
  7245. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7246. }
  7247. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  7248. if ( _enableLighting === true ) {
  7249. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsWorld.length == 3 ) {
  7250. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  7251. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  7252. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  7253. calculateLight( _lights, element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7254. calculateLight( _lights, element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7255. calculateLight( _lights, element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  7256. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  7257. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  7258. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  7259. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  7260. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  7261. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  7262. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  7263. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  7264. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  7265. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7266. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7267. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7268. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7269. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7270. } else {
  7271. _color.r = _ambientLight.r;
  7272. _color.g = _ambientLight.g;
  7273. _color.b = _ambientLight.b;
  7274. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  7275. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  7276. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  7277. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  7278. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7279. }
  7280. } else {
  7281. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7282. }
  7283. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7284. _near = camera.near;
  7285. _far = camera.far;
  7286. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7287. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7288. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7289. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7290. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7291. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7292. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7293. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7294. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7295. _color.r = normalToComponent( element.normalWorld.x );
  7296. _color.g = normalToComponent( element.normalWorld.y );
  7297. _color.b = normalToComponent( element.normalWorld.z );
  7298. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7299. }
  7300. }
  7301. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  7302. _this.info.render.vertices += 4;
  7303. _this.info.render.faces ++;
  7304. setOpacity( material.opacity );
  7305. setBlending( material.blending );
  7306. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  7307. // Let renderFace3() handle this
  7308. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  7309. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  7310. return;
  7311. }
  7312. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7313. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7314. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7315. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  7316. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  7317. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  7318. if ( material instanceof THREE.MeshBasicMaterial ) {
  7319. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7320. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7321. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  7322. if ( _enableLighting === true ) {
  7323. if ( !material.wireframe && material.shading == THREE.SmoothShading && element.vertexNormalsWorld.length == 4 ) {
  7324. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  7325. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  7326. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  7327. calculateLight( _lights, element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7328. calculateLight( _lights, element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7329. calculateLight( _lights, element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  7330. calculateLight( _lights, element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  7331. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  7332. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  7333. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  7334. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  7335. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  7336. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  7337. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  7338. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  7339. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  7340. _color4.r = Math.max( 0, Math.min( material.color.r * _color4.r, 1 ) );
  7341. _color4.g = Math.max( 0, Math.min( material.color.g * _color4.g, 1 ) );
  7342. _color4.b = Math.max( 0, Math.min( material.color.b * _color4.b, 1 ) );
  7343. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7344. // TODO: UVs are incorrect, v4->v3?
  7345. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7346. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7347. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7348. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7349. } else {
  7350. _color.r = _ambientLight.r;
  7351. _color.g = _ambientLight.g;
  7352. _color.b = _ambientLight.b;
  7353. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  7354. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  7355. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  7356. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  7357. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7358. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7359. }
  7360. } else {
  7361. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7362. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7363. }
  7364. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7365. _color.r = normalToComponent( element.normalWorld.x );
  7366. _color.g = normalToComponent( element.normalWorld.y );
  7367. _color.b = normalToComponent( element.normalWorld.z );
  7368. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7369. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7370. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7371. _near = camera.near;
  7372. _far = camera.far;
  7373. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7374. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7375. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  7376. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7377. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7378. // TODO: UVs are incorrect, v4->v3?
  7379. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7380. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7381. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7382. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7383. }
  7384. }
  7385. //
  7386. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  7387. _context.beginPath();
  7388. _context.moveTo( x0, y0 );
  7389. _context.lineTo( x1, y1 );
  7390. _context.lineTo( x2, y2 );
  7391. _context.lineTo( x0, y0 );
  7392. }
  7393. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  7394. _context.beginPath();
  7395. _context.moveTo( x0, y0 );
  7396. _context.lineTo( x1, y1 );
  7397. _context.lineTo( x2, y2 );
  7398. _context.lineTo( x3, y3 );
  7399. _context.lineTo( x0, y0 );
  7400. }
  7401. function strokePath( color, linewidth, linecap, linejoin ) {
  7402. setLineWidth( linewidth );
  7403. setLineCap( linecap );
  7404. setLineJoin( linejoin );
  7405. setStrokeStyle( color.getContextStyle() );
  7406. _context.stroke();
  7407. _bboxRect.inflate( linewidth * 2 );
  7408. }
  7409. function fillPath( color ) {
  7410. setFillStyle( color.getContextStyle() );
  7411. _context.fill();
  7412. }
  7413. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  7414. if ( texture.image === undefined || texture.image.width === 0 ) return;
  7415. if ( texture.needsUpdate === true || _patterns[ texture.id ] === undefined ) {
  7416. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  7417. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  7418. _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' );
  7419. texture.needsUpdate = false;
  7420. }
  7421. setFillStyle( _patterns[ texture.id ] );
  7422. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7423. var a, b, c, d, e, f, det, idet,
  7424. offsetX = texture.offset.x / texture.repeat.x,
  7425. offsetY = texture.offset.y / texture.repeat.y,
  7426. width = texture.image.width * texture.repeat.x,
  7427. height = texture.image.height * texture.repeat.y;
  7428. u0 = ( u0 + offsetX ) * width;
  7429. v0 = ( 1.0 - v0 + offsetY ) * height;
  7430. u1 = ( u1 + offsetX ) * width;
  7431. v1 = ( 1.0 - v1 + offsetY ) * height;
  7432. u2 = ( u2 + offsetX ) * width;
  7433. v2 = ( 1.0 - v2 + offsetY ) * height;
  7434. x1 -= x0; y1 -= y0;
  7435. x2 -= x0; y2 -= y0;
  7436. u1 -= u0; v1 -= v0;
  7437. u2 -= u0; v2 -= v0;
  7438. det = u1 * v2 - u2 * v1;
  7439. if ( det === 0 ) {
  7440. if ( _imagedatas[ texture.id ] === undefined ) {
  7441. var canvas = document.createElement( 'canvas' )
  7442. canvas.width = texture.image.width;
  7443. canvas.height = texture.image.height;
  7444. var context = canvas.getContext( '2d' );
  7445. context.drawImage( texture.image, 0, 0 );
  7446. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  7447. // variables cannot be deleted in ES5 strict mode
  7448. //delete canvas;
  7449. }
  7450. var data = _imagedatas[ texture.id ];
  7451. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  7452. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  7453. fillPath( _color );
  7454. return;
  7455. }
  7456. idet = 1 / det;
  7457. a = ( v2 * x1 - v1 * x2 ) * idet;
  7458. b = ( v2 * y1 - v1 * y2 ) * idet;
  7459. c = ( u1 * x2 - u2 * x1 ) * idet;
  7460. d = ( u1 * y2 - u2 * y1 ) * idet;
  7461. e = x0 - a * u0 - c * v0;
  7462. f = y0 - b * u0 - d * v0;
  7463. _context.save();
  7464. _context.transform( a, b, c, d, e, f );
  7465. _context.fill();
  7466. _context.restore();
  7467. }
  7468. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  7469. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7470. var a, b, c, d, e, f, det, idet,
  7471. width = image.width - 1,
  7472. height = image.height - 1;
  7473. u0 *= width; v0 *= height;
  7474. u1 *= width; v1 *= height;
  7475. u2 *= width; v2 *= height;
  7476. x1 -= x0; y1 -= y0;
  7477. x2 -= x0; y2 -= y0;
  7478. u1 -= u0; v1 -= v0;
  7479. u2 -= u0; v2 -= v0;
  7480. det = u1 * v2 - u2 * v1;
  7481. idet = 1 / det;
  7482. a = ( v2 * x1 - v1 * x2 ) * idet;
  7483. b = ( v2 * y1 - v1 * y2 ) * idet;
  7484. c = ( u1 * x2 - u2 * x1 ) * idet;
  7485. d = ( u1 * y2 - u2 * y1 ) * idet;
  7486. e = x0 - a * u0 - c * v0;
  7487. f = y0 - b * u0 - d * v0;
  7488. _context.save();
  7489. _context.transform( a, b, c, d, e, f );
  7490. _context.clip();
  7491. _context.drawImage( image, 0, 0 );
  7492. _context.restore();
  7493. }
  7494. function getGradientTexture( color1, color2, color3, color4 ) {
  7495. // http://mrdoob.com/blog/post/710
  7496. var c1r = ~~ ( color1.r * 255 ), c1g = ~~ ( color1.g * 255 ), c1b = ~~ ( color1.b * 255 ),
  7497. c2r = ~~ ( color2.r * 255 ), c2g = ~~ ( color2.g * 255 ), c2b = ~~ ( color2.b * 255 ),
  7498. c3r = ~~ ( color3.r * 255 ), c3g = ~~ ( color3.g * 255 ), c3b = ~~ ( color3.b * 255 ),
  7499. c4r = ~~ ( color4.r * 255 ), c4g = ~~ ( color4.g * 255 ), c4b = ~~ ( color4.b * 255 );
  7500. _pixelMapData[ 0 ] = c1r < 0 ? 0 : c1r > 255 ? 255 : c1r;
  7501. _pixelMapData[ 1 ] = c1g < 0 ? 0 : c1g > 255 ? 255 : c1g;
  7502. _pixelMapData[ 2 ] = c1b < 0 ? 0 : c1b > 255 ? 255 : c1b;
  7503. _pixelMapData[ 4 ] = c2r < 0 ? 0 : c2r > 255 ? 255 : c2r;
  7504. _pixelMapData[ 5 ] = c2g < 0 ? 0 : c2g > 255 ? 255 : c2g;
  7505. _pixelMapData[ 6 ] = c2b < 0 ? 0 : c2b > 255 ? 255 : c2b;
  7506. _pixelMapData[ 8 ] = c3r < 0 ? 0 : c3r > 255 ? 255 : c3r;
  7507. _pixelMapData[ 9 ] = c3g < 0 ? 0 : c3g > 255 ? 255 : c3g;
  7508. _pixelMapData[ 10 ] = c3b < 0 ? 0 : c3b > 255 ? 255 : c3b;
  7509. _pixelMapData[ 12 ] = c4r < 0 ? 0 : c4r > 255 ? 255 : c4r;
  7510. _pixelMapData[ 13 ] = c4g < 0 ? 0 : c4g > 255 ? 255 : c4g;
  7511. _pixelMapData[ 14 ] = c4b < 0 ? 0 : c4b > 255 ? 255 : c4b;
  7512. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  7513. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  7514. return _gradientMap;
  7515. }
  7516. function smoothstep( value, min, max ) {
  7517. var x = ( value - min ) / ( max - min );
  7518. return x * x * ( 3 - 2 * x );
  7519. }
  7520. function normalToComponent( normal ) {
  7521. var component = ( normal + 1 ) * 0.5;
  7522. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  7523. }
  7524. // Hide anti-alias gaps
  7525. function expand( v1, v2 ) {
  7526. var x = v2.x - v1.x, y = v2.y - v1.y,
  7527. det = x * x + y * y, idet;
  7528. if ( det === 0 ) return;
  7529. idet = 1 / Math.sqrt( det );
  7530. x *= idet; y *= idet;
  7531. v2.x += x; v2.y += y;
  7532. v1.x -= x; v1.y -= y;
  7533. }
  7534. };
  7535. // Context cached methods.
  7536. function setOpacity( value ) {
  7537. if ( _contextGlobalAlpha !== value ) {
  7538. _context.globalAlpha = value;
  7539. _contextGlobalAlpha = value;
  7540. }
  7541. }
  7542. function setBlending( value ) {
  7543. if ( _contextGlobalCompositeOperation !== value ) {
  7544. if ( value === THREE.NormalBlending ) {
  7545. _context.globalCompositeOperation = 'source-over';
  7546. } else if ( value === THREE.AdditiveBlending ) {
  7547. _context.globalCompositeOperation = 'lighter';
  7548. } else if ( value === THREE.SubtractiveBlending ) {
  7549. _context.globalCompositeOperation = 'darker';
  7550. }
  7551. _contextGlobalCompositeOperation = value;
  7552. }
  7553. }
  7554. function setLineWidth( value ) {
  7555. if ( _contextLineWidth !== value ) {
  7556. _context.lineWidth = value;
  7557. _contextLineWidth = value;
  7558. }
  7559. }
  7560. function setLineCap( value ) {
  7561. // "butt", "round", "square"
  7562. if ( _contextLineCap !== value ) {
  7563. _context.lineCap = value;
  7564. _contextLineCap = value;
  7565. }
  7566. }
  7567. function setLineJoin( value ) {
  7568. // "round", "bevel", "miter"
  7569. if ( _contextLineJoin !== value ) {
  7570. _context.lineJoin = value;
  7571. _contextLineJoin = value;
  7572. }
  7573. }
  7574. function setStrokeStyle( value ) {
  7575. if ( _contextStrokeStyle !== value ) {
  7576. _context.strokeStyle = value;
  7577. _contextStrokeStyle = value;
  7578. }
  7579. }
  7580. function setFillStyle( value ) {
  7581. if ( _contextFillStyle !== value ) {
  7582. _context.fillStyle = value;
  7583. _contextFillStyle = value;
  7584. }
  7585. }
  7586. };
  7587. /**
  7588. * @author alteredq / http://alteredqualia.com/
  7589. * @author mrdoob / http://mrdoob.com/
  7590. * @author mikael emtinger / http://gomo.se/
  7591. */
  7592. THREE.ShaderChunk = {
  7593. // FOG
  7594. fog_pars_fragment: [
  7595. "#ifdef USE_FOG",
  7596. "uniform vec3 fogColor;",
  7597. "#ifdef FOG_EXP2",
  7598. "uniform float fogDensity;",
  7599. "#else",
  7600. "uniform float fogNear;",
  7601. "uniform float fogFar;",
  7602. "#endif",
  7603. "#endif"
  7604. ].join("\n"),
  7605. fog_fragment: [
  7606. "#ifdef USE_FOG",
  7607. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  7608. "#ifdef FOG_EXP2",
  7609. "const float LOG2 = 1.442695;",
  7610. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  7611. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  7612. "#else",
  7613. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  7614. "#endif",
  7615. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  7616. "#endif"
  7617. ].join("\n"),
  7618. // ENVIRONMENT MAP
  7619. envmap_pars_fragment: [
  7620. "#ifdef USE_ENVMAP",
  7621. "uniform float reflectivity;",
  7622. "uniform samplerCube envMap;",
  7623. "uniform float flipEnvMap;",
  7624. "uniform int combine;",
  7625. "#ifdef USE_BUMPMAP",
  7626. "uniform bool useRefract;",
  7627. "uniform float refractionRatio;",
  7628. "#else",
  7629. "varying vec3 vReflect;",
  7630. "#endif",
  7631. "#endif"
  7632. ].join("\n"),
  7633. envmap_fragment: [
  7634. "#ifdef USE_ENVMAP",
  7635. "vec3 reflectVec;",
  7636. "#ifdef USE_BUMPMAP",
  7637. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  7638. "if ( useRefract ) {",
  7639. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  7640. "} else { ",
  7641. "reflectVec = reflect( cameraToVertex, normal );",
  7642. "}",
  7643. "#else",
  7644. "reflectVec = vReflect;",
  7645. "#endif",
  7646. "#ifdef DOUBLE_SIDED",
  7647. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  7648. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  7649. "#else",
  7650. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  7651. "#endif",
  7652. "#ifdef GAMMA_INPUT",
  7653. "cubeColor.xyz *= cubeColor.xyz;",
  7654. "#endif",
  7655. "if ( combine == 1 ) {",
  7656. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  7657. "} else {",
  7658. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  7659. "}",
  7660. "#endif"
  7661. ].join("\n"),
  7662. envmap_pars_vertex: [
  7663. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP )",
  7664. "varying vec3 vReflect;",
  7665. "uniform float refractionRatio;",
  7666. "uniform bool useRefract;",
  7667. "#endif"
  7668. ].join("\n"),
  7669. envmap_vertex : [
  7670. "#ifdef USE_ENVMAP",
  7671. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  7672. "#endif",
  7673. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP )",
  7674. "vec3 nWorld = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * normal;",
  7675. "if ( useRefract ) {",
  7676. "vReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refractionRatio );",
  7677. "} else {",
  7678. "vReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );",
  7679. "}",
  7680. "#endif"
  7681. ].join("\n"),
  7682. // COLOR MAP (particles)
  7683. map_particle_pars_fragment: [
  7684. "#ifdef USE_MAP",
  7685. "uniform sampler2D map;",
  7686. "#endif"
  7687. ].join("\n"),
  7688. map_particle_fragment: [
  7689. "#ifdef USE_MAP",
  7690. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  7691. "#endif"
  7692. ].join("\n"),
  7693. // COLOR MAP (triangles)
  7694. map_pars_vertex: [
  7695. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_SPECULARMAP )",
  7696. "varying vec2 vUv;",
  7697. "uniform vec4 offsetRepeat;",
  7698. "#endif"
  7699. ].join("\n"),
  7700. map_pars_fragment: [
  7701. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_SPECULARMAP )",
  7702. "varying vec2 vUv;",
  7703. "#endif",
  7704. "#ifdef USE_MAP",
  7705. "uniform sampler2D map;",
  7706. "#endif",
  7707. ].join("\n"),
  7708. map_vertex: [
  7709. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_SPECULARMAP )",
  7710. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  7711. "#endif"
  7712. ].join("\n"),
  7713. map_fragment: [
  7714. "#ifdef USE_MAP",
  7715. "#ifdef GAMMA_INPUT",
  7716. "vec4 texelColor = texture2D( map, vUv );",
  7717. "texelColor.xyz *= texelColor.xyz;",
  7718. "gl_FragColor = gl_FragColor * texelColor;",
  7719. "#else",
  7720. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  7721. "#endif",
  7722. "#endif"
  7723. ].join("\n"),
  7724. // LIGHT MAP
  7725. lightmap_pars_fragment: [
  7726. "#ifdef USE_LIGHTMAP",
  7727. "varying vec2 vUv2;",
  7728. "uniform sampler2D lightMap;",
  7729. "#endif"
  7730. ].join("\n"),
  7731. lightmap_pars_vertex: [
  7732. "#ifdef USE_LIGHTMAP",
  7733. "varying vec2 vUv2;",
  7734. "#endif"
  7735. ].join("\n"),
  7736. lightmap_fragment: [
  7737. "#ifdef USE_LIGHTMAP",
  7738. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  7739. "#endif"
  7740. ].join("\n"),
  7741. lightmap_vertex: [
  7742. "#ifdef USE_LIGHTMAP",
  7743. "vUv2 = uv2;",
  7744. "#endif"
  7745. ].join("\n"),
  7746. // BUMP MAP
  7747. bumpmap_pars_fragment: [
  7748. "#ifdef USE_BUMPMAP",
  7749. "uniform sampler2D bumpMap;",
  7750. "uniform float bumpScale;",
  7751. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  7752. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  7753. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  7754. "vec2 dHdxy_fwd() {",
  7755. "vec2 dSTdx = dFdx( vUv );",
  7756. "vec2 dSTdy = dFdy( vUv );",
  7757. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  7758. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  7759. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  7760. "return vec2( dBx, dBy );",
  7761. "}",
  7762. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  7763. "vec3 vSigmaX = dFdx( surf_pos );",
  7764. "vec3 vSigmaY = dFdy( surf_pos );",
  7765. "vec3 vN = surf_norm;", // normalized
  7766. "vec3 R1 = cross( vSigmaY, vN );",
  7767. "vec3 R2 = cross( vN, vSigmaX );",
  7768. "float fDet = dot( vSigmaX, R1 );",
  7769. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  7770. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  7771. "}",
  7772. "#endif"
  7773. ].join("\n"),
  7774. // SPECULAR MAP
  7775. specularmap_pars_fragment: [
  7776. "#ifdef USE_SPECULARMAP",
  7777. "uniform sampler2D specularMap;",
  7778. "#endif"
  7779. ].join("\n"),
  7780. specularmap_fragment: [
  7781. "float specularStrength;",
  7782. "#ifdef USE_SPECULARMAP",
  7783. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  7784. "specularStrength = texelSpecular.r;",
  7785. "#else",
  7786. "specularStrength = 1.0;",
  7787. "#endif"
  7788. ].join("\n"),
  7789. // LIGHTS LAMBERT
  7790. lights_lambert_pars_vertex: [
  7791. "uniform vec3 ambient;",
  7792. "uniform vec3 diffuse;",
  7793. "uniform vec3 emissive;",
  7794. "uniform vec3 ambientLightColor;",
  7795. "#if MAX_DIR_LIGHTS > 0",
  7796. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  7797. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  7798. "#endif",
  7799. "#if MAX_POINT_LIGHTS > 0",
  7800. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  7801. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  7802. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  7803. "#endif",
  7804. "#if MAX_SPOT_LIGHTS > 0",
  7805. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  7806. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  7807. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  7808. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  7809. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  7810. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  7811. "#endif",
  7812. "#ifdef WRAP_AROUND",
  7813. "uniform vec3 wrapRGB;",
  7814. "#endif"
  7815. ].join("\n"),
  7816. lights_lambert_vertex: [
  7817. "vLightFront = vec3( 0.0 );",
  7818. "#ifdef DOUBLE_SIDED",
  7819. "vLightBack = vec3( 0.0 );",
  7820. "#endif",
  7821. "transformedNormal = normalize( transformedNormal );",
  7822. "#if MAX_DIR_LIGHTS > 0",
  7823. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  7824. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  7825. "vec3 dirVector = normalize( lDirection.xyz );",
  7826. "float dotProduct = dot( transformedNormal, dirVector );",
  7827. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  7828. "#ifdef DOUBLE_SIDED",
  7829. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  7830. "#ifdef WRAP_AROUND",
  7831. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  7832. "#endif",
  7833. "#endif",
  7834. "#ifdef WRAP_AROUND",
  7835. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  7836. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  7837. "#ifdef DOUBLE_SIDED",
  7838. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  7839. "#endif",
  7840. "#endif",
  7841. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  7842. "#ifdef DOUBLE_SIDED",
  7843. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  7844. "#endif",
  7845. "}",
  7846. "#endif",
  7847. "#if MAX_POINT_LIGHTS > 0",
  7848. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  7849. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  7850. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7851. "float lDistance = 1.0;",
  7852. "if ( pointLightDistance[ i ] > 0.0 )",
  7853. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  7854. "lVector = normalize( lVector );",
  7855. "float dotProduct = dot( transformedNormal, lVector );",
  7856. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  7857. "#ifdef DOUBLE_SIDED",
  7858. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  7859. "#ifdef WRAP_AROUND",
  7860. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  7861. "#endif",
  7862. "#endif",
  7863. "#ifdef WRAP_AROUND",
  7864. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  7865. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  7866. "#ifdef DOUBLE_SIDED",
  7867. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  7868. "#endif",
  7869. "#endif",
  7870. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  7871. "#ifdef DOUBLE_SIDED",
  7872. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  7873. "#endif",
  7874. "}",
  7875. "#endif",
  7876. "#if MAX_SPOT_LIGHTS > 0",
  7877. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  7878. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  7879. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7880. "lVector = normalize( lVector );",
  7881. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - mPosition.xyz ) );",
  7882. "if ( spotEffect > spotLightAngle[ i ] ) {",
  7883. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  7884. "float lDistance = 1.0;",
  7885. "if ( spotLightDistance[ i ] > 0.0 )",
  7886. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  7887. "float dotProduct = dot( transformedNormal, lVector );",
  7888. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  7889. "#ifdef DOUBLE_SIDED",
  7890. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  7891. "#ifdef WRAP_AROUND",
  7892. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  7893. "#endif",
  7894. "#endif",
  7895. "#ifdef WRAP_AROUND",
  7896. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  7897. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  7898. "#ifdef DOUBLE_SIDED",
  7899. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  7900. "#endif",
  7901. "#endif",
  7902. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  7903. "#ifdef DOUBLE_SIDED",
  7904. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  7905. "#endif",
  7906. "}",
  7907. "}",
  7908. "#endif",
  7909. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  7910. "#ifdef DOUBLE_SIDED",
  7911. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  7912. "#endif"
  7913. ].join("\n"),
  7914. // LIGHTS PHONG
  7915. lights_phong_pars_vertex: [
  7916. "#ifndef PHONG_PER_PIXEL",
  7917. "#if MAX_POINT_LIGHTS > 0",
  7918. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  7919. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  7920. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  7921. "#endif",
  7922. "#if MAX_SPOT_LIGHTS > 0",
  7923. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  7924. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  7925. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  7926. "#endif",
  7927. "#endif",
  7928. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  7929. "varying vec3 vWorldPosition;",
  7930. "#endif"
  7931. ].join("\n"),
  7932. lights_phong_vertex: [
  7933. "#ifndef PHONG_PER_PIXEL",
  7934. "#if MAX_POINT_LIGHTS > 0",
  7935. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  7936. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  7937. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7938. "float lDistance = 1.0;",
  7939. "if ( pointLightDistance[ i ] > 0.0 )",
  7940. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  7941. "vPointLight[ i ] = vec4( lVector, lDistance );",
  7942. "}",
  7943. "#endif",
  7944. "#if MAX_SPOT_LIGHTS > 0",
  7945. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  7946. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  7947. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7948. "float lDistance = 1.0;",
  7949. "if ( spotLightDistance[ i ] > 0.0 )",
  7950. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  7951. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  7952. "}",
  7953. "#endif",
  7954. "#endif",
  7955. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  7956. "vWorldPosition = mPosition.xyz;",
  7957. "#endif"
  7958. ].join("\n"),
  7959. lights_phong_pars_fragment: [
  7960. "uniform vec3 ambientLightColor;",
  7961. "#if MAX_DIR_LIGHTS > 0",
  7962. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  7963. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  7964. "#endif",
  7965. "#if MAX_POINT_LIGHTS > 0",
  7966. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  7967. "#ifdef PHONG_PER_PIXEL",
  7968. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  7969. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  7970. "#else",
  7971. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  7972. "#endif",
  7973. "#endif",
  7974. "#if MAX_SPOT_LIGHTS > 0",
  7975. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  7976. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  7977. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  7978. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  7979. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  7980. "#ifdef PHONG_PER_PIXEL",
  7981. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  7982. "#else",
  7983. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  7984. "#endif",
  7985. "#endif",
  7986. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  7987. "varying vec3 vWorldPosition;",
  7988. "#endif",
  7989. "#ifdef WRAP_AROUND",
  7990. "uniform vec3 wrapRGB;",
  7991. "#endif",
  7992. "varying vec3 vViewPosition;",
  7993. "varying vec3 vNormal;"
  7994. ].join("\n"),
  7995. lights_phong_fragment: [
  7996. "vec3 normal = normalize( vNormal );",
  7997. "vec3 viewPosition = normalize( vViewPosition );",
  7998. "#ifdef DOUBLE_SIDED",
  7999. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8000. "#endif",
  8001. "#ifdef USE_BUMPMAP",
  8002. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  8003. "#endif",
  8004. "#if MAX_POINT_LIGHTS > 0",
  8005. "vec3 pointDiffuse = vec3( 0.0 );",
  8006. "vec3 pointSpecular = vec3( 0.0 );",
  8007. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8008. "#ifdef PHONG_PER_PIXEL",
  8009. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8010. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8011. "float lDistance = 1.0;",
  8012. "if ( pointLightDistance[ i ] > 0.0 )",
  8013. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8014. "lVector = normalize( lVector );",
  8015. "#else",
  8016. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  8017. "float lDistance = vPointLight[ i ].w;",
  8018. "#endif",
  8019. // diffuse
  8020. "float dotProduct = dot( normal, lVector );",
  8021. "#ifdef WRAP_AROUND",
  8022. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  8023. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8024. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  8025. "#else",
  8026. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  8027. "#endif",
  8028. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  8029. // specular
  8030. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  8031. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  8032. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  8033. "#ifdef PHYSICALLY_BASED_SHADING",
  8034. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8035. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8036. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  8037. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  8038. "#else",
  8039. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  8040. "#endif",
  8041. "}",
  8042. "#endif",
  8043. "#if MAX_SPOT_LIGHTS > 0",
  8044. "vec3 spotDiffuse = vec3( 0.0 );",
  8045. "vec3 spotSpecular = vec3( 0.0 );",
  8046. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8047. "#ifdef PHONG_PER_PIXEL",
  8048. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8049. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8050. "float lDistance = 1.0;",
  8051. "if ( spotLightDistance[ i ] > 0.0 )",
  8052. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8053. "lVector = normalize( lVector );",
  8054. "#else",
  8055. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  8056. "float lDistance = vSpotLight[ i ].w;",
  8057. "#endif",
  8058. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  8059. "if ( spotEffect > spotLightAngle[ i ] ) {",
  8060. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  8061. // diffuse
  8062. "float dotProduct = dot( normal, lVector );",
  8063. "#ifdef WRAP_AROUND",
  8064. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  8065. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8066. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  8067. "#else",
  8068. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  8069. "#endif",
  8070. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  8071. // specular
  8072. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  8073. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  8074. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  8075. "#ifdef PHYSICALLY_BASED_SHADING",
  8076. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8077. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8078. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  8079. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  8080. "#else",
  8081. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  8082. "#endif",
  8083. "}",
  8084. "}",
  8085. "#endif",
  8086. "#if MAX_DIR_LIGHTS > 0",
  8087. "vec3 dirDiffuse = vec3( 0.0 );",
  8088. "vec3 dirSpecular = vec3( 0.0 );" ,
  8089. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8090. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8091. "vec3 dirVector = normalize( lDirection.xyz );",
  8092. // diffuse
  8093. "float dotProduct = dot( normal, dirVector );",
  8094. "#ifdef WRAP_AROUND",
  8095. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  8096. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8097. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  8098. "#else",
  8099. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  8100. "#endif",
  8101. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  8102. // specular
  8103. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  8104. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  8105. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  8106. "#ifdef PHYSICALLY_BASED_SHADING",
  8107. /*
  8108. // fresnel term from skin shader
  8109. "const float F0 = 0.128;",
  8110. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  8111. "float exponential = pow( base, 5.0 );",
  8112. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  8113. */
  8114. /*
  8115. // fresnel term from fresnel shader
  8116. "const float mFresnelBias = 0.08;",
  8117. "const float mFresnelScale = 0.3;",
  8118. "const float mFresnelPower = 5.0;",
  8119. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  8120. */
  8121. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8122. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8123. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  8124. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  8125. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  8126. "#else",
  8127. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  8128. "#endif",
  8129. "}",
  8130. "#endif",
  8131. "vec3 totalDiffuse = vec3( 0.0 );",
  8132. "vec3 totalSpecular = vec3( 0.0 );",
  8133. "#if MAX_DIR_LIGHTS > 0",
  8134. "totalDiffuse += dirDiffuse;",
  8135. "totalSpecular += dirSpecular;",
  8136. "#endif",
  8137. "#if MAX_POINT_LIGHTS > 0",
  8138. "totalDiffuse += pointDiffuse;",
  8139. "totalSpecular += pointSpecular;",
  8140. "#endif",
  8141. "#if MAX_SPOT_LIGHTS > 0",
  8142. "totalDiffuse += spotDiffuse;",
  8143. "totalSpecular += spotSpecular;",
  8144. "#endif",
  8145. "#ifdef METAL",
  8146. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  8147. "#else",
  8148. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  8149. "#endif"
  8150. ].join("\n"),
  8151. // VERTEX COLORS
  8152. color_pars_fragment: [
  8153. "#ifdef USE_COLOR",
  8154. "varying vec3 vColor;",
  8155. "#endif"
  8156. ].join("\n"),
  8157. color_fragment: [
  8158. "#ifdef USE_COLOR",
  8159. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  8160. "#endif"
  8161. ].join("\n"),
  8162. color_pars_vertex: [
  8163. "#ifdef USE_COLOR",
  8164. "varying vec3 vColor;",
  8165. "#endif"
  8166. ].join("\n"),
  8167. color_vertex: [
  8168. "#ifdef USE_COLOR",
  8169. "#ifdef GAMMA_INPUT",
  8170. "vColor = color * color;",
  8171. "#else",
  8172. "vColor = color;",
  8173. "#endif",
  8174. "#endif"
  8175. ].join("\n"),
  8176. // SKINNING
  8177. skinning_pars_vertex: [
  8178. "#ifdef USE_SKINNING",
  8179. "#ifdef BONE_TEXTURE",
  8180. "uniform sampler2D boneTexture;",
  8181. "mat4 getBoneMatrix( const in float i ) {",
  8182. "float j = i * 4.0;",
  8183. "float x = mod( j, N_BONE_PIXEL_X );",
  8184. "float y = floor( j / N_BONE_PIXEL_X );",
  8185. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  8186. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  8187. "y = dy * ( y + 0.5 );",
  8188. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  8189. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  8190. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  8191. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  8192. "mat4 bone = mat4( v1, v2, v3, v4 );",
  8193. "return bone;",
  8194. "}",
  8195. "#else",
  8196. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  8197. "mat4 getBoneMatrix( const in float i ) {",
  8198. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  8199. "return bone;",
  8200. "}",
  8201. "#endif",
  8202. "#endif"
  8203. ].join("\n"),
  8204. skinbase_vertex: [
  8205. "#ifdef USE_SKINNING",
  8206. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  8207. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  8208. "#endif"
  8209. ].join("\n"),
  8210. skinning_vertex: [
  8211. "#ifdef USE_SKINNING",
  8212. "vec4 skinned = boneMatX * skinVertexA * skinWeight.x;",
  8213. "skinned += boneMatY * skinVertexB * skinWeight.y;",
  8214. "gl_Position = projectionMatrix * modelViewMatrix * skinned;",
  8215. "#endif"
  8216. ].join("\n"),
  8217. // MORPHING
  8218. morphtarget_pars_vertex: [
  8219. "#ifdef USE_MORPHTARGETS",
  8220. "#ifndef USE_MORPHNORMALS",
  8221. "uniform float morphTargetInfluences[ 8 ];",
  8222. "#else",
  8223. "uniform float morphTargetInfluences[ 4 ];",
  8224. "#endif",
  8225. "#endif"
  8226. ].join("\n"),
  8227. morphtarget_vertex: [
  8228. "#ifdef USE_MORPHTARGETS",
  8229. "vec3 morphed = vec3( 0.0 );",
  8230. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  8231. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  8232. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  8233. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  8234. "#ifndef USE_MORPHNORMALS",
  8235. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  8236. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  8237. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  8238. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  8239. "#endif",
  8240. "morphed += position;",
  8241. "gl_Position = projectionMatrix * modelViewMatrix * vec4( morphed, 1.0 );",
  8242. "#endif"
  8243. ].join("\n"),
  8244. default_vertex : [
  8245. "#ifndef USE_MORPHTARGETS",
  8246. "#ifndef USE_SKINNING",
  8247. "gl_Position = projectionMatrix * mvPosition;",
  8248. "#endif",
  8249. "#endif"
  8250. ].join("\n"),
  8251. morphnormal_vertex: [
  8252. "#ifdef USE_MORPHNORMALS",
  8253. "vec3 morphedNormal = vec3( 0.0 );",
  8254. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  8255. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  8256. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  8257. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  8258. "morphedNormal += normal;",
  8259. "#endif"
  8260. ].join("\n"),
  8261. skinnormal_vertex: [
  8262. "#ifdef USE_SKINNING",
  8263. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  8264. "skinMatrix += skinWeight.y * boneMatY;",
  8265. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  8266. "#endif"
  8267. ].join("\n"),
  8268. defaultnormal_vertex: [
  8269. "vec3 transformedNormal;",
  8270. "#ifdef USE_SKINNING",
  8271. "transformedNormal = skinnedNormal.xyz;",
  8272. "#endif",
  8273. "#ifdef USE_MORPHNORMALS",
  8274. "transformedNormal = morphedNormal;",
  8275. "#endif",
  8276. "#ifndef USE_MORPHNORMALS",
  8277. "#ifndef USE_SKINNING",
  8278. "transformedNormal = normal;",
  8279. "#endif",
  8280. "#endif",
  8281. "transformedNormal = normalMatrix * transformedNormal;",
  8282. ].join("\n"),
  8283. // SHADOW MAP
  8284. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  8285. // http://spidergl.org/example.php?id=6
  8286. // http://fabiensanglard.net/shadowmapping
  8287. shadowmap_pars_fragment: [
  8288. "#ifdef USE_SHADOWMAP",
  8289. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  8290. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  8291. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  8292. "uniform float shadowBias[ MAX_SHADOWS ];",
  8293. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8294. "float unpackDepth( const in vec4 rgba_depth ) {",
  8295. "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 );",
  8296. "float depth = dot( rgba_depth, bit_shift );",
  8297. "return depth;",
  8298. "}",
  8299. "#endif"
  8300. ].join("\n"),
  8301. shadowmap_fragment: [
  8302. "#ifdef USE_SHADOWMAP",
  8303. "#ifdef SHADOWMAP_DEBUG",
  8304. "vec3 frustumColors[3];",
  8305. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  8306. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  8307. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  8308. "#endif",
  8309. "#ifdef SHADOWMAP_CASCADE",
  8310. "int inFrustumCount = 0;",
  8311. "#endif",
  8312. "float fDepth;",
  8313. "vec3 shadowColor = vec3( 1.0 );",
  8314. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8315. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  8316. // "if ( something && something )" breaks ATI OpenGL shader compiler
  8317. // "if ( all( something, something ) )" using this instead
  8318. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  8319. "bool inFrustum = all( inFrustumVec );",
  8320. // don't shadow pixels outside of light frustum
  8321. // use just first frustum (for cascades)
  8322. // don't shadow pixels behind far plane of light frustum
  8323. "#ifdef SHADOWMAP_CASCADE",
  8324. "inFrustumCount += int( inFrustum );",
  8325. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  8326. "#else",
  8327. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  8328. "#endif",
  8329. "bool frustumTest = all( frustumTestVec );",
  8330. "if ( frustumTest ) {",
  8331. "shadowCoord.z += shadowBias[ i ];",
  8332. "#ifdef SHADOWMAP_SOFT",
  8333. // Percentage-close filtering
  8334. // (9 pixel kernel)
  8335. // http://fabiensanglard.net/shadowmappingPCF/
  8336. "float shadow = 0.0;",
  8337. /*
  8338. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  8339. // must enroll loop manually
  8340. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  8341. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  8342. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  8343. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  8344. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  8345. "float fDepth = unpackDepth( rgbaDepth );",
  8346. "if ( fDepth < shadowCoord.z )",
  8347. "shadow += 1.0;",
  8348. "}",
  8349. "shadow /= 9.0;",
  8350. */
  8351. "const float shadowDelta = 1.0 / 9.0;",
  8352. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  8353. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  8354. "float dx0 = -1.25 * xPixelOffset;",
  8355. "float dy0 = -1.25 * yPixelOffset;",
  8356. "float dx1 = 1.25 * xPixelOffset;",
  8357. "float dy1 = 1.25 * yPixelOffset;",
  8358. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  8359. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8360. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  8361. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8362. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  8363. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8364. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  8365. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8366. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  8367. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8368. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  8369. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8370. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  8371. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8372. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  8373. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8374. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  8375. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8376. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  8377. "#else",
  8378. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  8379. "float fDepth = unpackDepth( rgbaDepth );",
  8380. "if ( fDepth < shadowCoord.z )",
  8381. // spot with multiple shadows is darker
  8382. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  8383. // spot with multiple shadows has the same color as single shadow spot
  8384. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  8385. "#endif",
  8386. "}",
  8387. "#ifdef SHADOWMAP_DEBUG",
  8388. "#ifdef SHADOWMAP_CASCADE",
  8389. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  8390. "#else",
  8391. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  8392. "#endif",
  8393. "#endif",
  8394. "}",
  8395. "#ifdef GAMMA_OUTPUT",
  8396. "shadowColor *= shadowColor;",
  8397. "#endif",
  8398. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  8399. "#endif"
  8400. ].join("\n"),
  8401. shadowmap_pars_vertex: [
  8402. "#ifdef USE_SHADOWMAP",
  8403. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8404. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  8405. "#endif"
  8406. ].join("\n"),
  8407. shadowmap_vertex: [
  8408. "#ifdef USE_SHADOWMAP",
  8409. "vec4 transformedPosition;",
  8410. "#ifdef USE_MORPHTARGETS",
  8411. "transformedPosition = modelMatrix * vec4( morphed, 1.0 );",
  8412. "#else",
  8413. "#ifdef USE_SKINNING",
  8414. "transformedPosition = modelMatrix * skinned;",
  8415. "#else",
  8416. "transformedPosition = modelMatrix * vec4( position, 1.0 );",
  8417. "#endif",
  8418. "#endif",
  8419. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8420. "vShadowCoord[ i ] = shadowMatrix[ i ] * transformedPosition;",
  8421. "}",
  8422. "#endif"
  8423. ].join("\n"),
  8424. // ALPHATEST
  8425. alphatest_fragment: [
  8426. "#ifdef ALPHATEST",
  8427. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  8428. "#endif"
  8429. ].join("\n"),
  8430. // LINEAR SPACE
  8431. linear_to_gamma_fragment: [
  8432. "#ifdef GAMMA_OUTPUT",
  8433. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  8434. "#endif"
  8435. ].join("\n"),
  8436. };
  8437. THREE.UniformsUtils = {
  8438. merge: function ( uniforms ) {
  8439. var u, p, tmp, merged = {};
  8440. for ( u = 0; u < uniforms.length; u++ ) {
  8441. tmp = this.clone( uniforms[ u ] );
  8442. for ( p in tmp ) {
  8443. merged[ p ] = tmp[ p ];
  8444. }
  8445. }
  8446. return merged;
  8447. },
  8448. clone: function ( uniforms_src ) {
  8449. var u, p, parameter, parameter_src, uniforms_dst = {};
  8450. for ( u in uniforms_src ) {
  8451. uniforms_dst[ u ] = {};
  8452. for ( p in uniforms_src[ u ] ) {
  8453. parameter_src = uniforms_src[ u ][ p ];
  8454. if ( parameter_src instanceof THREE.Color ||
  8455. parameter_src instanceof THREE.Vector2 ||
  8456. parameter_src instanceof THREE.Vector3 ||
  8457. parameter_src instanceof THREE.Vector4 ||
  8458. parameter_src instanceof THREE.Matrix4 ||
  8459. parameter_src instanceof THREE.Texture ) {
  8460. uniforms_dst[ u ][ p ] = parameter_src.clone();
  8461. } else if ( parameter_src instanceof Array ) {
  8462. uniforms_dst[ u ][ p ] = parameter_src.slice();
  8463. } else {
  8464. uniforms_dst[ u ][ p ] = parameter_src;
  8465. }
  8466. }
  8467. }
  8468. return uniforms_dst;
  8469. }
  8470. };
  8471. THREE.UniformsLib = {
  8472. common: {
  8473. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8474. "opacity" : { type: "f", value: 1.0 },
  8475. "map" : { type: "t", value: 0, texture: null },
  8476. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  8477. "lightMap" : { type: "t", value: 2, texture: null },
  8478. "specularMap" : { type: "t", value: 3, texture: null },
  8479. "envMap" : { type: "t", value: 1, texture: null },
  8480. "flipEnvMap" : { type: "f", value: -1 },
  8481. "useRefract" : { type: "i", value: 0 },
  8482. "reflectivity" : { type: "f", value: 1.0 },
  8483. "refractionRatio" : { type: "f", value: 0.98 },
  8484. "combine" : { type: "i", value: 0 },
  8485. "morphTargetInfluences" : { type: "f", value: 0 }
  8486. },
  8487. bump: {
  8488. "bumpMap" : { type: "t", value: 4, texture: null },
  8489. "bumpScale" : { type: "f", value: 1 }
  8490. },
  8491. fog : {
  8492. "fogDensity" : { type: "f", value: 0.00025 },
  8493. "fogNear" : { type: "f", value: 1 },
  8494. "fogFar" : { type: "f", value: 2000 },
  8495. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8496. },
  8497. lights: {
  8498. "ambientLightColor" : { type: "fv", value: [] },
  8499. "directionalLightDirection" : { type: "fv", value: [] },
  8500. "directionalLightColor" : { type: "fv", value: [] },
  8501. "pointLightColor" : { type: "fv", value: [] },
  8502. "pointLightPosition" : { type: "fv", value: [] },
  8503. "pointLightDistance" : { type: "fv1", value: [] },
  8504. "spotLightColor" : { type: "fv", value: [] },
  8505. "spotLightPosition" : { type: "fv", value: [] },
  8506. "spotLightDirection" : { type: "fv", value: [] },
  8507. "spotLightDistance" : { type: "fv1", value: [] },
  8508. "spotLightAngle" : { type: "fv1", value: [] },
  8509. "spotLightExponent" : { type: "fv1", value: [] }
  8510. },
  8511. particle: {
  8512. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8513. "opacity" : { type: "f", value: 1.0 },
  8514. "size" : { type: "f", value: 1.0 },
  8515. "scale" : { type: "f", value: 1.0 },
  8516. "map" : { type: "t", value: 0, texture: null },
  8517. "fogDensity" : { type: "f", value: 0.00025 },
  8518. "fogNear" : { type: "f", value: 1 },
  8519. "fogFar" : { type: "f", value: 2000 },
  8520. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8521. },
  8522. shadowmap: {
  8523. "shadowMap": { type: "tv", value: 6, texture: [] },
  8524. "shadowMapSize": { type: "v2v", value: [] },
  8525. "shadowBias" : { type: "fv1", value: [] },
  8526. "shadowDarkness": { type: "fv1", value: [] },
  8527. "shadowMatrix" : { type: "m4v", value: [] },
  8528. }
  8529. };
  8530. THREE.ShaderLib = {
  8531. 'depth': {
  8532. uniforms: {
  8533. "mNear": { type: "f", value: 1.0 },
  8534. "mFar" : { type: "f", value: 2000.0 },
  8535. "opacity" : { type: "f", value: 1.0 }
  8536. },
  8537. vertexShader: [
  8538. "void main() {",
  8539. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  8540. "}"
  8541. ].join("\n"),
  8542. fragmentShader: [
  8543. "uniform float mNear;",
  8544. "uniform float mFar;",
  8545. "uniform float opacity;",
  8546. "void main() {",
  8547. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8548. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  8549. "gl_FragColor = vec4( vec3( color ), opacity );",
  8550. "}"
  8551. ].join("\n")
  8552. },
  8553. 'normal': {
  8554. uniforms: {
  8555. "opacity" : { type: "f", value: 1.0 }
  8556. },
  8557. vertexShader: [
  8558. "varying vec3 vNormal;",
  8559. "void main() {",
  8560. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8561. "vNormal = normalMatrix * normal;",
  8562. "gl_Position = projectionMatrix * mvPosition;",
  8563. "}"
  8564. ].join("\n"),
  8565. fragmentShader: [
  8566. "uniform float opacity;",
  8567. "varying vec3 vNormal;",
  8568. "void main() {",
  8569. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  8570. "}"
  8571. ].join("\n")
  8572. },
  8573. 'basic': {
  8574. uniforms: THREE.UniformsUtils.merge( [
  8575. THREE.UniformsLib[ "common" ],
  8576. THREE.UniformsLib[ "fog" ],
  8577. THREE.UniformsLib[ "shadowmap" ]
  8578. ] ),
  8579. vertexShader: [
  8580. THREE.ShaderChunk[ "map_pars_vertex" ],
  8581. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  8582. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  8583. THREE.ShaderChunk[ "color_pars_vertex" ],
  8584. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8585. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8586. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8587. "void main() {",
  8588. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8589. THREE.ShaderChunk[ "map_vertex" ],
  8590. THREE.ShaderChunk[ "lightmap_vertex" ],
  8591. THREE.ShaderChunk[ "envmap_vertex" ],
  8592. THREE.ShaderChunk[ "color_vertex" ],
  8593. THREE.ShaderChunk[ "skinbase_vertex" ],
  8594. THREE.ShaderChunk[ "skinning_vertex" ],
  8595. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8596. THREE.ShaderChunk[ "default_vertex" ],
  8597. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8598. "}"
  8599. ].join("\n"),
  8600. fragmentShader: [
  8601. "uniform vec3 diffuse;",
  8602. "uniform float opacity;",
  8603. THREE.ShaderChunk[ "color_pars_fragment" ],
  8604. THREE.ShaderChunk[ "map_pars_fragment" ],
  8605. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  8606. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  8607. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8608. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8609. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  8610. "void main() {",
  8611. "gl_FragColor = vec4( diffuse, opacity );",
  8612. THREE.ShaderChunk[ "map_fragment" ],
  8613. THREE.ShaderChunk[ "alphatest_fragment" ],
  8614. THREE.ShaderChunk[ "specularmap_fragment" ],
  8615. THREE.ShaderChunk[ "lightmap_fragment" ],
  8616. THREE.ShaderChunk[ "color_fragment" ],
  8617. THREE.ShaderChunk[ "envmap_fragment" ],
  8618. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8619. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  8620. THREE.ShaderChunk[ "fog_fragment" ],
  8621. "}"
  8622. ].join("\n")
  8623. },
  8624. 'lambert': {
  8625. uniforms: THREE.UniformsUtils.merge( [
  8626. THREE.UniformsLib[ "common" ],
  8627. THREE.UniformsLib[ "fog" ],
  8628. THREE.UniformsLib[ "lights" ],
  8629. THREE.UniformsLib[ "shadowmap" ],
  8630. {
  8631. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  8632. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  8633. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  8634. }
  8635. ] ),
  8636. vertexShader: [
  8637. "varying vec3 vLightFront;",
  8638. "#ifdef DOUBLE_SIDED",
  8639. "varying vec3 vLightBack;",
  8640. "#endif",
  8641. THREE.ShaderChunk[ "map_pars_vertex" ],
  8642. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  8643. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  8644. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  8645. THREE.ShaderChunk[ "color_pars_vertex" ],
  8646. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8647. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8648. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8649. "void main() {",
  8650. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8651. THREE.ShaderChunk[ "map_vertex" ],
  8652. THREE.ShaderChunk[ "lightmap_vertex" ],
  8653. THREE.ShaderChunk[ "envmap_vertex" ],
  8654. THREE.ShaderChunk[ "color_vertex" ],
  8655. THREE.ShaderChunk[ "morphnormal_vertex" ],
  8656. THREE.ShaderChunk[ "skinbase_vertex" ],
  8657. THREE.ShaderChunk[ "skinnormal_vertex" ],
  8658. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  8659. "#ifndef USE_ENVMAP",
  8660. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  8661. "#endif",
  8662. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  8663. THREE.ShaderChunk[ "skinning_vertex" ],
  8664. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8665. THREE.ShaderChunk[ "default_vertex" ],
  8666. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8667. "}"
  8668. ].join("\n"),
  8669. fragmentShader: [
  8670. "uniform float opacity;",
  8671. "varying vec3 vLightFront;",
  8672. "#ifdef DOUBLE_SIDED",
  8673. "varying vec3 vLightBack;",
  8674. "#endif",
  8675. THREE.ShaderChunk[ "color_pars_fragment" ],
  8676. THREE.ShaderChunk[ "map_pars_fragment" ],
  8677. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  8678. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  8679. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8680. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8681. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  8682. "void main() {",
  8683. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  8684. THREE.ShaderChunk[ "map_fragment" ],
  8685. THREE.ShaderChunk[ "alphatest_fragment" ],
  8686. THREE.ShaderChunk[ "specularmap_fragment" ],
  8687. "#ifdef DOUBLE_SIDED",
  8688. //"float isFront = float( gl_FrontFacing );",
  8689. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  8690. "if ( gl_FrontFacing )",
  8691. "gl_FragColor.xyz *= vLightFront;",
  8692. "else",
  8693. "gl_FragColor.xyz *= vLightBack;",
  8694. "#else",
  8695. "gl_FragColor.xyz *= vLightFront;",
  8696. "#endif",
  8697. THREE.ShaderChunk[ "lightmap_fragment" ],
  8698. THREE.ShaderChunk[ "color_fragment" ],
  8699. THREE.ShaderChunk[ "envmap_fragment" ],
  8700. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8701. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  8702. THREE.ShaderChunk[ "fog_fragment" ],
  8703. "}"
  8704. ].join("\n")
  8705. },
  8706. 'phong': {
  8707. uniforms: THREE.UniformsUtils.merge( [
  8708. THREE.UniformsLib[ "common" ],
  8709. THREE.UniformsLib[ "bump" ],
  8710. THREE.UniformsLib[ "fog" ],
  8711. THREE.UniformsLib[ "lights" ],
  8712. THREE.UniformsLib[ "shadowmap" ],
  8713. {
  8714. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  8715. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  8716. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  8717. "shininess": { type: "f", value: 30 },
  8718. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  8719. }
  8720. ] ),
  8721. vertexShader: [
  8722. "varying vec3 vViewPosition;",
  8723. "varying vec3 vNormal;",
  8724. THREE.ShaderChunk[ "map_pars_vertex" ],
  8725. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  8726. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  8727. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  8728. THREE.ShaderChunk[ "color_pars_vertex" ],
  8729. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8730. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8731. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8732. "void main() {",
  8733. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8734. THREE.ShaderChunk[ "map_vertex" ],
  8735. THREE.ShaderChunk[ "lightmap_vertex" ],
  8736. THREE.ShaderChunk[ "envmap_vertex" ],
  8737. THREE.ShaderChunk[ "color_vertex" ],
  8738. "#ifndef USE_ENVMAP",
  8739. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  8740. "#endif",
  8741. "vViewPosition = -mvPosition.xyz;",
  8742. THREE.ShaderChunk[ "morphnormal_vertex" ],
  8743. THREE.ShaderChunk[ "skinbase_vertex" ],
  8744. THREE.ShaderChunk[ "skinnormal_vertex" ],
  8745. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  8746. "vNormal = transformedNormal;",
  8747. THREE.ShaderChunk[ "lights_phong_vertex" ],
  8748. THREE.ShaderChunk[ "skinning_vertex" ],
  8749. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8750. THREE.ShaderChunk[ "default_vertex" ],
  8751. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8752. "}"
  8753. ].join("\n"),
  8754. fragmentShader: [
  8755. "uniform vec3 diffuse;",
  8756. "uniform float opacity;",
  8757. "uniform vec3 ambient;",
  8758. "uniform vec3 emissive;",
  8759. "uniform vec3 specular;",
  8760. "uniform float shininess;",
  8761. THREE.ShaderChunk[ "color_pars_fragment" ],
  8762. THREE.ShaderChunk[ "map_pars_fragment" ],
  8763. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  8764. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  8765. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8766. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  8767. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8768. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  8769. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  8770. "void main() {",
  8771. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  8772. THREE.ShaderChunk[ "map_fragment" ],
  8773. THREE.ShaderChunk[ "alphatest_fragment" ],
  8774. THREE.ShaderChunk[ "specularmap_fragment" ],
  8775. THREE.ShaderChunk[ "lights_phong_fragment" ],
  8776. THREE.ShaderChunk[ "lightmap_fragment" ],
  8777. THREE.ShaderChunk[ "color_fragment" ],
  8778. THREE.ShaderChunk[ "envmap_fragment" ],
  8779. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8780. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  8781. THREE.ShaderChunk[ "fog_fragment" ],
  8782. "}"
  8783. ].join("\n")
  8784. },
  8785. 'particle_basic': {
  8786. uniforms: THREE.UniformsUtils.merge( [
  8787. THREE.UniformsLib[ "particle" ],
  8788. THREE.UniformsLib[ "shadowmap" ]
  8789. ] ),
  8790. vertexShader: [
  8791. "uniform float size;",
  8792. "uniform float scale;",
  8793. THREE.ShaderChunk[ "color_pars_vertex" ],
  8794. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8795. "void main() {",
  8796. THREE.ShaderChunk[ "color_vertex" ],
  8797. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8798. "#ifdef USE_SIZEATTENUATION",
  8799. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  8800. "#else",
  8801. "gl_PointSize = size;",
  8802. "#endif",
  8803. "gl_Position = projectionMatrix * mvPosition;",
  8804. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8805. "}"
  8806. ].join("\n"),
  8807. fragmentShader: [
  8808. "uniform vec3 psColor;",
  8809. "uniform float opacity;",
  8810. THREE.ShaderChunk[ "color_pars_fragment" ],
  8811. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  8812. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8813. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8814. "void main() {",
  8815. "gl_FragColor = vec4( psColor, opacity );",
  8816. THREE.ShaderChunk[ "map_particle_fragment" ],
  8817. THREE.ShaderChunk[ "alphatest_fragment" ],
  8818. THREE.ShaderChunk[ "color_fragment" ],
  8819. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8820. THREE.ShaderChunk[ "fog_fragment" ],
  8821. "}"
  8822. ].join("\n")
  8823. },
  8824. // Depth encoding into RGBA texture
  8825. // based on SpiderGL shadow map example
  8826. // http://spidergl.org/example.php?id=6
  8827. // originally from
  8828. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  8829. // see also here:
  8830. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  8831. 'depthRGBA': {
  8832. uniforms: {},
  8833. vertexShader: [
  8834. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8835. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8836. "void main() {",
  8837. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8838. THREE.ShaderChunk[ "skinbase_vertex" ],
  8839. THREE.ShaderChunk[ "skinning_vertex" ],
  8840. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8841. THREE.ShaderChunk[ "default_vertex" ],
  8842. "}"
  8843. ].join("\n"),
  8844. fragmentShader: [
  8845. "vec4 pack_depth( const in float depth ) {",
  8846. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  8847. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  8848. "vec4 res = fract( depth * bit_shift );",
  8849. "res -= res.xxyz * bit_mask;",
  8850. "return res;",
  8851. "}",
  8852. "void main() {",
  8853. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  8854. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  8855. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  8856. //"gl_FragData[ 0 ] = pack_depth( z );",
  8857. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  8858. "}"
  8859. ].join("\n")
  8860. }
  8861. };
  8862. /**
  8863. * @author supereggbert / http://www.paulbrunt.co.uk/
  8864. * @author mrdoob / http://mrdoob.com/
  8865. * @author alteredq / http://alteredqualia.com/
  8866. * @author szimek / https://github.com/szimek/
  8867. */
  8868. THREE.WebGLRenderer = function ( parameters ) {
  8869. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  8870. parameters = parameters || {};
  8871. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  8872. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  8873. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  8874. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  8875. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  8876. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  8877. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  8878. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  8879. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,
  8880. _maxLights = parameters.maxLights !== undefined ? parameters.maxLights : 4;
  8881. // public properties
  8882. this.domElement = _canvas;
  8883. this.context = null;
  8884. // clearing
  8885. this.autoClear = true;
  8886. this.autoClearColor = true;
  8887. this.autoClearDepth = true;
  8888. this.autoClearStencil = true;
  8889. // scene graph
  8890. this.sortObjects = true;
  8891. this.autoUpdateObjects = true;
  8892. this.autoUpdateScene = true;
  8893. // physically based shading
  8894. this.gammaInput = false;
  8895. this.gammaOutput = false;
  8896. this.physicallyBasedShading = false;
  8897. // shadow map
  8898. this.shadowMapEnabled = false;
  8899. this.shadowMapAutoUpdate = true;
  8900. this.shadowMapSoft = true;
  8901. this.shadowMapCullFrontFaces = true;
  8902. this.shadowMapDebug = false;
  8903. this.shadowMapCascade = false;
  8904. // morphs
  8905. this.maxMorphTargets = 8;
  8906. this.maxMorphNormals = 4;
  8907. // flags
  8908. this.autoScaleCubemaps = true;
  8909. // custom render plugins
  8910. this.renderPluginsPre = [];
  8911. this.renderPluginsPost = [];
  8912. // info
  8913. this.info = {
  8914. memory: {
  8915. programs: 0,
  8916. geometries: 0,
  8917. textures: 0
  8918. },
  8919. render: {
  8920. calls: 0,
  8921. vertices: 0,
  8922. faces: 0,
  8923. points: 0
  8924. }
  8925. };
  8926. // internal properties
  8927. var _this = this,
  8928. _programs = [],
  8929. _programs_counter = 0,
  8930. // internal state cache
  8931. _currentProgram = null,
  8932. _currentFramebuffer = null,
  8933. _currentMaterialId = -1,
  8934. _currentGeometryGroupHash = null,
  8935. _currentCamera = null,
  8936. _geometryGroupCounter = 0,
  8937. // GL state cache
  8938. _oldDoubleSided = -1,
  8939. _oldFlipSided = -1,
  8940. _oldBlending = -1,
  8941. _oldBlendEquation = -1,
  8942. _oldBlendSrc = -1,
  8943. _oldBlendDst = -1,
  8944. _oldDepthTest = -1,
  8945. _oldDepthWrite = -1,
  8946. _oldPolygonOffset = null,
  8947. _oldPolygonOffsetFactor = null,
  8948. _oldPolygonOffsetUnits = null,
  8949. _oldLineWidth = null,
  8950. _viewportX = 0,
  8951. _viewportY = 0,
  8952. _viewportWidth = 0,
  8953. _viewportHeight = 0,
  8954. _currentWidth = 0,
  8955. _currentHeight = 0,
  8956. // frustum
  8957. _frustum = new THREE.Frustum(),
  8958. // camera matrices cache
  8959. _projScreenMatrix = new THREE.Matrix4(),
  8960. _projScreenMatrixPS = new THREE.Matrix4(),
  8961. _vector3 = new THREE.Vector4(),
  8962. // light arrays cache
  8963. _direction = new THREE.Vector3(),
  8964. _lightsNeedUpdate = true,
  8965. _lights = {
  8966. ambient: [ 0, 0, 0 ],
  8967. directional: { length: 0, colors: new Array(), positions: new Array() },
  8968. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  8969. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), angles: new Array(), exponents: new Array() }
  8970. };
  8971. // initialize
  8972. var _gl;
  8973. var _glExtensionTextureFloat;
  8974. var _glExtensionStandardDerivatives;
  8975. var _glExtensionTextureFilterAnisotropic;
  8976. initGL();
  8977. setDefaultGLState();
  8978. this.context = _gl;
  8979. // GPU capabilities
  8980. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ),
  8981. _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ),
  8982. _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  8983. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  8984. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  8985. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  8986. // API
  8987. this.getContext = function () {
  8988. return _gl;
  8989. };
  8990. this.supportsVertexTextures = function () {
  8991. return _supportsVertexTextures;
  8992. };
  8993. this.getMaxAnisotropy = function () {
  8994. return _maxAnisotropy;
  8995. };
  8996. this.setSize = function ( width, height ) {
  8997. _canvas.width = width;
  8998. _canvas.height = height;
  8999. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  9000. };
  9001. this.setViewport = function ( x, y, width, height ) {
  9002. _viewportX = x !== undefined ? x : 0;
  9003. _viewportY = y !== undefined ? y : 0;
  9004. _viewportWidth = width !== undefined ? width : _canvas.width;
  9005. _viewportHeight = height !== undefined ? height : _canvas.height;
  9006. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  9007. };
  9008. this.setScissor = function ( x, y, width, height ) {
  9009. _gl.scissor( x, y, width, height );
  9010. };
  9011. this.enableScissorTest = function ( enable ) {
  9012. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  9013. };
  9014. // Clearing
  9015. this.setClearColorHex = function ( hex, alpha ) {
  9016. _clearColor.setHex( hex );
  9017. _clearAlpha = alpha;
  9018. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9019. };
  9020. this.setClearColor = function ( color, alpha ) {
  9021. _clearColor.copy( color );
  9022. _clearAlpha = alpha;
  9023. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9024. };
  9025. this.getClearColor = function () {
  9026. return _clearColor;
  9027. };
  9028. this.getClearAlpha = function () {
  9029. return _clearAlpha;
  9030. };
  9031. this.clear = function ( color, depth, stencil ) {
  9032. var bits = 0;
  9033. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  9034. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  9035. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  9036. _gl.clear( bits );
  9037. };
  9038. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  9039. this.setRenderTarget( renderTarget );
  9040. this.clear( color, depth, stencil );
  9041. };
  9042. // Plugins
  9043. this.addPostPlugin = function ( plugin ) {
  9044. plugin.init( this );
  9045. this.renderPluginsPost.push( plugin );
  9046. };
  9047. this.addPrePlugin = function ( plugin ) {
  9048. plugin.init( this );
  9049. this.renderPluginsPre.push( plugin );
  9050. };
  9051. // Deallocation
  9052. this.deallocateObject = function ( object ) {
  9053. if ( ! object.__webglInit ) return;
  9054. object.__webglInit = false;
  9055. delete object._modelViewMatrix;
  9056. delete object._normalMatrix;
  9057. delete object._normalMatrixArray;
  9058. delete object._modelViewMatrixArray;
  9059. delete object._modelMatrixArray;
  9060. if ( object instanceof THREE.Mesh ) {
  9061. for ( var g in object.geometry.geometryGroups ) {
  9062. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  9063. }
  9064. } else if ( object instanceof THREE.Ribbon ) {
  9065. deleteRibbonBuffers( object.geometry );
  9066. } else if ( object instanceof THREE.Line ) {
  9067. deleteLineBuffers( object.geometry );
  9068. } else if ( object instanceof THREE.ParticleSystem ) {
  9069. deleteParticleBuffers( object.geometry );
  9070. }
  9071. };
  9072. this.deallocateTexture = function ( texture ) {
  9073. if ( ! texture.__webglInit ) return;
  9074. texture.__webglInit = false;
  9075. _gl.deleteTexture( texture.__webglTexture );
  9076. _this.info.memory.textures --;
  9077. };
  9078. this.deallocateRenderTarget = function ( renderTarget ) {
  9079. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  9080. _gl.deleteTexture( renderTarget.__webglTexture );
  9081. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9082. for ( var i = 0; i < 6; i ++ ) {
  9083. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  9084. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  9085. }
  9086. } else {
  9087. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  9088. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  9089. }
  9090. };
  9091. this.deallocateMaterial = function ( material ) {
  9092. var program = material.program;
  9093. if ( ! program ) return;
  9094. material.program = undefined;
  9095. // only deallocate GL program if this was the last use of shared program
  9096. // assumed there is only single copy of any program in the _programs list
  9097. // (that's how it's constructed)
  9098. var i, il, programInfo;
  9099. var deleteProgram = false;
  9100. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9101. programInfo = _programs[ i ];
  9102. if ( programInfo.program === program ) {
  9103. programInfo.usedTimes --;
  9104. if ( programInfo.usedTimes === 0 ) {
  9105. deleteProgram = true;
  9106. }
  9107. break;
  9108. }
  9109. }
  9110. if ( deleteProgram ) {
  9111. // avoid using array.splice, this is costlier than creating new array from scratch
  9112. var newPrograms = [];
  9113. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9114. programInfo = _programs[ i ];
  9115. if ( programInfo.program !== program ) {
  9116. newPrograms.push( programInfo );
  9117. }
  9118. }
  9119. _programs = newPrograms;
  9120. _gl.deleteProgram( program );
  9121. _this.info.memory.programs --;
  9122. }
  9123. };
  9124. // Rendering
  9125. this.updateShadowMap = function ( scene, camera ) {
  9126. _currentProgram = null;
  9127. _oldBlending = -1;
  9128. _oldDepthTest = -1;
  9129. _oldDepthWrite = -1;
  9130. _currentGeometryGroupHash = -1;
  9131. _currentMaterialId = -1;
  9132. _lightsNeedUpdate = true;
  9133. _oldDoubleSided = -1;
  9134. _oldFlipSided = -1;
  9135. this.shadowMapPlugin.update( scene, camera );
  9136. };
  9137. // Internal functions
  9138. // Buffer allocation
  9139. function createParticleBuffers ( geometry ) {
  9140. geometry.__webglVertexBuffer = _gl.createBuffer();
  9141. geometry.__webglColorBuffer = _gl.createBuffer();
  9142. _this.info.geometries ++;
  9143. };
  9144. function createLineBuffers ( geometry ) {
  9145. geometry.__webglVertexBuffer = _gl.createBuffer();
  9146. geometry.__webglColorBuffer = _gl.createBuffer();
  9147. _this.info.memory.geometries ++;
  9148. };
  9149. function createRibbonBuffers ( geometry ) {
  9150. geometry.__webglVertexBuffer = _gl.createBuffer();
  9151. geometry.__webglColorBuffer = _gl.createBuffer();
  9152. _this.info.memory.geometries ++;
  9153. };
  9154. function createMeshBuffers ( geometryGroup ) {
  9155. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  9156. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  9157. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  9158. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  9159. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  9160. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  9161. geometryGroup.__webglSkinVertexABuffer = _gl.createBuffer();
  9162. geometryGroup.__webglSkinVertexBBuffer = _gl.createBuffer();
  9163. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  9164. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  9165. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  9166. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  9167. var m, ml;
  9168. if ( geometryGroup.numMorphTargets ) {
  9169. geometryGroup.__webglMorphTargetsBuffers = [];
  9170. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9171. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  9172. }
  9173. }
  9174. if ( geometryGroup.numMorphNormals ) {
  9175. geometryGroup.__webglMorphNormalsBuffers = [];
  9176. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9177. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  9178. }
  9179. }
  9180. _this.info.memory.geometries ++;
  9181. };
  9182. // Buffer deallocation
  9183. function deleteParticleBuffers ( geometry ) {
  9184. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9185. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9186. _this.info.memory.geometries --;
  9187. };
  9188. function deleteLineBuffers ( geometry ) {
  9189. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9190. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9191. _this.info.memory.geometries --;
  9192. };
  9193. function deleteRibbonBuffers ( geometry ) {
  9194. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9195. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9196. _this.info.memory.geometries --;
  9197. };
  9198. function deleteMeshBuffers ( geometryGroup ) {
  9199. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  9200. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  9201. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  9202. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  9203. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  9204. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  9205. _gl.deleteBuffer( geometryGroup.__webglSkinVertexABuffer );
  9206. _gl.deleteBuffer( geometryGroup.__webglSkinVertexBBuffer );
  9207. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  9208. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  9209. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  9210. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  9211. var m, ml;
  9212. if ( geometryGroup.numMorphTargets ) {
  9213. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9214. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  9215. }
  9216. }
  9217. if ( geometryGroup.numMorphNormals ) {
  9218. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9219. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  9220. }
  9221. }
  9222. if ( geometryGroup.__webglCustomAttributesList ) {
  9223. for ( var id in geometryGroup.__webglCustomAttributesList ) {
  9224. _gl.deleteBuffer( geometryGroup.__webglCustomAttributesList[ id ].buffer );
  9225. }
  9226. }
  9227. _this.info.memory.geometries --;
  9228. };
  9229. // Buffer initialization
  9230. function initCustomAttributes ( geometry, object ) {
  9231. var nvertices = geometry.vertices.length;
  9232. var material = object.material;
  9233. if ( material.attributes ) {
  9234. if ( geometry.__webglCustomAttributesList === undefined ) {
  9235. geometry.__webglCustomAttributesList = [];
  9236. }
  9237. for ( var a in material.attributes ) {
  9238. var attribute = material.attributes[ a ];
  9239. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9240. attribute.__webglInitialized = true;
  9241. var size = 1; // "f" and "i"
  9242. if ( attribute.type === "v2" ) size = 2;
  9243. else if ( attribute.type === "v3" ) size = 3;
  9244. else if ( attribute.type === "v4" ) size = 4;
  9245. else if ( attribute.type === "c" ) size = 3;
  9246. attribute.size = size;
  9247. attribute.array = new Float32Array( nvertices * size );
  9248. attribute.buffer = _gl.createBuffer();
  9249. attribute.buffer.belongsToAttribute = a;
  9250. attribute.needsUpdate = true;
  9251. }
  9252. geometry.__webglCustomAttributesList.push( attribute );
  9253. }
  9254. }
  9255. };
  9256. function initParticleBuffers ( geometry, object ) {
  9257. var nvertices = geometry.vertices.length;
  9258. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9259. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9260. geometry.__sortArray = [];
  9261. geometry.__webglParticleCount = nvertices;
  9262. initCustomAttributes ( geometry, object );
  9263. };
  9264. function initLineBuffers ( geometry, object ) {
  9265. var nvertices = geometry.vertices.length;
  9266. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9267. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9268. geometry.__webglLineCount = nvertices;
  9269. initCustomAttributes ( geometry, object );
  9270. };
  9271. function initRibbonBuffers ( geometry ) {
  9272. var nvertices = geometry.vertices.length;
  9273. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9274. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9275. geometry.__webglVertexCount = nvertices;
  9276. };
  9277. function initMeshBuffers ( geometryGroup, object ) {
  9278. var geometry = object.geometry,
  9279. faces3 = geometryGroup.faces3,
  9280. faces4 = geometryGroup.faces4,
  9281. nvertices = faces3.length * 3 + faces4.length * 4,
  9282. ntris = faces3.length * 1 + faces4.length * 2,
  9283. nlines = faces3.length * 3 + faces4.length * 4,
  9284. material = getBufferMaterial( object, geometryGroup ),
  9285. uvType = bufferGuessUVType( material ),
  9286. normalType = bufferGuessNormalType( material ),
  9287. vertexColorType = bufferGuessVertexColorType( material );
  9288. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  9289. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  9290. if ( normalType ) {
  9291. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  9292. }
  9293. if ( geometry.hasTangents ) {
  9294. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  9295. }
  9296. if ( vertexColorType ) {
  9297. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  9298. }
  9299. if ( uvType ) {
  9300. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  9301. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  9302. }
  9303. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  9304. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  9305. }
  9306. }
  9307. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  9308. geometryGroup.__skinVertexAArray = new Float32Array( nvertices * 4 );
  9309. geometryGroup.__skinVertexBArray = new Float32Array( nvertices * 4 );
  9310. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  9311. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  9312. }
  9313. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  9314. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  9315. var m, ml;
  9316. if ( geometryGroup.numMorphTargets ) {
  9317. geometryGroup.__morphTargetsArrays = [];
  9318. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9319. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  9320. }
  9321. }
  9322. if ( geometryGroup.numMorphNormals ) {
  9323. geometryGroup.__morphNormalsArrays = [];
  9324. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9325. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  9326. }
  9327. }
  9328. geometryGroup.__webglFaceCount = ntris * 3;
  9329. geometryGroup.__webglLineCount = nlines * 2;
  9330. // custom attributes
  9331. if ( material.attributes ) {
  9332. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  9333. geometryGroup.__webglCustomAttributesList = [];
  9334. }
  9335. for ( var a in material.attributes ) {
  9336. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  9337. // attribute buffers which are correctly indexed in the setMeshBuffers function
  9338. var originalAttribute = material.attributes[ a ];
  9339. var attribute = {};
  9340. for ( var property in originalAttribute ) {
  9341. attribute[ property ] = originalAttribute[ property ];
  9342. }
  9343. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9344. attribute.__webglInitialized = true;
  9345. var size = 1; // "f" and "i"
  9346. if( attribute.type === "v2" ) size = 2;
  9347. else if( attribute.type === "v3" ) size = 3;
  9348. else if( attribute.type === "v4" ) size = 4;
  9349. else if( attribute.type === "c" ) size = 3;
  9350. attribute.size = size;
  9351. attribute.array = new Float32Array( nvertices * size );
  9352. attribute.buffer = _gl.createBuffer();
  9353. attribute.buffer.belongsToAttribute = a;
  9354. originalAttribute.needsUpdate = true;
  9355. attribute.__original = originalAttribute;
  9356. }
  9357. geometryGroup.__webglCustomAttributesList.push( attribute );
  9358. }
  9359. }
  9360. geometryGroup.__inittedArrays = true;
  9361. };
  9362. function getBufferMaterial( object, geometryGroup ) {
  9363. if ( object.material && ! ( object.material instanceof THREE.MeshFaceMaterial ) ) {
  9364. return object.material;
  9365. } else if ( geometryGroup.materialIndex >= 0 ) {
  9366. return object.geometry.materials[ geometryGroup.materialIndex ];
  9367. }
  9368. };
  9369. function materialNeedsSmoothNormals ( material ) {
  9370. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  9371. };
  9372. function bufferGuessNormalType ( material ) {
  9373. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  9374. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  9375. return false;
  9376. }
  9377. if ( materialNeedsSmoothNormals( material ) ) {
  9378. return THREE.SmoothShading;
  9379. } else {
  9380. return THREE.FlatShading;
  9381. }
  9382. };
  9383. function bufferGuessVertexColorType ( material ) {
  9384. if ( material.vertexColors ) {
  9385. return material.vertexColors;
  9386. }
  9387. return false;
  9388. };
  9389. function bufferGuessUVType ( material ) {
  9390. // material must use some texture to require uvs
  9391. if ( material.map || material.lightMap || material.bumpMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  9392. return true;
  9393. }
  9394. return false;
  9395. };
  9396. //
  9397. function initDirectBuffers( geometry ) {
  9398. var a, attribute, type;
  9399. for ( a in geometry.attributes ) {
  9400. if ( a === "index" ) {
  9401. type = _gl.ELEMENT_ARRAY_BUFFER;
  9402. } else {
  9403. type = _gl.ARRAY_BUFFER;
  9404. }
  9405. attribute = geometry.attributes[ a ];
  9406. attribute.buffer = _gl.createBuffer();
  9407. _gl.bindBuffer( type, attribute.buffer );
  9408. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  9409. }
  9410. };
  9411. // Buffer setting
  9412. function setParticleBuffers ( geometry, hint, object ) {
  9413. var v, c, vertex, offset, index, color,
  9414. vertices = geometry.vertices,
  9415. vl = vertices.length,
  9416. colors = geometry.colors,
  9417. cl = colors.length,
  9418. vertexArray = geometry.__vertexArray,
  9419. colorArray = geometry.__colorArray,
  9420. sortArray = geometry.__sortArray,
  9421. dirtyVertices = geometry.verticesNeedUpdate,
  9422. dirtyElements = geometry.elementsNeedUpdate,
  9423. dirtyColors = geometry.colorsNeedUpdate,
  9424. customAttributes = geometry.__webglCustomAttributesList,
  9425. i, il,
  9426. a, ca, cal, value,
  9427. customAttribute;
  9428. if ( object.sortParticles ) {
  9429. _projScreenMatrixPS.copy( _projScreenMatrix );
  9430. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  9431. for ( v = 0; v < vl; v ++ ) {
  9432. vertex = vertices[ v ];
  9433. _vector3.copy( vertex );
  9434. _projScreenMatrixPS.multiplyVector3( _vector3 );
  9435. sortArray[ v ] = [ _vector3.z, v ];
  9436. }
  9437. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  9438. for ( v = 0; v < vl; v ++ ) {
  9439. vertex = vertices[ sortArray[v][1] ];
  9440. offset = v * 3;
  9441. vertexArray[ offset ] = vertex.x;
  9442. vertexArray[ offset + 1 ] = vertex.y;
  9443. vertexArray[ offset + 2 ] = vertex.z;
  9444. }
  9445. for ( c = 0; c < cl; c ++ ) {
  9446. offset = c * 3;
  9447. color = colors[ sortArray[c][1] ];
  9448. colorArray[ offset ] = color.r;
  9449. colorArray[ offset + 1 ] = color.g;
  9450. colorArray[ offset + 2 ] = color.b;
  9451. }
  9452. if ( customAttributes ) {
  9453. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9454. customAttribute = customAttributes[ i ];
  9455. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  9456. offset = 0;
  9457. cal = customAttribute.value.length;
  9458. if ( customAttribute.size === 1 ) {
  9459. for ( ca = 0; ca < cal; ca ++ ) {
  9460. index = sortArray[ ca ][ 1 ];
  9461. customAttribute.array[ ca ] = customAttribute.value[ index ];
  9462. }
  9463. } else if ( customAttribute.size === 2 ) {
  9464. for ( ca = 0; ca < cal; ca ++ ) {
  9465. index = sortArray[ ca ][ 1 ];
  9466. value = customAttribute.value[ index ];
  9467. customAttribute.array[ offset ] = value.x;
  9468. customAttribute.array[ offset + 1 ] = value.y;
  9469. offset += 2;
  9470. }
  9471. } else if ( customAttribute.size === 3 ) {
  9472. if ( customAttribute.type === "c" ) {
  9473. for ( ca = 0; ca < cal; ca ++ ) {
  9474. index = sortArray[ ca ][ 1 ];
  9475. value = customAttribute.value[ index ];
  9476. customAttribute.array[ offset ] = value.r;
  9477. customAttribute.array[ offset + 1 ] = value.g;
  9478. customAttribute.array[ offset + 2 ] = value.b;
  9479. offset += 3;
  9480. }
  9481. } else {
  9482. for ( ca = 0; ca < cal; ca ++ ) {
  9483. index = sortArray[ ca ][ 1 ];
  9484. value = customAttribute.value[ index ];
  9485. customAttribute.array[ offset ] = value.x;
  9486. customAttribute.array[ offset + 1 ] = value.y;
  9487. customAttribute.array[ offset + 2 ] = value.z;
  9488. offset += 3;
  9489. }
  9490. }
  9491. } else if ( customAttribute.size === 4 ) {
  9492. for ( ca = 0; ca < cal; ca ++ ) {
  9493. index = sortArray[ ca ][ 1 ];
  9494. value = customAttribute.value[ index ];
  9495. customAttribute.array[ offset ] = value.x;
  9496. customAttribute.array[ offset + 1 ] = value.y;
  9497. customAttribute.array[ offset + 2 ] = value.z;
  9498. customAttribute.array[ offset + 3 ] = value.w;
  9499. offset += 4;
  9500. }
  9501. }
  9502. }
  9503. }
  9504. } else {
  9505. if ( dirtyVertices ) {
  9506. for ( v = 0; v < vl; v ++ ) {
  9507. vertex = vertices[ v ];
  9508. offset = v * 3;
  9509. vertexArray[ offset ] = vertex.x;
  9510. vertexArray[ offset + 1 ] = vertex.y;
  9511. vertexArray[ offset + 2 ] = vertex.z;
  9512. }
  9513. }
  9514. if ( dirtyColors ) {
  9515. for ( c = 0; c < cl; c ++ ) {
  9516. color = colors[ c ];
  9517. offset = c * 3;
  9518. colorArray[ offset ] = color.r;
  9519. colorArray[ offset + 1 ] = color.g;
  9520. colorArray[ offset + 2 ] = color.b;
  9521. }
  9522. }
  9523. if ( customAttributes ) {
  9524. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9525. customAttribute = customAttributes[ i ];
  9526. if ( customAttribute.needsUpdate &&
  9527. ( customAttribute.boundTo === undefined ||
  9528. customAttribute.boundTo === "vertices") ) {
  9529. cal = customAttribute.value.length;
  9530. offset = 0;
  9531. if ( customAttribute.size === 1 ) {
  9532. for ( ca = 0; ca < cal; ca ++ ) {
  9533. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  9534. }
  9535. } else if ( customAttribute.size === 2 ) {
  9536. for ( ca = 0; ca < cal; ca ++ ) {
  9537. value = customAttribute.value[ ca ];
  9538. customAttribute.array[ offset ] = value.x;
  9539. customAttribute.array[ offset + 1 ] = value.y;
  9540. offset += 2;
  9541. }
  9542. } else if ( customAttribute.size === 3 ) {
  9543. if ( customAttribute.type === "c" ) {
  9544. for ( ca = 0; ca < cal; ca ++ ) {
  9545. value = customAttribute.value[ ca ];
  9546. customAttribute.array[ offset ] = value.r;
  9547. customAttribute.array[ offset + 1 ] = value.g;
  9548. customAttribute.array[ offset + 2 ] = value.b;
  9549. offset += 3;
  9550. }
  9551. } else {
  9552. for ( ca = 0; ca < cal; ca ++ ) {
  9553. value = customAttribute.value[ ca ];
  9554. customAttribute.array[ offset ] = value.x;
  9555. customAttribute.array[ offset + 1 ] = value.y;
  9556. customAttribute.array[ offset + 2 ] = value.z;
  9557. offset += 3;
  9558. }
  9559. }
  9560. } else if ( customAttribute.size === 4 ) {
  9561. for ( ca = 0; ca < cal; ca ++ ) {
  9562. value = customAttribute.value[ ca ];
  9563. customAttribute.array[ offset ] = value.x;
  9564. customAttribute.array[ offset + 1 ] = value.y;
  9565. customAttribute.array[ offset + 2 ] = value.z;
  9566. customAttribute.array[ offset + 3 ] = value.w;
  9567. offset += 4;
  9568. }
  9569. }
  9570. }
  9571. }
  9572. }
  9573. }
  9574. if ( dirtyVertices || object.sortParticles ) {
  9575. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  9576. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9577. }
  9578. if ( dirtyColors || object.sortParticles ) {
  9579. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  9580. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  9581. }
  9582. if ( customAttributes ) {
  9583. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9584. customAttribute = customAttributes[ i ];
  9585. if ( customAttribute.needsUpdate || object.sortParticles ) {
  9586. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  9587. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  9588. }
  9589. }
  9590. }
  9591. };
  9592. function setLineBuffers ( geometry, hint ) {
  9593. var v, c, vertex, offset, color,
  9594. vertices = geometry.vertices,
  9595. colors = geometry.colors,
  9596. vl = vertices.length,
  9597. cl = colors.length,
  9598. vertexArray = geometry.__vertexArray,
  9599. colorArray = geometry.__colorArray,
  9600. dirtyVertices = geometry.verticesNeedUpdate,
  9601. dirtyColors = geometry.colorsNeedUpdate,
  9602. customAttributes = geometry.__webglCustomAttributesList,
  9603. i, il,
  9604. a, ca, cal, value,
  9605. customAttribute;
  9606. if ( dirtyVertices ) {
  9607. for ( v = 0; v < vl; v ++ ) {
  9608. vertex = vertices[ v ];
  9609. offset = v * 3;
  9610. vertexArray[ offset ] = vertex.x;
  9611. vertexArray[ offset + 1 ] = vertex.y;
  9612. vertexArray[ offset + 2 ] = vertex.z;
  9613. }
  9614. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  9615. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9616. }
  9617. if ( dirtyColors ) {
  9618. for ( c = 0; c < cl; c ++ ) {
  9619. color = colors[ c ];
  9620. offset = c * 3;
  9621. colorArray[ offset ] = color.r;
  9622. colorArray[ offset + 1 ] = color.g;
  9623. colorArray[ offset + 2 ] = color.b;
  9624. }
  9625. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  9626. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  9627. }
  9628. if ( customAttributes ) {
  9629. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9630. customAttribute = customAttributes[ i ];
  9631. if ( customAttribute.needsUpdate &&
  9632. ( customAttribute.boundTo === undefined ||
  9633. customAttribute.boundTo === "vertices" ) ) {
  9634. offset = 0;
  9635. cal = customAttribute.value.length;
  9636. if ( customAttribute.size === 1 ) {
  9637. for ( ca = 0; ca < cal; ca ++ ) {
  9638. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  9639. }
  9640. } else if ( customAttribute.size === 2 ) {
  9641. for ( ca = 0; ca < cal; ca ++ ) {
  9642. value = customAttribute.value[ ca ];
  9643. customAttribute.array[ offset ] = value.x;
  9644. customAttribute.array[ offset + 1 ] = value.y;
  9645. offset += 2;
  9646. }
  9647. } else if ( customAttribute.size === 3 ) {
  9648. if ( customAttribute.type === "c" ) {
  9649. for ( ca = 0; ca < cal; ca ++ ) {
  9650. value = customAttribute.value[ ca ];
  9651. customAttribute.array[ offset ] = value.r;
  9652. customAttribute.array[ offset + 1 ] = value.g;
  9653. customAttribute.array[ offset + 2 ] = value.b;
  9654. offset += 3;
  9655. }
  9656. } else {
  9657. for ( ca = 0; ca < cal; ca ++ ) {
  9658. value = customAttribute.value[ ca ];
  9659. customAttribute.array[ offset ] = value.x;
  9660. customAttribute.array[ offset + 1 ] = value.y;
  9661. customAttribute.array[ offset + 2 ] = value.z;
  9662. offset += 3;
  9663. }
  9664. }
  9665. } else if ( customAttribute.size === 4 ) {
  9666. for ( ca = 0; ca < cal; ca ++ ) {
  9667. value = customAttribute.value[ ca ];
  9668. customAttribute.array[ offset ] = value.x;
  9669. customAttribute.array[ offset + 1 ] = value.y;
  9670. customAttribute.array[ offset + 2 ] = value.z;
  9671. customAttribute.array[ offset + 3 ] = value.w;
  9672. offset += 4;
  9673. }
  9674. }
  9675. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  9676. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  9677. }
  9678. }
  9679. }
  9680. };
  9681. function setRibbonBuffers ( geometry, hint ) {
  9682. var v, c, vertex, offset, color,
  9683. vertices = geometry.vertices,
  9684. colors = geometry.colors,
  9685. vl = vertices.length,
  9686. cl = colors.length,
  9687. vertexArray = geometry.__vertexArray,
  9688. colorArray = geometry.__colorArray,
  9689. dirtyVertices = geometry.verticesNeedUpdate,
  9690. dirtyColors = geometry.colorsNeedUpdate;
  9691. if ( dirtyVertices ) {
  9692. for ( v = 0; v < vl; v ++ ) {
  9693. vertex = vertices[ v ];
  9694. offset = v * 3;
  9695. vertexArray[ offset ] = vertex.x;
  9696. vertexArray[ offset + 1 ] = vertex.y;
  9697. vertexArray[ offset + 2 ] = vertex.z;
  9698. }
  9699. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  9700. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9701. }
  9702. if ( dirtyColors ) {
  9703. for ( c = 0; c < cl; c ++ ) {
  9704. color = colors[ c ];
  9705. offset = c * 3;
  9706. colorArray[ offset ] = color.r;
  9707. colorArray[ offset + 1 ] = color.g;
  9708. colorArray[ offset + 2 ] = color.b;
  9709. }
  9710. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  9711. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  9712. }
  9713. };
  9714. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  9715. if ( ! geometryGroup.__inittedArrays ) {
  9716. // console.log( object );
  9717. return;
  9718. }
  9719. var normalType = bufferGuessNormalType( material ),
  9720. vertexColorType = bufferGuessVertexColorType( material ),
  9721. uvType = bufferGuessUVType( material ),
  9722. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  9723. var f, fl, fi, face,
  9724. vertexNormals, faceNormal, normal,
  9725. vertexColors, faceColor,
  9726. vertexTangents,
  9727. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  9728. c1, c2, c3, c4,
  9729. sw1, sw2, sw3, sw4,
  9730. si1, si2, si3, si4,
  9731. sa1, sa2, sa3, sa4,
  9732. sb1, sb2, sb3, sb4,
  9733. m, ml, i, il,
  9734. vn, uvi, uv2i,
  9735. vk, vkl, vka,
  9736. nka, chf, faceVertexNormals,
  9737. a,
  9738. vertexIndex = 0,
  9739. offset = 0,
  9740. offset_uv = 0,
  9741. offset_uv2 = 0,
  9742. offset_face = 0,
  9743. offset_normal = 0,
  9744. offset_tangent = 0,
  9745. offset_line = 0,
  9746. offset_color = 0,
  9747. offset_skin = 0,
  9748. offset_morphTarget = 0,
  9749. offset_custom = 0,
  9750. offset_customSrc = 0,
  9751. value,
  9752. vertexArray = geometryGroup.__vertexArray,
  9753. uvArray = geometryGroup.__uvArray,
  9754. uv2Array = geometryGroup.__uv2Array,
  9755. normalArray = geometryGroup.__normalArray,
  9756. tangentArray = geometryGroup.__tangentArray,
  9757. colorArray = geometryGroup.__colorArray,
  9758. skinVertexAArray = geometryGroup.__skinVertexAArray,
  9759. skinVertexBArray = geometryGroup.__skinVertexBArray,
  9760. skinIndexArray = geometryGroup.__skinIndexArray,
  9761. skinWeightArray = geometryGroup.__skinWeightArray,
  9762. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  9763. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  9764. customAttributes = geometryGroup.__webglCustomAttributesList,
  9765. customAttribute,
  9766. faceArray = geometryGroup.__faceArray,
  9767. lineArray = geometryGroup.__lineArray,
  9768. geometry = object.geometry, // this is shared for all chunks
  9769. dirtyVertices = geometry.verticesNeedUpdate,
  9770. dirtyElements = geometry.elementsNeedUpdate,
  9771. dirtyUvs = geometry.uvsNeedUpdate,
  9772. dirtyNormals = geometry.normalsNeedUpdate,
  9773. dirtyTangents = geometry.tangentsNeedUpdate,
  9774. dirtyColors = geometry.colorsNeedUpdate,
  9775. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  9776. vertices = geometry.vertices,
  9777. chunk_faces3 = geometryGroup.faces3,
  9778. chunk_faces4 = geometryGroup.faces4,
  9779. obj_faces = geometry.faces,
  9780. obj_uvs = geometry.faceVertexUvs[ 0 ],
  9781. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  9782. obj_colors = geometry.colors,
  9783. obj_skinVerticesA = geometry.skinVerticesA,
  9784. obj_skinVerticesB = geometry.skinVerticesB,
  9785. obj_skinIndices = geometry.skinIndices,
  9786. obj_skinWeights = geometry.skinWeights,
  9787. morphTargets = geometry.morphTargets,
  9788. morphNormals = geometry.morphNormals;
  9789. if ( dirtyVertices ) {
  9790. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  9791. face = obj_faces[ chunk_faces3[ f ] ];
  9792. v1 = vertices[ face.a ];
  9793. v2 = vertices[ face.b ];
  9794. v3 = vertices[ face.c ];
  9795. vertexArray[ offset ] = v1.x;
  9796. vertexArray[ offset + 1 ] = v1.y;
  9797. vertexArray[ offset + 2 ] = v1.z;
  9798. vertexArray[ offset + 3 ] = v2.x;
  9799. vertexArray[ offset + 4 ] = v2.y;
  9800. vertexArray[ offset + 5 ] = v2.z;
  9801. vertexArray[ offset + 6 ] = v3.x;
  9802. vertexArray[ offset + 7 ] = v3.y;
  9803. vertexArray[ offset + 8 ] = v3.z;
  9804. offset += 9;
  9805. }
  9806. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  9807. face = obj_faces[ chunk_faces4[ f ] ];
  9808. v1 = vertices[ face.a ];
  9809. v2 = vertices[ face.b ];
  9810. v3 = vertices[ face.c ];
  9811. v4 = vertices[ face.d ];
  9812. vertexArray[ offset ] = v1.x;
  9813. vertexArray[ offset + 1 ] = v1.y;
  9814. vertexArray[ offset + 2 ] = v1.z;
  9815. vertexArray[ offset + 3 ] = v2.x;
  9816. vertexArray[ offset + 4 ] = v2.y;
  9817. vertexArray[ offset + 5 ] = v2.z;
  9818. vertexArray[ offset + 6 ] = v3.x;
  9819. vertexArray[ offset + 7 ] = v3.y;
  9820. vertexArray[ offset + 8 ] = v3.z;
  9821. vertexArray[ offset + 9 ] = v4.x;
  9822. vertexArray[ offset + 10 ] = v4.y;
  9823. vertexArray[ offset + 11 ] = v4.z;
  9824. offset += 12;
  9825. }
  9826. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  9827. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9828. }
  9829. if ( dirtyMorphTargets ) {
  9830. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  9831. offset_morphTarget = 0;
  9832. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  9833. chf = chunk_faces3[ f ];
  9834. face = obj_faces[ chf ];
  9835. // morph positions
  9836. v1 = morphTargets[ vk ].vertices[ face.a ];
  9837. v2 = morphTargets[ vk ].vertices[ face.b ];
  9838. v3 = morphTargets[ vk ].vertices[ face.c ];
  9839. vka = morphTargetsArrays[ vk ];
  9840. vka[ offset_morphTarget ] = v1.x;
  9841. vka[ offset_morphTarget + 1 ] = v1.y;
  9842. vka[ offset_morphTarget + 2 ] = v1.z;
  9843. vka[ offset_morphTarget + 3 ] = v2.x;
  9844. vka[ offset_morphTarget + 4 ] = v2.y;
  9845. vka[ offset_morphTarget + 5 ] = v2.z;
  9846. vka[ offset_morphTarget + 6 ] = v3.x;
  9847. vka[ offset_morphTarget + 7 ] = v3.y;
  9848. vka[ offset_morphTarget + 8 ] = v3.z;
  9849. // morph normals
  9850. if ( material.morphNormals ) {
  9851. if ( needsSmoothNormals ) {
  9852. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  9853. n1 = faceVertexNormals.a;
  9854. n2 = faceVertexNormals.b;
  9855. n3 = faceVertexNormals.c;
  9856. } else {
  9857. n1 = morphNormals[ vk ].faceNormals[ chf ];
  9858. n2 = n1;
  9859. n3 = n1;
  9860. }
  9861. nka = morphNormalsArrays[ vk ];
  9862. nka[ offset_morphTarget ] = n1.x;
  9863. nka[ offset_morphTarget + 1 ] = n1.y;
  9864. nka[ offset_morphTarget + 2 ] = n1.z;
  9865. nka[ offset_morphTarget + 3 ] = n2.x;
  9866. nka[ offset_morphTarget + 4 ] = n2.y;
  9867. nka[ offset_morphTarget + 5 ] = n2.z;
  9868. nka[ offset_morphTarget + 6 ] = n3.x;
  9869. nka[ offset_morphTarget + 7 ] = n3.y;
  9870. nka[ offset_morphTarget + 8 ] = n3.z;
  9871. }
  9872. //
  9873. offset_morphTarget += 9;
  9874. }
  9875. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  9876. chf = chunk_faces4[ f ];
  9877. face = obj_faces[ chf ];
  9878. // morph positions
  9879. v1 = morphTargets[ vk ].vertices[ face.a ];
  9880. v2 = morphTargets[ vk ].vertices[ face.b ];
  9881. v3 = morphTargets[ vk ].vertices[ face.c ];
  9882. v4 = morphTargets[ vk ].vertices[ face.d ];
  9883. vka = morphTargetsArrays[ vk ];
  9884. vka[ offset_morphTarget ] = v1.x;
  9885. vka[ offset_morphTarget + 1 ] = v1.y;
  9886. vka[ offset_morphTarget + 2 ] = v1.z;
  9887. vka[ offset_morphTarget + 3 ] = v2.x;
  9888. vka[ offset_morphTarget + 4 ] = v2.y;
  9889. vka[ offset_morphTarget + 5 ] = v2.z;
  9890. vka[ offset_morphTarget + 6 ] = v3.x;
  9891. vka[ offset_morphTarget + 7 ] = v3.y;
  9892. vka[ offset_morphTarget + 8 ] = v3.z;
  9893. vka[ offset_morphTarget + 9 ] = v4.x;
  9894. vka[ offset_morphTarget + 10 ] = v4.y;
  9895. vka[ offset_morphTarget + 11 ] = v4.z;
  9896. // morph normals
  9897. if ( material.morphNormals ) {
  9898. if ( needsSmoothNormals ) {
  9899. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  9900. n1 = faceVertexNormals.a;
  9901. n2 = faceVertexNormals.b;
  9902. n3 = faceVertexNormals.c;
  9903. n4 = faceVertexNormals.d;
  9904. } else {
  9905. n1 = morphNormals[ vk ].faceNormals[ chf ];
  9906. n2 = n1;
  9907. n3 = n1;
  9908. n4 = n1;
  9909. }
  9910. nka = morphNormalsArrays[ vk ];
  9911. nka[ offset_morphTarget ] = n1.x;
  9912. nka[ offset_morphTarget + 1 ] = n1.y;
  9913. nka[ offset_morphTarget + 2 ] = n1.z;
  9914. nka[ offset_morphTarget + 3 ] = n2.x;
  9915. nka[ offset_morphTarget + 4 ] = n2.y;
  9916. nka[ offset_morphTarget + 5 ] = n2.z;
  9917. nka[ offset_morphTarget + 6 ] = n3.x;
  9918. nka[ offset_morphTarget + 7 ] = n3.y;
  9919. nka[ offset_morphTarget + 8 ] = n3.z;
  9920. nka[ offset_morphTarget + 9 ] = n4.x;
  9921. nka[ offset_morphTarget + 10 ] = n4.y;
  9922. nka[ offset_morphTarget + 11 ] = n4.z;
  9923. }
  9924. //
  9925. offset_morphTarget += 12;
  9926. }
  9927. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  9928. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  9929. if ( material.morphNormals ) {
  9930. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  9931. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  9932. }
  9933. }
  9934. }
  9935. if ( obj_skinWeights.length ) {
  9936. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  9937. face = obj_faces[ chunk_faces3[ f ] ];
  9938. // weights
  9939. sw1 = obj_skinWeights[ face.a ];
  9940. sw2 = obj_skinWeights[ face.b ];
  9941. sw3 = obj_skinWeights[ face.c ];
  9942. skinWeightArray[ offset_skin ] = sw1.x;
  9943. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  9944. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  9945. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  9946. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  9947. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  9948. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  9949. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  9950. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  9951. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  9952. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  9953. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  9954. // indices
  9955. si1 = obj_skinIndices[ face.a ];
  9956. si2 = obj_skinIndices[ face.b ];
  9957. si3 = obj_skinIndices[ face.c ];
  9958. skinIndexArray[ offset_skin ] = si1.x;
  9959. skinIndexArray[ offset_skin + 1 ] = si1.y;
  9960. skinIndexArray[ offset_skin + 2 ] = si1.z;
  9961. skinIndexArray[ offset_skin + 3 ] = si1.w;
  9962. skinIndexArray[ offset_skin + 4 ] = si2.x;
  9963. skinIndexArray[ offset_skin + 5 ] = si2.y;
  9964. skinIndexArray[ offset_skin + 6 ] = si2.z;
  9965. skinIndexArray[ offset_skin + 7 ] = si2.w;
  9966. skinIndexArray[ offset_skin + 8 ] = si3.x;
  9967. skinIndexArray[ offset_skin + 9 ] = si3.y;
  9968. skinIndexArray[ offset_skin + 10 ] = si3.z;
  9969. skinIndexArray[ offset_skin + 11 ] = si3.w;
  9970. // vertices A
  9971. sa1 = obj_skinVerticesA[ face.a ];
  9972. sa2 = obj_skinVerticesA[ face.b ];
  9973. sa3 = obj_skinVerticesA[ face.c ];
  9974. skinVertexAArray[ offset_skin ] = sa1.x;
  9975. skinVertexAArray[ offset_skin + 1 ] = sa1.y;
  9976. skinVertexAArray[ offset_skin + 2 ] = sa1.z;
  9977. skinVertexAArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  9978. skinVertexAArray[ offset_skin + 4 ] = sa2.x;
  9979. skinVertexAArray[ offset_skin + 5 ] = sa2.y;
  9980. skinVertexAArray[ offset_skin + 6 ] = sa2.z;
  9981. skinVertexAArray[ offset_skin + 7 ] = 1;
  9982. skinVertexAArray[ offset_skin + 8 ] = sa3.x;
  9983. skinVertexAArray[ offset_skin + 9 ] = sa3.y;
  9984. skinVertexAArray[ offset_skin + 10 ] = sa3.z;
  9985. skinVertexAArray[ offset_skin + 11 ] = 1;
  9986. // vertices B
  9987. sb1 = obj_skinVerticesB[ face.a ];
  9988. sb2 = obj_skinVerticesB[ face.b ];
  9989. sb3 = obj_skinVerticesB[ face.c ];
  9990. skinVertexBArray[ offset_skin ] = sb1.x;
  9991. skinVertexBArray[ offset_skin + 1 ] = sb1.y;
  9992. skinVertexBArray[ offset_skin + 2 ] = sb1.z;
  9993. skinVertexBArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  9994. skinVertexBArray[ offset_skin + 4 ] = sb2.x;
  9995. skinVertexBArray[ offset_skin + 5 ] = sb2.y;
  9996. skinVertexBArray[ offset_skin + 6 ] = sb2.z;
  9997. skinVertexBArray[ offset_skin + 7 ] = 1;
  9998. skinVertexBArray[ offset_skin + 8 ] = sb3.x;
  9999. skinVertexBArray[ offset_skin + 9 ] = sb3.y;
  10000. skinVertexBArray[ offset_skin + 10 ] = sb3.z;
  10001. skinVertexBArray[ offset_skin + 11 ] = 1;
  10002. offset_skin += 12;
  10003. }
  10004. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10005. face = obj_faces[ chunk_faces4[ f ] ];
  10006. // weights
  10007. sw1 = obj_skinWeights[ face.a ];
  10008. sw2 = obj_skinWeights[ face.b ];
  10009. sw3 = obj_skinWeights[ face.c ];
  10010. sw4 = obj_skinWeights[ face.d ];
  10011. skinWeightArray[ offset_skin ] = sw1.x;
  10012. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10013. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10014. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10015. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10016. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10017. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10018. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10019. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10020. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10021. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10022. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10023. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  10024. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  10025. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  10026. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  10027. // indices
  10028. si1 = obj_skinIndices[ face.a ];
  10029. si2 = obj_skinIndices[ face.b ];
  10030. si3 = obj_skinIndices[ face.c ];
  10031. si4 = obj_skinIndices[ face.d ];
  10032. skinIndexArray[ offset_skin ] = si1.x;
  10033. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10034. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10035. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10036. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10037. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10038. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10039. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10040. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10041. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10042. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10043. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10044. skinIndexArray[ offset_skin + 12 ] = si4.x;
  10045. skinIndexArray[ offset_skin + 13 ] = si4.y;
  10046. skinIndexArray[ offset_skin + 14 ] = si4.z;
  10047. skinIndexArray[ offset_skin + 15 ] = si4.w;
  10048. // vertices A
  10049. sa1 = obj_skinVerticesA[ face.a ];
  10050. sa2 = obj_skinVerticesA[ face.b ];
  10051. sa3 = obj_skinVerticesA[ face.c ];
  10052. sa4 = obj_skinVerticesA[ face.d ];
  10053. skinVertexAArray[ offset_skin ] = sa1.x;
  10054. skinVertexAArray[ offset_skin + 1 ] = sa1.y;
  10055. skinVertexAArray[ offset_skin + 2 ] = sa1.z;
  10056. skinVertexAArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  10057. skinVertexAArray[ offset_skin + 4 ] = sa2.x;
  10058. skinVertexAArray[ offset_skin + 5 ] = sa2.y;
  10059. skinVertexAArray[ offset_skin + 6 ] = sa2.z;
  10060. skinVertexAArray[ offset_skin + 7 ] = 1;
  10061. skinVertexAArray[ offset_skin + 8 ] = sa3.x;
  10062. skinVertexAArray[ offset_skin + 9 ] = sa3.y;
  10063. skinVertexAArray[ offset_skin + 10 ] = sa3.z;
  10064. skinVertexAArray[ offset_skin + 11 ] = 1;
  10065. skinVertexAArray[ offset_skin + 12 ] = sa4.x;
  10066. skinVertexAArray[ offset_skin + 13 ] = sa4.y;
  10067. skinVertexAArray[ offset_skin + 14 ] = sa4.z;
  10068. skinVertexAArray[ offset_skin + 15 ] = 1;
  10069. // vertices B
  10070. sb1 = obj_skinVerticesB[ face.a ];
  10071. sb2 = obj_skinVerticesB[ face.b ];
  10072. sb3 = obj_skinVerticesB[ face.c ];
  10073. sb4 = obj_skinVerticesB[ face.d ];
  10074. skinVertexBArray[ offset_skin ] = sb1.x;
  10075. skinVertexBArray[ offset_skin + 1 ] = sb1.y;
  10076. skinVertexBArray[ offset_skin + 2 ] = sb1.z;
  10077. skinVertexBArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  10078. skinVertexBArray[ offset_skin + 4 ] = sb2.x;
  10079. skinVertexBArray[ offset_skin + 5 ] = sb2.y;
  10080. skinVertexBArray[ offset_skin + 6 ] = sb2.z;
  10081. skinVertexBArray[ offset_skin + 7 ] = 1;
  10082. skinVertexBArray[ offset_skin + 8 ] = sb3.x;
  10083. skinVertexBArray[ offset_skin + 9 ] = sb3.y;
  10084. skinVertexBArray[ offset_skin + 10 ] = sb3.z;
  10085. skinVertexBArray[ offset_skin + 11 ] = 1;
  10086. skinVertexBArray[ offset_skin + 12 ] = sb4.x;
  10087. skinVertexBArray[ offset_skin + 13 ] = sb4.y;
  10088. skinVertexBArray[ offset_skin + 14 ] = sb4.z;
  10089. skinVertexBArray[ offset_skin + 15 ] = 1;
  10090. offset_skin += 16;
  10091. }
  10092. if ( offset_skin > 0 ) {
  10093. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexABuffer );
  10094. _gl.bufferData( _gl.ARRAY_BUFFER, skinVertexAArray, hint );
  10095. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexBBuffer );
  10096. _gl.bufferData( _gl.ARRAY_BUFFER, skinVertexBArray, hint );
  10097. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10098. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  10099. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10100. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  10101. }
  10102. }
  10103. if ( dirtyColors && vertexColorType ) {
  10104. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10105. face = obj_faces[ chunk_faces3[ f ] ];
  10106. vertexColors = face.vertexColors;
  10107. faceColor = face.color;
  10108. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  10109. c1 = vertexColors[ 0 ];
  10110. c2 = vertexColors[ 1 ];
  10111. c3 = vertexColors[ 2 ];
  10112. } else {
  10113. c1 = faceColor;
  10114. c2 = faceColor;
  10115. c3 = faceColor;
  10116. }
  10117. colorArray[ offset_color ] = c1.r;
  10118. colorArray[ offset_color + 1 ] = c1.g;
  10119. colorArray[ offset_color + 2 ] = c1.b;
  10120. colorArray[ offset_color + 3 ] = c2.r;
  10121. colorArray[ offset_color + 4 ] = c2.g;
  10122. colorArray[ offset_color + 5 ] = c2.b;
  10123. colorArray[ offset_color + 6 ] = c3.r;
  10124. colorArray[ offset_color + 7 ] = c3.g;
  10125. colorArray[ offset_color + 8 ] = c3.b;
  10126. offset_color += 9;
  10127. }
  10128. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10129. face = obj_faces[ chunk_faces4[ f ] ];
  10130. vertexColors = face.vertexColors;
  10131. faceColor = face.color;
  10132. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  10133. c1 = vertexColors[ 0 ];
  10134. c2 = vertexColors[ 1 ];
  10135. c3 = vertexColors[ 2 ];
  10136. c4 = vertexColors[ 3 ];
  10137. } else {
  10138. c1 = faceColor;
  10139. c2 = faceColor;
  10140. c3 = faceColor;
  10141. c4 = faceColor;
  10142. }
  10143. colorArray[ offset_color ] = c1.r;
  10144. colorArray[ offset_color + 1 ] = c1.g;
  10145. colorArray[ offset_color + 2 ] = c1.b;
  10146. colorArray[ offset_color + 3 ] = c2.r;
  10147. colorArray[ offset_color + 4 ] = c2.g;
  10148. colorArray[ offset_color + 5 ] = c2.b;
  10149. colorArray[ offset_color + 6 ] = c3.r;
  10150. colorArray[ offset_color + 7 ] = c3.g;
  10151. colorArray[ offset_color + 8 ] = c3.b;
  10152. colorArray[ offset_color + 9 ] = c4.r;
  10153. colorArray[ offset_color + 10 ] = c4.g;
  10154. colorArray[ offset_color + 11 ] = c4.b;
  10155. offset_color += 12;
  10156. }
  10157. if ( offset_color > 0 ) {
  10158. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10159. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10160. }
  10161. }
  10162. if ( dirtyTangents && geometry.hasTangents ) {
  10163. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10164. face = obj_faces[ chunk_faces3[ f ] ];
  10165. vertexTangents = face.vertexTangents;
  10166. t1 = vertexTangents[ 0 ];
  10167. t2 = vertexTangents[ 1 ];
  10168. t3 = vertexTangents[ 2 ];
  10169. tangentArray[ offset_tangent ] = t1.x;
  10170. tangentArray[ offset_tangent + 1 ] = t1.y;
  10171. tangentArray[ offset_tangent + 2 ] = t1.z;
  10172. tangentArray[ offset_tangent + 3 ] = t1.w;
  10173. tangentArray[ offset_tangent + 4 ] = t2.x;
  10174. tangentArray[ offset_tangent + 5 ] = t2.y;
  10175. tangentArray[ offset_tangent + 6 ] = t2.z;
  10176. tangentArray[ offset_tangent + 7 ] = t2.w;
  10177. tangentArray[ offset_tangent + 8 ] = t3.x;
  10178. tangentArray[ offset_tangent + 9 ] = t3.y;
  10179. tangentArray[ offset_tangent + 10 ] = t3.z;
  10180. tangentArray[ offset_tangent + 11 ] = t3.w;
  10181. offset_tangent += 12;
  10182. }
  10183. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10184. face = obj_faces[ chunk_faces4[ f ] ];
  10185. vertexTangents = face.vertexTangents;
  10186. t1 = vertexTangents[ 0 ];
  10187. t2 = vertexTangents[ 1 ];
  10188. t3 = vertexTangents[ 2 ];
  10189. t4 = vertexTangents[ 3 ];
  10190. tangentArray[ offset_tangent ] = t1.x;
  10191. tangentArray[ offset_tangent + 1 ] = t1.y;
  10192. tangentArray[ offset_tangent + 2 ] = t1.z;
  10193. tangentArray[ offset_tangent + 3 ] = t1.w;
  10194. tangentArray[ offset_tangent + 4 ] = t2.x;
  10195. tangentArray[ offset_tangent + 5 ] = t2.y;
  10196. tangentArray[ offset_tangent + 6 ] = t2.z;
  10197. tangentArray[ offset_tangent + 7 ] = t2.w;
  10198. tangentArray[ offset_tangent + 8 ] = t3.x;
  10199. tangentArray[ offset_tangent + 9 ] = t3.y;
  10200. tangentArray[ offset_tangent + 10 ] = t3.z;
  10201. tangentArray[ offset_tangent + 11 ] = t3.w;
  10202. tangentArray[ offset_tangent + 12 ] = t4.x;
  10203. tangentArray[ offset_tangent + 13 ] = t4.y;
  10204. tangentArray[ offset_tangent + 14 ] = t4.z;
  10205. tangentArray[ offset_tangent + 15 ] = t4.w;
  10206. offset_tangent += 16;
  10207. }
  10208. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10209. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  10210. }
  10211. if ( dirtyNormals && normalType ) {
  10212. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10213. face = obj_faces[ chunk_faces3[ f ] ];
  10214. vertexNormals = face.vertexNormals;
  10215. faceNormal = face.normal;
  10216. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  10217. for ( i = 0; i < 3; i ++ ) {
  10218. vn = vertexNormals[ i ];
  10219. normalArray[ offset_normal ] = vn.x;
  10220. normalArray[ offset_normal + 1 ] = vn.y;
  10221. normalArray[ offset_normal + 2 ] = vn.z;
  10222. offset_normal += 3;
  10223. }
  10224. } else {
  10225. for ( i = 0; i < 3; i ++ ) {
  10226. normalArray[ offset_normal ] = faceNormal.x;
  10227. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10228. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10229. offset_normal += 3;
  10230. }
  10231. }
  10232. }
  10233. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10234. face = obj_faces[ chunk_faces4[ f ] ];
  10235. vertexNormals = face.vertexNormals;
  10236. faceNormal = face.normal;
  10237. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  10238. for ( i = 0; i < 4; i ++ ) {
  10239. vn = vertexNormals[ i ];
  10240. normalArray[ offset_normal ] = vn.x;
  10241. normalArray[ offset_normal + 1 ] = vn.y;
  10242. normalArray[ offset_normal + 2 ] = vn.z;
  10243. offset_normal += 3;
  10244. }
  10245. } else {
  10246. for ( i = 0; i < 4; i ++ ) {
  10247. normalArray[ offset_normal ] = faceNormal.x;
  10248. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10249. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10250. offset_normal += 3;
  10251. }
  10252. }
  10253. }
  10254. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10255. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10256. }
  10257. if ( dirtyUvs && obj_uvs && uvType ) {
  10258. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10259. fi = chunk_faces3[ f ];
  10260. face = obj_faces[ fi ];
  10261. uv = obj_uvs[ fi ];
  10262. if ( uv === undefined ) continue;
  10263. for ( i = 0; i < 3; i ++ ) {
  10264. uvi = uv[ i ];
  10265. uvArray[ offset_uv ] = uvi.u;
  10266. uvArray[ offset_uv + 1 ] = uvi.v;
  10267. offset_uv += 2;
  10268. }
  10269. }
  10270. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10271. fi = chunk_faces4[ f ];
  10272. face = obj_faces[ fi ];
  10273. uv = obj_uvs[ fi ];
  10274. if ( uv === undefined ) continue;
  10275. for ( i = 0; i < 4; i ++ ) {
  10276. uvi = uv[ i ];
  10277. uvArray[ offset_uv ] = uvi.u;
  10278. uvArray[ offset_uv + 1 ] = uvi.v;
  10279. offset_uv += 2;
  10280. }
  10281. }
  10282. if ( offset_uv > 0 ) {
  10283. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10284. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  10285. }
  10286. }
  10287. if ( dirtyUvs && obj_uvs2 && uvType ) {
  10288. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10289. fi = chunk_faces3[ f ];
  10290. face = obj_faces[ fi ];
  10291. uv2 = obj_uvs2[ fi ];
  10292. if ( uv2 === undefined ) continue;
  10293. for ( i = 0; i < 3; i ++ ) {
  10294. uv2i = uv2[ i ];
  10295. uv2Array[ offset_uv2 ] = uv2i.u;
  10296. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10297. offset_uv2 += 2;
  10298. }
  10299. }
  10300. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10301. fi = chunk_faces4[ f ];
  10302. face = obj_faces[ fi ];
  10303. uv2 = obj_uvs2[ fi ];
  10304. if ( uv2 === undefined ) continue;
  10305. for ( i = 0; i < 4; i ++ ) {
  10306. uv2i = uv2[ i ];
  10307. uv2Array[ offset_uv2 ] = uv2i.u;
  10308. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10309. offset_uv2 += 2;
  10310. }
  10311. }
  10312. if ( offset_uv2 > 0 ) {
  10313. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10314. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  10315. }
  10316. }
  10317. if ( dirtyElements ) {
  10318. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10319. face = obj_faces[ chunk_faces3[ f ] ];
  10320. faceArray[ offset_face ] = vertexIndex;
  10321. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10322. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  10323. offset_face += 3;
  10324. lineArray[ offset_line ] = vertexIndex;
  10325. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10326. lineArray[ offset_line + 2 ] = vertexIndex;
  10327. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  10328. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10329. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10330. offset_line += 6;
  10331. vertexIndex += 3;
  10332. }
  10333. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10334. face = obj_faces[ chunk_faces4[ f ] ];
  10335. faceArray[ offset_face ] = vertexIndex;
  10336. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10337. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  10338. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  10339. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  10340. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  10341. offset_face += 6;
  10342. lineArray[ offset_line ] = vertexIndex;
  10343. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10344. lineArray[ offset_line + 2 ] = vertexIndex;
  10345. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  10346. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10347. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10348. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  10349. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  10350. offset_line += 8;
  10351. vertexIndex += 4;
  10352. }
  10353. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10354. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  10355. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10356. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  10357. }
  10358. if ( customAttributes ) {
  10359. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10360. customAttribute = customAttributes[ i ];
  10361. if ( ! customAttribute.__original.needsUpdate ) continue;
  10362. offset_custom = 0;
  10363. offset_customSrc = 0;
  10364. if ( customAttribute.size === 1 ) {
  10365. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10366. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10367. face = obj_faces[ chunk_faces3[ f ] ];
  10368. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10369. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10370. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10371. offset_custom += 3;
  10372. }
  10373. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10374. face = obj_faces[ chunk_faces4[ f ] ];
  10375. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10376. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10377. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10378. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  10379. offset_custom += 4;
  10380. }
  10381. } else if ( customAttribute.boundTo === "faces" ) {
  10382. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10383. value = customAttribute.value[ chunk_faces3[ f ] ];
  10384. customAttribute.array[ offset_custom ] = value;
  10385. customAttribute.array[ offset_custom + 1 ] = value;
  10386. customAttribute.array[ offset_custom + 2 ] = value;
  10387. offset_custom += 3;
  10388. }
  10389. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10390. value = customAttribute.value[ chunk_faces4[ f ] ];
  10391. customAttribute.array[ offset_custom ] = value;
  10392. customAttribute.array[ offset_custom + 1 ] = value;
  10393. customAttribute.array[ offset_custom + 2 ] = value;
  10394. customAttribute.array[ offset_custom + 3 ] = value;
  10395. offset_custom += 4;
  10396. }
  10397. }
  10398. } else if ( customAttribute.size === 2 ) {
  10399. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10400. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10401. face = obj_faces[ chunk_faces3[ f ] ];
  10402. v1 = customAttribute.value[ face.a ];
  10403. v2 = customAttribute.value[ face.b ];
  10404. v3 = customAttribute.value[ face.c ];
  10405. customAttribute.array[ offset_custom ] = v1.x;
  10406. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10407. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10408. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10409. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10410. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10411. offset_custom += 6;
  10412. }
  10413. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10414. face = obj_faces[ chunk_faces4[ f ] ];
  10415. v1 = customAttribute.value[ face.a ];
  10416. v2 = customAttribute.value[ face.b ];
  10417. v3 = customAttribute.value[ face.c ];
  10418. v4 = customAttribute.value[ face.d ];
  10419. customAttribute.array[ offset_custom ] = v1.x;
  10420. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10421. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10422. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10423. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10424. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10425. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10426. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10427. offset_custom += 8;
  10428. }
  10429. } else if ( customAttribute.boundTo === "faces" ) {
  10430. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10431. value = customAttribute.value[ chunk_faces3[ f ] ];
  10432. v1 = value;
  10433. v2 = value;
  10434. v3 = value;
  10435. customAttribute.array[ offset_custom ] = v1.x;
  10436. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10437. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10438. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10439. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10440. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10441. offset_custom += 6;
  10442. }
  10443. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10444. value = customAttribute.value[ chunk_faces4[ f ] ];
  10445. v1 = value;
  10446. v2 = value;
  10447. v3 = value;
  10448. v4 = value;
  10449. customAttribute.array[ offset_custom ] = v1.x;
  10450. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10451. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10452. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10453. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10454. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10455. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10456. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10457. offset_custom += 8;
  10458. }
  10459. }
  10460. } else if ( customAttribute.size === 3 ) {
  10461. var pp;
  10462. if ( customAttribute.type === "c" ) {
  10463. pp = [ "r", "g", "b" ];
  10464. } else {
  10465. pp = [ "x", "y", "z" ];
  10466. }
  10467. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10468. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10469. face = obj_faces[ chunk_faces3[ f ] ];
  10470. v1 = customAttribute.value[ face.a ];
  10471. v2 = customAttribute.value[ face.b ];
  10472. v3 = customAttribute.value[ face.c ];
  10473. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10474. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10475. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10476. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10477. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10478. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10479. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10480. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10481. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10482. offset_custom += 9;
  10483. }
  10484. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10485. face = obj_faces[ chunk_faces4[ f ] ];
  10486. v1 = customAttribute.value[ face.a ];
  10487. v2 = customAttribute.value[ face.b ];
  10488. v3 = customAttribute.value[ face.c ];
  10489. v4 = customAttribute.value[ face.d ];
  10490. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10491. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10492. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10493. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10494. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10495. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10496. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10497. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10498. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10499. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10500. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10501. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10502. offset_custom += 12;
  10503. }
  10504. } else if ( customAttribute.boundTo === "faces" ) {
  10505. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10506. value = customAttribute.value[ chunk_faces3[ f ] ];
  10507. v1 = value;
  10508. v2 = value;
  10509. v3 = value;
  10510. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10511. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10512. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10513. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10514. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10515. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10516. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10517. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10518. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10519. offset_custom += 9;
  10520. }
  10521. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10522. value = customAttribute.value[ chunk_faces4[ f ] ];
  10523. v1 = value;
  10524. v2 = value;
  10525. v3 = value;
  10526. v4 = value;
  10527. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10528. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10529. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10530. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10531. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10532. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10533. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10534. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10535. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10536. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10537. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10538. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10539. offset_custom += 12;
  10540. }
  10541. } else if ( customAttribute.boundTo === "faceVertices" ) {
  10542. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10543. value = customAttribute.value[ chunk_faces3[ f ] ];
  10544. v1 = value[ 0 ];
  10545. v2 = value[ 1 ];
  10546. v3 = value[ 2 ];
  10547. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10548. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10549. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10550. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10551. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10552. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10553. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10554. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10555. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10556. offset_custom += 9;
  10557. }
  10558. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10559. value = customAttribute.value[ chunk_faces4[ f ] ];
  10560. v1 = value[ 0 ];
  10561. v2 = value[ 1 ];
  10562. v3 = value[ 2 ];
  10563. v4 = value[ 3 ];
  10564. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10565. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10566. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10567. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10568. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10569. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10570. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10571. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10572. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10573. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10574. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10575. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10576. offset_custom += 12;
  10577. }
  10578. }
  10579. } else if ( customAttribute.size === 4 ) {
  10580. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10581. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10582. face = obj_faces[ chunk_faces3[ f ] ];
  10583. v1 = customAttribute.value[ face.a ];
  10584. v2 = customAttribute.value[ face.b ];
  10585. v3 = customAttribute.value[ face.c ];
  10586. customAttribute.array[ offset_custom ] = v1.x;
  10587. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10588. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10589. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10590. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10591. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10592. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10593. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10594. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10595. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10596. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10597. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10598. offset_custom += 12;
  10599. }
  10600. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10601. face = obj_faces[ chunk_faces4[ f ] ];
  10602. v1 = customAttribute.value[ face.a ];
  10603. v2 = customAttribute.value[ face.b ];
  10604. v3 = customAttribute.value[ face.c ];
  10605. v4 = customAttribute.value[ face.d ];
  10606. customAttribute.array[ offset_custom ] = v1.x;
  10607. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10608. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10609. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10610. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10611. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10612. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10613. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10614. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10615. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10616. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10617. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10618. customAttribute.array[ offset_custom + 12 ] = v4.x;
  10619. customAttribute.array[ offset_custom + 13 ] = v4.y;
  10620. customAttribute.array[ offset_custom + 14 ] = v4.z;
  10621. customAttribute.array[ offset_custom + 15 ] = v4.w;
  10622. offset_custom += 16;
  10623. }
  10624. } else if ( customAttribute.boundTo === "faces" ) {
  10625. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10626. value = customAttribute.value[ chunk_faces3[ f ] ];
  10627. v1 = value;
  10628. v2 = value;
  10629. v3 = value;
  10630. customAttribute.array[ offset_custom ] = v1.x;
  10631. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10632. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10633. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10634. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10635. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10636. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10637. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10638. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10639. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10640. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10641. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10642. offset_custom += 12;
  10643. }
  10644. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10645. value = customAttribute.value[ chunk_faces4[ f ] ];
  10646. v1 = value;
  10647. v2 = value;
  10648. v3 = value;
  10649. v4 = value;
  10650. customAttribute.array[ offset_custom ] = v1.x;
  10651. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10652. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10653. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10654. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10655. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10656. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10657. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10658. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10659. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10660. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10661. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10662. customAttribute.array[ offset_custom + 12 ] = v4.x;
  10663. customAttribute.array[ offset_custom + 13 ] = v4.y;
  10664. customAttribute.array[ offset_custom + 14 ] = v4.z;
  10665. customAttribute.array[ offset_custom + 15 ] = v4.w;
  10666. offset_custom += 16;
  10667. }
  10668. } else if ( customAttribute.boundTo === "faceVertices" ) {
  10669. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10670. value = customAttribute.value[ chunk_faces3[ f ] ];
  10671. v1 = value[ 0 ];
  10672. v2 = value[ 1 ];
  10673. v3 = value[ 2 ];
  10674. customAttribute.array[ offset_custom ] = v1.x;
  10675. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10676. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10677. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10678. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10679. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10680. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10681. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10682. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10683. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10684. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10685. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10686. offset_custom += 12;
  10687. }
  10688. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10689. value = customAttribute.value[ chunk_faces4[ f ] ];
  10690. v1 = value[ 0 ];
  10691. v2 = value[ 1 ];
  10692. v3 = value[ 2 ];
  10693. v4 = value[ 3 ];
  10694. customAttribute.array[ offset_custom ] = v1.x;
  10695. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10696. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10697. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10698. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10699. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10700. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10701. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10702. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10703. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10704. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10705. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10706. customAttribute.array[ offset_custom + 12 ] = v4.x;
  10707. customAttribute.array[ offset_custom + 13 ] = v4.y;
  10708. customAttribute.array[ offset_custom + 14 ] = v4.z;
  10709. customAttribute.array[ offset_custom + 15 ] = v4.w;
  10710. offset_custom += 16;
  10711. }
  10712. }
  10713. }
  10714. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10715. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10716. }
  10717. }
  10718. if ( dispose ) {
  10719. delete geometryGroup.__inittedArrays;
  10720. delete geometryGroup.__colorArray;
  10721. delete geometryGroup.__normalArray;
  10722. delete geometryGroup.__tangentArray;
  10723. delete geometryGroup.__uvArray;
  10724. delete geometryGroup.__uv2Array;
  10725. delete geometryGroup.__faceArray;
  10726. delete geometryGroup.__vertexArray;
  10727. delete geometryGroup.__lineArray;
  10728. delete geometryGroup.__skinVertexAArray;
  10729. delete geometryGroup.__skinVertexBArray;
  10730. delete geometryGroup.__skinIndexArray;
  10731. delete geometryGroup.__skinWeightArray;
  10732. }
  10733. };
  10734. function setDirectBuffers ( geometry, hint, dispose ) {
  10735. var attributes = geometry.attributes;
  10736. var index = attributes[ "index" ];
  10737. var position = attributes[ "position" ];
  10738. var normal = attributes[ "normal" ];
  10739. var uv = attributes[ "uv" ];
  10740. var color = attributes[ "color" ];
  10741. var tangent = attributes[ "tangent" ];
  10742. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  10743. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  10744. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  10745. }
  10746. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  10747. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  10748. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  10749. }
  10750. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  10751. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  10752. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  10753. }
  10754. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  10755. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  10756. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  10757. }
  10758. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  10759. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  10760. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  10761. }
  10762. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  10763. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  10764. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  10765. }
  10766. if ( dispose ) {
  10767. for ( var i in geometry.attributes ) {
  10768. delete geometry.attributes[ i ].array;
  10769. }
  10770. }
  10771. };
  10772. // Buffer rendering
  10773. this.renderBufferImmediate = function ( object, program, material ) {
  10774. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  10775. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  10776. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  10777. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  10778. if ( object.hasPositions ) {
  10779. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  10780. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  10781. _gl.enableVertexAttribArray( program.attributes.position );
  10782. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  10783. }
  10784. if ( object.hasNormals ) {
  10785. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  10786. if ( material.shading === THREE.FlatShading ) {
  10787. var nx, ny, nz,
  10788. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  10789. normalArray,
  10790. i, il = object.count * 3;
  10791. for( i = 0; i < il; i += 9 ) {
  10792. normalArray = object.normalArray;
  10793. nax = normalArray[ i ];
  10794. nay = normalArray[ i + 1 ];
  10795. naz = normalArray[ i + 2 ];
  10796. nbx = normalArray[ i + 3 ];
  10797. nby = normalArray[ i + 4 ];
  10798. nbz = normalArray[ i + 5 ];
  10799. ncx = normalArray[ i + 6 ];
  10800. ncy = normalArray[ i + 7 ];
  10801. ncz = normalArray[ i + 8 ];
  10802. nx = ( nax + nbx + ncx ) / 3;
  10803. ny = ( nay + nby + ncy ) / 3;
  10804. nz = ( naz + nbz + ncz ) / 3;
  10805. normalArray[ i ] = nx;
  10806. normalArray[ i + 1 ] = ny;
  10807. normalArray[ i + 2 ] = nz;
  10808. normalArray[ i + 3 ] = nx;
  10809. normalArray[ i + 4 ] = ny;
  10810. normalArray[ i + 5 ] = nz;
  10811. normalArray[ i + 6 ] = nx;
  10812. normalArray[ i + 7 ] = ny;
  10813. normalArray[ i + 8 ] = nz;
  10814. }
  10815. }
  10816. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  10817. _gl.enableVertexAttribArray( program.attributes.normal );
  10818. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  10819. }
  10820. if ( object.hasUvs && material.map ) {
  10821. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  10822. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  10823. _gl.enableVertexAttribArray( program.attributes.uv );
  10824. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  10825. }
  10826. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  10827. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  10828. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  10829. _gl.enableVertexAttribArray( program.attributes.color );
  10830. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  10831. }
  10832. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  10833. object.count = 0;
  10834. };
  10835. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  10836. if ( material.visible === false ) return;
  10837. var program, attributes, linewidth, primitives, a, attribute;
  10838. program = setProgram( camera, lights, fog, material, object );
  10839. attributes = program.attributes;
  10840. var updateBuffers = false,
  10841. wireframeBit = material.wireframe ? 1 : 0,
  10842. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  10843. if ( geometryHash !== _currentGeometryGroupHash ) {
  10844. _currentGeometryGroupHash = geometryHash;
  10845. updateBuffers = true;
  10846. }
  10847. // render mesh
  10848. if ( object instanceof THREE.Mesh ) {
  10849. var offsets = geometry.offsets;
  10850. // if there is more than 1 chunk
  10851. // must set attribute pointers to use new offsets for each chunk
  10852. // even if geometry and materials didn't change
  10853. if ( offsets.length > 1 ) updateBuffers = true;
  10854. for ( var i = 0, il = offsets.length; i < il; ++ i ) {
  10855. var startIndex = offsets[ i ].index;
  10856. if ( updateBuffers ) {
  10857. // vertices
  10858. var position = geometry.attributes[ "position" ];
  10859. var positionSize = position.itemSize;
  10860. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  10861. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  10862. // normals
  10863. var normal = geometry.attributes[ "normal" ];
  10864. if ( attributes.normal >= 0 && normal ) {
  10865. var normalSize = normal.itemSize;
  10866. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  10867. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  10868. }
  10869. // uvs
  10870. var uv = geometry.attributes[ "uv" ];
  10871. if ( attributes.uv >= 0 && uv ) {
  10872. if ( uv.buffer ) {
  10873. var uvSize = uv.itemSize;
  10874. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  10875. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  10876. _gl.enableVertexAttribArray( attributes.uv );
  10877. } else {
  10878. _gl.disableVertexAttribArray( attributes.uv );
  10879. }
  10880. }
  10881. // colors
  10882. var color = geometry.attributes[ "color" ];
  10883. if ( attributes.color >= 0 && color ) {
  10884. var colorSize = color.itemSize;
  10885. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  10886. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  10887. }
  10888. // tangents
  10889. var tangent = geometry.attributes[ "tangent" ];
  10890. if ( attributes.tangent >= 0 && tangent ) {
  10891. var tangentSize = tangent.itemSize;
  10892. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  10893. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  10894. }
  10895. // indices
  10896. var index = geometry.attributes[ "index" ];
  10897. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  10898. }
  10899. // render indexed triangles
  10900. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  10901. _this.info.render.calls ++;
  10902. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  10903. _this.info.render.faces += offsets[ i ].count / 3;
  10904. }
  10905. }
  10906. };
  10907. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  10908. if ( material.visible === false ) return;
  10909. var program, attributes, linewidth, primitives, a, attribute, i, il;
  10910. program = setProgram( camera, lights, fog, material, object );
  10911. attributes = program.attributes;
  10912. var updateBuffers = false,
  10913. wireframeBit = material.wireframe ? 1 : 0,
  10914. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  10915. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  10916. _currentGeometryGroupHash = geometryGroupHash;
  10917. updateBuffers = true;
  10918. }
  10919. // vertices
  10920. if ( !material.morphTargets && attributes.position >= 0 ) {
  10921. if ( updateBuffers ) {
  10922. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10923. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  10924. }
  10925. } else {
  10926. if ( object.morphTargetBase ) {
  10927. setupMorphTargets( material, geometryGroup, object );
  10928. }
  10929. }
  10930. if ( updateBuffers ) {
  10931. // custom attributes
  10932. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  10933. if ( geometryGroup.__webglCustomAttributesList ) {
  10934. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  10935. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  10936. if( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  10937. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  10938. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  10939. }
  10940. }
  10941. }
  10942. // colors
  10943. if ( attributes.color >= 0 ) {
  10944. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10945. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  10946. }
  10947. // normals
  10948. if ( attributes.normal >= 0 ) {
  10949. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10950. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  10951. }
  10952. // tangents
  10953. if ( attributes.tangent >= 0 ) {
  10954. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10955. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  10956. }
  10957. // uvs
  10958. if ( attributes.uv >= 0 ) {
  10959. if ( geometryGroup.__webglUVBuffer ) {
  10960. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10961. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  10962. _gl.enableVertexAttribArray( attributes.uv );
  10963. } else {
  10964. _gl.disableVertexAttribArray( attributes.uv );
  10965. }
  10966. }
  10967. if ( attributes.uv2 >= 0 ) {
  10968. if ( geometryGroup.__webglUV2Buffer ) {
  10969. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10970. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  10971. _gl.enableVertexAttribArray( attributes.uv2 );
  10972. } else {
  10973. _gl.disableVertexAttribArray( attributes.uv2 );
  10974. }
  10975. }
  10976. if ( material.skinning &&
  10977. attributes.skinVertexA >= 0 && attributes.skinVertexB >= 0 &&
  10978. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  10979. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexABuffer );
  10980. _gl.vertexAttribPointer( attributes.skinVertexA, 4, _gl.FLOAT, false, 0, 0 );
  10981. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexBBuffer );
  10982. _gl.vertexAttribPointer( attributes.skinVertexB, 4, _gl.FLOAT, false, 0, 0 );
  10983. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10984. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  10985. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10986. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  10987. }
  10988. }
  10989. // render mesh
  10990. if ( object instanceof THREE.Mesh ) {
  10991. // wireframe
  10992. if ( material.wireframe ) {
  10993. setLineWidth( material.wireframeLinewidth );
  10994. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10995. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  10996. // triangles
  10997. } else {
  10998. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10999. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  11000. }
  11001. _this.info.render.calls ++;
  11002. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  11003. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11004. // render lines
  11005. } else if ( object instanceof THREE.Line ) {
  11006. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  11007. setLineWidth( material.linewidth );
  11008. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  11009. _this.info.render.calls ++;
  11010. // render particles
  11011. } else if ( object instanceof THREE.ParticleSystem ) {
  11012. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  11013. _this.info.render.calls ++;
  11014. _this.info.render.points += geometryGroup.__webglParticleCount;
  11015. // render ribbon
  11016. } else if ( object instanceof THREE.Ribbon ) {
  11017. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  11018. _this.info.render.calls ++;
  11019. }
  11020. };
  11021. function setupMorphTargets ( material, geometryGroup, object ) {
  11022. // set base
  11023. var attributes = material.program.attributes;
  11024. if ( object.morphTargetBase !== -1 ) {
  11025. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  11026. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11027. } else if ( attributes.position >= 0 ) {
  11028. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11029. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11030. }
  11031. if ( object.morphTargetForcedOrder.length ) {
  11032. // set forced order
  11033. var m = 0;
  11034. var order = object.morphTargetForcedOrder;
  11035. var influences = object.morphTargetInfluences;
  11036. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11037. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  11038. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11039. if ( material.morphNormals ) {
  11040. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  11041. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11042. }
  11043. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11044. m ++;
  11045. }
  11046. } else {
  11047. // find the most influencing
  11048. var influence, activeInfluenceIndices = [];
  11049. var influences = object.morphTargetInfluences;
  11050. var i, il = influences.length;
  11051. for ( i = 0; i < il; i ++ ) {
  11052. influence = influences[ i ];
  11053. if ( influence > 0 ) {
  11054. activeInfluenceIndices.push( [ i, influence ] );
  11055. }
  11056. }
  11057. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11058. activeInfluenceIndices.sort( numericalSort );
  11059. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11060. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11061. activeInfluenceIndices.sort( numericalSort );
  11062. } else if ( activeInfluenceIndices.length === 0 ) {
  11063. activeInfluenceIndices.push( [ 0, 0 ] );
  11064. };
  11065. var influenceIndex, m = 0;
  11066. while ( m < material.numSupportedMorphTargets ) {
  11067. if ( activeInfluenceIndices[ m ] ) {
  11068. influenceIndex = activeInfluenceIndices[ m ][ 0 ];
  11069. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  11070. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11071. if ( material.morphNormals ) {
  11072. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  11073. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11074. }
  11075. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11076. } else {
  11077. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11078. if ( material.morphNormals ) {
  11079. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11080. }
  11081. object.__webglMorphTargetInfluences[ m ] = 0;
  11082. }
  11083. m ++;
  11084. }
  11085. }
  11086. // load updated influences uniform
  11087. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11088. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11089. }
  11090. };
  11091. // Sorting
  11092. function painterSort ( a, b ) {
  11093. return b.z - a.z;
  11094. };
  11095. function numericalSort ( a, b ) {
  11096. return b[ 1 ] - a[ 1 ];
  11097. };
  11098. // Rendering
  11099. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11100. if ( camera instanceof THREE.Camera === false ) {
  11101. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11102. return;
  11103. }
  11104. var i, il,
  11105. webglObject, object,
  11106. renderList,
  11107. lights = scene.__lights,
  11108. fog = scene.fog;
  11109. // reset caching for this frame
  11110. _currentMaterialId = -1;
  11111. _lightsNeedUpdate = true;
  11112. // update scene graph
  11113. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11114. // update camera matrices and frustum
  11115. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11116. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  11117. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  11118. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11119. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  11120. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  11121. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11122. _frustum.setFromMatrix( _projScreenMatrix );
  11123. // update WebGL objects
  11124. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11125. // custom render plugins (pre pass)
  11126. renderPlugins( this.renderPluginsPre, scene, camera );
  11127. //
  11128. _this.info.render.calls = 0;
  11129. _this.info.render.vertices = 0;
  11130. _this.info.render.faces = 0;
  11131. _this.info.render.points = 0;
  11132. this.setRenderTarget( renderTarget );
  11133. if ( this.autoClear || forceClear ) {
  11134. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11135. }
  11136. // set matrices for regular objects (frustum culled)
  11137. renderList = scene.__webglObjects;
  11138. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11139. webglObject = renderList[ i ];
  11140. object = webglObject.object;
  11141. webglObject.render = false;
  11142. if ( object.visible ) {
  11143. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11144. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11145. setupMatrices( object, camera );
  11146. unrollBufferMaterial( webglObject );
  11147. webglObject.render = true;
  11148. if ( this.sortObjects ) {
  11149. if ( object.renderDepth ) {
  11150. webglObject.z = object.renderDepth;
  11151. } else {
  11152. _vector3.copy( object.matrixWorld.getPosition() );
  11153. _projScreenMatrix.multiplyVector3( _vector3 );
  11154. webglObject.z = _vector3.z;
  11155. }
  11156. }
  11157. }
  11158. }
  11159. }
  11160. if ( this.sortObjects ) {
  11161. renderList.sort( painterSort );
  11162. }
  11163. // set matrices for immediate objects
  11164. renderList = scene.__webglObjectsImmediate;
  11165. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11166. webglObject = renderList[ i ];
  11167. object = webglObject.object;
  11168. if ( object.visible ) {
  11169. /*
  11170. if ( object.matrixAutoUpdate ) {
  11171. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11172. }
  11173. */
  11174. setupMatrices( object, camera );
  11175. unrollImmediateBufferMaterial( webglObject );
  11176. }
  11177. }
  11178. if ( scene.overrideMaterial ) {
  11179. var material = scene.overrideMaterial;
  11180. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11181. this.setDepthTest( material.depthTest );
  11182. this.setDepthWrite( material.depthWrite );
  11183. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11184. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11185. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11186. } else {
  11187. // opaque pass (front-to-back order)
  11188. this.setBlending( THREE.NormalBlending );
  11189. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  11190. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  11191. // transparent pass (back-to-front order)
  11192. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  11193. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  11194. }
  11195. // custom render plugins (post pass)
  11196. renderPlugins( this.renderPluginsPost, scene, camera );
  11197. // Generate mipmap if we're using any kind of mipmap filtering
  11198. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11199. updateRenderTargetMipmap( renderTarget );
  11200. }
  11201. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11202. this.setDepthTest( true );
  11203. this.setDepthWrite( true );
  11204. // _gl.finish();
  11205. };
  11206. function renderPlugins( plugins, scene, camera ) {
  11207. if ( ! plugins.length ) return;
  11208. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11209. // reset state for plugin (to start from clean slate)
  11210. _currentProgram = null;
  11211. _currentCamera = null;
  11212. _oldBlending = -1;
  11213. _oldDepthTest = -1;
  11214. _oldDepthWrite = -1;
  11215. _oldDoubleSided = -1;
  11216. _oldFlipSided = -1;
  11217. _currentGeometryGroupHash = -1;
  11218. _currentMaterialId = -1;
  11219. _lightsNeedUpdate = true;
  11220. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  11221. // reset state after plugin (anything could have changed)
  11222. _currentProgram = null;
  11223. _currentCamera = null;
  11224. _oldBlending = -1;
  11225. _oldDepthTest = -1;
  11226. _oldDepthWrite = -1;
  11227. _oldDoubleSided = -1;
  11228. _oldFlipSided = -1;
  11229. _currentGeometryGroupHash = -1;
  11230. _currentMaterialId = -1;
  11231. _lightsNeedUpdate = true;
  11232. }
  11233. };
  11234. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11235. var webglObject, object, buffer, material, start, end, delta;
  11236. if ( reverse ) {
  11237. start = renderList.length - 1;
  11238. end = -1;
  11239. delta = -1;
  11240. } else {
  11241. start = 0;
  11242. end = renderList.length;
  11243. delta = 1;
  11244. }
  11245. for ( var i = start; i !== end; i += delta ) {
  11246. webglObject = renderList[ i ];
  11247. if ( webglObject.render ) {
  11248. object = webglObject.object;
  11249. buffer = webglObject.buffer;
  11250. if ( overrideMaterial ) {
  11251. material = overrideMaterial;
  11252. } else {
  11253. material = webglObject[ materialType ];
  11254. if ( ! material ) continue;
  11255. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11256. _this.setDepthTest( material.depthTest );
  11257. _this.setDepthWrite( material.depthWrite );
  11258. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11259. }
  11260. _this.setMaterialFaces( material );
  11261. if ( buffer instanceof THREE.BufferGeometry ) {
  11262. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11263. } else {
  11264. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11265. }
  11266. }
  11267. }
  11268. };
  11269. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11270. var webglObject, object, material, program;
  11271. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11272. webglObject = renderList[ i ];
  11273. object = webglObject.object;
  11274. if ( object.visible ) {
  11275. if ( overrideMaterial ) {
  11276. material = overrideMaterial;
  11277. } else {
  11278. material = webglObject[ materialType ];
  11279. if ( ! material ) continue;
  11280. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11281. _this.setDepthTest( material.depthTest );
  11282. _this.setDepthWrite( material.depthWrite );
  11283. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11284. }
  11285. _this.renderImmediateObject( camera, lights, fog, material, object );
  11286. }
  11287. }
  11288. };
  11289. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  11290. var program = setProgram( camera, lights, fog, material, object );
  11291. _currentGeometryGroupHash = -1;
  11292. _this.setMaterialFaces( material );
  11293. if ( object.immediateRenderCallback ) {
  11294. object.immediateRenderCallback( program, _gl, _frustum );
  11295. } else {
  11296. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  11297. }
  11298. };
  11299. function unrollImmediateBufferMaterial ( globject ) {
  11300. var object = globject.object,
  11301. material = object.material;
  11302. if ( material.transparent ) {
  11303. globject.transparent = material;
  11304. globject.opaque = null;
  11305. } else {
  11306. globject.opaque = material;
  11307. globject.transparent = null;
  11308. }
  11309. };
  11310. function unrollBufferMaterial ( globject ) {
  11311. var object = globject.object,
  11312. buffer = globject.buffer,
  11313. material, materialIndex, meshMaterial;
  11314. meshMaterial = object.material;
  11315. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  11316. materialIndex = buffer.materialIndex;
  11317. if ( materialIndex >= 0 ) {
  11318. material = object.geometry.materials[ materialIndex ];
  11319. if ( material.transparent ) {
  11320. globject.transparent = material;
  11321. globject.opaque = null;
  11322. } else {
  11323. globject.opaque = material;
  11324. globject.transparent = null;
  11325. }
  11326. }
  11327. } else {
  11328. material = meshMaterial;
  11329. if ( material ) {
  11330. if ( material.transparent ) {
  11331. globject.transparent = material;
  11332. globject.opaque = null;
  11333. } else {
  11334. globject.opaque = material;
  11335. globject.transparent = null;
  11336. }
  11337. }
  11338. }
  11339. };
  11340. // Geometry splitting
  11341. function sortFacesByMaterial ( geometry ) {
  11342. var f, fl, face, materialIndex, vertices,
  11343. materialHash, groupHash,
  11344. hash_map = {};
  11345. var numMorphTargets = geometry.morphTargets.length;
  11346. var numMorphNormals = geometry.morphNormals.length;
  11347. geometry.geometryGroups = {};
  11348. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  11349. face = geometry.faces[ f ];
  11350. materialIndex = face.materialIndex;
  11351. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  11352. if ( hash_map[ materialHash ] === undefined ) {
  11353. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  11354. }
  11355. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11356. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11357. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11358. }
  11359. vertices = face instanceof THREE.Face3 ? 3 : 4;
  11360. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  11361. hash_map[ materialHash ].counter += 1;
  11362. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11363. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11364. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11365. }
  11366. }
  11367. if ( face instanceof THREE.Face3 ) {
  11368. geometry.geometryGroups[ groupHash ].faces3.push( f );
  11369. } else {
  11370. geometry.geometryGroups[ groupHash ].faces4.push( f );
  11371. }
  11372. geometry.geometryGroups[ groupHash ].vertices += vertices;
  11373. }
  11374. geometry.geometryGroupsList = [];
  11375. for ( var g in geometry.geometryGroups ) {
  11376. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  11377. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  11378. }
  11379. };
  11380. // Objects refresh
  11381. this.initWebGLObjects = function ( scene ) {
  11382. if ( !scene.__webglObjects ) {
  11383. scene.__webglObjects = [];
  11384. scene.__webglObjectsImmediate = [];
  11385. scene.__webglSprites = [];
  11386. scene.__webglFlares = [];
  11387. }
  11388. while ( scene.__objectsAdded.length ) {
  11389. addObject( scene.__objectsAdded[ 0 ], scene );
  11390. scene.__objectsAdded.splice( 0, 1 );
  11391. }
  11392. while ( scene.__objectsRemoved.length ) {
  11393. removeObject( scene.__objectsRemoved[ 0 ], scene );
  11394. scene.__objectsRemoved.splice( 0, 1 );
  11395. }
  11396. // update must be called after objects adding / removal
  11397. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  11398. updateObject( scene.__webglObjects[ o ].object );
  11399. }
  11400. };
  11401. // Objects adding
  11402. function addObject ( object, scene ) {
  11403. var g, geometry, geometryGroup;
  11404. if ( ! object.__webglInit ) {
  11405. object.__webglInit = true;
  11406. object._modelViewMatrix = new THREE.Matrix4();
  11407. object._normalMatrix = new THREE.Matrix3();
  11408. if ( object instanceof THREE.Mesh ) {
  11409. geometry = object.geometry;
  11410. if ( geometry instanceof THREE.Geometry ) {
  11411. if ( geometry.geometryGroups === undefined ) {
  11412. sortFacesByMaterial( geometry );
  11413. }
  11414. // create separate VBOs per geometry chunk
  11415. for ( g in geometry.geometryGroups ) {
  11416. geometryGroup = geometry.geometryGroups[ g ];
  11417. // initialise VBO on the first access
  11418. if ( ! geometryGroup.__webglVertexBuffer ) {
  11419. createMeshBuffers( geometryGroup );
  11420. initMeshBuffers( geometryGroup, object );
  11421. geometry.verticesNeedUpdate = true;
  11422. geometry.morphTargetsNeedUpdate = true;
  11423. geometry.elementsNeedUpdate = true;
  11424. geometry.uvsNeedUpdate = true;
  11425. geometry.normalsNeedUpdate = true;
  11426. geometry.tangentsNeedUpdate = true;
  11427. geometry.colorsNeedUpdate = true;
  11428. }
  11429. }
  11430. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11431. initDirectBuffers( geometry );
  11432. }
  11433. } else if ( object instanceof THREE.Ribbon ) {
  11434. geometry = object.geometry;
  11435. if( ! geometry.__webglVertexBuffer ) {
  11436. createRibbonBuffers( geometry );
  11437. initRibbonBuffers( geometry );
  11438. geometry.verticesNeedUpdate = true;
  11439. geometry.colorsNeedUpdate = true;
  11440. }
  11441. } else if ( object instanceof THREE.Line ) {
  11442. geometry = object.geometry;
  11443. if( ! geometry.__webglVertexBuffer ) {
  11444. createLineBuffers( geometry );
  11445. initLineBuffers( geometry, object );
  11446. geometry.verticesNeedUpdate = true;
  11447. geometry.colorsNeedUpdate = true;
  11448. }
  11449. } else if ( object instanceof THREE.ParticleSystem ) {
  11450. geometry = object.geometry;
  11451. if ( ! geometry.__webglVertexBuffer ) {
  11452. createParticleBuffers( geometry );
  11453. initParticleBuffers( geometry, object );
  11454. geometry.verticesNeedUpdate = true;
  11455. geometry.colorsNeedUpdate = true;
  11456. }
  11457. }
  11458. }
  11459. if ( ! object.__webglActive ) {
  11460. if ( object instanceof THREE.Mesh ) {
  11461. geometry = object.geometry;
  11462. if ( geometry instanceof THREE.BufferGeometry ) {
  11463. addBuffer( scene.__webglObjects, geometry, object );
  11464. } else {
  11465. for ( g in geometry.geometryGroups ) {
  11466. geometryGroup = geometry.geometryGroups[ g ];
  11467. addBuffer( scene.__webglObjects, geometryGroup, object );
  11468. }
  11469. }
  11470. } else if ( object instanceof THREE.Ribbon ||
  11471. object instanceof THREE.Line ||
  11472. object instanceof THREE.ParticleSystem ) {
  11473. geometry = object.geometry;
  11474. addBuffer( scene.__webglObjects, geometry, object );
  11475. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11476. addBufferImmediate( scene.__webglObjectsImmediate, object );
  11477. } else if ( object instanceof THREE.Sprite ) {
  11478. scene.__webglSprites.push( object );
  11479. } else if ( object instanceof THREE.LensFlare ) {
  11480. scene.__webglFlares.push( object );
  11481. }
  11482. object.__webglActive = true;
  11483. }
  11484. };
  11485. function addBuffer ( objlist, buffer, object ) {
  11486. objlist.push(
  11487. {
  11488. buffer: buffer,
  11489. object: object,
  11490. opaque: null,
  11491. transparent: null
  11492. }
  11493. );
  11494. };
  11495. function addBufferImmediate ( objlist, object ) {
  11496. objlist.push(
  11497. {
  11498. object: object,
  11499. opaque: null,
  11500. transparent: null
  11501. }
  11502. );
  11503. };
  11504. // Objects updates
  11505. function updateObject ( object ) {
  11506. var geometry = object.geometry,
  11507. geometryGroup, customAttributesDirty, material;
  11508. if ( object instanceof THREE.Mesh ) {
  11509. if ( geometry instanceof THREE.BufferGeometry ) {
  11510. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  11511. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11512. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  11513. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  11514. }
  11515. geometry.verticesNeedUpdate = false;
  11516. geometry.elementsNeedUpdate = false;
  11517. geometry.uvsNeedUpdate = false;
  11518. geometry.normalsNeedUpdate = false;
  11519. geometry.colorsNeedUpdate = false;
  11520. geometry.tangentsNeedUpdate = false;
  11521. } else {
  11522. // check all geometry groups
  11523. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  11524. geometryGroup = geometry.geometryGroupsList[ i ];
  11525. material = getBufferMaterial( object, geometryGroup );
  11526. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11527. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  11528. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11529. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  11530. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  11531. }
  11532. }
  11533. geometry.verticesNeedUpdate = false;
  11534. geometry.morphTargetsNeedUpdate = false;
  11535. geometry.elementsNeedUpdate = false;
  11536. geometry.uvsNeedUpdate = false;
  11537. geometry.normalsNeedUpdate = false;
  11538. geometry.colorsNeedUpdate = false;
  11539. geometry.tangentsNeedUpdate = false;
  11540. material.attributes && clearCustomAttributes( material );
  11541. }
  11542. } else if ( object instanceof THREE.Ribbon ) {
  11543. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  11544. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  11545. }
  11546. geometry.verticesNeedUpdate = false;
  11547. geometry.colorsNeedUpdate = false;
  11548. } else if ( object instanceof THREE.Line ) {
  11549. material = getBufferMaterial( object, geometryGroup );
  11550. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11551. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) {
  11552. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  11553. }
  11554. geometry.verticesNeedUpdate = false;
  11555. geometry.colorsNeedUpdate = false;
  11556. material.attributes && clearCustomAttributes( material );
  11557. } else if ( object instanceof THREE.ParticleSystem ) {
  11558. material = getBufferMaterial( object, geometryGroup );
  11559. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11560. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  11561. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  11562. }
  11563. geometry.verticesNeedUpdate = false;
  11564. geometry.colorsNeedUpdate = false;
  11565. material.attributes && clearCustomAttributes( material );
  11566. }
  11567. };
  11568. // Objects updates - custom attributes check
  11569. function areCustomAttributesDirty ( material ) {
  11570. for ( var a in material.attributes ) {
  11571. if ( material.attributes[ a ].needsUpdate ) return true;
  11572. }
  11573. return false;
  11574. };
  11575. function clearCustomAttributes ( material ) {
  11576. for ( var a in material.attributes ) {
  11577. material.attributes[ a ].needsUpdate = false;
  11578. }
  11579. };
  11580. // Objects removal
  11581. function removeObject ( object, scene ) {
  11582. if ( object instanceof THREE.Mesh ||
  11583. object instanceof THREE.ParticleSystem ||
  11584. object instanceof THREE.Ribbon ||
  11585. object instanceof THREE.Line ) {
  11586. removeInstances( scene.__webglObjects, object );
  11587. } else if ( object instanceof THREE.Sprite ) {
  11588. removeInstancesDirect( scene.__webglSprites, object );
  11589. } else if ( object instanceof THREE.LensFlare ) {
  11590. removeInstancesDirect( scene.__webglFlares, object );
  11591. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11592. removeInstances( scene.__webglObjectsImmediate, object );
  11593. }
  11594. object.__webglActive = false;
  11595. };
  11596. function removeInstances ( objlist, object ) {
  11597. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  11598. if ( objlist[ o ].object === object ) {
  11599. objlist.splice( o, 1 );
  11600. }
  11601. }
  11602. };
  11603. function removeInstancesDirect ( objlist, object ) {
  11604. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  11605. if ( objlist[ o ] === object ) {
  11606. objlist.splice( o, 1 );
  11607. }
  11608. }
  11609. };
  11610. // Materials
  11611. this.initMaterial = function ( material, lights, fog, object ) {
  11612. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  11613. if ( material instanceof THREE.MeshDepthMaterial ) {
  11614. shaderID = 'depth';
  11615. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  11616. shaderID = 'normal';
  11617. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  11618. shaderID = 'basic';
  11619. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  11620. shaderID = 'lambert';
  11621. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  11622. shaderID = 'phong';
  11623. } else if ( material instanceof THREE.LineBasicMaterial ) {
  11624. shaderID = 'basic';
  11625. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  11626. shaderID = 'particle_basic';
  11627. }
  11628. if ( shaderID ) {
  11629. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  11630. }
  11631. // heuristics to create shader parameters according to lights in the scene
  11632. // (not to blow over maxLights budget)
  11633. maxLightCount = allocateLights( lights );
  11634. maxShadows = allocateShadows( lights );
  11635. maxBones = allocateBones( object );
  11636. parameters = {
  11637. map: !!material.map,
  11638. envMap: !!material.envMap,
  11639. lightMap: !!material.lightMap,
  11640. bumpMap: !!material.bumpMap,
  11641. specularMap: !!material.specularMap,
  11642. vertexColors: material.vertexColors,
  11643. fog: fog,
  11644. useFog: material.fog,
  11645. sizeAttenuation: material.sizeAttenuation,
  11646. skinning: material.skinning,
  11647. maxBones: maxBones,
  11648. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  11649. boneTextureWidth: object && object.boneTextureWidth,
  11650. boneTextureHeight: object && object.boneTextureHeight,
  11651. morphTargets: material.morphTargets,
  11652. morphNormals: material.morphNormals,
  11653. maxMorphTargets: this.maxMorphTargets,
  11654. maxMorphNormals: this.maxMorphNormals,
  11655. maxDirLights: maxLightCount.directional,
  11656. maxPointLights: maxLightCount.point,
  11657. maxSpotLights: maxLightCount.spot,
  11658. maxShadows: maxShadows,
  11659. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  11660. shadowMapSoft: this.shadowMapSoft,
  11661. shadowMapDebug: this.shadowMapDebug,
  11662. shadowMapCascade: this.shadowMapCascade,
  11663. alphaTest: material.alphaTest,
  11664. metal: material.metal,
  11665. perPixel: material.perPixel,
  11666. wrapAround: material.wrapAround,
  11667. doubleSided: material.side === THREE.DoubleSide
  11668. };
  11669. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, parameters );
  11670. var attributes = material.program.attributes;
  11671. if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
  11672. if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
  11673. if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
  11674. if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );
  11675. if ( material.skinning &&
  11676. attributes.skinVertexA >=0 && attributes.skinVertexB >= 0 &&
  11677. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11678. _gl.enableVertexAttribArray( attributes.skinVertexA );
  11679. _gl.enableVertexAttribArray( attributes.skinVertexB );
  11680. _gl.enableVertexAttribArray( attributes.skinIndex );
  11681. _gl.enableVertexAttribArray( attributes.skinWeight );
  11682. }
  11683. if ( material.attributes ) {
  11684. for ( a in material.attributes ) {
  11685. if( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );
  11686. }
  11687. }
  11688. if ( material.morphTargets ) {
  11689. material.numSupportedMorphTargets = 0;
  11690. var id, base = "morphTarget";
  11691. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  11692. id = base + i;
  11693. if ( attributes[ id ] >= 0 ) {
  11694. _gl.enableVertexAttribArray( attributes[ id ] );
  11695. material.numSupportedMorphTargets ++;
  11696. }
  11697. }
  11698. }
  11699. if ( material.morphNormals ) {
  11700. material.numSupportedMorphNormals = 0;
  11701. var id, base = "morphNormal";
  11702. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  11703. id = base + i;
  11704. if ( attributes[ id ] >= 0 ) {
  11705. _gl.enableVertexAttribArray( attributes[ id ] );
  11706. material.numSupportedMorphNormals ++;
  11707. }
  11708. }
  11709. }
  11710. material.uniformsList = [];
  11711. for ( u in material.uniforms ) {
  11712. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  11713. }
  11714. };
  11715. function setMaterialShaders( material, shaders ) {
  11716. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  11717. material.vertexShader = shaders.vertexShader;
  11718. material.fragmentShader = shaders.fragmentShader;
  11719. };
  11720. function setProgram( camera, lights, fog, material, object ) {
  11721. if ( material.needsUpdate ) {
  11722. if ( material.program ) _this.deallocateMaterial( material );
  11723. _this.initMaterial( material, lights, fog, object );
  11724. material.needsUpdate = false;
  11725. }
  11726. if ( material.morphTargets ) {
  11727. if ( ! object.__webglMorphTargetInfluences ) {
  11728. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  11729. }
  11730. }
  11731. var refreshMaterial = false;
  11732. var program = material.program,
  11733. p_uniforms = program.uniforms,
  11734. m_uniforms = material.uniforms;
  11735. if ( program !== _currentProgram ) {
  11736. _gl.useProgram( program );
  11737. _currentProgram = program;
  11738. refreshMaterial = true;
  11739. }
  11740. if ( material.id !== _currentMaterialId ) {
  11741. _currentMaterialId = material.id;
  11742. refreshMaterial = true;
  11743. }
  11744. if ( refreshMaterial || camera !== _currentCamera ) {
  11745. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  11746. if ( camera !== _currentCamera ) _currentCamera = camera;
  11747. }
  11748. if ( refreshMaterial ) {
  11749. // refresh uniforms common to several materials
  11750. if ( fog && material.fog ) {
  11751. refreshUniformsFog( m_uniforms, fog );
  11752. }
  11753. if ( material instanceof THREE.MeshPhongMaterial ||
  11754. material instanceof THREE.MeshLambertMaterial ||
  11755. material.lights ) {
  11756. if ( _lightsNeedUpdate ) {
  11757. setupLights( program, lights );
  11758. _lightsNeedUpdate = false;
  11759. }
  11760. refreshUniformsLights( m_uniforms, _lights );
  11761. }
  11762. if ( material instanceof THREE.MeshBasicMaterial ||
  11763. material instanceof THREE.MeshLambertMaterial ||
  11764. material instanceof THREE.MeshPhongMaterial ) {
  11765. refreshUniformsCommon( m_uniforms, material );
  11766. }
  11767. // refresh single material specific uniforms
  11768. if ( material instanceof THREE.LineBasicMaterial ) {
  11769. refreshUniformsLine( m_uniforms, material );
  11770. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  11771. refreshUniformsParticle( m_uniforms, material );
  11772. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  11773. refreshUniformsPhong( m_uniforms, material );
  11774. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  11775. refreshUniformsLambert( m_uniforms, material );
  11776. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  11777. m_uniforms.mNear.value = camera.near;
  11778. m_uniforms.mFar.value = camera.far;
  11779. m_uniforms.opacity.value = material.opacity;
  11780. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  11781. m_uniforms.opacity.value = material.opacity;
  11782. }
  11783. if ( object.receiveShadow && ! material._shadowPass ) {
  11784. refreshUniformsShadow( m_uniforms, lights );
  11785. }
  11786. // load common uniforms
  11787. loadUniformsGeneric( program, material.uniformsList );
  11788. // load material specific uniforms
  11789. // (shader material also gets them for the sake of genericity)
  11790. if ( material instanceof THREE.ShaderMaterial ||
  11791. material instanceof THREE.MeshPhongMaterial ||
  11792. material.envMap ) {
  11793. if ( p_uniforms.cameraPosition !== null ) {
  11794. var position = camera.matrixWorld.getPosition();
  11795. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  11796. }
  11797. }
  11798. if ( material instanceof THREE.MeshPhongMaterial ||
  11799. material instanceof THREE.MeshLambertMaterial ||
  11800. material instanceof THREE.ShaderMaterial ||
  11801. material.skinning ) {
  11802. if ( p_uniforms.viewMatrix !== null ) {
  11803. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  11804. }
  11805. }
  11806. }
  11807. if ( material.skinning ) {
  11808. if ( _supportsBoneTextures && object.useVertexTexture ) {
  11809. if ( p_uniforms.boneTexture !== null ) {
  11810. // shadowMap texture array starts from 6
  11811. // texture unit 12 should leave space for 6 shadowmaps
  11812. var textureUnit = 12;
  11813. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  11814. _this.setTexture( object.boneTexture, textureUnit );
  11815. }
  11816. } else {
  11817. if ( p_uniforms.boneGlobalMatrices !== null ) {
  11818. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  11819. }
  11820. }
  11821. }
  11822. loadUniformsMatrices( p_uniforms, object );
  11823. if ( p_uniforms.modelMatrix !== null ) {
  11824. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  11825. }
  11826. return program;
  11827. };
  11828. // Uniforms (refresh uniforms objects)
  11829. function refreshUniformsCommon ( uniforms, material ) {
  11830. uniforms.opacity.value = material.opacity;
  11831. if ( _this.gammaInput ) {
  11832. uniforms.diffuse.value.copyGammaToLinear( material.color );
  11833. } else {
  11834. uniforms.diffuse.value = material.color;
  11835. }
  11836. uniforms.map.texture = material.map;
  11837. uniforms.lightMap.texture = material.lightMap;
  11838. uniforms.specularMap.texture = material.specularMap;
  11839. if ( material.bumpMap ) {
  11840. uniforms.bumpMap.texture = material.bumpMap;
  11841. uniforms.bumpScale.value = material.bumpScale;
  11842. }
  11843. // uv repeat and offset setting priorities
  11844. // 1. color map
  11845. // 2. specular map
  11846. // 3. bump map
  11847. var uvScaleMap;
  11848. if ( material.map ) {
  11849. uvScaleMap = material.map;
  11850. } else if ( material.specularMap ) {
  11851. uvScaleMap = material.specularMap;
  11852. } else if ( material.bumpMap ) {
  11853. uvScaleMap = material.bumpMap;
  11854. }
  11855. if ( uvScaleMap !== undefined ) {
  11856. var offset = uvScaleMap.offset;
  11857. var repeat = uvScaleMap.repeat;
  11858. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  11859. }
  11860. uniforms.envMap.texture = material.envMap;
  11861. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  11862. if ( _this.gammaInput ) {
  11863. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  11864. uniforms.reflectivity.value = material.reflectivity;
  11865. } else {
  11866. uniforms.reflectivity.value = material.reflectivity;
  11867. }
  11868. uniforms.refractionRatio.value = material.refractionRatio;
  11869. uniforms.combine.value = material.combine;
  11870. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  11871. };
  11872. function refreshUniformsLine ( uniforms, material ) {
  11873. uniforms.diffuse.value = material.color;
  11874. uniforms.opacity.value = material.opacity;
  11875. };
  11876. function refreshUniformsParticle ( uniforms, material ) {
  11877. uniforms.psColor.value = material.color;
  11878. uniforms.opacity.value = material.opacity;
  11879. uniforms.size.value = material.size;
  11880. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  11881. uniforms.map.texture = material.map;
  11882. };
  11883. function refreshUniformsFog ( uniforms, fog ) {
  11884. uniforms.fogColor.value = fog.color;
  11885. if ( fog instanceof THREE.Fog ) {
  11886. uniforms.fogNear.value = fog.near;
  11887. uniforms.fogFar.value = fog.far;
  11888. } else if ( fog instanceof THREE.FogExp2 ) {
  11889. uniforms.fogDensity.value = fog.density;
  11890. }
  11891. };
  11892. function refreshUniformsPhong ( uniforms, material ) {
  11893. uniforms.shininess.value = material.shininess;
  11894. if ( _this.gammaInput ) {
  11895. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  11896. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  11897. uniforms.specular.value.copyGammaToLinear( material.specular );
  11898. } else {
  11899. uniforms.ambient.value = material.ambient;
  11900. uniforms.emissive.value = material.emissive;
  11901. uniforms.specular.value = material.specular;
  11902. }
  11903. if ( material.wrapAround ) {
  11904. uniforms.wrapRGB.value.copy( material.wrapRGB );
  11905. }
  11906. };
  11907. function refreshUniformsLambert ( uniforms, material ) {
  11908. if ( _this.gammaInput ) {
  11909. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  11910. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  11911. } else {
  11912. uniforms.ambient.value = material.ambient;
  11913. uniforms.emissive.value = material.emissive;
  11914. }
  11915. if ( material.wrapAround ) {
  11916. uniforms.wrapRGB.value.copy( material.wrapRGB );
  11917. }
  11918. };
  11919. function refreshUniformsLights ( uniforms, lights ) {
  11920. uniforms.ambientLightColor.value = lights.ambient;
  11921. uniforms.directionalLightColor.value = lights.directional.colors;
  11922. uniforms.directionalLightDirection.value = lights.directional.positions;
  11923. uniforms.pointLightColor.value = lights.point.colors;
  11924. uniforms.pointLightPosition.value = lights.point.positions;
  11925. uniforms.pointLightDistance.value = lights.point.distances;
  11926. uniforms.spotLightColor.value = lights.spot.colors;
  11927. uniforms.spotLightPosition.value = lights.spot.positions;
  11928. uniforms.spotLightDistance.value = lights.spot.distances;
  11929. uniforms.spotLightDirection.value = lights.spot.directions;
  11930. uniforms.spotLightAngle.value = lights.spot.angles;
  11931. uniforms.spotLightExponent.value = lights.spot.exponents;
  11932. };
  11933. function refreshUniformsShadow ( uniforms, lights ) {
  11934. if ( uniforms.shadowMatrix ) {
  11935. var j = 0;
  11936. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  11937. var light = lights[ i ];
  11938. if ( ! light.castShadow ) continue;
  11939. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  11940. uniforms.shadowMap.texture[ j ] = light.shadowMap;
  11941. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  11942. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  11943. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  11944. uniforms.shadowBias.value[ j ] = light.shadowBias;
  11945. j ++;
  11946. }
  11947. }
  11948. }
  11949. };
  11950. // Uniforms (load to GPU)
  11951. function loadUniformsMatrices ( uniforms, object ) {
  11952. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  11953. if ( uniforms.normalMatrix ) {
  11954. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  11955. }
  11956. };
  11957. function loadUniformsGeneric ( program, uniforms ) {
  11958. var uniform, value, type, location, texture, i, il, j, jl, offset;
  11959. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  11960. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  11961. if ( !location ) continue;
  11962. uniform = uniforms[ j ][ 0 ];
  11963. type = uniform.type;
  11964. value = uniform.value;
  11965. if ( type === "i" ) { // single integer
  11966. _gl.uniform1i( location, value );
  11967. } else if ( type === "f" ) { // single float
  11968. _gl.uniform1f( location, value );
  11969. } else if ( type === "v2" ) { // single THREE.Vector2
  11970. _gl.uniform2f( location, value.x, value.y );
  11971. } else if ( type === "v3" ) { // single THREE.Vector3
  11972. _gl.uniform3f( location, value.x, value.y, value.z );
  11973. } else if ( type === "v4" ) { // single THREE.Vector4
  11974. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  11975. } else if ( type === "c" ) { // single THREE.Color
  11976. _gl.uniform3f( location, value.r, value.g, value.b );
  11977. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  11978. _gl.uniform1iv( location, value );
  11979. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  11980. _gl.uniform3iv( location, value );
  11981. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  11982. _gl.uniform1fv( location, value );
  11983. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  11984. _gl.uniform3fv( location, value );
  11985. } else if ( type === "v2v" ) { // array of THREE.Vector2
  11986. if ( uniform._array === undefined ) {
  11987. uniform._array = new Float32Array( 2 * value.length );
  11988. }
  11989. for ( i = 0, il = value.length; i < il; i ++ ) {
  11990. offset = i * 2;
  11991. uniform._array[ offset ] = value[ i ].x;
  11992. uniform._array[ offset + 1 ] = value[ i ].y;
  11993. }
  11994. _gl.uniform2fv( location, uniform._array );
  11995. } else if ( type === "v3v" ) { // array of THREE.Vector3
  11996. if ( uniform._array === undefined ) {
  11997. uniform._array = new Float32Array( 3 * value.length );
  11998. }
  11999. for ( i = 0, il = value.length; i < il; i ++ ) {
  12000. offset = i * 3;
  12001. uniform._array[ offset ] = value[ i ].x;
  12002. uniform._array[ offset + 1 ] = value[ i ].y;
  12003. uniform._array[ offset + 2 ] = value[ i ].z;
  12004. }
  12005. _gl.uniform3fv( location, uniform._array );
  12006. } else if ( type === "v4v" ) { // array of THREE.Vector4
  12007. if ( uniform._array === undefined ) {
  12008. uniform._array = new Float32Array( 4 * value.length );
  12009. }
  12010. for ( i = 0, il = value.length; i < il; i ++ ) {
  12011. offset = i * 4;
  12012. uniform._array[ offset ] = value[ i ].x;
  12013. uniform._array[ offset + 1 ] = value[ i ].y;
  12014. uniform._array[ offset + 2 ] = value[ i ].z;
  12015. uniform._array[ offset + 3 ] = value[ i ].w;
  12016. }
  12017. _gl.uniform4fv( location, uniform._array );
  12018. } else if ( type === "m4") { // single THREE.Matrix4
  12019. if ( uniform._array === undefined ) {
  12020. uniform._array = new Float32Array( 16 );
  12021. }
  12022. value.flattenToArray( uniform._array );
  12023. _gl.uniformMatrix4fv( location, false, uniform._array );
  12024. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  12025. if ( uniform._array === undefined ) {
  12026. uniform._array = new Float32Array( 16 * value.length );
  12027. }
  12028. for ( i = 0, il = value.length; i < il; i ++ ) {
  12029. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12030. }
  12031. _gl.uniformMatrix4fv( location, false, uniform._array );
  12032. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  12033. _gl.uniform1i( location, value );
  12034. texture = uniform.texture;
  12035. if ( !texture ) continue;
  12036. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  12037. setCubeTexture( texture, value );
  12038. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12039. setCubeTextureDynamic( texture, value );
  12040. } else {
  12041. _this.setTexture( texture, value );
  12042. }
  12043. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  12044. if ( uniform._array === undefined ) {
  12045. uniform._array = [];
  12046. for( i = 0, il = uniform.texture.length; i < il; i ++ ) {
  12047. uniform._array[ i ] = value + i;
  12048. }
  12049. }
  12050. _gl.uniform1iv( location, uniform._array );
  12051. for( i = 0, il = uniform.texture.length; i < il; i ++ ) {
  12052. texture = uniform.texture[ i ];
  12053. if ( !texture ) continue;
  12054. _this.setTexture( texture, uniform._array[ i ] );
  12055. }
  12056. }
  12057. }
  12058. };
  12059. function setupMatrices ( object, camera ) {
  12060. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  12061. object._normalMatrix.getInverse( object._modelViewMatrix );
  12062. object._normalMatrix.transpose();
  12063. };
  12064. function setupLights ( program, lights ) {
  12065. var l, ll, light, n,
  12066. r = 0, g = 0, b = 0,
  12067. color, position, intensity, distance,
  12068. zlights = _lights,
  12069. dcolors = zlights.directional.colors,
  12070. dpositions = zlights.directional.positions,
  12071. pcolors = zlights.point.colors,
  12072. ppositions = zlights.point.positions,
  12073. pdistances = zlights.point.distances,
  12074. scolors = zlights.spot.colors,
  12075. spositions = zlights.spot.positions,
  12076. sdistances = zlights.spot.distances,
  12077. sdirections = zlights.spot.directions,
  12078. sangles = zlights.spot.angles,
  12079. sexponents = zlights.spot.exponents,
  12080. dlength = 0,
  12081. plength = 0,
  12082. slength = 0,
  12083. doffset = 0,
  12084. poffset = 0,
  12085. soffset = 0;
  12086. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12087. light = lights[ l ];
  12088. if ( light.onlyShadow || ! light.visible ) continue;
  12089. color = light.color;
  12090. intensity = light.intensity;
  12091. distance = light.distance;
  12092. if ( light instanceof THREE.AmbientLight ) {
  12093. if ( _this.gammaInput ) {
  12094. r += color.r * color.r;
  12095. g += color.g * color.g;
  12096. b += color.b * color.b;
  12097. } else {
  12098. r += color.r;
  12099. g += color.g;
  12100. b += color.b;
  12101. }
  12102. } else if ( light instanceof THREE.DirectionalLight ) {
  12103. doffset = dlength * 3;
  12104. if ( _this.gammaInput ) {
  12105. dcolors[ doffset ] = color.r * color.r * intensity * intensity;
  12106. dcolors[ doffset + 1 ] = color.g * color.g * intensity * intensity;
  12107. dcolors[ doffset + 2 ] = color.b * color.b * intensity * intensity;
  12108. } else {
  12109. dcolors[ doffset ] = color.r * intensity;
  12110. dcolors[ doffset + 1 ] = color.g * intensity;
  12111. dcolors[ doffset + 2 ] = color.b * intensity;
  12112. }
  12113. _direction.copy( light.matrixWorld.getPosition() );
  12114. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12115. _direction.normalize();
  12116. dpositions[ doffset ] = _direction.x;
  12117. dpositions[ doffset + 1 ] = _direction.y;
  12118. dpositions[ doffset + 2 ] = _direction.z;
  12119. dlength += 1;
  12120. } else if( light instanceof THREE.PointLight ) {
  12121. poffset = plength * 3;
  12122. if ( _this.gammaInput ) {
  12123. pcolors[ poffset ] = color.r * color.r * intensity * intensity;
  12124. pcolors[ poffset + 1 ] = color.g * color.g * intensity * intensity;
  12125. pcolors[ poffset + 2 ] = color.b * color.b * intensity * intensity;
  12126. } else {
  12127. pcolors[ poffset ] = color.r * intensity;
  12128. pcolors[ poffset + 1 ] = color.g * intensity;
  12129. pcolors[ poffset + 2 ] = color.b * intensity;
  12130. }
  12131. position = light.matrixWorld.getPosition();
  12132. ppositions[ poffset ] = position.x;
  12133. ppositions[ poffset + 1 ] = position.y;
  12134. ppositions[ poffset + 2 ] = position.z;
  12135. pdistances[ plength ] = distance;
  12136. plength += 1;
  12137. } else if( light instanceof THREE.SpotLight ) {
  12138. soffset = slength * 3;
  12139. if ( _this.gammaInput ) {
  12140. scolors[ soffset ] = color.r * color.r * intensity * intensity;
  12141. scolors[ soffset + 1 ] = color.g * color.g * intensity * intensity;
  12142. scolors[ soffset + 2 ] = color.b * color.b * intensity * intensity;
  12143. } else {
  12144. scolors[ soffset ] = color.r * intensity;
  12145. scolors[ soffset + 1 ] = color.g * intensity;
  12146. scolors[ soffset + 2 ] = color.b * intensity;
  12147. }
  12148. position = light.matrixWorld.getPosition();
  12149. spositions[ soffset ] = position.x;
  12150. spositions[ soffset + 1 ] = position.y;
  12151. spositions[ soffset + 2 ] = position.z;
  12152. sdistances[ slength ] = distance;
  12153. _direction.copy( position );
  12154. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12155. _direction.normalize();
  12156. sdirections[ soffset ] = _direction.x;
  12157. sdirections[ soffset + 1 ] = _direction.y;
  12158. sdirections[ soffset + 2 ] = _direction.z;
  12159. sangles[ slength ] = Math.cos( light.angle );
  12160. sexponents[ slength ] = light.exponent;
  12161. slength += 1;
  12162. }
  12163. }
  12164. // null eventual remains from removed lights
  12165. // (this is to avoid if in shader)
  12166. for ( l = dlength * 3, ll = dcolors.length; l < ll; l ++ ) dcolors[ l ] = 0.0;
  12167. for ( l = plength * 3, ll = pcolors.length; l < ll; l ++ ) pcolors[ l ] = 0.0;
  12168. for ( l = slength * 3, ll = scolors.length; l < ll; l ++ ) scolors[ l ] = 0.0;
  12169. zlights.directional.length = dlength;
  12170. zlights.point.length = plength;
  12171. zlights.spot.length = slength;
  12172. zlights.ambient[ 0 ] = r;
  12173. zlights.ambient[ 1 ] = g;
  12174. zlights.ambient[ 2 ] = b;
  12175. };
  12176. // GL state setting
  12177. this.setFaceCulling = function ( cullFace, frontFace ) {
  12178. if ( cullFace ) {
  12179. if ( !frontFace || frontFace === "ccw" ) {
  12180. _gl.frontFace( _gl.CCW );
  12181. } else {
  12182. _gl.frontFace( _gl.CW );
  12183. }
  12184. if( cullFace === "back" ) {
  12185. _gl.cullFace( _gl.BACK );
  12186. } else if( cullFace === "front" ) {
  12187. _gl.cullFace( _gl.FRONT );
  12188. } else {
  12189. _gl.cullFace( _gl.FRONT_AND_BACK );
  12190. }
  12191. _gl.enable( _gl.CULL_FACE );
  12192. } else {
  12193. _gl.disable( _gl.CULL_FACE );
  12194. }
  12195. };
  12196. this.setMaterialFaces = function ( material ) {
  12197. var doubleSided = material.side === THREE.DoubleSide;
  12198. var flipSided = material.side === THREE.BackSide;
  12199. if ( _oldDoubleSided !== doubleSided ) {
  12200. if ( doubleSided ) {
  12201. _gl.disable( _gl.CULL_FACE );
  12202. } else {
  12203. _gl.enable( _gl.CULL_FACE );
  12204. }
  12205. _oldDoubleSided = doubleSided;
  12206. }
  12207. if ( _oldFlipSided !== flipSided ) {
  12208. if ( flipSided ) {
  12209. _gl.frontFace( _gl.CW );
  12210. } else {
  12211. _gl.frontFace( _gl.CCW );
  12212. }
  12213. _oldFlipSided = flipSided;
  12214. }
  12215. };
  12216. this.setDepthTest = function ( depthTest ) {
  12217. if ( _oldDepthTest !== depthTest ) {
  12218. if ( depthTest ) {
  12219. _gl.enable( _gl.DEPTH_TEST );
  12220. } else {
  12221. _gl.disable( _gl.DEPTH_TEST );
  12222. }
  12223. _oldDepthTest = depthTest;
  12224. }
  12225. };
  12226. this.setDepthWrite = function ( depthWrite ) {
  12227. if ( _oldDepthWrite !== depthWrite ) {
  12228. _gl.depthMask( depthWrite );
  12229. _oldDepthWrite = depthWrite;
  12230. }
  12231. };
  12232. function setLineWidth ( width ) {
  12233. if ( width !== _oldLineWidth ) {
  12234. _gl.lineWidth( width );
  12235. _oldLineWidth = width;
  12236. }
  12237. };
  12238. function setPolygonOffset ( polygonoffset, factor, units ) {
  12239. if ( _oldPolygonOffset !== polygonoffset ) {
  12240. if ( polygonoffset ) {
  12241. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  12242. } else {
  12243. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  12244. }
  12245. _oldPolygonOffset = polygonoffset;
  12246. }
  12247. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  12248. _gl.polygonOffset( factor, units );
  12249. _oldPolygonOffsetFactor = factor;
  12250. _oldPolygonOffsetUnits = units;
  12251. }
  12252. };
  12253. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  12254. if ( blending !== _oldBlending ) {
  12255. if ( blending === THREE.NoBlending ) {
  12256. _gl.disable( _gl.BLEND );
  12257. } else if ( blending === THREE.AdditiveBlending ) {
  12258. _gl.enable( _gl.BLEND );
  12259. _gl.blendEquation( _gl.FUNC_ADD );
  12260. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  12261. } else if ( blending === THREE.SubtractiveBlending ) {
  12262. // TODO: Find blendFuncSeparate() combination
  12263. _gl.enable( _gl.BLEND );
  12264. _gl.blendEquation( _gl.FUNC_ADD );
  12265. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  12266. } else if ( blending === THREE.MultiplyBlending ) {
  12267. // TODO: Find blendFuncSeparate() combination
  12268. _gl.enable( _gl.BLEND );
  12269. _gl.blendEquation( _gl.FUNC_ADD );
  12270. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  12271. } else if ( blending === THREE.CustomBlending ) {
  12272. _gl.enable( _gl.BLEND );
  12273. } else {
  12274. _gl.enable( _gl.BLEND );
  12275. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  12276. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  12277. }
  12278. _oldBlending = blending;
  12279. }
  12280. if ( blending === THREE.CustomBlending ) {
  12281. if ( blendEquation !== _oldBlendEquation ) {
  12282. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  12283. _oldBlendEquation = blendEquation;
  12284. }
  12285. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  12286. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  12287. _oldBlendSrc = blendSrc;
  12288. _oldBlendDst = blendDst;
  12289. }
  12290. } else {
  12291. _oldBlendEquation = null;
  12292. _oldBlendSrc = null;
  12293. _oldBlendDst = null;
  12294. }
  12295. };
  12296. // Shaders
  12297. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, parameters ) {
  12298. var p, pl, program, code;
  12299. var chunks = [];
  12300. // Generate code
  12301. if ( shaderID ) {
  12302. chunks.push( shaderID );
  12303. } else {
  12304. chunks.push( fragmentShader );
  12305. chunks.push( vertexShader );
  12306. }
  12307. for ( p in parameters ) {
  12308. chunks.push( p );
  12309. chunks.push( parameters[ p ] );
  12310. }
  12311. code = chunks.join();
  12312. // Check if code has been already compiled
  12313. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  12314. var programInfo = _programs[ p ];
  12315. if ( programInfo.code === code ) {
  12316. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  12317. programInfo.usedTimes ++;
  12318. return programInfo.program;
  12319. }
  12320. }
  12321. //console.log( "building new program " );
  12322. //
  12323. program = _gl.createProgram();
  12324. var prefix_vertex = [
  12325. "precision " + _precision + " float;",
  12326. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  12327. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  12328. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  12329. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  12330. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  12331. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  12332. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  12333. "#define MAX_SHADOWS " + parameters.maxShadows,
  12334. "#define MAX_BONES " + parameters.maxBones,
  12335. parameters.map ? "#define USE_MAP" : "",
  12336. parameters.envMap ? "#define USE_ENVMAP" : "",
  12337. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  12338. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  12339. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  12340. parameters.vertexColors ? "#define USE_COLOR" : "",
  12341. parameters.skinning ? "#define USE_SKINNING" : "",
  12342. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  12343. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  12344. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  12345. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  12346. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  12347. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  12348. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  12349. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  12350. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  12351. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  12352. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  12353. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  12354. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  12355. "uniform mat4 modelMatrix;",
  12356. "uniform mat4 modelViewMatrix;",
  12357. "uniform mat4 projectionMatrix;",
  12358. "uniform mat4 viewMatrix;",
  12359. "uniform mat3 normalMatrix;",
  12360. "uniform vec3 cameraPosition;",
  12361. "attribute vec3 position;",
  12362. "attribute vec3 normal;",
  12363. "attribute vec2 uv;",
  12364. "attribute vec2 uv2;",
  12365. "#ifdef USE_COLOR",
  12366. "attribute vec3 color;",
  12367. "#endif",
  12368. "#ifdef USE_MORPHTARGETS",
  12369. "attribute vec3 morphTarget0;",
  12370. "attribute vec3 morphTarget1;",
  12371. "attribute vec3 morphTarget2;",
  12372. "attribute vec3 morphTarget3;",
  12373. "#ifdef USE_MORPHNORMALS",
  12374. "attribute vec3 morphNormal0;",
  12375. "attribute vec3 morphNormal1;",
  12376. "attribute vec3 morphNormal2;",
  12377. "attribute vec3 morphNormal3;",
  12378. "#else",
  12379. "attribute vec3 morphTarget4;",
  12380. "attribute vec3 morphTarget5;",
  12381. "attribute vec3 morphTarget6;",
  12382. "attribute vec3 morphTarget7;",
  12383. "#endif",
  12384. "#endif",
  12385. "#ifdef USE_SKINNING",
  12386. "attribute vec4 skinVertexA;",
  12387. "attribute vec4 skinVertexB;",
  12388. "attribute vec4 skinIndex;",
  12389. "attribute vec4 skinWeight;",
  12390. "#endif",
  12391. ""
  12392. ].join("\n");
  12393. var prefix_fragment = [
  12394. "precision " + _precision + " float;",
  12395. parameters.bumpMap ? "#extension GL_OES_standard_derivatives : enable" : "",
  12396. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  12397. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  12398. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  12399. "#define MAX_SHADOWS " + parameters.maxShadows,
  12400. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  12401. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  12402. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  12403. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  12404. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  12405. ( parameters.useFog && parameters.fog instanceof THREE.FogExp2 ) ? "#define FOG_EXP2" : "",
  12406. parameters.map ? "#define USE_MAP" : "",
  12407. parameters.envMap ? "#define USE_ENVMAP" : "",
  12408. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  12409. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  12410. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  12411. parameters.vertexColors ? "#define USE_COLOR" : "",
  12412. parameters.metal ? "#define METAL" : "",
  12413. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  12414. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  12415. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  12416. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  12417. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  12418. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  12419. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  12420. "uniform mat4 viewMatrix;",
  12421. "uniform vec3 cameraPosition;",
  12422. ""
  12423. ].join("\n");
  12424. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  12425. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  12426. _gl.attachShader( program, glVertexShader );
  12427. _gl.attachShader( program, glFragmentShader );
  12428. _gl.linkProgram( program );
  12429. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  12430. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  12431. }
  12432. // clean up
  12433. _gl.deleteShader( glFragmentShader );
  12434. _gl.deleteShader( glVertexShader );
  12435. //console.log( prefix_fragment + fragmentShader );
  12436. //console.log( prefix_vertex + vertexShader );
  12437. program.uniforms = {};
  12438. program.attributes = {};
  12439. var identifiers, u, a, i;
  12440. // cache uniform locations
  12441. identifiers = [
  12442. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  12443. 'morphTargetInfluences'
  12444. ];
  12445. if ( parameters.useVertexTexture ) {
  12446. identifiers.push( 'boneTexture' );
  12447. } else {
  12448. identifiers.push( 'boneGlobalMatrices' );
  12449. }
  12450. for ( u in uniforms ) {
  12451. identifiers.push( u );
  12452. }
  12453. cacheUniformLocations( program, identifiers );
  12454. // cache attributes locations
  12455. identifiers = [
  12456. "position", "normal", "uv", "uv2", "tangent", "color",
  12457. "skinVertexA", "skinVertexB", "skinIndex", "skinWeight"
  12458. ];
  12459. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  12460. identifiers.push( "morphTarget" + i );
  12461. }
  12462. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  12463. identifiers.push( "morphNormal" + i );
  12464. }
  12465. for ( a in attributes ) {
  12466. identifiers.push( a );
  12467. }
  12468. cacheAttributeLocations( program, identifiers );
  12469. program.id = _programs_counter ++;
  12470. _programs.push( { program: program, code: code, usedTimes: 1 } );
  12471. _this.info.memory.programs = _programs.length;
  12472. return program;
  12473. };
  12474. // Shader parameters cache
  12475. function cacheUniformLocations ( program, identifiers ) {
  12476. var i, l, id;
  12477. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  12478. id = identifiers[ i ];
  12479. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  12480. }
  12481. };
  12482. function cacheAttributeLocations ( program, identifiers ) {
  12483. var i, l, id;
  12484. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  12485. id = identifiers[ i ];
  12486. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  12487. }
  12488. };
  12489. function addLineNumbers ( string ) {
  12490. var chunks = string.split( "\n" );
  12491. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  12492. // Chrome reports shader errors on lines
  12493. // starting counting from 1
  12494. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  12495. }
  12496. return chunks.join( "\n" );
  12497. };
  12498. function getShader ( type, string ) {
  12499. var shader;
  12500. if ( type === "fragment" ) {
  12501. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  12502. } else if ( type === "vertex" ) {
  12503. shader = _gl.createShader( _gl.VERTEX_SHADER );
  12504. }
  12505. _gl.shaderSource( shader, string );
  12506. _gl.compileShader( shader );
  12507. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  12508. console.error( _gl.getShaderInfoLog( shader ) );
  12509. console.error( addLineNumbers( string ) );
  12510. return null;
  12511. }
  12512. return shader;
  12513. };
  12514. // Textures
  12515. function isPowerOfTwo ( value ) {
  12516. return ( value & ( value - 1 ) ) === 0;
  12517. };
  12518. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  12519. if ( isImagePowerOfTwo ) {
  12520. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  12521. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  12522. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  12523. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  12524. } else {
  12525. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  12526. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  12527. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  12528. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  12529. }
  12530. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  12531. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  12532. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  12533. texture.__oldAnisotropy = texture.anisotropy;
  12534. }
  12535. }
  12536. };
  12537. this.setTexture = function ( texture, slot ) {
  12538. if ( texture.needsUpdate ) {
  12539. if ( ! texture.__webglInit ) {
  12540. texture.__webglInit = true;
  12541. texture.__webglTexture = _gl.createTexture();
  12542. _this.info.memory.textures ++;
  12543. }
  12544. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12545. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  12546. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  12547. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  12548. var image = texture.image,
  12549. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  12550. glFormat = paramThreeToGL( texture.format ),
  12551. glType = paramThreeToGL( texture.type );
  12552. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  12553. if ( texture instanceof THREE.DataTexture ) {
  12554. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  12555. } else {
  12556. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  12557. }
  12558. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  12559. texture.needsUpdate = false;
  12560. if ( texture.onUpdate ) texture.onUpdate();
  12561. } else {
  12562. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12563. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  12564. }
  12565. };
  12566. function clampToMaxSize ( image, maxSize ) {
  12567. if ( image.width <= maxSize && image.height <= maxSize ) {
  12568. return image;
  12569. }
  12570. // Warning: Scaling through the canvas will only work with images that use
  12571. // premultiplied alpha.
  12572. var maxDimension = Math.max( image.width, image.height );
  12573. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  12574. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  12575. var canvas = document.createElement( 'canvas' );
  12576. canvas.width = newWidth;
  12577. canvas.height = newHeight;
  12578. var ctx = canvas.getContext( "2d" );
  12579. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  12580. return canvas;
  12581. }
  12582. function setCubeTexture ( texture, slot ) {
  12583. if ( texture.image.length === 6 ) {
  12584. if ( texture.needsUpdate ) {
  12585. if ( ! texture.image.__webglTextureCube ) {
  12586. texture.image.__webglTextureCube = _gl.createTexture();
  12587. }
  12588. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12589. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  12590. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  12591. var cubeImage = [];
  12592. for ( var i = 0; i < 6; i ++ ) {
  12593. if ( _this.autoScaleCubemaps ) {
  12594. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  12595. } else {
  12596. cubeImage[ i ] = texture.image[ i ];
  12597. }
  12598. }
  12599. var image = cubeImage[ 0 ],
  12600. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  12601. glFormat = paramThreeToGL( texture.format ),
  12602. glType = paramThreeToGL( texture.type );
  12603. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  12604. for ( var i = 0; i < 6; i ++ ) {
  12605. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  12606. }
  12607. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  12608. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  12609. }
  12610. texture.needsUpdate = false;
  12611. if ( texture.onUpdate ) texture.onUpdate();
  12612. } else {
  12613. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12614. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  12615. }
  12616. }
  12617. };
  12618. function setCubeTextureDynamic ( texture, slot ) {
  12619. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12620. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  12621. };
  12622. // Render targets
  12623. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  12624. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12625. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  12626. };
  12627. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  12628. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  12629. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  12630. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  12631. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  12632. /* For some reason this is not working. Defaulting to RGBA4.
  12633. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  12634. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  12635. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  12636. */
  12637. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  12638. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  12639. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  12640. } else {
  12641. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  12642. }
  12643. };
  12644. this.setRenderTarget = function ( renderTarget ) {
  12645. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  12646. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  12647. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  12648. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  12649. renderTarget.__webglTexture = _gl.createTexture();
  12650. // Setup texture, create render and frame buffers
  12651. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  12652. glFormat = paramThreeToGL( renderTarget.format ),
  12653. glType = paramThreeToGL( renderTarget.type );
  12654. if ( isCube ) {
  12655. renderTarget.__webglFramebuffer = [];
  12656. renderTarget.__webglRenderbuffer = [];
  12657. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  12658. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  12659. for ( var i = 0; i < 6; i ++ ) {
  12660. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  12661. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  12662. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  12663. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  12664. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  12665. }
  12666. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  12667. } else {
  12668. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  12669. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  12670. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  12671. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  12672. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  12673. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  12674. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  12675. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  12676. }
  12677. // Release everything
  12678. if ( isCube ) {
  12679. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  12680. } else {
  12681. _gl.bindTexture( _gl.TEXTURE_2D, null );
  12682. }
  12683. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  12684. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  12685. }
  12686. var framebuffer, width, height, vx, vy;
  12687. if ( renderTarget ) {
  12688. if ( isCube ) {
  12689. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  12690. } else {
  12691. framebuffer = renderTarget.__webglFramebuffer;
  12692. }
  12693. width = renderTarget.width;
  12694. height = renderTarget.height;
  12695. vx = 0;
  12696. vy = 0;
  12697. } else {
  12698. framebuffer = null;
  12699. width = _viewportWidth;
  12700. height = _viewportHeight;
  12701. vx = _viewportX;
  12702. vy = _viewportY;
  12703. }
  12704. if ( framebuffer !== _currentFramebuffer ) {
  12705. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12706. _gl.viewport( vx, vy, width, height );
  12707. _currentFramebuffer = framebuffer;
  12708. }
  12709. _currentWidth = width;
  12710. _currentHeight = height;
  12711. };
  12712. function updateRenderTargetMipmap ( renderTarget ) {
  12713. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12714. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  12715. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  12716. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  12717. } else {
  12718. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  12719. _gl.generateMipmap( _gl.TEXTURE_2D );
  12720. _gl.bindTexture( _gl.TEXTURE_2D, null );
  12721. }
  12722. };
  12723. // Fallback filters for non-power-of-2 textures
  12724. function filterFallback ( f ) {
  12725. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  12726. return _gl.NEAREST;
  12727. }
  12728. return _gl.LINEAR;
  12729. };
  12730. // Map three.js constants to WebGL constants
  12731. function paramThreeToGL ( p ) {
  12732. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  12733. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  12734. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  12735. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  12736. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  12737. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  12738. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  12739. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  12740. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  12741. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  12742. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  12743. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  12744. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  12745. if ( p === THREE.ByteType ) return _gl.BYTE;
  12746. if ( p === THREE.ShortType ) return _gl.SHORT;
  12747. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  12748. if ( p === THREE.IntType ) return _gl.INT;
  12749. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  12750. if ( p === THREE.FloatType ) return _gl.FLOAT;
  12751. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  12752. if ( p === THREE.RGBFormat ) return _gl.RGB;
  12753. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  12754. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  12755. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  12756. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  12757. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  12758. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  12759. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  12760. if ( p === THREE.OneFactor ) return _gl.ONE;
  12761. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  12762. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  12763. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  12764. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  12765. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  12766. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  12767. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  12768. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  12769. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  12770. return 0;
  12771. };
  12772. // Allocations
  12773. function allocateBones ( object ) {
  12774. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  12775. return 1024;
  12776. } else {
  12777. // default for when object is not specified
  12778. // ( for example when prebuilding shader
  12779. // to be used with multiple objects )
  12780. //
  12781. // - leave some extra space for other uniforms
  12782. // - limit here is ANGLE's 254 max uniform vectors
  12783. // (up to 54 should be safe)
  12784. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  12785. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  12786. var maxBones = nVertexMatrices;
  12787. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  12788. maxBones = Math.min( object.bones.length, maxBones );
  12789. if ( maxBones < object.bones.length ) {
  12790. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  12791. }
  12792. }
  12793. return maxBones;
  12794. }
  12795. };
  12796. function allocateLights ( lights ) {
  12797. var l, ll, light, dirLights, pointLights, spotLights, maxDirLights, maxPointLights, maxSpotLights;
  12798. dirLights = pointLights = spotLights = maxDirLights = maxPointLights = maxSpotLights = 0;
  12799. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12800. light = lights[ l ];
  12801. if ( light.onlyShadow ) continue;
  12802. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  12803. if ( light instanceof THREE.PointLight ) pointLights ++;
  12804. if ( light instanceof THREE.SpotLight ) spotLights ++;
  12805. }
  12806. if ( ( pointLights + spotLights + dirLights ) <= _maxLights ) {
  12807. maxDirLights = dirLights;
  12808. maxPointLights = pointLights;
  12809. maxSpotLights = spotLights;
  12810. } else {
  12811. maxDirLights = Math.ceil( _maxLights * dirLights / ( pointLights + dirLights ) );
  12812. maxPointLights = _maxLights - maxDirLights;
  12813. maxSpotLights = maxPointLights; // this is not really correct
  12814. }
  12815. return { 'directional' : maxDirLights, 'point' : maxPointLights, 'spot': maxSpotLights };
  12816. };
  12817. function allocateShadows ( lights ) {
  12818. var l, ll, light, maxShadows = 0;
  12819. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  12820. light = lights[ l ];
  12821. if ( ! light.castShadow ) continue;
  12822. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  12823. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  12824. }
  12825. return maxShadows;
  12826. };
  12827. // Initialization
  12828. function initGL () {
  12829. try {
  12830. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  12831. throw 'Error creating WebGL context.';
  12832. }
  12833. } catch ( error ) {
  12834. console.error( error );
  12835. }
  12836. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  12837. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  12838. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  12839. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  12840. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  12841. if ( ! _glExtensionTextureFloat ) {
  12842. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  12843. }
  12844. if ( ! _glExtensionStandardDerivatives ) {
  12845. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  12846. }
  12847. if ( ! _glExtensionTextureFilterAnisotropic ) {
  12848. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  12849. }
  12850. };
  12851. function setDefaultGLState () {
  12852. _gl.clearColor( 0, 0, 0, 1 );
  12853. _gl.clearDepth( 1 );
  12854. _gl.clearStencil( 0 );
  12855. _gl.enable( _gl.DEPTH_TEST );
  12856. _gl.depthFunc( _gl.LEQUAL );
  12857. _gl.frontFace( _gl.CCW );
  12858. _gl.cullFace( _gl.BACK );
  12859. _gl.enable( _gl.CULL_FACE );
  12860. _gl.enable( _gl.BLEND );
  12861. _gl.blendEquation( _gl.FUNC_ADD );
  12862. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  12863. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12864. };
  12865. // default plugins (order is important)
  12866. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  12867. this.addPrePlugin( this.shadowMapPlugin );
  12868. this.addPostPlugin( new THREE.SpritePlugin() );
  12869. this.addPostPlugin( new THREE.LensFlarePlugin() );
  12870. };
  12871. /**
  12872. * @author szimek / https://github.com/szimek/
  12873. * @author alteredq / http://alteredqualia.com/
  12874. */
  12875. THREE.WebGLRenderTarget = function ( width, height, options ) {
  12876. this.width = width;
  12877. this.height = height;
  12878. options = options || {};
  12879. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  12880. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  12881. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  12882. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  12883. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  12884. this.offset = new THREE.Vector2( 0, 0 );
  12885. this.repeat = new THREE.Vector2( 1, 1 );
  12886. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  12887. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  12888. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  12889. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  12890. this.generateMipmaps = true;
  12891. };
  12892. THREE.WebGLRenderTarget.prototype.clone = function() {
  12893. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  12894. tmp.wrapS = this.wrapS;
  12895. tmp.wrapT = this.wrapT;
  12896. tmp.magFilter = this.magFilter;
  12897. tmp.anisotropy = this.anisotropy;
  12898. tmp.minFilter = this.minFilter;
  12899. tmp.offset.copy( this.offset );
  12900. tmp.repeat.copy( this.repeat );
  12901. tmp.format = this.format;
  12902. tmp.type = this.type;
  12903. tmp.depthBuffer = this.depthBuffer;
  12904. tmp.stencilBuffer = this.stencilBuffer;
  12905. tmp.generateMipmaps = this.generateMipmaps;
  12906. return tmp;
  12907. };
  12908. /**
  12909. * @author alteredq / http://alteredqualia.com
  12910. */
  12911. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  12912. THREE.WebGLRenderTarget.call( this, width, height, options );
  12913. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  12914. };
  12915. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  12916. /**
  12917. * @author mrdoob / http://mrdoob.com/
  12918. */
  12919. THREE.RenderableVertex = function () {
  12920. this.positionWorld = new THREE.Vector3();
  12921. this.positionScreen = new THREE.Vector4();
  12922. this.visible = true;
  12923. };
  12924. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  12925. this.positionWorld.copy( vertex.positionWorld );
  12926. this.positionScreen.copy( vertex.positionScreen );
  12927. }
  12928. /**
  12929. * @author mrdoob / http://mrdoob.com/
  12930. */
  12931. THREE.RenderableFace3 = function () {
  12932. this.v1 = new THREE.RenderableVertex();
  12933. this.v2 = new THREE.RenderableVertex();
  12934. this.v3 = new THREE.RenderableVertex();
  12935. this.centroidWorld = new THREE.Vector3();
  12936. this.centroidScreen = new THREE.Vector3();
  12937. this.normalWorld = new THREE.Vector3();
  12938. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  12939. this.material = null;
  12940. this.uvs = [[]];
  12941. this.z = null;
  12942. };
  12943. /**
  12944. * @author mrdoob / http://mrdoob.com/
  12945. */
  12946. THREE.RenderableFace4 = function () {
  12947. this.v1 = new THREE.RenderableVertex();
  12948. this.v2 = new THREE.RenderableVertex();
  12949. this.v3 = new THREE.RenderableVertex();
  12950. this.v4 = new THREE.RenderableVertex();
  12951. this.centroidWorld = new THREE.Vector3();
  12952. this.centroidScreen = new THREE.Vector3();
  12953. this.normalWorld = new THREE.Vector3();
  12954. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  12955. this.material = null;
  12956. this.uvs = [[]];
  12957. this.z = null;
  12958. };
  12959. /**
  12960. * @author mrdoob / http://mrdoob.com/
  12961. */
  12962. THREE.RenderableObject = function () {
  12963. this.object = null;
  12964. this.z = null;
  12965. };
  12966. /**
  12967. * @author mrdoob / http://mrdoob.com/
  12968. */
  12969. THREE.RenderableParticle = function () {
  12970. this.object = null;
  12971. this.x = null;
  12972. this.y = null;
  12973. this.z = null;
  12974. this.rotation = null;
  12975. this.scale = new THREE.Vector2();
  12976. this.material = null;
  12977. };
  12978. /**
  12979. * @author mrdoob / http://mrdoob.com/
  12980. */
  12981. THREE.RenderableLine = function () {
  12982. this.z = null;
  12983. this.v1 = new THREE.RenderableVertex();
  12984. this.v2 = new THREE.RenderableVertex();
  12985. this.material = null;
  12986. };
  12987. /**
  12988. * @author alteredq / http://alteredqualia.com/
  12989. */
  12990. THREE.ColorUtils = {
  12991. adjustHSV : function ( color, h, s, v ) {
  12992. var hsv = THREE.ColorUtils.__hsv;
  12993. THREE.ColorUtils.rgbToHsv( color, hsv );
  12994. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  12995. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  12996. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  12997. color.setHSV( hsv.h, hsv.s, hsv.v );
  12998. },
  12999. // based on MochiKit implementation by Bob Ippolito
  13000. rgbToHsv : function ( color, hsv ) {
  13001. var r = color.r;
  13002. var g = color.g;
  13003. var b = color.b;
  13004. var max = Math.max( Math.max( r, g ), b );
  13005. var min = Math.min( Math.min( r, g ), b );
  13006. var hue;
  13007. var saturation;
  13008. var value = max;
  13009. if ( min === max ) {
  13010. hue = 0;
  13011. saturation = 0;
  13012. } else {
  13013. var delta = ( max - min );
  13014. saturation = delta / max;
  13015. if ( r === max ) {
  13016. hue = ( g - b ) / delta;
  13017. } else if ( g === max ) {
  13018. hue = 2 + ( ( b - r ) / delta );
  13019. } else {
  13020. hue = 4 + ( ( r - g ) / delta );
  13021. }
  13022. hue /= 6;
  13023. if ( hue < 0 ) {
  13024. hue += 1;
  13025. }
  13026. if ( hue > 1 ) {
  13027. hue -= 1;
  13028. }
  13029. }
  13030. if ( hsv === undefined ) {
  13031. hsv = { h: 0, s: 0, v: 0 };
  13032. }
  13033. hsv.h = hue;
  13034. hsv.s = saturation;
  13035. hsv.v = value;
  13036. return hsv;
  13037. }
  13038. };
  13039. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  13040. * @author mrdoob / http://mrdoob.com/
  13041. * @author alteredq / http://alteredqualia.com/
  13042. */
  13043. THREE.GeometryUtils = {
  13044. // Merge two geometries or geometry and geometry from object (using object's transform)
  13045. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  13046. var matrix, matrixRotation,
  13047. vertexOffset = geometry1.vertices.length,
  13048. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  13049. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  13050. vertices1 = geometry1.vertices,
  13051. vertices2 = geometry2.vertices,
  13052. faces1 = geometry1.faces,
  13053. faces2 = geometry2.faces,
  13054. uvs1 = geometry1.faceVertexUvs[ 0 ],
  13055. uvs2 = geometry2.faceVertexUvs[ 0 ];
  13056. var geo1MaterialsMap = {};
  13057. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  13058. var id = geometry1.materials[ i ].id;
  13059. geo1MaterialsMap[ id ] = i;
  13060. }
  13061. if ( object2 instanceof THREE.Mesh ) {
  13062. object2.matrixAutoUpdate && object2.updateMatrix();
  13063. matrix = object2.matrix;
  13064. matrixRotation = new THREE.Matrix4();
  13065. matrixRotation.extractRotation( matrix, object2.scale );
  13066. }
  13067. // vertices
  13068. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  13069. var vertex = vertices2[ i ];
  13070. var vertexCopy = vertex.clone();
  13071. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  13072. vertices1.push( vertexCopy );
  13073. }
  13074. // faces
  13075. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  13076. var face = faces2[ i ], faceCopy, normal, color,
  13077. faceVertexNormals = face.vertexNormals,
  13078. faceVertexColors = face.vertexColors;
  13079. if ( face instanceof THREE.Face3 ) {
  13080. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  13081. } else if ( face instanceof THREE.Face4 ) {
  13082. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  13083. }
  13084. faceCopy.normal.copy( face.normal );
  13085. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  13086. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  13087. normal = faceVertexNormals[ j ].clone();
  13088. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  13089. faceCopy.vertexNormals.push( normal );
  13090. }
  13091. faceCopy.color.copy( face.color );
  13092. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  13093. color = faceVertexColors[ j ];
  13094. faceCopy.vertexColors.push( color.clone() );
  13095. }
  13096. if ( face.materialIndex !== undefined ) {
  13097. var material2 = geometry2.materials[ face.materialIndex ];
  13098. var materialId2 = material2.id;
  13099. var materialIndex = geo1MaterialsMap[ materialId2 ];
  13100. if ( materialIndex === undefined ) {
  13101. materialIndex = geometry1.materials.length;
  13102. geo1MaterialsMap[ materialId2 ] = materialIndex;
  13103. geometry1.materials.push( material2 );
  13104. }
  13105. faceCopy.materialIndex = materialIndex;
  13106. }
  13107. faceCopy.centroid.copy( face.centroid );
  13108. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  13109. faces1.push( faceCopy );
  13110. }
  13111. // uvs
  13112. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  13113. var uv = uvs2[ i ], uvCopy = [];
  13114. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13115. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13116. }
  13117. uvs1.push( uvCopy );
  13118. }
  13119. },
  13120. clone: function ( geometry ) {
  13121. var cloneGeo = new THREE.Geometry();
  13122. var i, il;
  13123. var vertices = geometry.vertices,
  13124. faces = geometry.faces,
  13125. uvs = geometry.faceVertexUvs[ 0 ];
  13126. // materials
  13127. if ( geometry.materials ) {
  13128. cloneGeo.materials = geometry.materials.slice();
  13129. }
  13130. // vertices
  13131. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  13132. var vertex = vertices[ i ];
  13133. cloneGeo.vertices.push( vertex.clone() );
  13134. }
  13135. // faces
  13136. for ( i = 0, il = faces.length; i < il; i ++ ) {
  13137. var face = faces[ i ];
  13138. cloneGeo.faces.push( face.clone() );
  13139. }
  13140. // uvs
  13141. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  13142. var uv = uvs[ i ], uvCopy = [];
  13143. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13144. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13145. }
  13146. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  13147. }
  13148. return cloneGeo;
  13149. },
  13150. // Get random point in triangle (via barycentric coordinates)
  13151. // (uniform distribution)
  13152. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  13153. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  13154. var a, b, c,
  13155. point = new THREE.Vector3(),
  13156. tmp = THREE.GeometryUtils.__v1;
  13157. a = THREE.GeometryUtils.random();
  13158. b = THREE.GeometryUtils.random();
  13159. if ( ( a + b ) > 1 ) {
  13160. a = 1 - a;
  13161. b = 1 - b;
  13162. }
  13163. c = 1 - a - b;
  13164. point.copy( vectorA );
  13165. point.multiplyScalar( a );
  13166. tmp.copy( vectorB );
  13167. tmp.multiplyScalar( b );
  13168. point.addSelf( tmp );
  13169. tmp.copy( vectorC );
  13170. tmp.multiplyScalar( c );
  13171. point.addSelf( tmp );
  13172. return point;
  13173. },
  13174. // Get random point in face (triangle / quad)
  13175. // (uniform distribution)
  13176. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  13177. var vA, vB, vC, vD;
  13178. if ( face instanceof THREE.Face3 ) {
  13179. vA = geometry.vertices[ face.a ];
  13180. vB = geometry.vertices[ face.b ];
  13181. vC = geometry.vertices[ face.c ];
  13182. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  13183. } else if ( face instanceof THREE.Face4 ) {
  13184. vA = geometry.vertices[ face.a ];
  13185. vB = geometry.vertices[ face.b ];
  13186. vC = geometry.vertices[ face.c ];
  13187. vD = geometry.vertices[ face.d ];
  13188. var area1, area2;
  13189. if ( useCachedAreas ) {
  13190. if ( face._area1 && face._area2 ) {
  13191. area1 = face._area1;
  13192. area2 = face._area2;
  13193. } else {
  13194. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13195. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13196. face._area1 = area1;
  13197. face._area2 = area2;
  13198. }
  13199. } else {
  13200. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  13201. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13202. }
  13203. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  13204. if ( r < area1 ) {
  13205. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  13206. } else {
  13207. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  13208. }
  13209. }
  13210. },
  13211. // Get uniformly distributed random points in mesh
  13212. // - create array with cumulative sums of face areas
  13213. // - pick random number from 0 to total area
  13214. // - find corresponding place in area array by binary search
  13215. // - get random point in face
  13216. randomPointsInGeometry: function ( geometry, n ) {
  13217. var face, i,
  13218. faces = geometry.faces,
  13219. vertices = geometry.vertices,
  13220. il = faces.length,
  13221. totalArea = 0,
  13222. cumulativeAreas = [],
  13223. vA, vB, vC, vD;
  13224. // precompute face areas
  13225. for ( i = 0; i < il; i ++ ) {
  13226. face = faces[ i ];
  13227. if ( face instanceof THREE.Face3 ) {
  13228. vA = vertices[ face.a ];
  13229. vB = vertices[ face.b ];
  13230. vC = vertices[ face.c ];
  13231. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  13232. } else if ( face instanceof THREE.Face4 ) {
  13233. vA = vertices[ face.a ];
  13234. vB = vertices[ face.b ];
  13235. vC = vertices[ face.c ];
  13236. vD = vertices[ face.d ];
  13237. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13238. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13239. face._area = face._area1 + face._area2;
  13240. }
  13241. totalArea += face._area;
  13242. cumulativeAreas[ i ] = totalArea;
  13243. }
  13244. // binary search cumulative areas array
  13245. function binarySearchIndices( value ) {
  13246. function binarySearch( start, end ) {
  13247. // return closest larger index
  13248. // if exact number is not found
  13249. if ( end < start )
  13250. return start;
  13251. var mid = start + Math.floor( ( end - start ) / 2 );
  13252. if ( cumulativeAreas[ mid ] > value ) {
  13253. return binarySearch( start, mid - 1 );
  13254. } else if ( cumulativeAreas[ mid ] < value ) {
  13255. return binarySearch( mid + 1, end );
  13256. } else {
  13257. return mid;
  13258. }
  13259. }
  13260. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  13261. return result;
  13262. }
  13263. // pick random face weighted by face area
  13264. var r, index,
  13265. result = [];
  13266. var stats = {};
  13267. for ( i = 0; i < n; i ++ ) {
  13268. r = THREE.GeometryUtils.random() * totalArea;
  13269. index = binarySearchIndices( r );
  13270. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  13271. if ( ! stats[ index ] ) {
  13272. stats[ index ] = 1;
  13273. } else {
  13274. stats[ index ] += 1;
  13275. }
  13276. }
  13277. return result;
  13278. },
  13279. // Get triangle area (by Heron's formula)
  13280. // http://en.wikipedia.org/wiki/Heron%27s_formula
  13281. triangleArea: function ( vectorA, vectorB, vectorC ) {
  13282. var s, a, b, c,
  13283. tmp = THREE.GeometryUtils.__v1;
  13284. tmp.sub( vectorA, vectorB );
  13285. a = tmp.length();
  13286. tmp.sub( vectorA, vectorC );
  13287. b = tmp.length();
  13288. tmp.sub( vectorB, vectorC );
  13289. c = tmp.length();
  13290. s = 0.5 * ( a + b + c );
  13291. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  13292. },
  13293. // Center geometry so that 0,0,0 is in center of bounding box
  13294. center: function ( geometry ) {
  13295. geometry.computeBoundingBox();
  13296. var bb = geometry.boundingBox;
  13297. var offset = new THREE.Vector3();
  13298. offset.add( bb.min, bb.max );
  13299. offset.multiplyScalar( -0.5 );
  13300. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  13301. geometry.computeBoundingBox();
  13302. return offset;
  13303. },
  13304. // Normalize UVs to be from <0,1>
  13305. // (for now just the first set of UVs)
  13306. normalizeUVs: function ( geometry ) {
  13307. var uvSet = geometry.faceVertexUvs[ 0 ];
  13308. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  13309. var uvs = uvSet[ i ];
  13310. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  13311. // texture repeat
  13312. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  13313. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  13314. }
  13315. }
  13316. },
  13317. triangulateQuads: function ( geometry ) {
  13318. var i, il, j, jl;
  13319. var faces = [];
  13320. var faceUvs = [];
  13321. var faceVertexUvs = [];
  13322. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  13323. faceUvs[ i ] = [];
  13324. }
  13325. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13326. faceVertexUvs[ i ] = [];
  13327. }
  13328. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13329. var face = geometry.faces[ i ];
  13330. if ( face instanceof THREE.Face4 ) {
  13331. var a = face.a;
  13332. var b = face.b;
  13333. var c = face.c;
  13334. var d = face.d;
  13335. var triA = new THREE.Face3();
  13336. var triB = new THREE.Face3();
  13337. triA.color.copy( face.color );
  13338. triB.color.copy( face.color );
  13339. triA.materialIndex = face.materialIndex;
  13340. triB.materialIndex = face.materialIndex;
  13341. triA.a = a;
  13342. triA.b = b;
  13343. triA.c = d;
  13344. triB.a = b;
  13345. triB.b = c;
  13346. triB.c = d;
  13347. if ( face.vertexColors.length === 4 ) {
  13348. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  13349. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  13350. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13351. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  13352. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  13353. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13354. }
  13355. faces.push( triA, triB );
  13356. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13357. if ( geometry.faceVertexUvs[ j ].length ) {
  13358. var uvs = geometry.faceVertexUvs[ j ][ i ];
  13359. var uvA = uvs[ 0 ];
  13360. var uvB = uvs[ 1 ];
  13361. var uvC = uvs[ 2 ];
  13362. var uvD = uvs[ 3 ];
  13363. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  13364. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  13365. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  13366. }
  13367. }
  13368. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13369. if ( geometry.faceUvs[ j ].length ) {
  13370. var faceUv = geometry.faceUvs[ j ][ i ];
  13371. faceUvs[ j ].push( faceUv, faceUv );
  13372. }
  13373. }
  13374. } else {
  13375. faces.push( face );
  13376. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13377. faceUvs[ j ].push( geometry.faceUvs[ j ] );
  13378. }
  13379. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13380. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  13381. }
  13382. }
  13383. }
  13384. geometry.faces = faces;
  13385. geometry.faceUvs = faceUvs;
  13386. geometry.faceVertexUvs = faceVertexUvs;
  13387. geometry.computeCentroids();
  13388. geometry.computeFaceNormals();
  13389. geometry.computeVertexNormals();
  13390. if ( geometry.hasTangents ) geometry.computeTangents();
  13391. },
  13392. // Make all faces use unique vertices
  13393. // so that each face can be separated from others
  13394. explode: function( geometry ) {
  13395. var vertices = [];
  13396. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13397. var n = vertices.length;
  13398. var face = geometry.faces[ i ];
  13399. if ( face instanceof THREE.Face4 ) {
  13400. var a = face.a;
  13401. var b = face.b;
  13402. var c = face.c;
  13403. var d = face.d;
  13404. var va = geometry.vertices[ a ];
  13405. var vb = geometry.vertices[ b ];
  13406. var vc = geometry.vertices[ c ];
  13407. var vd = geometry.vertices[ d ];
  13408. vertices.push( va.clone() );
  13409. vertices.push( vb.clone() );
  13410. vertices.push( vc.clone() );
  13411. vertices.push( vd.clone() );
  13412. face.a = n;
  13413. face.b = n + 1;
  13414. face.c = n + 2;
  13415. face.d = n + 3;
  13416. } else {
  13417. var a = face.a;
  13418. var b = face.b;
  13419. var c = face.c;
  13420. var va = geometry.vertices[ a ];
  13421. var vb = geometry.vertices[ b ];
  13422. var vc = geometry.vertices[ c ];
  13423. vertices.push( va.clone() );
  13424. vertices.push( vb.clone() );
  13425. vertices.push( vc.clone() );
  13426. face.a = n;
  13427. face.b = n + 1;
  13428. face.c = n + 2;
  13429. }
  13430. }
  13431. geometry.vertices = vertices;
  13432. delete geometry.__tmpVertices;
  13433. },
  13434. // Break faces with edges longer than maxEdgeLength
  13435. // - not recursive
  13436. tessellate: function ( geometry, maxEdgeLength ) {
  13437. var i, il, face,
  13438. a, b, c, d,
  13439. va, vb, vc, vd,
  13440. dab, dbc, dac, dcd, dad,
  13441. m, m1, m2,
  13442. vm, vm1, vm2,
  13443. vnm, vnm1, vnm2,
  13444. vcm, vcm1, vcm2,
  13445. triA, triB,
  13446. quadA, quadB,
  13447. edge;
  13448. var faces = [];
  13449. var faceVertexUvs = [];
  13450. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13451. faceVertexUvs[ i ] = [];
  13452. }
  13453. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13454. face = geometry.faces[ i ];
  13455. if ( face instanceof THREE.Face3 ) {
  13456. a = face.a;
  13457. b = face.b;
  13458. c = face.c;
  13459. va = geometry.vertices[ a ];
  13460. vb = geometry.vertices[ b ];
  13461. vc = geometry.vertices[ c ];
  13462. dab = va.distanceTo( vb );
  13463. dbc = vb.distanceTo( vc );
  13464. dac = va.distanceTo( vc );
  13465. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  13466. m = geometry.vertices.length;
  13467. triA = face.clone();
  13468. triB = face.clone();
  13469. if ( dab >= dbc && dab >= dac ) {
  13470. vm = va.clone();
  13471. vm.lerpSelf( vb, 0.5 );
  13472. triA.a = a;
  13473. triA.b = m;
  13474. triA.c = c;
  13475. triB.a = m;
  13476. triB.b = b;
  13477. triB.c = c;
  13478. if ( face.vertexNormals.length === 3 ) {
  13479. vnm = face.vertexNormals[ 0 ].clone();
  13480. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  13481. triA.vertexNormals[ 1 ].copy( vnm );
  13482. triB.vertexNormals[ 0 ].copy( vnm );
  13483. }
  13484. if ( face.vertexColors.length === 3 ) {
  13485. vcm = face.vertexColors[ 0 ].clone();
  13486. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  13487. triA.vertexColors[ 1 ].copy( vcm );
  13488. triB.vertexColors[ 0 ].copy( vcm );
  13489. }
  13490. edge = 0;
  13491. } else if ( dbc >= dab && dbc >= dac ) {
  13492. vm = vb.clone();
  13493. vm.lerpSelf( vc, 0.5 );
  13494. triA.a = a;
  13495. triA.b = b;
  13496. triA.c = m;
  13497. triB.a = m;
  13498. triB.b = c;
  13499. triB.c = a;
  13500. if ( face.vertexNormals.length === 3 ) {
  13501. vnm = face.vertexNormals[ 1 ].clone();
  13502. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  13503. triA.vertexNormals[ 2 ].copy( vnm );
  13504. triB.vertexNormals[ 0 ].copy( vnm );
  13505. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  13506. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  13507. }
  13508. if ( face.vertexColors.length === 3 ) {
  13509. vcm = face.vertexColors[ 1 ].clone();
  13510. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  13511. triA.vertexColors[ 2 ].copy( vcm );
  13512. triB.vertexColors[ 0 ].copy( vcm );
  13513. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  13514. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  13515. }
  13516. edge = 1;
  13517. } else {
  13518. vm = va.clone();
  13519. vm.lerpSelf( vc, 0.5 );
  13520. triA.a = a;
  13521. triA.b = b;
  13522. triA.c = m;
  13523. triB.a = m;
  13524. triB.b = b;
  13525. triB.c = c;
  13526. if ( face.vertexNormals.length === 3 ) {
  13527. vnm = face.vertexNormals[ 0 ].clone();
  13528. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  13529. triA.vertexNormals[ 2 ].copy( vnm );
  13530. triB.vertexNormals[ 0 ].copy( vnm );
  13531. }
  13532. if ( face.vertexColors.length === 3 ) {
  13533. vcm = face.vertexColors[ 0 ].clone();
  13534. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  13535. triA.vertexColors[ 2 ].copy( vcm );
  13536. triB.vertexColors[ 0 ].copy( vcm );
  13537. }
  13538. edge = 2;
  13539. }
  13540. faces.push( triA, triB );
  13541. geometry.vertices.push( vm );
  13542. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  13543. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13544. if ( geometry.faceVertexUvs[ j ].length ) {
  13545. uvs = geometry.faceVertexUvs[ j ][ i ];
  13546. uvA = uvs[ 0 ];
  13547. uvB = uvs[ 1 ];
  13548. uvC = uvs[ 2 ];
  13549. // AB
  13550. if ( edge === 0 ) {
  13551. uvM = uvA.clone();
  13552. uvM.lerpSelf( uvB, 0.5 );
  13553. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  13554. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  13555. // BC
  13556. } else if ( edge === 1 ) {
  13557. uvM = uvB.clone();
  13558. uvM.lerpSelf( uvC, 0.5 );
  13559. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  13560. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  13561. // AC
  13562. } else {
  13563. uvM = uvA.clone();
  13564. uvM.lerpSelf( uvC, 0.5 );
  13565. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  13566. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  13567. }
  13568. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  13569. }
  13570. }
  13571. } else {
  13572. faces.push( face );
  13573. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13574. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  13575. }
  13576. }
  13577. } else {
  13578. a = face.a;
  13579. b = face.b;
  13580. c = face.c;
  13581. d = face.d;
  13582. va = geometry.vertices[ a ];
  13583. vb = geometry.vertices[ b ];
  13584. vc = geometry.vertices[ c ];
  13585. vd = geometry.vertices[ d ];
  13586. dab = va.distanceTo( vb );
  13587. dbc = vb.distanceTo( vc );
  13588. dcd = vc.distanceTo( vd );
  13589. dad = va.distanceTo( vd );
  13590. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  13591. m1 = geometry.vertices.length;
  13592. m2 = geometry.vertices.length + 1;
  13593. quadA = face.clone();
  13594. quadB = face.clone();
  13595. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  13596. vm1 = va.clone();
  13597. vm1.lerpSelf( vb, 0.5 );
  13598. vm2 = vc.clone();
  13599. vm2.lerpSelf( vd, 0.5 );
  13600. quadA.a = a;
  13601. quadA.b = m1;
  13602. quadA.c = m2;
  13603. quadA.d = d;
  13604. quadB.a = m1;
  13605. quadB.b = b;
  13606. quadB.c = c;
  13607. quadB.d = m2;
  13608. if ( face.vertexNormals.length === 4 ) {
  13609. vnm1 = face.vertexNormals[ 0 ].clone();
  13610. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  13611. vnm2 = face.vertexNormals[ 2 ].clone();
  13612. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  13613. quadA.vertexNormals[ 1 ].copy( vnm1 );
  13614. quadA.vertexNormals[ 2 ].copy( vnm2 );
  13615. quadB.vertexNormals[ 0 ].copy( vnm1 );
  13616. quadB.vertexNormals[ 3 ].copy( vnm2 );
  13617. }
  13618. if ( face.vertexColors.length === 4 ) {
  13619. vcm1 = face.vertexColors[ 0 ].clone();
  13620. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  13621. vcm2 = face.vertexColors[ 2 ].clone();
  13622. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  13623. quadA.vertexColors[ 1 ].copy( vcm1 );
  13624. quadA.vertexColors[ 2 ].copy( vcm2 );
  13625. quadB.vertexColors[ 0 ].copy( vcm1 );
  13626. quadB.vertexColors[ 3 ].copy( vcm2 );
  13627. }
  13628. edge = 0;
  13629. } else {
  13630. vm1 = vb.clone();
  13631. vm1.lerpSelf( vc, 0.5 );
  13632. vm2 = vd.clone();
  13633. vm2.lerpSelf( va, 0.5 );
  13634. quadA.a = a;
  13635. quadA.b = b;
  13636. quadA.c = m1;
  13637. quadA.d = m2;
  13638. quadB.a = m2;
  13639. quadB.b = m1;
  13640. quadB.c = c;
  13641. quadB.d = d;
  13642. if ( face.vertexNormals.length === 4 ) {
  13643. vnm1 = face.vertexNormals[ 1 ].clone();
  13644. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  13645. vnm2 = face.vertexNormals[ 3 ].clone();
  13646. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  13647. quadA.vertexNormals[ 2 ].copy( vnm1 );
  13648. quadA.vertexNormals[ 3 ].copy( vnm2 );
  13649. quadB.vertexNormals[ 0 ].copy( vnm2 );
  13650. quadB.vertexNormals[ 1 ].copy( vnm1 );
  13651. }
  13652. if ( face.vertexColors.length === 4 ) {
  13653. vcm1 = face.vertexColors[ 1 ].clone();
  13654. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  13655. vcm2 = face.vertexColors[ 3 ].clone();
  13656. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  13657. quadA.vertexColors[ 2 ].copy( vcm1 );
  13658. quadA.vertexColors[ 3 ].copy( vcm2 );
  13659. quadB.vertexColors[ 0 ].copy( vcm2 );
  13660. quadB.vertexColors[ 1 ].copy( vcm1 );
  13661. }
  13662. edge = 1;
  13663. }
  13664. faces.push( quadA, quadB );
  13665. geometry.vertices.push( vm1, vm2 );
  13666. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  13667. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13668. if ( geometry.faceVertexUvs[ j ].length ) {
  13669. uvs = geometry.faceVertexUvs[ j ][ i ];
  13670. uvA = uvs[ 0 ];
  13671. uvB = uvs[ 1 ];
  13672. uvC = uvs[ 2 ];
  13673. uvD = uvs[ 3 ];
  13674. // AB + CD
  13675. if ( edge === 0 ) {
  13676. uvM1 = uvA.clone();
  13677. uvM1.lerpSelf( uvB, 0.5 );
  13678. uvM2 = uvC.clone();
  13679. uvM2.lerpSelf( uvD, 0.5 );
  13680. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  13681. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  13682. // BC + AD
  13683. } else {
  13684. uvM1 = uvB.clone();
  13685. uvM1.lerpSelf( uvC, 0.5 );
  13686. uvM2 = uvD.clone();
  13687. uvM2.lerpSelf( uvA, 0.5 );
  13688. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  13689. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  13690. }
  13691. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  13692. }
  13693. }
  13694. } else {
  13695. faces.push( face );
  13696. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13697. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  13698. }
  13699. }
  13700. }
  13701. }
  13702. geometry.faces = faces;
  13703. geometry.faceVertexUvs = faceVertexUvs;
  13704. }
  13705. };
  13706. THREE.GeometryUtils.random = THREE.Math.random16;
  13707. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  13708. /**
  13709. * @author alteredq / http://alteredqualia.com/
  13710. * @author mrdoob / http://mrdoob.com/
  13711. */
  13712. THREE.ImageUtils = {
  13713. crossOrigin: 'anonymous',
  13714. loadTexture: function ( url, mapping, onLoad, onError ) {
  13715. var image = new Image();
  13716. var texture = new THREE.Texture( image, mapping );
  13717. var loader = new THREE.ImageLoader();
  13718. loader.addEventListener( 'load', function ( event ) {
  13719. texture.image = event.content;
  13720. texture.needsUpdate = true;
  13721. if ( onLoad ) onLoad( texture );
  13722. } );
  13723. loader.addEventListener( 'error', function ( event ) {
  13724. if ( onError ) onError( event.message );
  13725. } );
  13726. loader.crossOrigin = this.crossOrigin;
  13727. loader.load( url, image );
  13728. return texture;
  13729. },
  13730. loadTextureCube: function ( array, mapping, onLoad ) {
  13731. var i, l, images = [];
  13732. var texture = new THREE.Texture( images, mapping );
  13733. texture.flipY = false;
  13734. images.loadCount = 0;
  13735. for ( i = 0, l = array.length; i < l; ++ i ) {
  13736. images[ i ] = new Image();
  13737. images[ i ].onload = function () {
  13738. images.loadCount += 1;
  13739. if ( images.loadCount === 6 ) {
  13740. texture.needsUpdate = true;
  13741. if ( onLoad ) onLoad();
  13742. }
  13743. };
  13744. images[ i ].crossOrigin = this.crossOrigin;
  13745. images[ i ].src = array[ i ];
  13746. }
  13747. return texture;
  13748. },
  13749. getNormalMap: function ( image, depth ) {
  13750. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  13751. var cross = function ( a, b ) {
  13752. 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 ] ];
  13753. }
  13754. var subtract = function ( a, b ) {
  13755. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  13756. }
  13757. var normalize = function ( a ) {
  13758. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  13759. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  13760. }
  13761. depth = depth | 1;
  13762. var width = image.width;
  13763. var height = image.height;
  13764. var canvas = document.createElement( 'canvas' );
  13765. canvas.width = width;
  13766. canvas.height = height;
  13767. var context = canvas.getContext( '2d' );
  13768. context.drawImage( image, 0, 0 );
  13769. var data = context.getImageData( 0, 0, width, height ).data;
  13770. var imageData = context.createImageData( width, height );
  13771. var output = imageData.data;
  13772. for ( var x = 0; x < width; x ++ ) {
  13773. for ( var y = 0; y < height; y ++ ) {
  13774. var ly = y - 1 < 0 ? 0 : y - 1;
  13775. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  13776. var lx = x - 1 < 0 ? 0 : x - 1;
  13777. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  13778. var points = [];
  13779. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  13780. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  13781. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  13782. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  13783. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  13784. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  13785. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  13786. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  13787. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  13788. var normals = [];
  13789. var num_points = points.length;
  13790. for ( var i = 0; i < num_points; i ++ ) {
  13791. var v1 = points[ i ];
  13792. var v2 = points[ ( i + 1 ) % num_points ];
  13793. v1 = subtract( v1, origin );
  13794. v2 = subtract( v2, origin );
  13795. normals.push( normalize( cross( v1, v2 ) ) );
  13796. }
  13797. var normal = [ 0, 0, 0 ];
  13798. for ( var i = 0; i < normals.length; i ++ ) {
  13799. normal[ 0 ] += normals[ i ][ 0 ];
  13800. normal[ 1 ] += normals[ i ][ 1 ];
  13801. normal[ 2 ] += normals[ i ][ 2 ];
  13802. }
  13803. normal[ 0 ] /= normals.length;
  13804. normal[ 1 ] /= normals.length;
  13805. normal[ 2 ] /= normals.length;
  13806. var idx = ( y * width + x ) * 4;
  13807. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  13808. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  13809. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  13810. output[ idx + 3 ] = 255;
  13811. }
  13812. }
  13813. context.putImageData( imageData, 0, 0 );
  13814. return canvas;
  13815. },
  13816. generateDataTexture: function ( width, height, color ) {
  13817. var size = width * height;
  13818. var data = new Uint8Array( 3 * size );
  13819. var r = Math.floor( color.r * 255 );
  13820. var g = Math.floor( color.g * 255 );
  13821. var b = Math.floor( color.b * 255 );
  13822. for ( var i = 0; i < size; i ++ ) {
  13823. data[ i * 3 ] = r;
  13824. data[ i * 3 + 1 ] = g;
  13825. data[ i * 3 + 2 ] = b;
  13826. }
  13827. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  13828. texture.needsUpdate = true;
  13829. return texture;
  13830. }
  13831. };
  13832. /**
  13833. * @author alteredq / http://alteredqualia.com/
  13834. */
  13835. THREE.SceneUtils = {
  13836. showHierarchy : function ( root, visible ) {
  13837. THREE.SceneUtils.traverseHierarchy( root, function( node ) { node.visible = visible; } );
  13838. },
  13839. traverseHierarchy : function ( root, callback ) {
  13840. var n, i, l = root.children.length;
  13841. for ( i = 0; i < l; i ++ ) {
  13842. n = root.children[ i ];
  13843. callback( n );
  13844. THREE.SceneUtils.traverseHierarchy( n, callback );
  13845. }
  13846. },
  13847. createMultiMaterialObject : function ( geometry, materials ) {
  13848. var i, il = materials.length,
  13849. group = new THREE.Object3D();
  13850. for ( i = 0; i < il; i ++ ) {
  13851. var object = new THREE.Mesh( geometry, materials[ i ] );
  13852. group.add( object );
  13853. }
  13854. return group;
  13855. },
  13856. cloneObject: function ( source ) {
  13857. var object;
  13858. // subclass specific properties
  13859. // (must process in order from more specific subclasses to more abstract classes)
  13860. if ( source instanceof THREE.MorphAnimMesh ) {
  13861. object = new THREE.MorphAnimMesh( source.geometry, source.material );
  13862. object.duration = source.duration;
  13863. object.mirroredLoop = source.mirroredLoop;
  13864. object.time = source.time;
  13865. object.lastKeyframe = source.lastKeyframe;
  13866. object.currentKeyframe = source.currentKeyframe;
  13867. object.direction = source.direction;
  13868. object.directionBackwards = source.directionBackwards;
  13869. } else if ( source instanceof THREE.SkinnedMesh ) {
  13870. object = new THREE.SkinnedMesh( source.geometry, source.material );
  13871. } else if ( source instanceof THREE.Mesh ) {
  13872. object = new THREE.Mesh( source.geometry, source.material );
  13873. } else if ( source instanceof THREE.Line ) {
  13874. object = new THREE.Line( source.geometry, source.material, source.type );
  13875. } else if ( source instanceof THREE.Ribbon ) {
  13876. object = new THREE.Ribbon( source.geometry, source.material );
  13877. } else if ( source instanceof THREE.ParticleSystem ) {
  13878. object = new THREE.ParticleSystem( source.geometry, source.material );
  13879. object.sortParticles = source.sortParticles;
  13880. } else if ( source instanceof THREE.Particle ) {
  13881. object = new THREE.Particle( source.material );
  13882. } else if ( source instanceof THREE.Sprite ) {
  13883. object = new THREE.Sprite( {} );
  13884. object.color.copy( source.color );
  13885. object.map = source.map;
  13886. object.blending = source.blending;
  13887. object.useScreenCoordinates = source.useScreenCoordinates;
  13888. object.mergeWith3D = source.mergeWith3D;
  13889. object.affectedByDistance = source.affectedByDistance;
  13890. object.scaleByViewport = source.scaleByViewport;
  13891. object.alignment = source.alignment;
  13892. object.rotation3d.copy( source.rotation3d );
  13893. object.rotation = source.rotation;
  13894. object.opacity = source.opacity;
  13895. object.uvOffset.copy( source.uvOffset );
  13896. object.uvScale.copy( source.uvScale);
  13897. } else if ( source instanceof THREE.LOD ) {
  13898. object = new THREE.LOD();
  13899. /*
  13900. } else if ( source instanceof THREE.MarchingCubes ) {
  13901. object = new THREE.MarchingCubes( source.resolution, source.material );
  13902. object.field.set( source.field );
  13903. object.isolation = source.isolation;
  13904. */
  13905. } else if ( source instanceof THREE.Object3D ) {
  13906. object = new THREE.Object3D();
  13907. }
  13908. // base class properties
  13909. object.name = source.name;
  13910. object.parent = source.parent;
  13911. object.up.copy( source.up );
  13912. object.position.copy( source.position );
  13913. // because of Sprite madness
  13914. if ( object.rotation instanceof THREE.Vector3 )
  13915. object.rotation.copy( source.rotation );
  13916. object.eulerOrder = source.eulerOrder;
  13917. object.scale.copy( source.scale );
  13918. object.dynamic = source.dynamic;
  13919. object.renderDepth = source.renderDepth;
  13920. object.rotationAutoUpdate = source.rotationAutoUpdate;
  13921. object.matrix.copy( source.matrix );
  13922. object.matrixWorld.copy( source.matrixWorld );
  13923. object.matrixRotationWorld.copy( source.matrixRotationWorld );
  13924. object.matrixAutoUpdate = source.matrixAutoUpdate;
  13925. object.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  13926. object.quaternion.copy( source.quaternion );
  13927. object.useQuaternion = source.useQuaternion;
  13928. object.boundRadius = source.boundRadius;
  13929. object.boundRadiusScale = source.boundRadiusScale;
  13930. object.visible = source.visible;
  13931. object.castShadow = source.castShadow;
  13932. object.receiveShadow = source.receiveShadow;
  13933. object.frustumCulled = source.frustumCulled;
  13934. // children
  13935. for ( var i = 0; i < source.children.length; i ++ ) {
  13936. var child = THREE.SceneUtils.cloneObject( source.children[ i ] );
  13937. object.children[ i ] = child;
  13938. child.parent = object;
  13939. }
  13940. // LODs need to be patched separately to use cloned children
  13941. if ( source instanceof THREE.LOD ) {
  13942. for ( var i = 0; i < source.LODs.length; i ++ ) {
  13943. var lod = source.LODs[ i ];
  13944. object.LODs[ i ] = { visibleAtDistance: lod.visibleAtDistance, object3D: object.children[ i ] };
  13945. }
  13946. }
  13947. return object;
  13948. },
  13949. detach : function ( child, parent, scene ) {
  13950. child.applyMatrix( parent.matrixWorld );
  13951. parent.remove( child );
  13952. scene.add( child );
  13953. },
  13954. attach: function ( child, scene, parent ) {
  13955. var matrixWorldInverse = new THREE.Matrix4();
  13956. matrixWorldInverse.getInverse( parent.matrixWorld );
  13957. child.applyMatrix( matrixWorldInverse );
  13958. scene.remove( child );
  13959. parent.add( child );
  13960. }
  13961. };
  13962. /**
  13963. * @author alteredq / http://alteredqualia.com/
  13964. * @author mrdoob / http://mrdoob.com/
  13965. *
  13966. * ShaderUtils currently contains:
  13967. *
  13968. * fresnel
  13969. * normal
  13970. * cube
  13971. *
  13972. */
  13973. if ( THREE.WebGLRenderer ) {
  13974. THREE.ShaderUtils = {
  13975. lib: {
  13976. /* -------------------------------------------------------------------------
  13977. // Fresnel shader
  13978. // - based on Nvidia Cg tutorial
  13979. ------------------------------------------------------------------------- */
  13980. 'fresnel': {
  13981. uniforms: {
  13982. "mRefractionRatio": { type: "f", value: 1.02 },
  13983. "mFresnelBias": { type: "f", value: 0.1 },
  13984. "mFresnelPower": { type: "f", value: 2.0 },
  13985. "mFresnelScale": { type: "f", value: 1.0 },
  13986. "tCube": { type: "t", value: 1, texture: null }
  13987. },
  13988. fragmentShader: [
  13989. "uniform samplerCube tCube;",
  13990. "varying vec3 vReflect;",
  13991. "varying vec3 vRefract[3];",
  13992. "varying float vReflectionFactor;",
  13993. "void main() {",
  13994. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  13995. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  13996. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  13997. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  13998. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  13999. "refractedColor.a = 1.0;",
  14000. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  14001. "}"
  14002. ].join("\n"),
  14003. vertexShader: [
  14004. "uniform float mRefractionRatio;",
  14005. "uniform float mFresnelBias;",
  14006. "uniform float mFresnelScale;",
  14007. "uniform float mFresnelPower;",
  14008. "varying vec3 vReflect;",
  14009. "varying vec3 vRefract[3];",
  14010. "varying float vReflectionFactor;",
  14011. "void main() {",
  14012. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14013. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  14014. "vec3 nWorld = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  14015. "vec3 I = mPosition.xyz - cameraPosition;",
  14016. "vReflect = reflect( I, nWorld );",
  14017. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  14018. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  14019. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  14020. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  14021. "gl_Position = projectionMatrix * mvPosition;",
  14022. "}"
  14023. ].join("\n")
  14024. },
  14025. /* -------------------------------------------------------------------------
  14026. // Normal map shader
  14027. // - Blinn-Phong
  14028. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  14029. // - point and directional lights (use with "lights: true" material option)
  14030. ------------------------------------------------------------------------- */
  14031. 'normal' : {
  14032. uniforms: THREE.UniformsUtils.merge( [
  14033. THREE.UniformsLib[ "fog" ],
  14034. THREE.UniformsLib[ "lights" ],
  14035. THREE.UniformsLib[ "shadowmap" ],
  14036. {
  14037. "enableAO" : { type: "i", value: 0 },
  14038. "enableDiffuse" : { type: "i", value: 0 },
  14039. "enableSpecular" : { type: "i", value: 0 },
  14040. "enableReflection": { type: "i", value: 0 },
  14041. "enableDisplacement": { type: "i", value: 0 },
  14042. "tDiffuse" : { type: "t", value: 0, texture: null },
  14043. "tCube" : { type: "t", value: 1, texture: null },
  14044. "tNormal" : { type: "t", value: 2, texture: null },
  14045. "tSpecular" : { type: "t", value: 3, texture: null },
  14046. "tAO" : { type: "t", value: 4, texture: null },
  14047. "tDisplacement": { type: "t", value: 5, texture: null },
  14048. "uNormalScale": { type: "f", value: 1.0 },
  14049. "uDisplacementBias": { type: "f", value: 0.0 },
  14050. "uDisplacementScale": { type: "f", value: 1.0 },
  14051. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14052. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  14053. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14054. "uShininess": { type: "f", value: 30 },
  14055. "uOpacity": { type: "f", value: 1 },
  14056. "useRefract": { type: "i", value: 0 },
  14057. "uRefractionRatio": { type: "f", value: 0.98 },
  14058. "uReflectivity": { type: "f", value: 0.5 },
  14059. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  14060. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14061. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  14062. }
  14063. ] ),
  14064. fragmentShader: [
  14065. "uniform vec3 uAmbientColor;",
  14066. "uniform vec3 uDiffuseColor;",
  14067. "uniform vec3 uSpecularColor;",
  14068. "uniform float uShininess;",
  14069. "uniform float uOpacity;",
  14070. "uniform bool enableDiffuse;",
  14071. "uniform bool enableSpecular;",
  14072. "uniform bool enableAO;",
  14073. "uniform bool enableReflection;",
  14074. "uniform sampler2D tDiffuse;",
  14075. "uniform sampler2D tNormal;",
  14076. "uniform sampler2D tSpecular;",
  14077. "uniform sampler2D tAO;",
  14078. "uniform samplerCube tCube;",
  14079. "uniform float uNormalScale;",
  14080. "uniform bool useRefract;",
  14081. "uniform float uRefractionRatio;",
  14082. "uniform float uReflectivity;",
  14083. "varying vec3 vTangent;",
  14084. "varying vec3 vBinormal;",
  14085. "varying vec3 vNormal;",
  14086. "varying vec2 vUv;",
  14087. "uniform vec3 ambientLightColor;",
  14088. "#if MAX_DIR_LIGHTS > 0",
  14089. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  14090. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  14091. "#endif",
  14092. "#if MAX_POINT_LIGHTS > 0",
  14093. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  14094. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  14095. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  14096. "#endif",
  14097. "#if MAX_SPOT_LIGHTS > 0",
  14098. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  14099. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  14100. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  14101. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  14102. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  14103. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  14104. "#endif",
  14105. "#ifdef WRAP_AROUND",
  14106. "uniform vec3 wrapRGB;",
  14107. "#endif",
  14108. "varying vec3 vWorldPosition;",
  14109. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14110. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14111. "void main() {",
  14112. "vec3 vViewPosition = cameraPosition - vWorldPosition;",
  14113. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  14114. "vec3 specularTex = vec3( 1.0 );",
  14115. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  14116. "normalTex.xy *= uNormalScale;",
  14117. "normalTex = normalize( normalTex );",
  14118. "if( enableDiffuse ) {",
  14119. "#ifdef GAMMA_INPUT",
  14120. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  14121. "texelColor.xyz *= texelColor.xyz;",
  14122. "gl_FragColor = gl_FragColor * texelColor;",
  14123. "#else",
  14124. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  14125. "#endif",
  14126. "}",
  14127. "if( enableAO ) {",
  14128. "#ifdef GAMMA_INPUT",
  14129. "vec4 aoColor = texture2D( tAO, vUv );",
  14130. "aoColor.xyz *= aoColor.xyz;",
  14131. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  14132. "#else",
  14133. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  14134. "#endif",
  14135. "}",
  14136. "if( enableSpecular )",
  14137. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  14138. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  14139. "vec3 finalNormal = tsb * normalTex;",
  14140. "vec3 normal = normalize( finalNormal );",
  14141. "vec3 viewPosition = normalize( vViewPosition );",
  14142. // point lights
  14143. "#if MAX_POINT_LIGHTS > 0",
  14144. "vec3 pointDiffuse = vec3( 0.0 );",
  14145. "vec3 pointSpecular = vec3( 0.0 );",
  14146. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  14147. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  14148. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  14149. "float pointDistance = 1.0;",
  14150. "if ( pointLightDistance[ i ] > 0.0 )",
  14151. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  14152. "pointVector = normalize( pointVector );",
  14153. // diffuse
  14154. "#ifdef WRAP_AROUND",
  14155. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  14156. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  14157. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  14158. "#else",
  14159. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  14160. "#endif",
  14161. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  14162. // specular
  14163. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  14164. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  14165. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, 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( pointVector, pointHalfVector ), 5.0 );",
  14170. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  14171. "#else",
  14172. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  14173. "#endif",
  14174. "}",
  14175. "#endif",
  14176. // spot lights
  14177. "#if MAX_SPOT_LIGHTS > 0",
  14178. "vec3 spotDiffuse = vec3( 0.0 );",
  14179. "vec3 spotSpecular = vec3( 0.0 );",
  14180. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  14181. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  14182. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  14183. "float spotDistance = 1.0;",
  14184. "if ( spotLightDistance[ i ] > 0.0 )",
  14185. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  14186. "spotVector = normalize( spotVector );",
  14187. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  14188. "if ( spotEffect > spotLightAngle[ i ] ) {",
  14189. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  14190. // diffuse
  14191. "#ifdef WRAP_AROUND",
  14192. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  14193. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  14194. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  14195. "#else",
  14196. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  14197. "#endif",
  14198. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  14199. // specular
  14200. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  14201. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  14202. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  14203. "#ifdef PHYSICALLY_BASED_SHADING",
  14204. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14205. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14206. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  14207. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  14208. "#else",
  14209. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  14210. "#endif",
  14211. "}",
  14212. "}",
  14213. "#endif",
  14214. // directional lights
  14215. "#if MAX_DIR_LIGHTS > 0",
  14216. "vec3 dirDiffuse = vec3( 0.0 );",
  14217. "vec3 dirSpecular = vec3( 0.0 );",
  14218. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  14219. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  14220. "vec3 dirVector = normalize( lDirection.xyz );",
  14221. // diffuse
  14222. "#ifdef WRAP_AROUND",
  14223. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  14224. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  14225. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  14226. "#else",
  14227. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  14228. "#endif",
  14229. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  14230. // specular
  14231. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  14232. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  14233. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  14234. "#ifdef PHYSICALLY_BASED_SHADING",
  14235. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14236. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14237. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  14238. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  14239. "#else",
  14240. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  14241. "#endif",
  14242. "}",
  14243. "#endif",
  14244. // all lights contribution summation
  14245. "vec3 totalDiffuse = vec3( 0.0 );",
  14246. "vec3 totalSpecular = vec3( 0.0 );",
  14247. "#if MAX_DIR_LIGHTS > 0",
  14248. "totalDiffuse += dirDiffuse;",
  14249. "totalSpecular += dirSpecular;",
  14250. "#endif",
  14251. "#if MAX_POINT_LIGHTS > 0",
  14252. "totalDiffuse += pointDiffuse;",
  14253. "totalSpecular += pointSpecular;",
  14254. "#endif",
  14255. "#if MAX_SPOT_LIGHTS > 0",
  14256. "totalDiffuse += spotDiffuse;",
  14257. "totalSpecular += spotSpecular;",
  14258. "#endif",
  14259. "#ifdef METAL",
  14260. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  14261. "#else",
  14262. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  14263. "#endif",
  14264. "if ( enableReflection ) {",
  14265. "vec3 vReflect;",
  14266. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  14267. "if ( useRefract ) {",
  14268. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  14269. "} else {",
  14270. "vReflect = reflect( cameraToVertex, normal );",
  14271. "}",
  14272. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14273. "#ifdef GAMMA_INPUT",
  14274. "cubeColor.xyz *= cubeColor.xyz;",
  14275. "#endif",
  14276. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  14277. "}",
  14278. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14279. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14280. THREE.ShaderChunk[ "fog_fragment" ],
  14281. "}"
  14282. ].join("\n"),
  14283. vertexShader: [
  14284. "attribute vec4 tangent;",
  14285. "uniform vec2 uOffset;",
  14286. "uniform vec2 uRepeat;",
  14287. "uniform bool enableDisplacement;",
  14288. "#ifdef VERTEX_TEXTURES",
  14289. "uniform sampler2D tDisplacement;",
  14290. "uniform float uDisplacementScale;",
  14291. "uniform float uDisplacementBias;",
  14292. "#endif",
  14293. "varying vec3 vTangent;",
  14294. "varying vec3 vBinormal;",
  14295. "varying vec3 vNormal;",
  14296. "varying vec2 vUv;",
  14297. "varying vec3 vWorldPosition;",
  14298. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14299. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14300. "void main() {",
  14301. THREE.ShaderChunk[ "skinbase_vertex" ],
  14302. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14303. // normal, tangent and binormal vectors
  14304. "#ifdef USE_SKINNING",
  14305. "vNormal = normalMatrix * skinnedNormal.xyz;",
  14306. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  14307. "vTangent = normalMatrix * skinnedTangent.xyz;",
  14308. "#else",
  14309. "vNormal = normalMatrix * normal;",
  14310. "vTangent = normalMatrix * tangent.xyz;",
  14311. "#endif",
  14312. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  14313. "vUv = uv * uRepeat + uOffset;",
  14314. // displacement mapping
  14315. "vec3 displacedPosition;",
  14316. "#ifdef VERTEX_TEXTURES",
  14317. "if ( enableDisplacement ) {",
  14318. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  14319. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  14320. "displacedPosition = position + normalize( normal ) * df;",
  14321. "} else {",
  14322. "#ifdef USE_SKINNING",
  14323. "vec4 skinned = boneMatX * skinVertexA * skinWeight.x;",
  14324. "skinned += boneMatY * skinVertexB * skinWeight.y;",
  14325. "displacedPosition = skinned.xyz;",
  14326. "#else",
  14327. "displacedPosition = position;",
  14328. "#endif",
  14329. "}",
  14330. "#else",
  14331. "#ifdef USE_SKINNING",
  14332. "vec4 skinned = boneMatX * skinVertexA * skinWeight.x;",
  14333. "skinned += boneMatY * skinVertexB * skinWeight.y;",
  14334. "displacedPosition = skinned.xyz;",
  14335. "#else",
  14336. "displacedPosition = position;",
  14337. "#endif",
  14338. "#endif",
  14339. //
  14340. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  14341. "vec4 wPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  14342. "gl_Position = projectionMatrix * mvPosition;",
  14343. //
  14344. "vWorldPosition = wPosition.xyz;",
  14345. // shadows
  14346. "#ifdef USE_SHADOWMAP",
  14347. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  14348. "vShadowCoord[ i ] = shadowMatrix[ i ] * wPosition;",
  14349. "}",
  14350. "#endif",
  14351. "}"
  14352. ].join("\n")
  14353. },
  14354. /* -------------------------------------------------------------------------
  14355. // Cube map shader
  14356. ------------------------------------------------------------------------- */
  14357. 'cube': {
  14358. uniforms: { "tCube": { type: "t", value: 1, texture: null },
  14359. "tFlip": { type: "f", value: -1 } },
  14360. vertexShader: [
  14361. "varying vec3 vViewPosition;",
  14362. "void main() {",
  14363. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  14364. "vViewPosition = cameraPosition - mPosition.xyz;",
  14365. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  14366. "}"
  14367. ].join("\n"),
  14368. fragmentShader: [
  14369. "uniform samplerCube tCube;",
  14370. "uniform float tFlip;",
  14371. "varying vec3 vViewPosition;",
  14372. "void main() {",
  14373. "vec3 wPos = cameraPosition - vViewPosition;",
  14374. "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
  14375. "}"
  14376. ].join("\n")
  14377. }
  14378. }
  14379. };
  14380. };
  14381. /**
  14382. * @author zz85 / http://www.lab4games.net/zz85/blog
  14383. * @author alteredq / http://alteredqualia.com/
  14384. *
  14385. * For Text operations in three.js (See TextGeometry)
  14386. *
  14387. * It uses techniques used in:
  14388. *
  14389. * typeface.js and canvastext
  14390. * For converting fonts and rendering with javascript
  14391. * http://typeface.neocracy.org
  14392. *
  14393. * Triangulation ported from AS3
  14394. * Simple Polygon Triangulation
  14395. * http://actionsnippet.com/?p=1462
  14396. *
  14397. * A Method to triangulate shapes with holes
  14398. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  14399. *
  14400. */
  14401. THREE.FontUtils = {
  14402. faces : {},
  14403. // Just for now. face[weight][style]
  14404. face : "helvetiker",
  14405. weight: "normal",
  14406. style : "normal",
  14407. size : 150,
  14408. divisions : 10,
  14409. getFace : function() {
  14410. return this.faces[ this.face ][ this.weight ][ this.style ];
  14411. },
  14412. loadFace : function( data ) {
  14413. var family = data.familyName.toLowerCase();
  14414. var ThreeFont = this;
  14415. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  14416. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  14417. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  14418. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  14419. return data;
  14420. },
  14421. drawText : function( text ) {
  14422. var characterPts = [], allPts = [];
  14423. // RenderText
  14424. var i, p,
  14425. face = this.getFace(),
  14426. scale = this.size / face.resolution,
  14427. offset = 0,
  14428. chars = String( text ).split( '' ),
  14429. length = chars.length;
  14430. var fontPaths = [];
  14431. for ( i = 0; i < length; i ++ ) {
  14432. var path = new THREE.Path();
  14433. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  14434. offset += ret.offset;
  14435. fontPaths.push( ret.path );
  14436. }
  14437. // get the width
  14438. var width = offset / 2;
  14439. //
  14440. // for ( p = 0; p < allPts.length; p++ ) {
  14441. //
  14442. // allPts[ p ].x -= width;
  14443. //
  14444. // }
  14445. //var extract = this.extractPoints( allPts, characterPts );
  14446. //extract.contour = allPts;
  14447. //extract.paths = fontPaths;
  14448. //extract.offset = width;
  14449. return { paths : fontPaths, offset : width };
  14450. },
  14451. extractGlyphPoints : function( c, face, scale, offset, path ) {
  14452. var pts = [];
  14453. var i, i2, divisions,
  14454. outline, action, length,
  14455. scaleX, scaleY,
  14456. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  14457. laste,
  14458. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  14459. if ( !glyph ) return;
  14460. if ( glyph.o ) {
  14461. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  14462. length = outline.length;
  14463. scaleX = scale;
  14464. scaleY = scale;
  14465. for ( i = 0; i < length; ) {
  14466. action = outline[ i ++ ];
  14467. //console.log( action );
  14468. switch( action ) {
  14469. case 'm':
  14470. // Move To
  14471. x = outline[ i++ ] * scaleX + offset;
  14472. y = outline[ i++ ] * scaleY;
  14473. path.moveTo( x, y );
  14474. break;
  14475. case 'l':
  14476. // Line To
  14477. x = outline[ i++ ] * scaleX + offset;
  14478. y = outline[ i++ ] * scaleY;
  14479. path.lineTo(x,y);
  14480. break;
  14481. case 'q':
  14482. // QuadraticCurveTo
  14483. cpx = outline[ i++ ] * scaleX + offset;
  14484. cpy = outline[ i++ ] * scaleY;
  14485. cpx1 = outline[ i++ ] * scaleX + offset;
  14486. cpy1 = outline[ i++ ] * scaleY;
  14487. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  14488. laste = pts[ pts.length - 1 ];
  14489. if ( laste ) {
  14490. cpx0 = laste.x;
  14491. cpy0 = laste.y;
  14492. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  14493. var t = i2 / divisions;
  14494. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  14495. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  14496. }
  14497. }
  14498. break;
  14499. case 'b':
  14500. // Cubic Bezier Curve
  14501. cpx = outline[ i++ ] * scaleX + offset;
  14502. cpy = outline[ i++ ] * scaleY;
  14503. cpx1 = outline[ i++ ] * scaleX + offset;
  14504. cpy1 = outline[ i++ ] * -scaleY;
  14505. cpx2 = outline[ i++ ] * scaleX + offset;
  14506. cpy2 = outline[ i++ ] * -scaleY;
  14507. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  14508. laste = pts[ pts.length - 1 ];
  14509. if ( laste ) {
  14510. cpx0 = laste.x;
  14511. cpy0 = laste.y;
  14512. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  14513. var t = i2 / divisions;
  14514. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  14515. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  14516. }
  14517. }
  14518. break;
  14519. }
  14520. }
  14521. }
  14522. return { offset: glyph.ha*scale, path:path};
  14523. }
  14524. };
  14525. THREE.FontUtils.generateShapes = function( text, parameters ) {
  14526. // Parameters
  14527. parameters = parameters || {};
  14528. var size = parameters.size !== undefined ? parameters.size : 100;
  14529. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  14530. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  14531. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  14532. var style = parameters.style !== undefined ? parameters.style : "normal";
  14533. THREE.FontUtils.size = size;
  14534. THREE.FontUtils.divisions = curveSegments;
  14535. THREE.FontUtils.face = font;
  14536. THREE.FontUtils.weight = weight;
  14537. THREE.FontUtils.style = style;
  14538. // Get a Font data json object
  14539. var data = THREE.FontUtils.drawText( text );
  14540. var paths = data.paths;
  14541. var shapes = [];
  14542. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  14543. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  14544. }
  14545. return shapes;
  14546. };
  14547. /**
  14548. * This code is a quick port of code written in C++ which was submitted to
  14549. * flipcode.com by John W. Ratcliff // July 22, 2000
  14550. * See original code and more information here:
  14551. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  14552. *
  14553. * ported to actionscript by Zevan Rosser
  14554. * www.actionsnippet.com
  14555. *
  14556. * ported to javascript by Joshua Koo
  14557. * http://www.lab4games.net/zz85/blog
  14558. *
  14559. */
  14560. ( function( namespace ) {
  14561. var EPSILON = 0.0000000001;
  14562. // takes in an contour array and returns
  14563. var process = function( contour, indices ) {
  14564. var n = contour.length;
  14565. if ( n < 3 ) return null;
  14566. var result = [],
  14567. verts = [],
  14568. vertIndices = [];
  14569. /* we want a counter-clockwise polygon in verts */
  14570. var u, v, w;
  14571. if ( area( contour ) > 0.0 ) {
  14572. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  14573. } else {
  14574. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  14575. }
  14576. var nv = n;
  14577. /* remove nv - 2 vertices, creating 1 triangle every time */
  14578. var count = 2 * nv; /* error detection */
  14579. for( v = nv - 1; nv > 2; ) {
  14580. /* if we loop, it is probably a non-simple polygon */
  14581. if ( ( count-- ) <= 0 ) {
  14582. //** Triangulate: ERROR - probable bad polygon!
  14583. //throw ( "Warning, unable to triangulate polygon!" );
  14584. //return null;
  14585. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  14586. console.log( "Warning, unable to triangulate polygon!" );
  14587. if ( indices ) return vertIndices;
  14588. return result;
  14589. }
  14590. /* three consecutive vertices in current polygon, <u,v,w> */
  14591. u = v; if ( nv <= u ) u = 0; /* previous */
  14592. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  14593. w = v + 1; if ( nv <= w ) w = 0; /* next */
  14594. if ( snip( contour, u, v, w, nv, verts ) ) {
  14595. var a, b, c, s, t;
  14596. /* true names of the vertices */
  14597. a = verts[ u ];
  14598. b = verts[ v ];
  14599. c = verts[ w ];
  14600. /* output Triangle */
  14601. /*
  14602. result.push( contour[ a ] );
  14603. result.push( contour[ b ] );
  14604. result.push( contour[ c ] );
  14605. */
  14606. result.push( [ contour[ a ],
  14607. contour[ b ],
  14608. contour[ c ] ] );
  14609. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  14610. /* remove v from the remaining polygon */
  14611. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  14612. verts[ s ] = verts[ t ];
  14613. }
  14614. nv--;
  14615. /* reset error detection counter */
  14616. count = 2 * nv;
  14617. }
  14618. }
  14619. if ( indices ) return vertIndices;
  14620. return result;
  14621. };
  14622. // calculate area of the contour polygon
  14623. var area = function ( contour ) {
  14624. var n = contour.length;
  14625. var a = 0.0;
  14626. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  14627. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  14628. }
  14629. return a * 0.5;
  14630. };
  14631. // see if p is inside triangle abc
  14632. var insideTriangle = function( ax, ay,
  14633. bx, by,
  14634. cx, cy,
  14635. px, py ) {
  14636. var aX, aY, bX, bY;
  14637. var cX, cY, apx, apy;
  14638. var bpx, bpy, cpx, cpy;
  14639. var cCROSSap, bCROSScp, aCROSSbp;
  14640. aX = cx - bx; aY = cy - by;
  14641. bX = ax - cx; bY = ay - cy;
  14642. cX = bx - ax; cY = by - ay;
  14643. apx= px -ax; apy= py - ay;
  14644. bpx= px - bx; bpy= py - by;
  14645. cpx= px - cx; cpy= py - cy;
  14646. aCROSSbp = aX*bpy - aY*bpx;
  14647. cCROSSap = cX*apy - cY*apx;
  14648. bCROSScp = bX*cpy - bY*cpx;
  14649. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  14650. };
  14651. var snip = function ( contour, u, v, w, n, verts ) {
  14652. var p;
  14653. var ax, ay, bx, by;
  14654. var cx, cy, px, py;
  14655. ax = contour[ verts[ u ] ].x;
  14656. ay = contour[ verts[ u ] ].y;
  14657. bx = contour[ verts[ v ] ].x;
  14658. by = contour[ verts[ v ] ].y;
  14659. cx = contour[ verts[ w ] ].x;
  14660. cy = contour[ verts[ w ] ].y;
  14661. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  14662. for ( p = 0; p < n; p++ ) {
  14663. if( (p == u) || (p == v) || (p == w) ) continue;
  14664. px = contour[ verts[ p ] ].x
  14665. py = contour[ verts[ p ] ].y
  14666. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  14667. }
  14668. return true;
  14669. };
  14670. namespace.Triangulate = process;
  14671. namespace.Triangulate.area = area;
  14672. return namespace;
  14673. })(THREE.FontUtils);
  14674. // To use the typeface.js face files, hook up the API
  14675. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  14676. * @author zz85 / http://www.lab4games.net/zz85/blog
  14677. * Extensible curve object
  14678. *
  14679. * Some common of Curve methods
  14680. * .getPoint(t), getTangent(t)
  14681. * .getPointAt(u), getTagentAt(u)
  14682. * .getPoints(), .getSpacedPoints()
  14683. * .getLength()
  14684. * .updateArcLengths()
  14685. *
  14686. * This file contains following classes:
  14687. *
  14688. * -- 2d classes --
  14689. * THREE.Curve
  14690. * THREE.LineCurve
  14691. * THREE.QuadraticBezierCurve
  14692. * THREE.CubicBezierCurve
  14693. * THREE.SplineCurve
  14694. * THREE.ArcCurve
  14695. * THREE.EllipseCurve
  14696. *
  14697. * -- 3d classes --
  14698. * THREE.LineCurve3
  14699. * THREE.QuadraticBezierCurve3
  14700. * THREE.CubicBezierCurve3
  14701. * THREE.SplineCurve3
  14702. * THREE.ClosedSplineCurve3
  14703. *
  14704. * A series of curves can be represented as a THREE.CurvePath
  14705. *
  14706. **/
  14707. /**************************************************************
  14708. * Abstract Curve base class
  14709. **************************************************************/
  14710. THREE.Curve = function () {
  14711. };
  14712. // Virtual base class method to overwrite and implement in subclasses
  14713. // - t [0 .. 1]
  14714. THREE.Curve.prototype.getPoint = function ( t ) {
  14715. console.log( "Warning, getPoint() not implemented!" );
  14716. return null;
  14717. };
  14718. // Get point at relative position in curve according to arc length
  14719. // - u [0 .. 1]
  14720. THREE.Curve.prototype.getPointAt = function ( u ) {
  14721. var t = this.getUtoTmapping( u );
  14722. return this.getPoint( t );
  14723. };
  14724. // Get sequence of points using getPoint( t )
  14725. THREE.Curve.prototype.getPoints = function ( divisions ) {
  14726. if ( !divisions ) divisions = 5;
  14727. var d, pts = [];
  14728. for ( d = 0; d <= divisions; d ++ ) {
  14729. pts.push( this.getPoint( d / divisions ) );
  14730. }
  14731. return pts;
  14732. };
  14733. // Get sequence of points using getPointAt( u )
  14734. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  14735. if ( !divisions ) divisions = 5;
  14736. var d, pts = [];
  14737. for ( d = 0; d <= divisions; d ++ ) {
  14738. pts.push( this.getPointAt( d / divisions ) );
  14739. }
  14740. return pts;
  14741. };
  14742. // Get total curve arc length
  14743. THREE.Curve.prototype.getLength = function () {
  14744. var lengths = this.getLengths();
  14745. return lengths[ lengths.length - 1 ];
  14746. };
  14747. // Get list of cumulative segment lengths
  14748. THREE.Curve.prototype.getLengths = function ( divisions ) {
  14749. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  14750. if ( this.cacheArcLengths
  14751. && ( this.cacheArcLengths.length == divisions + 1 )
  14752. && !this.needsUpdate) {
  14753. //console.log( "cached", this.cacheArcLengths );
  14754. return this.cacheArcLengths;
  14755. }
  14756. this.needsUpdate = false;
  14757. var cache = [];
  14758. var current, last = this.getPoint( 0 );
  14759. var p, sum = 0;
  14760. cache.push( 0 );
  14761. for ( p = 1; p <= divisions; p ++ ) {
  14762. current = this.getPoint ( p / divisions );
  14763. sum += current.distanceTo( last );
  14764. cache.push( sum );
  14765. last = current;
  14766. }
  14767. this.cacheArcLengths = cache;
  14768. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  14769. };
  14770. THREE.Curve.prototype.updateArcLengths = function() {
  14771. this.needsUpdate = true;
  14772. this.getLengths();
  14773. };
  14774. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  14775. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  14776. var arcLengths = this.getLengths();
  14777. var i = 0, il = arcLengths.length;
  14778. var targetArcLength; // The targeted u distance value to get
  14779. if ( distance ) {
  14780. targetArcLength = distance;
  14781. } else {
  14782. targetArcLength = u * arcLengths[ il - 1 ];
  14783. }
  14784. //var time = Date.now();
  14785. // binary search for the index with largest value smaller than target u distance
  14786. var low = 0, high = il - 1, comparison;
  14787. while ( low <= high ) {
  14788. 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
  14789. comparison = arcLengths[ i ] - targetArcLength;
  14790. if ( comparison < 0 ) {
  14791. low = i + 1;
  14792. continue;
  14793. } else if ( comparison > 0 ) {
  14794. high = i - 1;
  14795. continue;
  14796. } else {
  14797. high = i;
  14798. break;
  14799. // DONE
  14800. }
  14801. }
  14802. i = high;
  14803. //console.log('b' , i, low, high, Date.now()- time);
  14804. if ( arcLengths[ i ] == targetArcLength ) {
  14805. var t = i / ( il - 1 );
  14806. return t;
  14807. }
  14808. // we could get finer grain at lengths, or use simple interpolatation between two points
  14809. var lengthBefore = arcLengths[ i ];
  14810. var lengthAfter = arcLengths[ i + 1 ];
  14811. var segmentLength = lengthAfter - lengthBefore;
  14812. // determine where we are between the 'before' and 'after' points
  14813. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  14814. // add that fractional amount to t
  14815. var t = ( i + segmentFraction ) / ( il -1 );
  14816. return t;
  14817. };
  14818. // In 2D space, there are actually 2 normal vectors,
  14819. // and in 3D space, infinte
  14820. // TODO this should be depreciated.
  14821. THREE.Curve.prototype.getNormalVector = function( t ) {
  14822. var vec = this.getTangent( t );
  14823. return new THREE.Vector2( -vec.y , vec.x );
  14824. };
  14825. // Returns a unit vector tangent at t
  14826. // In case any sub curve does not implement its tangent / normal finding,
  14827. // we get 2 points with a small delta and find a gradient of the 2 points
  14828. // which seems to make a reasonable approximation
  14829. THREE.Curve.prototype.getTangent = function( t ) {
  14830. var delta = 0.0001;
  14831. var t1 = t - delta;
  14832. var t2 = t + delta;
  14833. // Capping in case of danger
  14834. if ( t1 < 0 ) t1 = 0;
  14835. if ( t2 > 1 ) t2 = 1;
  14836. var pt1 = this.getPoint( t1 );
  14837. var pt2 = this.getPoint( t2 );
  14838. var vec = pt2.clone().subSelf(pt1);
  14839. return vec.normalize();
  14840. };
  14841. THREE.Curve.prototype.getTangentAt = function ( u ) {
  14842. var t = this.getUtoTmapping( u );
  14843. return this.getTangent( t );
  14844. };
  14845. /**************************************************************
  14846. * Line
  14847. **************************************************************/
  14848. THREE.LineCurve = function ( v1, v2 ) {
  14849. this.v1 = v1;
  14850. this.v2 = v2;
  14851. };
  14852. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  14853. THREE.LineCurve.prototype.getPoint = function ( t ) {
  14854. var point = this.v2.clone().subSelf(this.v1);
  14855. point.multiplyScalar( t ).addSelf( this.v1 );
  14856. return point;
  14857. };
  14858. // Line curve is linear, so we can overwrite default getPointAt
  14859. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  14860. return this.getPoint( u );
  14861. };
  14862. THREE.LineCurve.prototype.getTangent = function( t ) {
  14863. var tangent = this.v2.clone().subSelf(this.v1);
  14864. return tangent.normalize();
  14865. };
  14866. /**************************************************************
  14867. * Quadratic Bezier curve
  14868. **************************************************************/
  14869. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  14870. this.v0 = v0;
  14871. this.v1 = v1;
  14872. this.v2 = v2;
  14873. };
  14874. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  14875. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  14876. var tx, ty;
  14877. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  14878. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  14879. return new THREE.Vector2( tx, ty );
  14880. };
  14881. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  14882. var tx, ty;
  14883. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  14884. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  14885. // returns unit vector
  14886. var tangent = new THREE.Vector2( tx, ty );
  14887. tangent.normalize();
  14888. return tangent;
  14889. };
  14890. /**************************************************************
  14891. * Cubic Bezier curve
  14892. **************************************************************/
  14893. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  14894. this.v0 = v0;
  14895. this.v1 = v1;
  14896. this.v2 = v2;
  14897. this.v3 = v3;
  14898. };
  14899. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  14900. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  14901. var tx, ty;
  14902. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  14903. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  14904. return new THREE.Vector2( tx, ty );
  14905. };
  14906. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  14907. var tx, ty;
  14908. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  14909. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  14910. var tangent = new THREE.Vector2( tx, ty );
  14911. tangent.normalize();
  14912. return tangent;
  14913. };
  14914. /**************************************************************
  14915. * Spline curve
  14916. **************************************************************/
  14917. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  14918. this.points = (points == undefined) ? [] : points;
  14919. };
  14920. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  14921. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  14922. var v = new THREE.Vector2();
  14923. var c = [];
  14924. var points = this.points, point, intPoint, weight;
  14925. point = ( points.length - 1 ) * t;
  14926. intPoint = Math.floor( point );
  14927. weight = point - intPoint;
  14928. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  14929. c[ 1 ] = intPoint;
  14930. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  14931. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  14932. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  14933. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  14934. return v;
  14935. };
  14936. /**************************************************************
  14937. * Ellipse curve
  14938. **************************************************************/
  14939. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  14940. aStartAngle, aEndAngle,
  14941. aClockwise ) {
  14942. this.aX = aX;
  14943. this.aY = aY;
  14944. this.xRadius = xRadius;
  14945. this.yRadius = yRadius;
  14946. this.aStartAngle = aStartAngle;
  14947. this.aEndAngle = aEndAngle;
  14948. this.aClockwise = aClockwise;
  14949. };
  14950. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  14951. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  14952. var deltaAngle = this.aEndAngle - this.aStartAngle;
  14953. if ( !this.aClockwise ) {
  14954. t = 1 - t;
  14955. }
  14956. var angle = this.aStartAngle + t * deltaAngle;
  14957. var tx = this.aX + this.xRadius * Math.cos( angle );
  14958. var ty = this.aY + this.yRadius * Math.sin( angle );
  14959. return new THREE.Vector2( tx, ty );
  14960. };
  14961. /**************************************************************
  14962. * Arc curve
  14963. **************************************************************/
  14964. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  14965. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  14966. };
  14967. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  14968. /**************************************************************
  14969. * Utils
  14970. **************************************************************/
  14971. THREE.Curve.Utils = {
  14972. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  14973. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  14974. },
  14975. // Puay Bing, thanks for helping with this derivative!
  14976. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  14977. return -3 * p0 * (1 - t) * (1 - t) +
  14978. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  14979. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  14980. 3 * t * t * p3;
  14981. },
  14982. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  14983. // To check if my formulas are correct
  14984. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  14985. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  14986. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  14987. var h11 = 3 * t * t - 2 * t; // t3 − t2
  14988. return h00 + h10 + h01 + h11;
  14989. },
  14990. // Catmull-Rom
  14991. interpolate: function( p0, p1, p2, p3, t ) {
  14992. var v0 = ( p2 - p0 ) * 0.5;
  14993. var v1 = ( p3 - p1 ) * 0.5;
  14994. var t2 = t * t;
  14995. var t3 = t * t2;
  14996. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  14997. }
  14998. };
  14999. // TODO: Transformation for Curves?
  15000. /**************************************************************
  15001. * 3D Curves
  15002. **************************************************************/
  15003. // A Factory method for creating new curve subclasses
  15004. THREE.Curve.create = function ( constructor, getPointFunc ) {
  15005. constructor.prototype = Object.create( THREE.Curve.prototype );
  15006. constructor.prototype.getPoint = getPointFunc;
  15007. return constructor;
  15008. };
  15009. /**************************************************************
  15010. * Line3D
  15011. **************************************************************/
  15012. THREE.LineCurve3 = THREE.Curve.create(
  15013. function ( v1, v2 ) {
  15014. this.v1 = v1;
  15015. this.v2 = v2;
  15016. },
  15017. function ( t ) {
  15018. var r = new THREE.Vector3();
  15019. r.sub( this.v2, this.v1 ); // diff
  15020. r.multiplyScalar( t );
  15021. r.addSelf( this.v1 );
  15022. return r;
  15023. }
  15024. );
  15025. /**************************************************************
  15026. * Quadratic Bezier 3D curve
  15027. **************************************************************/
  15028. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  15029. function ( v0, v1, v2 ) {
  15030. this.v0 = v0;
  15031. this.v1 = v1;
  15032. this.v2 = v2;
  15033. },
  15034. function ( t ) {
  15035. var tx, ty, tz;
  15036. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15037. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15038. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  15039. return new THREE.Vector3( tx, ty, tz );
  15040. }
  15041. );
  15042. /**************************************************************
  15043. * Cubic Bezier 3D curve
  15044. **************************************************************/
  15045. THREE.CubicBezierCurve3 = THREE.Curve.create(
  15046. function ( v0, v1, v2, v3 ) {
  15047. this.v0 = v0;
  15048. this.v1 = v1;
  15049. this.v2 = v2;
  15050. this.v3 = v3;
  15051. },
  15052. function ( t ) {
  15053. var tx, ty, tz;
  15054. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15055. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15056. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  15057. return new THREE.Vector3( tx, ty, tz );
  15058. }
  15059. );
  15060. /**************************************************************
  15061. * Spline 3D curve
  15062. **************************************************************/
  15063. THREE.SplineCurve3 = THREE.Curve.create(
  15064. function ( points /* array of Vector3 */) {
  15065. this.points = (points == undefined) ? [] : points;
  15066. },
  15067. function ( t ) {
  15068. var v = new THREE.Vector3();
  15069. var c = [];
  15070. var points = this.points, point, intPoint, weight;
  15071. point = ( points.length - 1 ) * t;
  15072. intPoint = Math.floor( point );
  15073. weight = point - intPoint;
  15074. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15075. c[ 1 ] = intPoint;
  15076. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15077. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15078. var pt0 = points[ c[0] ],
  15079. pt1 = points[ c[1] ],
  15080. pt2 = points[ c[2] ],
  15081. pt3 = points[ c[3] ];
  15082. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  15083. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  15084. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  15085. return v;
  15086. }
  15087. );
  15088. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  15089. // var v = new THREE.Vector3();
  15090. // var c = [];
  15091. // var points = this.points, point, intPoint, weight;
  15092. // point = ( points.length - 1 ) * t;
  15093. // intPoint = Math.floor( point );
  15094. // weight = point - intPoint;
  15095. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15096. // c[ 1 ] = intPoint;
  15097. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15098. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15099. // var pt0 = points[ c[0] ],
  15100. // pt1 = points[ c[1] ],
  15101. // pt2 = points[ c[2] ],
  15102. // pt3 = points[ c[3] ];
  15103. // // t = weight;
  15104. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  15105. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  15106. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  15107. // return v;
  15108. // }
  15109. /**************************************************************
  15110. * Closed Spline 3D curve
  15111. **************************************************************/
  15112. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  15113. function ( points /* array of Vector3 */) {
  15114. this.points = (points == undefined) ? [] : points;
  15115. },
  15116. function ( t ) {
  15117. var v = new THREE.Vector3();
  15118. var c = [];
  15119. var points = this.points, point, intPoint, weight;
  15120. point = ( points.length - 0 ) * t;
  15121. // This needs to be from 0-length +1
  15122. intPoint = Math.floor( point );
  15123. weight = point - intPoint;
  15124. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  15125. c[ 0 ] = ( intPoint - 1 ) % points.length;
  15126. c[ 1 ] = ( intPoint ) % points.length;
  15127. c[ 2 ] = ( intPoint + 1 ) % points.length;
  15128. c[ 3 ] = ( intPoint + 2 ) % points.length;
  15129. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15130. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15131. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  15132. return v;
  15133. }
  15134. );
  15135. /**
  15136. * @author zz85 / http://www.lab4games.net/zz85/blog
  15137. *
  15138. **/
  15139. /**************************************************************
  15140. * Curved Path - a curve path is simply a array of connected
  15141. * curves, but retains the api of a curve
  15142. **************************************************************/
  15143. THREE.CurvePath = function () {
  15144. this.curves = [];
  15145. this.bends = [];
  15146. this.autoClose = false; // Automatically closes the path
  15147. };
  15148. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  15149. THREE.CurvePath.prototype.add = function ( curve ) {
  15150. this.curves.push( curve );
  15151. };
  15152. THREE.CurvePath.prototype.checkConnection = function() {
  15153. // TODO
  15154. // If the ending of curve is not connected to the starting
  15155. // or the next curve, then, this is not a real path
  15156. };
  15157. THREE.CurvePath.prototype.closePath = function() {
  15158. // TODO Test
  15159. // and verify for vector3 (needs to implement equals)
  15160. // Add a line curve if start and end of lines are not connected
  15161. var startPoint = this.curves[0].getPoint(0);
  15162. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  15163. if (!startPoint.equals(endPoint)) {
  15164. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  15165. }
  15166. };
  15167. // To get accurate point with reference to
  15168. // entire path distance at time t,
  15169. // following has to be done:
  15170. // 1. Length of each sub path have to be known
  15171. // 2. Locate and identify type of curve
  15172. // 3. Get t for the curve
  15173. // 4. Return curve.getPointAt(t')
  15174. THREE.CurvePath.prototype.getPoint = function( t ) {
  15175. var d = t * this.getLength();
  15176. var curveLengths = this.getCurveLengths();
  15177. var i = 0, diff, curve;
  15178. // To think about boundaries points.
  15179. while ( i < curveLengths.length ) {
  15180. if ( curveLengths[ i ] >= d ) {
  15181. diff = curveLengths[ i ] - d;
  15182. curve = this.curves[ i ];
  15183. var u = 1 - diff / curve.getLength();
  15184. return curve.getPointAt( u );
  15185. break;
  15186. }
  15187. i ++;
  15188. }
  15189. return null;
  15190. // loop where sum != 0, sum > d , sum+1 <d
  15191. };
  15192. /*
  15193. THREE.CurvePath.prototype.getTangent = function( t ) {
  15194. };*/
  15195. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  15196. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  15197. // getPoint() depends on getLength
  15198. THREE.CurvePath.prototype.getLength = function() {
  15199. var lens = this.getCurveLengths();
  15200. return lens[ lens.length - 1 ];
  15201. };
  15202. // Compute lengths and cache them
  15203. // We cannot overwrite getLengths() because UtoT mapping uses it.
  15204. THREE.CurvePath.prototype.getCurveLengths = function() {
  15205. // We use cache values if curves and cache array are same length
  15206. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  15207. return this.cacheLengths;
  15208. };
  15209. // Get length of subsurve
  15210. // Push sums into cached array
  15211. var lengths = [], sums = 0;
  15212. var i, il = this.curves.length;
  15213. for ( i = 0; i < il; i ++ ) {
  15214. sums += this.curves[ i ].getLength();
  15215. lengths.push( sums );
  15216. }
  15217. this.cacheLengths = lengths;
  15218. return lengths;
  15219. };
  15220. // Returns min and max coordinates, as well as centroid
  15221. THREE.CurvePath.prototype.getBoundingBox = function () {
  15222. var points = this.getPoints();
  15223. var maxX, maxY, maxZ;
  15224. var minX, minY, minZ;
  15225. maxX = maxY = Number.NEGATIVE_INFINITY;
  15226. minX = minY = Number.POSITIVE_INFINITY;
  15227. var p, i, il, sum;
  15228. var v3 = points[0] instanceof THREE.Vector3;
  15229. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  15230. for ( i = 0, il = points.length; i < il; i ++ ) {
  15231. p = points[ i ];
  15232. if ( p.x > maxX ) maxX = p.x;
  15233. else if ( p.x < minX ) minX = p.x;
  15234. if ( p.y > maxY ) maxY = p.y;
  15235. else if ( p.y < minY ) minY = p.y;
  15236. if (v3) {
  15237. if ( p.z > maxZ ) maxZ = p.z;
  15238. else if ( p.z < minZ ) minZ = p.z;
  15239. }
  15240. sum.addSelf( p );
  15241. }
  15242. var ret = {
  15243. minX: minX,
  15244. minY: minY,
  15245. maxX: maxX,
  15246. maxY: maxY,
  15247. centroid: sum.divideScalar( il )
  15248. };
  15249. if (v3) {
  15250. ret.maxZ = maxZ;
  15251. ret.minZ = minZ;
  15252. }
  15253. return ret;
  15254. };
  15255. /**************************************************************
  15256. * Create Geometries Helpers
  15257. **************************************************************/
  15258. /// Generate geometry from path points (for Line or ParticleSystem objects)
  15259. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  15260. var pts = this.getPoints( divisions, true );
  15261. return this.createGeometry( pts );
  15262. };
  15263. // Generate geometry from equidistance sampling along the path
  15264. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  15265. var pts = this.getSpacedPoints( divisions, true );
  15266. return this.createGeometry( pts );
  15267. };
  15268. THREE.CurvePath.prototype.createGeometry = function( points ) {
  15269. var geometry = new THREE.Geometry();
  15270. for ( var i = 0; i < points.length; i ++ ) {
  15271. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  15272. }
  15273. return geometry;
  15274. };
  15275. /**************************************************************
  15276. * Bend / Wrap Helper Methods
  15277. **************************************************************/
  15278. // Wrap path / Bend modifiers?
  15279. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  15280. this.bends.push( bendpath );
  15281. };
  15282. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  15283. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  15284. var i, il;
  15285. if ( !bends ) {
  15286. bends = this.bends;
  15287. }
  15288. for ( i = 0, il = bends.length; i < il; i ++ ) {
  15289. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  15290. }
  15291. return oldPts;
  15292. };
  15293. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  15294. var oldPts = this.getSpacedPoints( segments );
  15295. var i, il;
  15296. if ( !bends ) {
  15297. bends = this.bends;
  15298. }
  15299. for ( i = 0, il = bends.length; i < il; i ++ ) {
  15300. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  15301. }
  15302. return oldPts;
  15303. };
  15304. // This returns getPoints() bend/wrapped around the contour of a path.
  15305. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  15306. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  15307. var bounds = this.getBoundingBox();
  15308. var i, il, p, oldX, oldY, xNorm;
  15309. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  15310. p = oldPts[ i ];
  15311. oldX = p.x;
  15312. oldY = p.y;
  15313. xNorm = oldX / bounds.maxX;
  15314. // If using actual distance, for length > path, requires line extrusions
  15315. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  15316. xNorm = path.getUtoTmapping( xNorm, oldX );
  15317. // check for out of bounds?
  15318. var pathPt = path.getPoint( xNorm );
  15319. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  15320. p.x = pathPt.x + normal.x;
  15321. p.y = pathPt.y + normal.y;
  15322. }
  15323. return oldPts;
  15324. };
  15325. /**
  15326. * @author alteredq / http://alteredqualia.com/
  15327. */
  15328. THREE.Gyroscope = function () {
  15329. THREE.Object3D.call( this );
  15330. };
  15331. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  15332. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  15333. this.matrixAutoUpdate && this.updateMatrix();
  15334. // update matrixWorld
  15335. if ( this.matrixWorldNeedsUpdate || force ) {
  15336. if ( this.parent ) {
  15337. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  15338. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  15339. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  15340. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  15341. } else {
  15342. this.matrixWorld.copy( this.matrix );
  15343. }
  15344. this.matrixWorldNeedsUpdate = false;
  15345. force = true;
  15346. }
  15347. // update children
  15348. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  15349. this.children[ i ].updateMatrixWorld( force );
  15350. }
  15351. };
  15352. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  15353. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  15354. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  15355. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  15356. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  15357. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  15358. /**
  15359. * @author zz85 / http://www.lab4games.net/zz85/blog
  15360. * Creates free form 2d path using series of points, lines or curves.
  15361. *
  15362. **/
  15363. THREE.Path = function ( points ) {
  15364. THREE.CurvePath.call(this);
  15365. this.actions = [];
  15366. if ( points ) {
  15367. this.fromPoints( points );
  15368. }
  15369. };
  15370. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  15371. THREE.PathActions = {
  15372. MOVE_TO: 'moveTo',
  15373. LINE_TO: 'lineTo',
  15374. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  15375. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  15376. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  15377. ARC: 'arc', // Circle
  15378. ELLIPSE: 'ellipse'
  15379. };
  15380. // TODO Clean up PATH API
  15381. // Create path using straight lines to connect all points
  15382. // - vectors: array of Vector2
  15383. THREE.Path.prototype.fromPoints = function ( vectors ) {
  15384. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  15385. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  15386. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  15387. };
  15388. };
  15389. // startPath() endPath()?
  15390. THREE.Path.prototype.moveTo = function ( x, y ) {
  15391. var args = Array.prototype.slice.call( arguments );
  15392. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  15393. };
  15394. THREE.Path.prototype.lineTo = function ( x, y ) {
  15395. var args = Array.prototype.slice.call( arguments );
  15396. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15397. var x0 = lastargs[ lastargs.length - 2 ];
  15398. var y0 = lastargs[ lastargs.length - 1 ];
  15399. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  15400. this.curves.push( curve );
  15401. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  15402. };
  15403. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  15404. var args = Array.prototype.slice.call( arguments );
  15405. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15406. var x0 = lastargs[ lastargs.length - 2 ];
  15407. var y0 = lastargs[ lastargs.length - 1 ];
  15408. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  15409. new THREE.Vector2( aCPx, aCPy ),
  15410. new THREE.Vector2( aX, aY ) );
  15411. this.curves.push( curve );
  15412. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  15413. };
  15414. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  15415. aCP2x, aCP2y,
  15416. aX, aY ) {
  15417. var args = Array.prototype.slice.call( arguments );
  15418. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15419. var x0 = lastargs[ lastargs.length - 2 ];
  15420. var y0 = lastargs[ lastargs.length - 1 ];
  15421. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  15422. new THREE.Vector2( aCP1x, aCP1y ),
  15423. new THREE.Vector2( aCP2x, aCP2y ),
  15424. new THREE.Vector2( aX, aY ) );
  15425. this.curves.push( curve );
  15426. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  15427. };
  15428. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  15429. var args = Array.prototype.slice.call( arguments );
  15430. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15431. var x0 = lastargs[ lastargs.length - 2 ];
  15432. var y0 = lastargs[ lastargs.length - 1 ];
  15433. //---
  15434. var npts = [ new THREE.Vector2( x0, y0 ) ];
  15435. Array.prototype.push.apply( npts, pts );
  15436. var curve = new THREE.SplineCurve( npts );
  15437. this.curves.push( curve );
  15438. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  15439. };
  15440. // FUTURE: Change the API or follow canvas API?
  15441. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  15442. aStartAngle, aEndAngle, aClockwise ) {
  15443. var lastargs = this.actions[ this.actions.length - 1].args;
  15444. var x0 = lastargs[ lastargs.length - 2 ];
  15445. var y0 = lastargs[ lastargs.length - 1 ];
  15446. this.absarc(aX + x0, aY + y0, aRadius,
  15447. aStartAngle, aEndAngle, aClockwise );
  15448. };
  15449. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  15450. aStartAngle, aEndAngle, aClockwise ) {
  15451. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  15452. };
  15453. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  15454. aStartAngle, aEndAngle, aClockwise ) {
  15455. var lastargs = this.actions[ this.actions.length - 1].args;
  15456. var x0 = lastargs[ lastargs.length - 2 ];
  15457. var y0 = lastargs[ lastargs.length - 1 ];
  15458. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  15459. aStartAngle, aEndAngle, aClockwise );
  15460. };
  15461. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  15462. aStartAngle, aEndAngle, aClockwise ) {
  15463. var args = Array.prototype.slice.call( arguments );
  15464. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  15465. aStartAngle, aEndAngle, aClockwise );
  15466. this.curves.push( curve );
  15467. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  15468. args.push(lastPoint.x);
  15469. args.push(lastPoint.y);
  15470. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  15471. };
  15472. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  15473. if ( ! divisions ) divisions = 40;
  15474. var points = [];
  15475. for ( var i = 0; i < divisions; i ++ ) {
  15476. points.push( this.getPoint( i / divisions ) );
  15477. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  15478. }
  15479. // if ( closedPath ) {
  15480. //
  15481. // points.push( points[ 0 ] );
  15482. //
  15483. // }
  15484. return points;
  15485. };
  15486. /* Return an array of vectors based on contour of the path */
  15487. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  15488. if (this.useSpacedPoints) {
  15489. console.log('tata');
  15490. return this.getSpacedPoints( divisions, closedPath );
  15491. }
  15492. divisions = divisions || 12;
  15493. var points = [];
  15494. var i, il, item, action, args;
  15495. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  15496. laste, j,
  15497. t, tx, ty;
  15498. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  15499. item = this.actions[ i ];
  15500. action = item.action;
  15501. args = item.args;
  15502. switch( action ) {
  15503. case THREE.PathActions.MOVE_TO:
  15504. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  15505. break;
  15506. case THREE.PathActions.LINE_TO:
  15507. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  15508. break;
  15509. case THREE.PathActions.QUADRATIC_CURVE_TO:
  15510. cpx = args[ 2 ];
  15511. cpy = args[ 3 ];
  15512. cpx1 = args[ 0 ];
  15513. cpy1 = args[ 1 ];
  15514. if ( points.length > 0 ) {
  15515. laste = points[ points.length - 1 ];
  15516. cpx0 = laste.x;
  15517. cpy0 = laste.y;
  15518. } else {
  15519. laste = this.actions[ i - 1 ].args;
  15520. cpx0 = laste[ laste.length - 2 ];
  15521. cpy0 = laste[ laste.length - 1 ];
  15522. }
  15523. for ( j = 1; j <= divisions; j ++ ) {
  15524. t = j / divisions;
  15525. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15526. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15527. points.push( new THREE.Vector2( tx, ty ) );
  15528. }
  15529. break;
  15530. case THREE.PathActions.BEZIER_CURVE_TO:
  15531. cpx = args[ 4 ];
  15532. cpy = args[ 5 ];
  15533. cpx1 = args[ 0 ];
  15534. cpy1 = args[ 1 ];
  15535. cpx2 = args[ 2 ];
  15536. cpy2 = args[ 3 ];
  15537. if ( points.length > 0 ) {
  15538. laste = points[ points.length - 1 ];
  15539. cpx0 = laste.x;
  15540. cpy0 = laste.y;
  15541. } else {
  15542. laste = this.actions[ i - 1 ].args;
  15543. cpx0 = laste[ laste.length - 2 ];
  15544. cpy0 = laste[ laste.length - 1 ];
  15545. }
  15546. for ( j = 1; j <= divisions; j ++ ) {
  15547. t = j / divisions;
  15548. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15549. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15550. points.push( new THREE.Vector2( tx, ty ) );
  15551. }
  15552. break;
  15553. case THREE.PathActions.CSPLINE_THRU:
  15554. laste = this.actions[ i - 1 ].args;
  15555. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  15556. var spts = [ last ];
  15557. var n = divisions * args[ 0 ].length;
  15558. spts = spts.concat( args[ 0 ] );
  15559. var spline = new THREE.SplineCurve( spts );
  15560. for ( j = 1; j <= n; j ++ ) {
  15561. points.push( spline.getPointAt( j / n ) ) ;
  15562. }
  15563. break;
  15564. case THREE.PathActions.ARC:
  15565. var aX = args[ 0 ], aY = args[ 1 ],
  15566. aRadius = args[ 2 ],
  15567. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  15568. aClockwise = !!args[ 5 ];
  15569. var deltaAngle = aEndAngle - aStartAngle;
  15570. var angle;
  15571. var tdivisions = divisions * 2;
  15572. for ( j = 1; j <= tdivisions; j ++ ) {
  15573. t = j / tdivisions;
  15574. if ( ! aClockwise ) {
  15575. t = 1 - t;
  15576. }
  15577. angle = aStartAngle + t * deltaAngle;
  15578. tx = aX + aRadius * Math.cos( angle );
  15579. ty = aY + aRadius * Math.sin( angle );
  15580. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  15581. points.push( new THREE.Vector2( tx, ty ) );
  15582. }
  15583. //console.log(points);
  15584. break;
  15585. case THREE.PathActions.ELLIPSE:
  15586. var aX = args[ 0 ], aY = args[ 1 ],
  15587. xRadius = args[ 2 ],
  15588. yRadius = args[ 3 ],
  15589. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  15590. aClockwise = !!args[ 6 ];
  15591. var deltaAngle = aEndAngle - aStartAngle;
  15592. var angle;
  15593. var tdivisions = divisions * 2;
  15594. for ( j = 1; j <= tdivisions; j ++ ) {
  15595. t = j / tdivisions;
  15596. if ( ! aClockwise ) {
  15597. t = 1 - t;
  15598. }
  15599. angle = aStartAngle + t * deltaAngle;
  15600. tx = aX + xRadius * Math.cos( angle );
  15601. ty = aY + yRadius * Math.sin( angle );
  15602. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  15603. points.push( new THREE.Vector2( tx, ty ) );
  15604. }
  15605. //console.log(points);
  15606. break;
  15607. } // end switch
  15608. }
  15609. // Normalize to remove the closing point by default.
  15610. var lastPoint = points[ points.length - 1];
  15611. var EPSILON = 0.0000000001;
  15612. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  15613. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  15614. points.splice( points.length - 1, 1);
  15615. if ( closedPath ) {
  15616. points.push( points[ 0 ] );
  15617. }
  15618. return points;
  15619. };
  15620. // Breaks path into shapes
  15621. THREE.Path.prototype.toShapes = function() {
  15622. var i, il, item, action, args;
  15623. var subPaths = [], lastPath = new THREE.Path();
  15624. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  15625. item = this.actions[ i ];
  15626. args = item.args;
  15627. action = item.action;
  15628. if ( action == THREE.PathActions.MOVE_TO ) {
  15629. if ( lastPath.actions.length != 0 ) {
  15630. subPaths.push( lastPath );
  15631. lastPath = new THREE.Path();
  15632. }
  15633. }
  15634. lastPath[ action ].apply( lastPath, args );
  15635. }
  15636. if ( lastPath.actions.length != 0 ) {
  15637. subPaths.push( lastPath );
  15638. }
  15639. // console.log(subPaths);
  15640. if ( subPaths.length == 0 ) return [];
  15641. var tmpPath, tmpShape, shapes = [];
  15642. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  15643. // console.log("Holes first", holesFirst);
  15644. if ( subPaths.length == 1) {
  15645. tmpPath = subPaths[0];
  15646. tmpShape = new THREE.Shape();
  15647. tmpShape.actions = tmpPath.actions;
  15648. tmpShape.curves = tmpPath.curves;
  15649. shapes.push( tmpShape );
  15650. return shapes;
  15651. };
  15652. if ( holesFirst ) {
  15653. tmpShape = new THREE.Shape();
  15654. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  15655. tmpPath = subPaths[ i ];
  15656. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  15657. tmpShape.actions = tmpPath.actions;
  15658. tmpShape.curves = tmpPath.curves;
  15659. shapes.push( tmpShape );
  15660. tmpShape = new THREE.Shape();
  15661. //console.log('cw', i);
  15662. } else {
  15663. tmpShape.holes.push( tmpPath );
  15664. //console.log('ccw', i);
  15665. }
  15666. }
  15667. } else {
  15668. // Shapes first
  15669. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  15670. tmpPath = subPaths[ i ];
  15671. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  15672. if ( tmpShape ) shapes.push( tmpShape );
  15673. tmpShape = new THREE.Shape();
  15674. tmpShape.actions = tmpPath.actions;
  15675. tmpShape.curves = tmpPath.curves;
  15676. } else {
  15677. tmpShape.holes.push( tmpPath );
  15678. }
  15679. }
  15680. shapes.push( tmpShape );
  15681. }
  15682. //console.log("shape", shapes);
  15683. return shapes;
  15684. };
  15685. /**
  15686. * @author zz85 / http://www.lab4games.net/zz85/blog
  15687. * Defines a 2d shape plane using paths.
  15688. **/
  15689. // STEP 1 Create a path.
  15690. // STEP 2 Turn path into shape.
  15691. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  15692. // STEP 3a - Extract points from each shape, turn to vertices
  15693. // STEP 3b - Triangulate each shape, add faces.
  15694. THREE.Shape = function ( ) {
  15695. THREE.Path.apply( this, arguments );
  15696. this.holes = [];
  15697. };
  15698. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  15699. // Convenience method to return ExtrudeGeometry
  15700. THREE.Shape.prototype.extrude = function ( options ) {
  15701. var extruded = new THREE.ExtrudeGeometry( this, options );
  15702. return extruded;
  15703. };
  15704. // Get points of holes
  15705. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  15706. var i, il = this.holes.length, holesPts = [];
  15707. for ( i = 0; i < il; i ++ ) {
  15708. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  15709. }
  15710. return holesPts;
  15711. };
  15712. // Get points of holes (spaced by regular distance)
  15713. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  15714. var i, il = this.holes.length, holesPts = [];
  15715. for ( i = 0; i < il; i ++ ) {
  15716. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  15717. }
  15718. return holesPts;
  15719. };
  15720. // Get points of shape and holes (keypoints based on segments parameter)
  15721. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  15722. return {
  15723. shape: this.getTransformedPoints( divisions ),
  15724. holes: this.getPointsHoles( divisions )
  15725. };
  15726. };
  15727. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  15728. if (this.useSpacedPoints) {
  15729. return this.extractAllSpacedPoints(divisions);
  15730. }
  15731. return this.extractAllPoints(divisions);
  15732. };
  15733. //
  15734. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  15735. //
  15736. // return {
  15737. //
  15738. // shape: this.transform( bend, divisions ),
  15739. // holes: this.getPointsHoles( divisions, bend )
  15740. //
  15741. // };
  15742. //
  15743. // };
  15744. // Get points of shape and holes (spaced by regular distance)
  15745. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  15746. return {
  15747. shape: this.getTransformedSpacedPoints( divisions ),
  15748. holes: this.getSpacedPointsHoles( divisions )
  15749. };
  15750. };
  15751. /**************************************************************
  15752. * Utils
  15753. **************************************************************/
  15754. THREE.Shape.Utils = {
  15755. /*
  15756. contour - array of vector2 for contour
  15757. holes - array of array of vector2
  15758. */
  15759. removeHoles: function ( contour, holes ) {
  15760. var shape = contour.concat(); // work on this shape
  15761. var allpoints = shape.concat();
  15762. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  15763. var prevShapeVert, nextShapeVert,
  15764. prevHoleVert, nextHoleVert,
  15765. holeIndex, shapeIndex,
  15766. shapeId, shapeGroup,
  15767. h, h2,
  15768. hole, shortest, d,
  15769. p, pts1, pts2,
  15770. tmpShape1, tmpShape2,
  15771. tmpHole1, tmpHole2,
  15772. verts = [];
  15773. for ( h = 0; h < holes.length; h ++ ) {
  15774. hole = holes[ h ];
  15775. /*
  15776. shapeholes[ h ].concat(); // preserves original
  15777. holes.push( hole );
  15778. */
  15779. Array.prototype.push.apply( allpoints, hole );
  15780. shortest = Number.POSITIVE_INFINITY;
  15781. // Find the shortest pair of pts between shape and hole
  15782. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  15783. // Using distanceToSquared() intead of distanceTo() should speed a little
  15784. // since running square roots operations are reduced.
  15785. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  15786. pts1 = hole[ h2 ];
  15787. var dist = [];
  15788. for ( p = 0; p < shape.length; p++ ) {
  15789. pts2 = shape[ p ];
  15790. d = pts1.distanceToSquared( pts2 );
  15791. dist.push( d );
  15792. if ( d < shortest ) {
  15793. shortest = d;
  15794. holeIndex = h2;
  15795. shapeIndex = p;
  15796. }
  15797. }
  15798. }
  15799. //console.log("shortest", shortest, dist);
  15800. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  15801. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  15802. var areaapts = [
  15803. hole[ holeIndex ],
  15804. shape[ shapeIndex ],
  15805. shape[ prevShapeVert ]
  15806. ];
  15807. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  15808. var areabpts = [
  15809. hole[ holeIndex ],
  15810. hole[ prevHoleVert ],
  15811. shape[ shapeIndex ]
  15812. ];
  15813. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  15814. var shapeOffset = 1;
  15815. var holeOffset = -1;
  15816. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  15817. shapeIndex += shapeOffset;
  15818. holeIndex += holeOffset;
  15819. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  15820. shapeIndex %= shape.length;
  15821. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  15822. holeIndex %= hole.length;
  15823. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  15824. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  15825. areaapts = [
  15826. hole[ holeIndex ],
  15827. shape[ shapeIndex ],
  15828. shape[ prevShapeVert ]
  15829. ];
  15830. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  15831. areabpts = [
  15832. hole[ holeIndex ],
  15833. hole[ prevHoleVert ],
  15834. shape[ shapeIndex ]
  15835. ];
  15836. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  15837. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  15838. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  15839. // In case areas are not correct.
  15840. //console.log("USE THIS");
  15841. shapeIndex = oldShapeIndex;
  15842. holeIndex = oldHoleIndex ;
  15843. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  15844. shapeIndex %= shape.length;
  15845. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  15846. holeIndex %= hole.length;
  15847. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  15848. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  15849. } else {
  15850. //console.log("USE THAT ")
  15851. }
  15852. tmpShape1 = shape.slice( 0, shapeIndex );
  15853. tmpShape2 = shape.slice( shapeIndex );
  15854. tmpHole1 = hole.slice( holeIndex );
  15855. tmpHole2 = hole.slice( 0, holeIndex );
  15856. // Should check orders here again?
  15857. var trianglea = [
  15858. hole[ holeIndex ],
  15859. shape[ shapeIndex ],
  15860. shape[ prevShapeVert ]
  15861. ];
  15862. var triangleb = [
  15863. hole[ holeIndex ] ,
  15864. hole[ prevHoleVert ],
  15865. shape[ shapeIndex ]
  15866. ];
  15867. verts.push( trianglea );
  15868. verts.push( triangleb );
  15869. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15870. }
  15871. return {
  15872. shape:shape, /* shape with no holes */
  15873. isolatedPts: verts, /* isolated faces */
  15874. allpoints: allpoints
  15875. }
  15876. },
  15877. triangulateShape: function ( contour, holes ) {
  15878. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  15879. var shape = shapeWithoutHoles.shape,
  15880. allpoints = shapeWithoutHoles.allpoints,
  15881. isolatedPts = shapeWithoutHoles.isolatedPts;
  15882. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  15883. // 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.
  15884. //console.log( "triangles",triangles, triangles.length );
  15885. //console.log( "allpoints",allpoints, allpoints.length );
  15886. var i, il, f, face,
  15887. key, index,
  15888. allPointsMap = {},
  15889. isolatedPointsMap = {};
  15890. // prepare all points map
  15891. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15892. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  15893. if ( allPointsMap[ key ] !== undefined ) {
  15894. console.log( "Duplicate point", key );
  15895. }
  15896. allPointsMap[ key ] = i;
  15897. }
  15898. // check all face vertices against all points map
  15899. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15900. face = triangles[ i ];
  15901. for ( f = 0; f < 3; f ++ ) {
  15902. key = face[ f ].x + ":" + face[ f ].y;
  15903. index = allPointsMap[ key ];
  15904. if ( index !== undefined ) {
  15905. face[ f ] = index;
  15906. }
  15907. }
  15908. }
  15909. // check isolated points vertices against all points map
  15910. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  15911. face = isolatedPts[ i ];
  15912. for ( f = 0; f < 3; f ++ ) {
  15913. key = face[ f ].x + ":" + face[ f ].y;
  15914. index = allPointsMap[ key ];
  15915. if ( index !== undefined ) {
  15916. face[ f ] = index;
  15917. }
  15918. }
  15919. }
  15920. return triangles.concat( isolatedPts );
  15921. }, // end triangulate shapes
  15922. /*
  15923. triangulate2 : function( pts, holes ) {
  15924. // For use with Poly2Tri.js
  15925. var allpts = pts.concat();
  15926. var shape = [];
  15927. for (var p in pts) {
  15928. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  15929. }
  15930. var swctx = new js.poly2tri.SweepContext(shape);
  15931. for (var h in holes) {
  15932. var aHole = holes[h];
  15933. var newHole = []
  15934. for (i in aHole) {
  15935. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  15936. allpts.push(aHole[i]);
  15937. }
  15938. swctx.AddHole(newHole);
  15939. }
  15940. var find;
  15941. var findIndexForPt = function (pt) {
  15942. find = new THREE.Vector2(pt.x, pt.y);
  15943. var p;
  15944. for (p=0, pl = allpts.length; p<pl; p++) {
  15945. if (allpts[p].equals(find)) return p;
  15946. }
  15947. return -1;
  15948. };
  15949. // triangulate
  15950. js.poly2tri.sweep.Triangulate(swctx);
  15951. var triangles = swctx.GetTriangles();
  15952. var tr ;
  15953. var facesPts = [];
  15954. for (var t in triangles) {
  15955. tr = triangles[t];
  15956. facesPts.push([
  15957. findIndexForPt(tr.GetPoint(0)),
  15958. findIndexForPt(tr.GetPoint(1)),
  15959. findIndexForPt(tr.GetPoint(2))
  15960. ]);
  15961. }
  15962. // console.log(facesPts);
  15963. // console.log("triangles", triangles.length, triangles);
  15964. // Returns array of faces with 3 element each
  15965. return facesPts;
  15966. },
  15967. */
  15968. isClockWise: function ( pts ) {
  15969. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  15970. },
  15971. // Bezier Curves formulas obtained from
  15972. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  15973. // Quad Bezier Functions
  15974. b2p0: function ( t, p ) {
  15975. var k = 1 - t;
  15976. return k * k * p;
  15977. },
  15978. b2p1: function ( t, p ) {
  15979. return 2 * ( 1 - t ) * t * p;
  15980. },
  15981. b2p2: function ( t, p ) {
  15982. return t * t * p;
  15983. },
  15984. b2: function ( t, p0, p1, p2 ) {
  15985. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  15986. },
  15987. // Cubic Bezier Functions
  15988. b3p0: function ( t, p ) {
  15989. var k = 1 - t;
  15990. return k * k * k * p;
  15991. },
  15992. b3p1: function ( t, p ) {
  15993. var k = 1 - t;
  15994. return 3 * k * k * t * p;
  15995. },
  15996. b3p2: function ( t, p ) {
  15997. var k = 1 - t;
  15998. return 3 * k * t * t * p;
  15999. },
  16000. b3p3: function ( t, p ) {
  16001. return t * t * t * p;
  16002. },
  16003. b3: function ( t, p0, p1, p2, p3 ) {
  16004. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  16005. }
  16006. };
  16007. /**
  16008. * @author mikael emtinger / http://gomo.se/
  16009. */
  16010. THREE.AnimationHandler = (function() {
  16011. var playing = [];
  16012. var library = {};
  16013. var that = {};
  16014. //--- update ---
  16015. that.update = function( deltaTimeMS ) {
  16016. for( var i = 0; i < playing.length; i ++ )
  16017. playing[ i ].update( deltaTimeMS );
  16018. };
  16019. //--- add ---
  16020. that.addToUpdate = function( animation ) {
  16021. if ( playing.indexOf( animation ) === -1 )
  16022. playing.push( animation );
  16023. };
  16024. //--- remove ---
  16025. that.removeFromUpdate = function( animation ) {
  16026. var index = playing.indexOf( animation );
  16027. if( index !== -1 )
  16028. playing.splice( index, 1 );
  16029. };
  16030. //--- add ---
  16031. that.add = function( data ) {
  16032. if ( library[ data.name ] !== undefined )
  16033. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  16034. library[ data.name ] = data;
  16035. initData( data );
  16036. };
  16037. //--- get ---
  16038. that.get = function( name ) {
  16039. if ( typeof name === "string" ) {
  16040. if ( library[ name ] ) {
  16041. return library[ name ];
  16042. } else {
  16043. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  16044. return null;
  16045. }
  16046. } else {
  16047. // todo: add simple tween library
  16048. }
  16049. };
  16050. //--- parse ---
  16051. that.parse = function( root ) {
  16052. // setup hierarchy
  16053. var hierarchy = [];
  16054. if ( root instanceof THREE.SkinnedMesh ) {
  16055. for( var b = 0; b < root.bones.length; b++ ) {
  16056. hierarchy.push( root.bones[ b ] );
  16057. }
  16058. } else {
  16059. parseRecurseHierarchy( root, hierarchy );
  16060. }
  16061. return hierarchy;
  16062. };
  16063. var parseRecurseHierarchy = function( root, hierarchy ) {
  16064. hierarchy.push( root );
  16065. for( var c = 0; c < root.children.length; c++ )
  16066. parseRecurseHierarchy( root.children[ c ], hierarchy );
  16067. }
  16068. //--- init data ---
  16069. var initData = function( data ) {
  16070. if( data.initialized === true )
  16071. return;
  16072. // loop through all keys
  16073. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  16074. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16075. // remove minus times
  16076. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  16077. data.hierarchy[ h ].keys[ k ].time = 0;
  16078. // create quaternions
  16079. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  16080. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  16081. var quat = data.hierarchy[ h ].keys[ k ].rot;
  16082. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  16083. }
  16084. }
  16085. // prepare morph target keys
  16086. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  16087. // get all used
  16088. var usedMorphTargets = {};
  16089. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16090. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16091. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  16092. usedMorphTargets[ morphTargetName ] = -1;
  16093. }
  16094. }
  16095. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  16096. // set all used on all frames
  16097. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16098. var influences = {};
  16099. for ( var morphTargetName in usedMorphTargets ) {
  16100. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16101. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  16102. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  16103. break;
  16104. }
  16105. }
  16106. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  16107. influences[ morphTargetName ] = 0;
  16108. }
  16109. }
  16110. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  16111. }
  16112. }
  16113. // remove all keys that are on the same time
  16114. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16115. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  16116. data.hierarchy[ h ].keys.splice( k, 1 );
  16117. k --;
  16118. }
  16119. }
  16120. // set index
  16121. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16122. data.hierarchy[ h ].keys[ k ].index = k;
  16123. }
  16124. }
  16125. // JIT
  16126. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  16127. data.JIT = {};
  16128. data.JIT.hierarchy = [];
  16129. for( var h = 0; h < data.hierarchy.length; h ++ )
  16130. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  16131. // done
  16132. data.initialized = true;
  16133. };
  16134. // interpolation types
  16135. that.LINEAR = 0;
  16136. that.CATMULLROM = 1;
  16137. that.CATMULLROM_FORWARD = 2;
  16138. return that;
  16139. }());
  16140. /**
  16141. * @author mikael emtinger / http://gomo.se/
  16142. * @author mrdoob / http://mrdoob.com/
  16143. * @author alteredq / http://alteredqualia.com/
  16144. */
  16145. THREE.Animation = function ( root, name, interpolationType ) {
  16146. this.root = root;
  16147. this.data = THREE.AnimationHandler.get( name );
  16148. this.hierarchy = THREE.AnimationHandler.parse( root );
  16149. this.currentTime = 0;
  16150. this.timeScale = 1;
  16151. this.isPlaying = false;
  16152. this.isPaused = true;
  16153. this.loop = true;
  16154. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  16155. this.points = [];
  16156. this.target = new THREE.Vector3();
  16157. };
  16158. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  16159. if ( this.isPlaying === false ) {
  16160. this.isPlaying = true;
  16161. this.loop = loop !== undefined ? loop : true;
  16162. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  16163. // reset key cache
  16164. var h, hl = this.hierarchy.length,
  16165. object;
  16166. for ( h = 0; h < hl; h ++ ) {
  16167. object = this.hierarchy[ h ];
  16168. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16169. object.useQuaternion = true;
  16170. }
  16171. object.matrixAutoUpdate = true;
  16172. if ( object.animationCache === undefined ) {
  16173. object.animationCache = {};
  16174. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  16175. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  16176. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  16177. }
  16178. var prevKey = object.animationCache.prevKey;
  16179. var nextKey = object.animationCache.nextKey;
  16180. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  16181. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  16182. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  16183. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  16184. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  16185. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  16186. }
  16187. this.update( 0 );
  16188. }
  16189. this.isPaused = false;
  16190. THREE.AnimationHandler.addToUpdate( this );
  16191. };
  16192. THREE.Animation.prototype.pause = function() {
  16193. if ( this.isPaused === true ) {
  16194. THREE.AnimationHandler.addToUpdate( this );
  16195. } else {
  16196. THREE.AnimationHandler.removeFromUpdate( this );
  16197. }
  16198. this.isPaused = !this.isPaused;
  16199. };
  16200. THREE.Animation.prototype.stop = function() {
  16201. this.isPlaying = false;
  16202. this.isPaused = false;
  16203. THREE.AnimationHandler.removeFromUpdate( this );
  16204. };
  16205. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  16206. // early out
  16207. if ( this.isPlaying === false ) return;
  16208. // vars
  16209. var types = [ "pos", "rot", "scl" ];
  16210. var type;
  16211. var scale;
  16212. var vector;
  16213. var prevXYZ, nextXYZ;
  16214. var prevKey, nextKey;
  16215. var object;
  16216. var animationCache;
  16217. var frame;
  16218. var JIThierarchy = this.data.JIT.hierarchy;
  16219. var currentTime, unloopedCurrentTime;
  16220. var currentPoint, forwardPoint, angle;
  16221. this.currentTime += deltaTimeMS * this.timeScale;
  16222. unloopedCurrentTime = this.currentTime;
  16223. currentTime = this.currentTime = this.currentTime % this.data.length;
  16224. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  16225. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  16226. object = this.hierarchy[ h ];
  16227. animationCache = object.animationCache;
  16228. // loop through pos/rot/scl
  16229. for ( var t = 0; t < 3; t ++ ) {
  16230. // get keys
  16231. type = types[ t ];
  16232. prevKey = animationCache.prevKey[ type ];
  16233. nextKey = animationCache.nextKey[ type ];
  16234. // switch keys?
  16235. if ( nextKey.time <= unloopedCurrentTime ) {
  16236. // did we loop?
  16237. if ( currentTime < unloopedCurrentTime ) {
  16238. if ( this.loop ) {
  16239. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  16240. nextKey = this.getNextKeyWith( type, h, 1 );
  16241. while( nextKey.time < currentTime ) {
  16242. prevKey = nextKey;
  16243. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16244. }
  16245. } else {
  16246. this.stop();
  16247. return;
  16248. }
  16249. } else {
  16250. do {
  16251. prevKey = nextKey;
  16252. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16253. } while( nextKey.time < currentTime )
  16254. }
  16255. animationCache.prevKey[ type ] = prevKey;
  16256. animationCache.nextKey[ type ] = nextKey;
  16257. }
  16258. object.matrixAutoUpdate = true;
  16259. object.matrixWorldNeedsUpdate = true;
  16260. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  16261. prevXYZ = prevKey[ type ];
  16262. nextXYZ = nextKey[ type ];
  16263. // check scale error
  16264. if ( scale < 0 || scale > 1 ) {
  16265. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  16266. scale = scale < 0 ? 0 : 1;
  16267. }
  16268. // interpolate
  16269. if ( type === "pos" ) {
  16270. vector = object.position;
  16271. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  16272. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  16273. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  16274. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  16275. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16276. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16277. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  16278. this.points[ 1 ] = prevXYZ;
  16279. this.points[ 2 ] = nextXYZ;
  16280. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  16281. scale = scale * 0.33 + 0.33;
  16282. currentPoint = this.interpolateCatmullRom( this.points, scale );
  16283. vector.x = currentPoint[ 0 ];
  16284. vector.y = currentPoint[ 1 ];
  16285. vector.z = currentPoint[ 2 ];
  16286. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16287. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  16288. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  16289. this.target.subSelf( vector );
  16290. this.target.y = 0;
  16291. this.target.normalize();
  16292. angle = Math.atan2( this.target.x, this.target.z );
  16293. object.rotation.set( 0, angle, 0 );
  16294. }
  16295. }
  16296. } else if ( type === "rot" ) {
  16297. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  16298. } else if ( type === "scl" ) {
  16299. vector = object.scale;
  16300. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  16301. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  16302. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  16303. }
  16304. }
  16305. }
  16306. };
  16307. // Catmull-Rom spline
  16308. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  16309. var c = [], v3 = [],
  16310. point, intPoint, weight, w2, w3,
  16311. pa, pb, pc, pd;
  16312. point = ( points.length - 1 ) * scale;
  16313. intPoint = Math.floor( point );
  16314. weight = point - intPoint;
  16315. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  16316. c[ 1 ] = intPoint;
  16317. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  16318. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  16319. pa = points[ c[ 0 ] ];
  16320. pb = points[ c[ 1 ] ];
  16321. pc = points[ c[ 2 ] ];
  16322. pd = points[ c[ 3 ] ];
  16323. w2 = weight * weight;
  16324. w3 = weight * w2;
  16325. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  16326. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  16327. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  16328. return v3;
  16329. };
  16330. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  16331. var v0 = ( p2 - p0 ) * 0.5,
  16332. v1 = ( p3 - p1 ) * 0.5;
  16333. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16334. };
  16335. // Get next key with
  16336. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  16337. var keys = this.data.hierarchy[ h ].keys;
  16338. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16339. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16340. key = key < keys.length - 1 ? key : keys.length - 1;
  16341. } else {
  16342. key = key % keys.length;
  16343. }
  16344. for ( ; key < keys.length; key++ ) {
  16345. if ( keys[ key ][ type ] !== undefined ) {
  16346. return keys[ key ];
  16347. }
  16348. }
  16349. return this.data.hierarchy[ h ].keys[ 0 ];
  16350. };
  16351. // Get previous key with
  16352. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  16353. var keys = this.data.hierarchy[ h ].keys;
  16354. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16355. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16356. key = key > 0 ? key : 0;
  16357. } else {
  16358. key = key >= 0 ? key : key + keys.length;
  16359. }
  16360. for ( ; key >= 0; key -- ) {
  16361. if ( keys[ key ][ type ] !== undefined ) {
  16362. return keys[ key ];
  16363. }
  16364. }
  16365. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  16366. };
  16367. /**
  16368. * @author mikael emtinger / http://gomo.se/
  16369. * @author mrdoob / http://mrdoob.com/
  16370. * @author alteredq / http://alteredqualia.com/
  16371. * @author khang duong
  16372. * @author erik kitson
  16373. */
  16374. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  16375. this.root = root;
  16376. this.data = THREE.AnimationHandler.get( data );
  16377. this.hierarchy = THREE.AnimationHandler.parse( root );
  16378. this.currentTime = 0;
  16379. this.timeScale = 0.001;
  16380. this.isPlaying = false;
  16381. this.isPaused = true;
  16382. this.loop = true;
  16383. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  16384. // initialize to first keyframes
  16385. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  16386. var keys = this.data.hierarchy[h].keys,
  16387. sids = this.data.hierarchy[h].sids,
  16388. obj = this.hierarchy[h];
  16389. if ( keys.length && sids ) {
  16390. for ( var s = 0; s < sids.length; s++ ) {
  16391. var sid = sids[ s ],
  16392. next = this.getNextKeyWith( sid, h, 0 );
  16393. if ( next ) {
  16394. next.apply( sid );
  16395. }
  16396. }
  16397. obj.matrixAutoUpdate = false;
  16398. this.data.hierarchy[h].node.updateMatrix();
  16399. obj.matrixWorldNeedsUpdate = true;
  16400. }
  16401. }
  16402. };
  16403. // Play
  16404. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  16405. if( !this.isPlaying ) {
  16406. this.isPlaying = true;
  16407. this.loop = loop !== undefined ? loop : true;
  16408. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  16409. this.startTimeMs = startTimeMS;
  16410. this.startTime = 10000000;
  16411. this.endTime = -this.startTime;
  16412. // reset key cache
  16413. var h, hl = this.hierarchy.length,
  16414. object,
  16415. node;
  16416. for ( h = 0; h < hl; h++ ) {
  16417. object = this.hierarchy[ h ];
  16418. node = this.data.hierarchy[ h ];
  16419. object.useQuaternion = true;
  16420. if ( node.animationCache === undefined ) {
  16421. node.animationCache = {};
  16422. node.animationCache.prevKey = null;
  16423. node.animationCache.nextKey = null;
  16424. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  16425. }
  16426. var keys = this.data.hierarchy[h].keys;
  16427. if (keys.length) {
  16428. node.animationCache.prevKey = keys[ 0 ];
  16429. node.animationCache.nextKey = keys[ 1 ];
  16430. this.startTime = Math.min( keys[0].time, this.startTime );
  16431. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  16432. }
  16433. }
  16434. this.update( 0 );
  16435. }
  16436. this.isPaused = false;
  16437. THREE.AnimationHandler.addToUpdate( this );
  16438. };
  16439. // Pause
  16440. THREE.KeyFrameAnimation.prototype.pause = function() {
  16441. if( this.isPaused ) {
  16442. THREE.AnimationHandler.addToUpdate( this );
  16443. } else {
  16444. THREE.AnimationHandler.removeFromUpdate( this );
  16445. }
  16446. this.isPaused = !this.isPaused;
  16447. };
  16448. // Stop
  16449. THREE.KeyFrameAnimation.prototype.stop = function() {
  16450. this.isPlaying = false;
  16451. this.isPaused = false;
  16452. THREE.AnimationHandler.removeFromUpdate( this );
  16453. // reset JIT matrix and remove cache
  16454. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  16455. var obj = this.hierarchy[ h ];
  16456. var node = this.data.hierarchy[ h ];
  16457. if ( node.animationCache !== undefined ) {
  16458. var original = node.animationCache.originalMatrix;
  16459. if( obj instanceof THREE.Bone ) {
  16460. original.copy( obj.skinMatrix );
  16461. obj.skinMatrix = original;
  16462. } else {
  16463. original.copy( obj.matrix );
  16464. obj.matrix = original;
  16465. }
  16466. delete node.animationCache;
  16467. }
  16468. }
  16469. };
  16470. // Update
  16471. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  16472. // early out
  16473. if( !this.isPlaying ) return;
  16474. // vars
  16475. var prevKey, nextKey;
  16476. var object;
  16477. var node;
  16478. var frame;
  16479. var JIThierarchy = this.data.JIT.hierarchy;
  16480. var currentTime, unloopedCurrentTime;
  16481. var looped;
  16482. // update
  16483. this.currentTime += deltaTimeMS * this.timeScale;
  16484. unloopedCurrentTime = this.currentTime;
  16485. currentTime = this.currentTime = this.currentTime % this.data.length;
  16486. // if looped around, the current time should be based on the startTime
  16487. if ( currentTime < this.startTimeMs ) {
  16488. currentTime = this.currentTime = this.startTimeMs + currentTime;
  16489. }
  16490. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  16491. looped = currentTime < unloopedCurrentTime;
  16492. if ( looped && !this.loop ) {
  16493. // Set the animation to the last keyframes and stop
  16494. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  16495. var keys = this.data.hierarchy[h].keys,
  16496. sids = this.data.hierarchy[h].sids,
  16497. end = keys.length-1,
  16498. obj = this.hierarchy[h];
  16499. if ( keys.length ) {
  16500. for ( var s = 0; s < sids.length; s++ ) {
  16501. var sid = sids[ s ],
  16502. prev = this.getPrevKeyWith( sid, h, end );
  16503. if ( prev ) {
  16504. prev.apply( sid );
  16505. }
  16506. }
  16507. this.data.hierarchy[h].node.updateMatrix();
  16508. obj.matrixWorldNeedsUpdate = true;
  16509. }
  16510. }
  16511. this.stop();
  16512. return;
  16513. }
  16514. // check pre-infinity
  16515. if ( currentTime < this.startTime ) {
  16516. return;
  16517. }
  16518. // update
  16519. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  16520. object = this.hierarchy[ h ];
  16521. node = this.data.hierarchy[ h ];
  16522. var keys = node.keys,
  16523. animationCache = node.animationCache;
  16524. // use JIT?
  16525. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  16526. if( object instanceof THREE.Bone ) {
  16527. object.skinMatrix = JIThierarchy[ h ][ frame ];
  16528. object.matrixWorldNeedsUpdate = false;
  16529. } else {
  16530. object.matrix = JIThierarchy[ h ][ frame ];
  16531. object.matrixWorldNeedsUpdate = true;
  16532. }
  16533. // use interpolation
  16534. } else if ( keys.length ) {
  16535. // make sure so original matrix and not JIT matrix is set
  16536. if ( this.JITCompile && animationCache ) {
  16537. if( object instanceof THREE.Bone ) {
  16538. object.skinMatrix = animationCache.originalMatrix;
  16539. } else {
  16540. object.matrix = animationCache.originalMatrix;
  16541. }
  16542. }
  16543. prevKey = animationCache.prevKey;
  16544. nextKey = animationCache.nextKey;
  16545. if ( prevKey && nextKey ) {
  16546. // switch keys?
  16547. if ( nextKey.time <= unloopedCurrentTime ) {
  16548. // did we loop?
  16549. if ( looped && this.loop ) {
  16550. prevKey = keys[ 0 ];
  16551. nextKey = keys[ 1 ];
  16552. while ( nextKey.time < currentTime ) {
  16553. prevKey = nextKey;
  16554. nextKey = keys[ prevKey.index + 1 ];
  16555. }
  16556. } else if ( !looped ) {
  16557. var lastIndex = keys.length - 1;
  16558. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  16559. prevKey = nextKey;
  16560. nextKey = keys[ prevKey.index + 1 ];
  16561. }
  16562. }
  16563. animationCache.prevKey = prevKey;
  16564. animationCache.nextKey = nextKey;
  16565. }
  16566. if(nextKey.time >= currentTime)
  16567. prevKey.interpolate( nextKey, currentTime );
  16568. else
  16569. prevKey.interpolate( nextKey, nextKey.time);
  16570. }
  16571. this.data.hierarchy[h].node.updateMatrix();
  16572. object.matrixWorldNeedsUpdate = true;
  16573. }
  16574. }
  16575. // update JIT?
  16576. if ( this.JITCompile ) {
  16577. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  16578. this.hierarchy[ 0 ].updateMatrixWorld( true );
  16579. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  16580. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  16581. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  16582. } else {
  16583. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  16584. }
  16585. }
  16586. }
  16587. }
  16588. };
  16589. // Get next key with
  16590. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  16591. var keys = this.data.hierarchy[ h ].keys;
  16592. key = key % keys.length;
  16593. for ( ; key < keys.length; key++ ) {
  16594. if ( keys[ key ].hasTarget( sid ) ) {
  16595. return keys[ key ];
  16596. }
  16597. }
  16598. return keys[ 0 ];
  16599. };
  16600. // Get previous key with
  16601. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  16602. var keys = this.data.hierarchy[ h ].keys;
  16603. key = key >= 0 ? key : key + keys.length;
  16604. for ( ; key >= 0; key-- ) {
  16605. if ( keys[ key ].hasTarget( sid ) ) {
  16606. return keys[ key ];
  16607. }
  16608. }
  16609. return keys[ keys.length - 1 ];
  16610. };
  16611. /**
  16612. * Camera for rendering cube maps
  16613. * - renders scene into axis-aligned cube
  16614. *
  16615. * @author alteredq / http://alteredqualia.com/
  16616. */
  16617. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  16618. THREE.Object3D.call( this );
  16619. var fov = 90, aspect = 1;
  16620. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16621. cameraPX.up.set( 0, -1, 0 );
  16622. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  16623. this.add( cameraPX );
  16624. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16625. cameraNX.up.set( 0, -1, 0 );
  16626. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  16627. this.add( cameraNX );
  16628. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16629. cameraPY.up.set( 0, 0, 1 );
  16630. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  16631. this.add( cameraPY );
  16632. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16633. cameraNY.up.set( 0, 0, -1 );
  16634. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  16635. this.add( cameraNY );
  16636. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16637. cameraPZ.up.set( 0, -1, 0 );
  16638. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  16639. this.add( cameraPZ );
  16640. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16641. cameraNZ.up.set( 0, -1, 0 );
  16642. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  16643. this.add( cameraNZ );
  16644. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  16645. this.updateCubeMap = function ( renderer, scene ) {
  16646. var renderTarget = this.renderTarget;
  16647. var generateMipmaps = renderTarget.generateMipmaps;
  16648. renderTarget.generateMipmaps = false;
  16649. renderTarget.activeCubeFace = 0;
  16650. renderer.render( scene, cameraPX, renderTarget );
  16651. renderTarget.activeCubeFace = 1;
  16652. renderer.render( scene, cameraNX, renderTarget );
  16653. renderTarget.activeCubeFace = 2;
  16654. renderer.render( scene, cameraPY, renderTarget );
  16655. renderTarget.activeCubeFace = 3;
  16656. renderer.render( scene, cameraNY, renderTarget );
  16657. renderTarget.activeCubeFace = 4;
  16658. renderer.render( scene, cameraPZ, renderTarget );
  16659. renderTarget.generateMipmaps = generateMipmaps;
  16660. renderTarget.activeCubeFace = 5;
  16661. renderer.render( scene, cameraNZ, renderTarget );
  16662. };
  16663. };
  16664. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  16665. /*
  16666. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  16667. *
  16668. * A general perpose camera, for setting FOV, Lens Focal Length,
  16669. * and switching between perspective and orthographic views easily.
  16670. * Use this only if you do not wish to manage
  16671. * both a Orthographic and Perspective Camera
  16672. *
  16673. */
  16674. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  16675. THREE.Camera.call( this );
  16676. this.fov = fov;
  16677. this.left = -width / 2;
  16678. this.right = width / 2
  16679. this.top = height / 2;
  16680. this.bottom = -height / 2;
  16681. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  16682. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  16683. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  16684. this.zoom = 1;
  16685. this.toPerspective();
  16686. var aspect = width/height;
  16687. };
  16688. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  16689. THREE.CombinedCamera.prototype.toPerspective = function () {
  16690. // Switches to the Perspective Camera
  16691. this.near = this.cameraP.near;
  16692. this.far = this.cameraP.far;
  16693. this.cameraP.fov = this.fov / this.zoom ;
  16694. this.cameraP.updateProjectionMatrix();
  16695. this.projectionMatrix = this.cameraP.projectionMatrix;
  16696. this.inPerspectiveMode = true;
  16697. this.inOrthographicMode = false;
  16698. };
  16699. THREE.CombinedCamera.prototype.toOrthographic = function () {
  16700. // Switches to the Orthographic camera estimating viewport from Perspective
  16701. var fov = this.fov;
  16702. var aspect = this.cameraP.aspect;
  16703. var near = this.cameraP.near;
  16704. var far = this.cameraP.far;
  16705. // The size that we set is the mid plane of the viewing frustum
  16706. var hyperfocus = ( near + far ) / 2;
  16707. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  16708. var planeHeight = 2 * halfHeight;
  16709. var planeWidth = planeHeight * aspect;
  16710. var halfWidth = planeWidth / 2;
  16711. halfHeight /= this.zoom;
  16712. halfWidth /= this.zoom;
  16713. this.cameraO.left = -halfWidth;
  16714. this.cameraO.right = halfWidth;
  16715. this.cameraO.top = halfHeight;
  16716. this.cameraO.bottom = -halfHeight;
  16717. // this.cameraO.left = -farHalfWidth;
  16718. // this.cameraO.right = farHalfWidth;
  16719. // this.cameraO.top = farHalfHeight;
  16720. // this.cameraO.bottom = -farHalfHeight;
  16721. // this.cameraO.left = this.left / this.zoom;
  16722. // this.cameraO.right = this.right / this.zoom;
  16723. // this.cameraO.top = this.top / this.zoom;
  16724. // this.cameraO.bottom = this.bottom / this.zoom;
  16725. this.cameraO.updateProjectionMatrix();
  16726. this.near = this.cameraO.near;
  16727. this.far = this.cameraO.far;
  16728. this.projectionMatrix = this.cameraO.projectionMatrix;
  16729. this.inPerspectiveMode = false;
  16730. this.inOrthographicMode = true;
  16731. };
  16732. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  16733. this.cameraP.aspect = width / height;
  16734. this.left = -width / 2;
  16735. this.right = width / 2
  16736. this.top = height / 2;
  16737. this.bottom = -height / 2;
  16738. };
  16739. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  16740. this.fov = fov;
  16741. if ( this.inPerspectiveMode ) {
  16742. this.toPerspective();
  16743. } else {
  16744. this.toOrthographic();
  16745. }
  16746. };
  16747. // For mantaining similar API with PerspectiveCamera
  16748. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  16749. if ( this.inPerspectiveMode ) {
  16750. this.toPerspective();
  16751. } else {
  16752. this.toPerspective();
  16753. this.toOrthographic();
  16754. }
  16755. };
  16756. /*
  16757. * Uses Focal Length (in mm) to estimate and set FOV
  16758. * 35mm (fullframe) camera is used if frame size is not specified;
  16759. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  16760. */
  16761. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  16762. frameHeight = frameHeight !== undefined ? frameHeight : 24;
  16763. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  16764. this.setFov( fov );
  16765. return fov;
  16766. };
  16767. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  16768. this.zoom = zoom;
  16769. if ( this.inPerspectiveMode ) {
  16770. this.toPerspective();
  16771. } else {
  16772. this.toOrthographic();
  16773. }
  16774. };
  16775. THREE.CombinedCamera.prototype.toFrontView = function() {
  16776. this.rotation.x = 0;
  16777. this.rotation.y = 0;
  16778. this.rotation.z = 0;
  16779. // should we be modifing the matrix instead?
  16780. this.rotationAutoUpdate = false;
  16781. };
  16782. THREE.CombinedCamera.prototype.toBackView = function() {
  16783. this.rotation.x = 0;
  16784. this.rotation.y = Math.PI;
  16785. this.rotation.z = 0;
  16786. this.rotationAutoUpdate = false;
  16787. };
  16788. THREE.CombinedCamera.prototype.toLeftView = function() {
  16789. this.rotation.x = 0;
  16790. this.rotation.y = - Math.PI / 2;
  16791. this.rotation.z = 0;
  16792. this.rotationAutoUpdate = false;
  16793. };
  16794. THREE.CombinedCamera.prototype.toRightView = function() {
  16795. this.rotation.x = 0;
  16796. this.rotation.y = Math.PI / 2;
  16797. this.rotation.z = 0;
  16798. this.rotationAutoUpdate = false;
  16799. };
  16800. THREE.CombinedCamera.prototype.toTopView = function() {
  16801. this.rotation.x = - Math.PI / 2;
  16802. this.rotation.y = 0;
  16803. this.rotation.z = 0;
  16804. this.rotationAutoUpdate = false;
  16805. };
  16806. THREE.CombinedCamera.prototype.toBottomView = function() {
  16807. this.rotation.x = Math.PI / 2;
  16808. this.rotation.y = 0;
  16809. this.rotation.z = 0;
  16810. this.rotationAutoUpdate = false;
  16811. };
  16812. /**
  16813. * @author mrdoob / http://mrdoob.com/
  16814. * @author alteredq / http://alteredqualia.com/
  16815. * @author paulirish / http://paulirish.com/
  16816. */
  16817. THREE.FirstPersonControls = function ( object, domElement ) {
  16818. this.object = object;
  16819. this.target = new THREE.Vector3( 0, 0, 0 );
  16820. this.domElement = ( domElement !== undefined ) ? domElement : document;
  16821. this.movementSpeed = 1.0;
  16822. this.lookSpeed = 0.005;
  16823. this.lookVertical = true;
  16824. this.autoForward = false;
  16825. // this.invertVertical = false;
  16826. this.activeLook = true;
  16827. this.heightSpeed = false;
  16828. this.heightCoef = 1.0;
  16829. this.heightMin = 0.0;
  16830. this.heightMax = 1.0;
  16831. this.constrainVertical = false;
  16832. this.verticalMin = 0;
  16833. this.verticalMax = Math.PI;
  16834. this.autoSpeedFactor = 0.0;
  16835. this.mouseX = 0;
  16836. this.mouseY = 0;
  16837. this.lat = 0;
  16838. this.lon = 0;
  16839. this.phi = 0;
  16840. this.theta = 0;
  16841. this.moveForward = false;
  16842. this.moveBackward = false;
  16843. this.moveLeft = false;
  16844. this.moveRight = false;
  16845. this.freeze = false;
  16846. this.mouseDragOn = false;
  16847. this.viewHalfX = 0;
  16848. this.viewHalfY = 0;
  16849. if ( this.domElement !== document ) {
  16850. this.domElement.setAttribute( 'tabindex', -1 );
  16851. }
  16852. //
  16853. this.handleResize = function () {
  16854. if ( this.domElement === document ) {
  16855. this.viewHalfX = window.innerWidth / 2;
  16856. this.viewHalfY = window.innerHeight / 2;
  16857. } else {
  16858. this.viewHalfX = this.domElement.offsetWidth / 2;
  16859. this.viewHalfY = this.domElement.offsetHeight / 2;
  16860. }
  16861. };
  16862. this.onMouseDown = function ( event ) {
  16863. if ( this.domElement !== document ) {
  16864. this.domElement.focus();
  16865. }
  16866. event.preventDefault();
  16867. event.stopPropagation();
  16868. if ( this.activeLook ) {
  16869. switch ( event.button ) {
  16870. case 0: this.moveForward = true; break;
  16871. case 2: this.moveBackward = true; break;
  16872. }
  16873. }
  16874. this.mouseDragOn = true;
  16875. };
  16876. this.onMouseUp = function ( event ) {
  16877. event.preventDefault();
  16878. event.stopPropagation();
  16879. if ( this.activeLook ) {
  16880. switch ( event.button ) {
  16881. case 0: this.moveForward = false; break;
  16882. case 2: this.moveBackward = false; break;
  16883. }
  16884. }
  16885. this.mouseDragOn = false;
  16886. };
  16887. this.onMouseMove = function ( event ) {
  16888. if ( this.domElement === document ) {
  16889. this.mouseX = event.pageX - this.viewHalfX;
  16890. this.mouseY = event.pageY - this.viewHalfY;
  16891. } else {
  16892. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  16893. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  16894. }
  16895. };
  16896. this.onKeyDown = function ( event ) {
  16897. //event.preventDefault();
  16898. switch ( event.keyCode ) {
  16899. case 38: /*up*/
  16900. case 87: /*W*/ this.moveForward = true; break;
  16901. case 37: /*left*/
  16902. case 65: /*A*/ this.moveLeft = true; break;
  16903. case 40: /*down*/
  16904. case 83: /*S*/ this.moveBackward = true; break;
  16905. case 39: /*right*/
  16906. case 68: /*D*/ this.moveRight = true; break;
  16907. case 82: /*R*/ this.moveUp = true; break;
  16908. case 70: /*F*/ this.moveDown = true; break;
  16909. case 81: /*Q*/ this.freeze = !this.freeze; break;
  16910. }
  16911. };
  16912. this.onKeyUp = function ( event ) {
  16913. switch( event.keyCode ) {
  16914. case 38: /*up*/
  16915. case 87: /*W*/ this.moveForward = false; break;
  16916. case 37: /*left*/
  16917. case 65: /*A*/ this.moveLeft = false; break;
  16918. case 40: /*down*/
  16919. case 83: /*S*/ this.moveBackward = false; break;
  16920. case 39: /*right*/
  16921. case 68: /*D*/ this.moveRight = false; break;
  16922. case 82: /*R*/ this.moveUp = false; break;
  16923. case 70: /*F*/ this.moveDown = false; break;
  16924. }
  16925. };
  16926. this.update = function( delta ) {
  16927. var actualMoveSpeed = 0;
  16928. if ( this.freeze ) {
  16929. return;
  16930. } else {
  16931. if ( this.heightSpeed ) {
  16932. var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
  16933. var heightDelta = y - this.heightMin;
  16934. this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );
  16935. } else {
  16936. this.autoSpeedFactor = 0.0;
  16937. }
  16938. actualMoveSpeed = delta * this.movementSpeed;
  16939. if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
  16940. if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed );
  16941. if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed );
  16942. if ( this.moveRight ) this.object.translateX( actualMoveSpeed );
  16943. if ( this.moveUp ) this.object.translateY( actualMoveSpeed );
  16944. if ( this.moveDown ) this.object.translateY( - actualMoveSpeed );
  16945. var actualLookSpeed = delta * this.lookSpeed;
  16946. if ( !this.activeLook ) {
  16947. actualLookSpeed = 0;
  16948. }
  16949. this.lon += this.mouseX * actualLookSpeed;
  16950. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed; // * this.invertVertical?-1:1;
  16951. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  16952. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  16953. this.theta = this.lon * Math.PI / 180;
  16954. var targetPosition = this.target,
  16955. position = this.object.position;
  16956. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  16957. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  16958. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  16959. }
  16960. var verticalLookRatio = 1;
  16961. if ( this.constrainVertical ) {
  16962. verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );
  16963. }
  16964. this.lon += this.mouseX * actualLookSpeed;
  16965. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;
  16966. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  16967. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  16968. this.theta = this.lon * Math.PI / 180;
  16969. if ( this.constrainVertical ) {
  16970. this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );
  16971. }
  16972. var targetPosition = this.target,
  16973. position = this.object.position;
  16974. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  16975. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  16976. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  16977. this.object.lookAt( targetPosition );
  16978. };
  16979. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  16980. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  16981. this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
  16982. this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
  16983. this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
  16984. this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
  16985. function bind( scope, fn ) {
  16986. return function () {
  16987. fn.apply( scope, arguments );
  16988. };
  16989. };
  16990. this.handleResize();
  16991. };
  16992. /**
  16993. * @author alteredq / http://alteredqualia.com/
  16994. */
  16995. THREE.PathControls = function ( object, domElement ) {
  16996. this.object = object;
  16997. this.domElement = ( domElement !== undefined ) ? domElement : document;
  16998. this.id = "PathControls" + THREE.PathControlsIdCounter ++;
  16999. // API
  17000. this.duration = 10 * 1000; // milliseconds
  17001. this.waypoints = [];
  17002. this.useConstantSpeed = true;
  17003. this.resamplingCoef = 50;
  17004. this.debugPath = new THREE.Object3D();
  17005. this.debugDummy = new THREE.Object3D();
  17006. this.animationParent = new THREE.Object3D();
  17007. this.lookSpeed = 0.005;
  17008. this.lookVertical = true;
  17009. this.lookHorizontal = true;
  17010. this.verticalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  17011. this.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  17012. // internals
  17013. this.target = new THREE.Object3D();
  17014. this.mouseX = 0;
  17015. this.mouseY = 0;
  17016. this.lat = 0;
  17017. this.lon = 0;
  17018. this.phi = 0;
  17019. this.theta = 0;
  17020. var PI2 = Math.PI * 2,
  17021. PI180 = Math.PI / 180;
  17022. this.viewHalfX = 0;
  17023. this.viewHalfY = 0;
  17024. if ( this.domElement !== document ) {
  17025. this.domElement.setAttribute( 'tabindex', -1 );
  17026. }
  17027. // methods
  17028. this.handleResize = function () {
  17029. if ( this.domElement === document ) {
  17030. this.viewHalfX = window.innerWidth / 2;
  17031. this.viewHalfY = window.innerHeight / 2;
  17032. } else {
  17033. this.viewHalfX = this.domElement.offsetWidth / 2;
  17034. this.viewHalfY = this.domElement.offsetHeight / 2;
  17035. }
  17036. };
  17037. this.update = function ( delta ) {
  17038. var srcRange, dstRange;
  17039. if( this.lookHorizontal ) this.lon += this.mouseX * this.lookSpeed * delta;
  17040. if( this.lookVertical ) this.lat -= this.mouseY * this.lookSpeed * delta;
  17041. this.lon = Math.max( 0, Math.min( 360, this.lon ) );
  17042. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  17043. this.phi = ( 90 - this.lat ) * PI180;
  17044. this.theta = this.lon * PI180;
  17045. this.phi = normalize_angle_rad( this.phi );
  17046. // constrain vertical look angle
  17047. srcRange = this.verticalAngleMap.srcRange;
  17048. dstRange = this.verticalAngleMap.dstRange;
  17049. var tmpPhi = THREE.Math.mapLinear( this.phi, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  17050. var tmpPhiFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  17051. var tmpPhiNormalized = ( tmpPhi - dstRange[ 0 ] ) / tmpPhiFullRange;
  17052. this.phi = QuadraticEaseInOut( tmpPhiNormalized ) * tmpPhiFullRange + dstRange[ 0 ];
  17053. // constrain horizontal look angle
  17054. srcRange = this.horizontalAngleMap.srcRange;
  17055. dstRange = this.horizontalAngleMap.dstRange;
  17056. var tmpTheta = THREE.Math.mapLinear( this.theta, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  17057. var tmpThetaFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  17058. var tmpThetaNormalized = ( tmpTheta - dstRange[ 0 ] ) / tmpThetaFullRange;
  17059. this.theta = QuadraticEaseInOut( tmpThetaNormalized ) * tmpThetaFullRange + dstRange[ 0 ];
  17060. var targetPosition = this.target.position,
  17061. position = this.object.position;
  17062. targetPosition.x = 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  17063. targetPosition.y = 100 * Math.cos( this.phi );
  17064. targetPosition.z = 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  17065. this.object.lookAt( this.target.position );
  17066. };
  17067. this.onMouseMove = function ( event ) {
  17068. if ( this.domElement === document ) {
  17069. this.mouseX = event.pageX - this.viewHalfX;
  17070. this.mouseY = event.pageY - this.viewHalfY;
  17071. } else {
  17072. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  17073. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  17074. }
  17075. };
  17076. // utils
  17077. function normalize_angle_rad( a ) {
  17078. var b = a % PI2;
  17079. return b >= 0 ? b : b + PI2;
  17080. };
  17081. function distance( a, b ) {
  17082. var dx = a[ 0 ] - b[ 0 ],
  17083. dy = a[ 1 ] - b[ 1 ],
  17084. dz = a[ 2 ] - b[ 2 ];
  17085. return Math.sqrt( dx * dx + dy * dy + dz * dz );
  17086. };
  17087. function QuadraticEaseInOut ( k ) {
  17088. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  17089. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  17090. };
  17091. function bind( scope, fn ) {
  17092. return function () {
  17093. fn.apply( scope, arguments );
  17094. };
  17095. };
  17096. function initAnimationPath( parent, spline, name, duration ) {
  17097. var animationData = {
  17098. name: name,
  17099. fps: 0.6,
  17100. length: duration,
  17101. hierarchy: []
  17102. };
  17103. var i,
  17104. parentAnimation, childAnimation,
  17105. path = spline.getControlPointsArray(),
  17106. sl = spline.getLength(),
  17107. pl = path.length,
  17108. t = 0,
  17109. first = 0,
  17110. last = pl - 1;
  17111. parentAnimation = { parent: -1, keys: [] };
  17112. parentAnimation.keys[ first ] = { time: 0, pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  17113. parentAnimation.keys[ last ] = { time: duration, pos: path[ last ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  17114. for ( i = 1; i < pl - 1; i++ ) {
  17115. // real distance (approximation via linear segments)
  17116. t = duration * sl.chunks[ i ] / sl.total;
  17117. // equal distance
  17118. //t = duration * ( i / pl );
  17119. // linear distance
  17120. //t += duration * distance( path[ i ], path[ i - 1 ] ) / sl.total;
  17121. parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };
  17122. }
  17123. animationData.hierarchy[ 0 ] = parentAnimation;
  17124. THREE.AnimationHandler.add( animationData );
  17125. return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );
  17126. };
  17127. function createSplineGeometry( spline, n_sub ) {
  17128. var i, index, position,
  17129. geometry = new THREE.Geometry();
  17130. for ( i = 0; i < spline.points.length * n_sub; i ++ ) {
  17131. index = i / ( spline.points.length * n_sub );
  17132. position = spline.getPoint( index );
  17133. geometry.vertices[ i ] = new THREE.Vector3( position.x, position.y, position.z );
  17134. }
  17135. return geometry;
  17136. };
  17137. function createPath( parent, spline ) {
  17138. var lineGeo = createSplineGeometry( spline, 10 ),
  17139. particleGeo = createSplineGeometry( spline, 10 ),
  17140. lineMat = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 3 } ),
  17141. lineObj = new THREE.Line( lineGeo, lineMat ),
  17142. particleObj = new THREE.ParticleSystem( particleGeo, new THREE.ParticleBasicMaterial( { color: 0xffaa00, size: 3 } ) );
  17143. lineObj.scale.set( 1, 1, 1 );
  17144. parent.add( lineObj );
  17145. particleObj.scale.set( 1, 1, 1 );
  17146. parent.add( particleObj );
  17147. var waypoint,
  17148. geo = new THREE.SphereGeometry( 1, 16, 8 ),
  17149. mat = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  17150. for ( var i = 0; i < spline.points.length; i ++ ) {
  17151. waypoint = new THREE.Mesh( geo, mat );
  17152. waypoint.position.copy( spline.points[ i ] );
  17153. parent.add( waypoint );
  17154. }
  17155. };
  17156. this.init = function ( ) {
  17157. // constructor
  17158. this.spline = new THREE.Spline();
  17159. this.spline.initFromArray( this.waypoints );
  17160. if ( this.useConstantSpeed ) {
  17161. this.spline.reparametrizeByArcLength( this.resamplingCoef );
  17162. }
  17163. if ( this.createDebugDummy ) {
  17164. var dummyParentMaterial = new THREE.MeshLambertMaterial( { color: 0x0077ff } ),
  17165. dummyChildMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ),
  17166. dummyParentGeo = new THREE.CubeGeometry( 10, 10, 20 ),
  17167. dummyChildGeo = new THREE.CubeGeometry( 2, 2, 10 );
  17168. this.animationParent = new THREE.Mesh( dummyParentGeo, dummyParentMaterial );
  17169. var dummyChild = new THREE.Mesh( dummyChildGeo, dummyChildMaterial );
  17170. dummyChild.position.set( 0, 10, 0 );
  17171. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  17172. this.animationParent.add( this.object );
  17173. this.animationParent.add( this.target );
  17174. this.animationParent.add( dummyChild );
  17175. } else {
  17176. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  17177. this.animationParent.add( this.target );
  17178. this.animationParent.add( this.object );
  17179. }
  17180. if ( this.createDebugPath ) {
  17181. createPath( this.debugPath, this.spline );
  17182. }
  17183. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  17184. };
  17185. this.handleResize();
  17186. };
  17187. THREE.PathControlsIdCounter = 0;
  17188. /**
  17189. * @author James Baicoianu / http://www.baicoianu.com/
  17190. */
  17191. THREE.FlyControls = function ( object, domElement ) {
  17192. this.object = object;
  17193. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17194. if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );
  17195. // API
  17196. this.movementSpeed = 1.0;
  17197. this.rollSpeed = 0.005;
  17198. this.dragToLook = false;
  17199. this.autoForward = false;
  17200. // disable default target object behavior
  17201. this.object.useQuaternion = true;
  17202. // internals
  17203. this.tmpQuaternion = new THREE.Quaternion();
  17204. this.mouseStatus = 0;
  17205. 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 };
  17206. this.moveVector = new THREE.Vector3( 0, 0, 0 );
  17207. this.rotationVector = new THREE.Vector3( 0, 0, 0 );
  17208. this.handleEvent = function ( event ) {
  17209. if ( typeof this[ event.type ] == 'function' ) {
  17210. this[ event.type ]( event );
  17211. }
  17212. };
  17213. this.keydown = function( event ) {
  17214. if ( event.altKey ) {
  17215. return;
  17216. }
  17217. //event.preventDefault();
  17218. switch ( event.keyCode ) {
  17219. case 16: /* shift */ this.movementSpeedMultiplier = .1; break;
  17220. case 87: /*W*/ this.moveState.forward = 1; break;
  17221. case 83: /*S*/ this.moveState.back = 1; break;
  17222. case 65: /*A*/ this.moveState.left = 1; break;
  17223. case 68: /*D*/ this.moveState.right = 1; break;
  17224. case 82: /*R*/ this.moveState.up = 1; break;
  17225. case 70: /*F*/ this.moveState.down = 1; break;
  17226. case 38: /*up*/ this.moveState.pitchUp = 1; break;
  17227. case 40: /*down*/ this.moveState.pitchDown = 1; break;
  17228. case 37: /*left*/ this.moveState.yawLeft = 1; break;
  17229. case 39: /*right*/ this.moveState.yawRight = 1; break;
  17230. case 81: /*Q*/ this.moveState.rollLeft = 1; break;
  17231. case 69: /*E*/ this.moveState.rollRight = 1; break;
  17232. }
  17233. this.updateMovementVector();
  17234. this.updateRotationVector();
  17235. };
  17236. this.keyup = function( event ) {
  17237. switch( event.keyCode ) {
  17238. case 16: /* shift */ this.movementSpeedMultiplier = 1; break;
  17239. case 87: /*W*/ this.moveState.forward = 0; break;
  17240. case 83: /*S*/ this.moveState.back = 0; break;
  17241. case 65: /*A*/ this.moveState.left = 0; break;
  17242. case 68: /*D*/ this.moveState.right = 0; break;
  17243. case 82: /*R*/ this.moveState.up = 0; break;
  17244. case 70: /*F*/ this.moveState.down = 0; break;
  17245. case 38: /*up*/ this.moveState.pitchUp = 0; break;
  17246. case 40: /*down*/ this.moveState.pitchDown = 0; break;
  17247. case 37: /*left*/ this.moveState.yawLeft = 0; break;
  17248. case 39: /*right*/ this.moveState.yawRight = 0; break;
  17249. case 81: /*Q*/ this.moveState.rollLeft = 0; break;
  17250. case 69: /*E*/ this.moveState.rollRight = 0; break;
  17251. }
  17252. this.updateMovementVector();
  17253. this.updateRotationVector();
  17254. };
  17255. this.mousedown = function( event ) {
  17256. if ( this.domElement !== document ) {
  17257. this.domElement.focus();
  17258. }
  17259. event.preventDefault();
  17260. event.stopPropagation();
  17261. if ( this.dragToLook ) {
  17262. this.mouseStatus ++;
  17263. } else {
  17264. switch ( event.button ) {
  17265. case 0: this.object.moveForward = true; break;
  17266. case 2: this.object.moveBackward = true; break;
  17267. }
  17268. }
  17269. };
  17270. this.mousemove = function( event ) {
  17271. if ( !this.dragToLook || this.mouseStatus > 0 ) {
  17272. var container = this.getContainerDimensions();
  17273. var halfWidth = container.size[ 0 ] / 2;
  17274. var halfHeight = container.size[ 1 ] / 2;
  17275. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  17276. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  17277. this.updateRotationVector();
  17278. }
  17279. };
  17280. this.mouseup = function( event ) {
  17281. event.preventDefault();
  17282. event.stopPropagation();
  17283. if ( this.dragToLook ) {
  17284. this.mouseStatus --;
  17285. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  17286. } else {
  17287. switch ( event.button ) {
  17288. case 0: this.moveForward = false; break;
  17289. case 2: this.moveBackward = false; break;
  17290. }
  17291. }
  17292. this.updateRotationVector();
  17293. };
  17294. this.update = function( delta ) {
  17295. var moveMult = delta * this.movementSpeed;
  17296. var rotMult = delta * this.rollSpeed;
  17297. this.object.translateX( this.moveVector.x * moveMult );
  17298. this.object.translateY( this.moveVector.y * moveMult );
  17299. this.object.translateZ( this.moveVector.z * moveMult );
  17300. this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
  17301. this.object.quaternion.multiplySelf( this.tmpQuaternion );
  17302. this.object.matrix.setPosition( this.object.position );
  17303. this.object.matrix.setRotationFromQuaternion( this.object.quaternion );
  17304. this.object.matrixWorldNeedsUpdate = true;
  17305. };
  17306. this.updateMovementVector = function() {
  17307. var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;
  17308. this.moveVector.x = ( -this.moveState.left + this.moveState.right );
  17309. this.moveVector.y = ( -this.moveState.down + this.moveState.up );
  17310. this.moveVector.z = ( -forward + this.moveState.back );
  17311. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  17312. };
  17313. this.updateRotationVector = function() {
  17314. this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
  17315. this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
  17316. this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
  17317. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  17318. };
  17319. this.getContainerDimensions = function() {
  17320. if ( this.domElement != document ) {
  17321. return {
  17322. size : [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  17323. offset : [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  17324. };
  17325. } else {
  17326. return {
  17327. size : [ window.innerWidth, window.innerHeight ],
  17328. offset : [ 0, 0 ]
  17329. };
  17330. }
  17331. };
  17332. function bind( scope, fn ) {
  17333. return function () {
  17334. fn.apply( scope, arguments );
  17335. };
  17336. };
  17337. this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
  17338. this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
  17339. this.domElement.addEventListener( 'mouseup', bind( this, this.mouseup ), false );
  17340. this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
  17341. this.domElement.addEventListener( 'keyup', bind( this, this.keyup ), false );
  17342. this.updateMovementVector();
  17343. this.updateRotationVector();
  17344. };
  17345. /**
  17346. * @author mikael emtinger / http://gomo.se/
  17347. * @author alteredq / http://alteredqualia.com/
  17348. */
  17349. THREE.RollControls = function ( object, domElement ) {
  17350. this.object = object;
  17351. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17352. // API
  17353. this.mouseLook = true;
  17354. this.autoForward = false;
  17355. this.lookSpeed = 1;
  17356. this.movementSpeed = 1;
  17357. this.rollSpeed = 1;
  17358. this.constrainVertical = [ -0.9, 0.9 ];
  17359. // disable default target object behavior
  17360. this.object.matrixAutoUpdate = false;
  17361. // internals
  17362. this.forward = new THREE.Vector3( 0, 0, 1 );
  17363. this.roll = 0;
  17364. var xTemp = new THREE.Vector3();
  17365. var yTemp = new THREE.Vector3();
  17366. var zTemp = new THREE.Vector3();
  17367. var rollMatrix = new THREE.Matrix4();
  17368. var doRoll = false, rollDirection = 1, forwardSpeed = 0, sideSpeed = 0, upSpeed = 0;
  17369. var mouseX = 0, mouseY = 0;
  17370. var windowHalfX = 0;
  17371. var windowHalfY = 0;
  17372. //
  17373. this.handleResize = function () {
  17374. windowHalfX = window.innerWidth / 2;
  17375. windowHalfY = window.innerHeight / 2;
  17376. };
  17377. // custom update
  17378. this.update = function ( delta ) {
  17379. if ( this.mouseLook ) {
  17380. var actualLookSpeed = delta * this.lookSpeed;
  17381. this.rotateHorizontally( actualLookSpeed * mouseX );
  17382. this.rotateVertically( actualLookSpeed * mouseY );
  17383. }
  17384. var actualSpeed = delta * this.movementSpeed;
  17385. var forwardOrAuto = ( forwardSpeed > 0 || ( this.autoForward && ! ( forwardSpeed < 0 ) ) ) ? 1 : forwardSpeed;
  17386. this.object.translateZ( -actualSpeed * forwardOrAuto );
  17387. this.object.translateX( actualSpeed * sideSpeed );
  17388. this.object.translateY( actualSpeed * upSpeed );
  17389. if( doRoll ) {
  17390. this.roll += this.rollSpeed * delta * rollDirection;
  17391. }
  17392. // cap forward up / down
  17393. if( this.forward.y > this.constrainVertical[ 1 ] ) {
  17394. this.forward.y = this.constrainVertical[ 1 ];
  17395. this.forward.normalize();
  17396. } else if( this.forward.y < this.constrainVertical[ 0 ] ) {
  17397. this.forward.y = this.constrainVertical[ 0 ];
  17398. this.forward.normalize();
  17399. }
  17400. // construct unrolled camera matrix
  17401. zTemp.copy( this.forward );
  17402. yTemp.set( 0, 1, 0 );
  17403. xTemp.cross( yTemp, zTemp ).normalize();
  17404. yTemp.cross( zTemp, xTemp ).normalize();
  17405. this.object.matrix.elements[0] = xTemp.x; this.object.matrix.elements[4] = yTemp.x; this.object.matrix.elements[8] = zTemp.x;
  17406. this.object.matrix.elements[1] = xTemp.y; this.object.matrix.elements[5] = yTemp.y; this.object.matrix.elements[9] = zTemp.y;
  17407. this.object.matrix.elements[2] = xTemp.z; this.object.matrix.elements[6] = yTemp.z; this.object.matrix.elements[10] = zTemp.z;
  17408. // calculate roll matrix
  17409. rollMatrix.identity();
  17410. rollMatrix.elements[0] = Math.cos( this.roll ); rollMatrix.elements[4] = -Math.sin( this.roll );
  17411. rollMatrix.elements[1] = Math.sin( this.roll ); rollMatrix.elements[5] = Math.cos( this.roll );
  17412. // multiply camera with roll
  17413. this.object.matrix.multiplySelf( rollMatrix );
  17414. this.object.matrixWorldNeedsUpdate = true;
  17415. // set position
  17416. this.object.matrix.elements[12] = this.object.position.x;
  17417. this.object.matrix.elements[13] = this.object.position.y;
  17418. this.object.matrix.elements[14] = this.object.position.z;
  17419. };
  17420. this.translateX = function ( distance ) {
  17421. this.object.position.x += this.object.matrix.elements[0] * distance;
  17422. this.object.position.y += this.object.matrix.elements[1] * distance;
  17423. this.object.position.z += this.object.matrix.elements[2] * distance;
  17424. };
  17425. this.translateY = function ( distance ) {
  17426. this.object.position.x += this.object.matrix.elements[4] * distance;
  17427. this.object.position.y += this.object.matrix.elements[5] * distance;
  17428. this.object.position.z += this.object.matrix.elements[6] * distance;
  17429. };
  17430. this.translateZ = function ( distance ) {
  17431. this.object.position.x -= this.object.matrix.elements[8] * distance;
  17432. this.object.position.y -= this.object.matrix.elements[9] * distance;
  17433. this.object.position.z -= this.object.matrix.elements[10] * distance;
  17434. };
  17435. this.rotateHorizontally = function ( amount ) {
  17436. // please note that the amount is NOT degrees, but a scale value
  17437. xTemp.set( this.object.matrix.elements[0], this.object.matrix.elements[1], this.object.matrix.elements[2] );
  17438. xTemp.multiplyScalar( amount );
  17439. this.forward.subSelf( xTemp );
  17440. this.forward.normalize();
  17441. };
  17442. this.rotateVertically = function ( amount ) {
  17443. // please note that the amount is NOT degrees, but a scale value
  17444. yTemp.set( this.object.matrix.elements[4], this.object.matrix.elements[5], this.object.matrix.elements[6] );
  17445. yTemp.multiplyScalar( amount );
  17446. this.forward.addSelf( yTemp );
  17447. this.forward.normalize();
  17448. };
  17449. function onKeyDown( event ) {
  17450. //event.preventDefault();
  17451. switch ( event.keyCode ) {
  17452. case 38: /*up*/
  17453. case 87: /*W*/ forwardSpeed = 1; break;
  17454. case 37: /*left*/
  17455. case 65: /*A*/ sideSpeed = -1; break;
  17456. case 40: /*down*/
  17457. case 83: /*S*/ forwardSpeed = -1; break;
  17458. case 39: /*right*/
  17459. case 68: /*D*/ sideSpeed = 1; break;
  17460. case 81: /*Q*/ doRoll = true; rollDirection = 1; break;
  17461. case 69: /*E*/ doRoll = true; rollDirection = -1; break;
  17462. case 82: /*R*/ upSpeed = 1; break;
  17463. case 70: /*F*/ upSpeed = -1; break;
  17464. }
  17465. };
  17466. function onKeyUp( event ) {
  17467. switch( event.keyCode ) {
  17468. case 38: /*up*/
  17469. case 87: /*W*/ forwardSpeed = 0; break;
  17470. case 37: /*left*/
  17471. case 65: /*A*/ sideSpeed = 0; break;
  17472. case 40: /*down*/
  17473. case 83: /*S*/ forwardSpeed = 0; break;
  17474. case 39: /*right*/
  17475. case 68: /*D*/ sideSpeed = 0; break;
  17476. case 81: /*Q*/ doRoll = false; break;
  17477. case 69: /*E*/ doRoll = false; break;
  17478. case 82: /*R*/ upSpeed = 0; break;
  17479. case 70: /*F*/ upSpeed = 0; break;
  17480. }
  17481. };
  17482. function onMouseMove( event ) {
  17483. mouseX = ( event.clientX - windowHalfX ) / window.innerWidth;
  17484. mouseY = ( event.clientY - windowHalfY ) / window.innerHeight;
  17485. };
  17486. function onMouseDown ( event ) {
  17487. event.preventDefault();
  17488. event.stopPropagation();
  17489. switch ( event.button ) {
  17490. case 0: forwardSpeed = 1; break;
  17491. case 2: forwardSpeed = -1; break;
  17492. }
  17493. };
  17494. function onMouseUp ( event ) {
  17495. event.preventDefault();
  17496. event.stopPropagation();
  17497. switch ( event.button ) {
  17498. case 0: forwardSpeed = 0; break;
  17499. case 2: forwardSpeed = 0; break;
  17500. }
  17501. };
  17502. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17503. this.domElement.addEventListener( 'mousemove', onMouseMove, false );
  17504. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  17505. this.domElement.addEventListener( 'mouseup', onMouseUp, false );
  17506. this.domElement.addEventListener( 'keydown', onKeyDown, false );
  17507. this.domElement.addEventListener( 'keyup', onKeyUp, false );
  17508. this.handleResize();
  17509. };
  17510. /**
  17511. * @author Eberhard Graether / http://egraether.com/
  17512. */
  17513. THREE.TrackballControls = function ( object, domElement ) {
  17514. THREE.EventTarget.call( this );
  17515. var _this = this,
  17516. STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };
  17517. this.object = object;
  17518. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17519. // API
  17520. this.enabled = true;
  17521. this.screen = { width: 0, height: 0, offsetLeft: 0, offsetTop: 0 };
  17522. this.radius = ( this.screen.width + this.screen.height ) / 4;
  17523. this.rotateSpeed = 1.0;
  17524. this.zoomSpeed = 1.2;
  17525. this.panSpeed = 0.3;
  17526. this.noRotate = false;
  17527. this.noZoom = false;
  17528. this.noPan = false;
  17529. this.staticMoving = false;
  17530. this.dynamicDampingFactor = 0.2;
  17531. this.minDistance = 0;
  17532. this.maxDistance = Infinity;
  17533. this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
  17534. // internals
  17535. this.target = new THREE.Vector3();
  17536. var lastPosition = new THREE.Vector3();
  17537. var _keyPressed = false,
  17538. _state = STATE.NONE,
  17539. _eye = new THREE.Vector3(),
  17540. _rotateStart = new THREE.Vector3(),
  17541. _rotateEnd = new THREE.Vector3(),
  17542. _zoomStart = new THREE.Vector2(),
  17543. _zoomEnd = new THREE.Vector2(),
  17544. _panStart = new THREE.Vector2(),
  17545. _panEnd = new THREE.Vector2();
  17546. // events
  17547. var changeEvent = { type: 'change' };
  17548. // methods
  17549. this.handleResize = function () {
  17550. this.screen.width = window.innerWidth;
  17551. this.screen.height = window.innerHeight;
  17552. this.screen.offsetLeft = 0;
  17553. this.screen.offsetTop = 0;
  17554. this.radius = ( this.screen.width + this.screen.height ) / 4;
  17555. };
  17556. this.handleEvent = function ( event ) {
  17557. if ( typeof this[ event.type ] == 'function' ) {
  17558. this[ event.type ]( event );
  17559. }
  17560. };
  17561. this.getMouseOnScreen = function ( clientX, clientY ) {
  17562. return new THREE.Vector2(
  17563. ( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
  17564. ( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
  17565. );
  17566. };
  17567. this.getMouseProjectionOnBall = function ( clientX, clientY ) {
  17568. var mouseOnBall = new THREE.Vector3(
  17569. ( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
  17570. ( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
  17571. 0.0
  17572. );
  17573. var length = mouseOnBall.length();
  17574. if ( length > 1.0 ) {
  17575. mouseOnBall.normalize();
  17576. } else {
  17577. mouseOnBall.z = Math.sqrt( 1.0 - length * length );
  17578. }
  17579. _eye.copy( _this.object.position ).subSelf( _this.target );
  17580. var projection = _this.object.up.clone().setLength( mouseOnBall.y );
  17581. projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
  17582. projection.addSelf( _eye.setLength( mouseOnBall.z ) );
  17583. return projection;
  17584. };
  17585. this.rotateCamera = function () {
  17586. var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
  17587. if ( angle ) {
  17588. var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
  17589. quaternion = new THREE.Quaternion();
  17590. angle *= _this.rotateSpeed;
  17591. quaternion.setFromAxisAngle( axis, -angle );
  17592. quaternion.multiplyVector3( _eye );
  17593. quaternion.multiplyVector3( _this.object.up );
  17594. quaternion.multiplyVector3( _rotateEnd );
  17595. if ( _this.staticMoving ) {
  17596. _rotateStart = _rotateEnd;
  17597. } else {
  17598. quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
  17599. quaternion.multiplyVector3( _rotateStart );
  17600. }
  17601. }
  17602. };
  17603. this.zoomCamera = function () {
  17604. var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
  17605. if ( factor !== 1.0 && factor > 0.0 ) {
  17606. _eye.multiplyScalar( factor );
  17607. if ( _this.staticMoving ) {
  17608. _zoomStart = _zoomEnd;
  17609. } else {
  17610. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  17611. }
  17612. }
  17613. };
  17614. this.panCamera = function () {
  17615. var mouseChange = _panEnd.clone().subSelf( _panStart );
  17616. if ( mouseChange.lengthSq() ) {
  17617. mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
  17618. var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
  17619. pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );
  17620. _this.object.position.addSelf( pan );
  17621. _this.target.addSelf( pan );
  17622. if ( _this.staticMoving ) {
  17623. _panStart = _panEnd;
  17624. } else {
  17625. _panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
  17626. }
  17627. }
  17628. };
  17629. this.checkDistances = function () {
  17630. if ( !_this.noZoom || !_this.noPan ) {
  17631. if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {
  17632. _this.object.position.setLength( _this.maxDistance );
  17633. }
  17634. if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
  17635. _this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );
  17636. }
  17637. }
  17638. };
  17639. this.update = function () {
  17640. _eye.copy( _this.object.position ).subSelf( _this.target );
  17641. if ( !_this.noRotate ) {
  17642. _this.rotateCamera();
  17643. }
  17644. if ( !_this.noZoom ) {
  17645. _this.zoomCamera();
  17646. }
  17647. if ( !_this.noPan ) {
  17648. _this.panCamera();
  17649. }
  17650. _this.object.position.add( _this.target, _eye );
  17651. _this.checkDistances();
  17652. _this.object.lookAt( _this.target );
  17653. if ( lastPosition.distanceToSquared( _this.object.position ) > 0 ) {
  17654. _this.dispatchEvent( changeEvent );
  17655. lastPosition.copy( _this.object.position );
  17656. }
  17657. };
  17658. // listeners
  17659. function keydown( event ) {
  17660. if ( ! _this.enabled ) return;
  17661. //event.preventDefault();
  17662. if ( _state !== STATE.NONE ) {
  17663. return;
  17664. } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
  17665. _state = STATE.ROTATE;
  17666. } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
  17667. _state = STATE.ZOOM;
  17668. } else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
  17669. _state = STATE.PAN;
  17670. }
  17671. if ( _state !== STATE.NONE ) {
  17672. _keyPressed = true;
  17673. }
  17674. }
  17675. function keyup( event ) {
  17676. if ( ! _this.enabled ) return;
  17677. if ( _state !== STATE.NONE ) {
  17678. _state = STATE.NONE;
  17679. }
  17680. }
  17681. function mousedown( event ) {
  17682. if ( ! _this.enabled ) return;
  17683. event.preventDefault();
  17684. event.stopPropagation();
  17685. if ( _state === STATE.NONE ) {
  17686. _state = event.button;
  17687. if ( _state === STATE.ROTATE && !_this.noRotate ) {
  17688. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  17689. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  17690. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17691. } else if ( !this.noPan ) {
  17692. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17693. }
  17694. }
  17695. }
  17696. function mousemove( event ) {
  17697. if ( ! _this.enabled ) return;
  17698. if ( _keyPressed ) {
  17699. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  17700. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17701. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17702. _keyPressed = false;
  17703. }
  17704. if ( _state === STATE.NONE ) {
  17705. return;
  17706. } else if ( _state === STATE.ROTATE && !_this.noRotate ) {
  17707. _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  17708. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  17709. _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17710. } else if ( _state === STATE.PAN && !_this.noPan ) {
  17711. _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17712. }
  17713. }
  17714. function mouseup( event ) {
  17715. if ( ! _this.enabled ) return;
  17716. event.preventDefault();
  17717. event.stopPropagation();
  17718. _state = STATE.NONE;
  17719. }
  17720. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17721. this.domElement.addEventListener( 'mousemove', mousemove, false );
  17722. this.domElement.addEventListener( 'mousedown', mousedown, false );
  17723. this.domElement.addEventListener( 'mouseup', mouseup, false );
  17724. // this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false );
  17725. // this.domElement.addEventListener( 'mousewheel', mousewheel, false );
  17726. window.addEventListener( 'keydown', keydown, false );
  17727. window.addEventListener( 'keyup', keyup, false );
  17728. this.handleResize();
  17729. };
  17730. /**
  17731. * @author qiao / https://github.com/qiao
  17732. * @author mrdoob / http://mrdoob.com
  17733. * @author alteredq / http://alteredqualia.com/
  17734. */
  17735. THREE.OrbitControls = function ( object, domElement ) {
  17736. THREE.EventTarget.call( this );
  17737. this.object = object;
  17738. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17739. // API
  17740. this.center = new THREE.Vector3();
  17741. this.userZoom = true;
  17742. this.userZoomSpeed = 1.0;
  17743. this.userRotate = true;
  17744. this.userRotateSpeed = 1.0;
  17745. this.autoRotate = false;
  17746. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  17747. // internals
  17748. var scope = this;
  17749. var EPS = 0.000001;
  17750. var PIXELS_PER_ROUND = 1800;
  17751. var rotateStart = new THREE.Vector2();
  17752. var rotateEnd = new THREE.Vector2();
  17753. var rotateDelta = new THREE.Vector2();
  17754. var zoomStart = new THREE.Vector2();
  17755. var zoomEnd = new THREE.Vector2();
  17756. var zoomDelta = new THREE.Vector2();
  17757. var phiDelta = 0;
  17758. var thetaDelta = 0;
  17759. var scale = 1;
  17760. var lastPosition = new THREE.Vector3();
  17761. var STATE = { NONE : -1, ROTATE : 0, ZOOM : 1 };
  17762. var state = STATE.NONE;
  17763. // events
  17764. var changeEvent = { type: 'change' };
  17765. this.rotateLeft = function ( angle ) {
  17766. if ( angle === undefined ) {
  17767. angle = getAutoRotationAngle();
  17768. }
  17769. thetaDelta -= angle;
  17770. };
  17771. this.rotateRight = function ( angle ) {
  17772. if ( angle === undefined ) {
  17773. angle = getAutoRotationAngle();
  17774. }
  17775. thetaDelta += angle;
  17776. };
  17777. this.rotateUp = function ( angle ) {
  17778. if ( angle === undefined ) {
  17779. angle = getAutoRotationAngle();
  17780. }
  17781. phiDelta -= angle;
  17782. };
  17783. this.rotateDown = function ( angle ) {
  17784. if ( angle === undefined ) {
  17785. angle = getAutoRotationAngle();
  17786. }
  17787. phiDelta += angle;
  17788. };
  17789. this.zoomIn = function ( zoomScale ) {
  17790. if ( zoomScale === undefined ) {
  17791. zoomScale = getZoomScale();
  17792. }
  17793. scale /= zoomScale;
  17794. };
  17795. this.zoomOut = function ( zoomScale ) {
  17796. if ( zoomScale === undefined ) {
  17797. zoomScale = getZoomScale();
  17798. }
  17799. scale *= zoomScale;
  17800. };
  17801. this.update = function () {
  17802. var position = this.object.position;
  17803. var offset = position.clone().subSelf( this.center )
  17804. // angle from z-axis around y-axis
  17805. var theta = Math.atan2( offset.x, offset.z );
  17806. // angle from y-axis
  17807. var phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y );
  17808. if ( this.autoRotate ) {
  17809. this.rotateLeft( getAutoRotationAngle() );
  17810. }
  17811. theta += thetaDelta;
  17812. phi += phiDelta;
  17813. // restrict phi to be betwee EPS and PI-EPS
  17814. phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) );
  17815. var radius = offset.length();
  17816. offset.x = radius * Math.sin( phi ) * Math.sin( theta );
  17817. offset.y = radius * Math.cos( phi );
  17818. offset.z = radius * Math.sin( phi ) * Math.cos( theta );
  17819. offset.multiplyScalar( scale );
  17820. position.copy( this.center ).addSelf( offset );
  17821. this.object.lookAt( this.center );
  17822. thetaDelta = 0;
  17823. phiDelta = 0;
  17824. scale = 1;
  17825. if ( lastPosition.distanceTo( this.object.position ) > 0 ) {
  17826. this.dispatchEvent( changeEvent );
  17827. lastPosition.copy( this.object.position );
  17828. }
  17829. };
  17830. function getAutoRotationAngle() {
  17831. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  17832. }
  17833. function getZoomScale() {
  17834. return Math.pow( 0.95, scope.userZoomSpeed );
  17835. }
  17836. function onMouseDown( event ) {
  17837. if ( !scope.userRotate ) return;
  17838. event.preventDefault();
  17839. if ( event.button === 0 || event.button === 2 ) {
  17840. state = STATE.ROTATE;
  17841. rotateStart.set( event.clientX, event.clientY );
  17842. } else if ( event.button === 1 ) {
  17843. state = STATE.ZOOM;
  17844. zoomStart.set( event.clientX, event.clientY );
  17845. }
  17846. document.addEventListener( 'mousemove', onMouseMove, false );
  17847. document.addEventListener( 'mouseup', onMouseUp, false );
  17848. }
  17849. function onMouseMove( event ) {
  17850. event.preventDefault();
  17851. if ( state === STATE.ROTATE ) {
  17852. rotateEnd.set( event.clientX, event.clientY );
  17853. rotateDelta.sub( rotateEnd, rotateStart );
  17854. scope.rotateLeft( 2 * Math.PI * rotateDelta.x / PIXELS_PER_ROUND * scope.userRotateSpeed );
  17855. scope.rotateUp( 2 * Math.PI * rotateDelta.y / PIXELS_PER_ROUND * scope.userRotateSpeed );
  17856. rotateStart.copy( rotateEnd );
  17857. } else if ( state === STATE.ZOOM ) {
  17858. zoomEnd.set( event.clientX, event.clientY );
  17859. zoomDelta.sub( zoomEnd, zoomStart );
  17860. if ( zoomDelta.y > 0 ) {
  17861. scope.zoomIn();
  17862. } else {
  17863. scope.zoomOut();
  17864. }
  17865. zoomStart.copy( zoomEnd );
  17866. }
  17867. }
  17868. function onMouseUp( event ) {
  17869. if ( ! scope.userRotate ) return;
  17870. document.removeEventListener( 'mousemove', onMouseMove, false );
  17871. document.removeEventListener( 'mouseup', onMouseUp, false );
  17872. state = STATE.NONE;
  17873. }
  17874. function onMouseWheel( event ) {
  17875. if ( ! scope.userZoom ) return;
  17876. if ( event.wheelDelta > 0 ) {
  17877. scope.zoomOut();
  17878. } else {
  17879. scope.zoomIn();
  17880. }
  17881. }
  17882. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17883. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  17884. this.domElement.addEventListener( 'mousewheel', onMouseWheel, false );
  17885. };
  17886. /**
  17887. * @author hughes
  17888. */
  17889. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  17890. THREE.Geometry.call( this );
  17891. radius = radius || 50;
  17892. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17893. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17894. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17895. var i, uvs = [],
  17896. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  17897. this.vertices.push(center);
  17898. uvs.push( centerUV );
  17899. for ( i = 0; i <= segments; i ++ ) {
  17900. var vertex = new THREE.Vector3();
  17901. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  17902. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  17903. this.vertices.push( vertex );
  17904. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  17905. }
  17906. var n = new THREE.Vector3( 0, 0, -1 );
  17907. for ( i = 1; i <= segments; i ++ ) {
  17908. var v1 = i;
  17909. var v2 = i + 1 ;
  17910. var v3 = 0;
  17911. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  17912. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  17913. }
  17914. this.computeCentroids();
  17915. this.computeFaceNormals();
  17916. this.boundingSphere = { radius: radius };
  17917. };
  17918. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17919. /**
  17920. * @author mrdoob / http://mrdoob.com/
  17921. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  17922. */
  17923. THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
  17924. THREE.Geometry.call( this );
  17925. var scope = this,
  17926. width_half = width / 2,
  17927. height_half = height / 2,
  17928. depth_half = depth / 2;
  17929. var mpx, mpy, mpz, mnx, mny, mnz;
  17930. if ( materials !== undefined ) {
  17931. if ( materials instanceof Array ) {
  17932. this.materials = materials;
  17933. } else {
  17934. this.materials = [];
  17935. for ( var i = 0; i < 6; i ++ ) {
  17936. this.materials.push( materials );
  17937. }
  17938. }
  17939. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  17940. } else {
  17941. this.materials = [];
  17942. }
  17943. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  17944. if ( sides != undefined ) {
  17945. for ( var s in sides ) {
  17946. if ( this.sides[ s ] !== undefined ) {
  17947. this.sides[ s ] = sides[ s ];
  17948. }
  17949. }
  17950. }
  17951. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
  17952. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, mnx ); // nx
  17953. this.sides.py && buildPlane( 'x', 'z', 1, 1, width, depth, height_half, mpy ); // py
  17954. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, mny ); // ny
  17955. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, mpz ); // pz
  17956. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz
  17957. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  17958. var w, ix, iy,
  17959. gridX = segmentsWidth || 1,
  17960. gridY = segmentsHeight || 1,
  17961. width_half = width / 2,
  17962. height_half = height / 2,
  17963. offset = scope.vertices.length;
  17964. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  17965. w = 'z';
  17966. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  17967. w = 'y';
  17968. gridY = segmentsDepth || 1;
  17969. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  17970. w = 'x';
  17971. gridX = segmentsDepth || 1;
  17972. }
  17973. var gridX1 = gridX + 1,
  17974. gridY1 = gridY + 1,
  17975. segment_width = width / gridX,
  17976. segment_height = height / gridY,
  17977. normal = new THREE.Vector3();
  17978. normal[ w ] = depth > 0 ? 1 : - 1;
  17979. for ( iy = 0; iy < gridY1; iy ++ ) {
  17980. for ( ix = 0; ix < gridX1; ix ++ ) {
  17981. var vector = new THREE.Vector3();
  17982. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  17983. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  17984. vector[ w ] = depth;
  17985. scope.vertices.push( vector );
  17986. }
  17987. }
  17988. for ( iy = 0; iy < gridY; iy++ ) {
  17989. for ( ix = 0; ix < gridX; ix++ ) {
  17990. var a = ix + gridX1 * iy;
  17991. var b = ix + gridX1 * ( iy + 1 );
  17992. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  17993. var d = ( ix + 1 ) + gridX1 * iy;
  17994. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  17995. face.normal.copy( normal );
  17996. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  17997. face.materialIndex = material;
  17998. scope.faces.push( face );
  17999. scope.faceVertexUvs[ 0 ].push( [
  18000. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  18001. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18002. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18003. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18004. ] );
  18005. }
  18006. }
  18007. }
  18008. this.computeCentroids();
  18009. this.mergeVertices();
  18010. };
  18011. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18012. /**
  18013. * @author mrdoob / http://mrdoob.com/
  18014. */
  18015. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded ) {
  18016. THREE.Geometry.call( this );
  18017. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18018. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18019. height = height !== undefined ? height : 100;
  18020. var heightHalf = height / 2;
  18021. var segmentsX = segmentsRadius || 8;
  18022. var segmentsY = segmentsHeight || 1;
  18023. var x, y, vertices = [], uvs = [];
  18024. for ( y = 0; y <= segmentsY; y ++ ) {
  18025. var verticesRow = [];
  18026. var uvsRow = [];
  18027. var v = y / segmentsY;
  18028. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18029. for ( x = 0; x <= segmentsX; x ++ ) {
  18030. var u = x / segmentsX;
  18031. var vertex = new THREE.Vector3();
  18032. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18033. vertex.y = - v * height + heightHalf;
  18034. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18035. this.vertices.push( vertex );
  18036. verticesRow.push( this.vertices.length - 1 );
  18037. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18038. }
  18039. vertices.push( verticesRow );
  18040. uvs.push( uvsRow );
  18041. }
  18042. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18043. var na, nb;
  18044. for ( x = 0; x < segmentsX; x ++ ) {
  18045. if ( radiusTop !== 0 ) {
  18046. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18047. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18048. } else {
  18049. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18050. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18051. }
  18052. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18053. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18054. for ( y = 0; y < segmentsY; y ++ ) {
  18055. var v1 = vertices[ y ][ x ];
  18056. var v2 = vertices[ y + 1 ][ x ];
  18057. var v3 = vertices[ y + 1 ][ x + 1 ];
  18058. var v4 = vertices[ y ][ x + 1 ];
  18059. var n1 = na.clone();
  18060. var n2 = na.clone();
  18061. var n3 = nb.clone();
  18062. var n4 = nb.clone();
  18063. var uv1 = uvs[ y ][ x ].clone();
  18064. var uv2 = uvs[ y + 1 ][ x ].clone();
  18065. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18066. var uv4 = uvs[ y ][ x + 1 ].clone();
  18067. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18068. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18069. }
  18070. }
  18071. // top cap
  18072. if ( !openEnded && radiusTop > 0 ) {
  18073. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18074. for ( x = 0; x < segmentsX; x ++ ) {
  18075. var v1 = vertices[ 0 ][ x ];
  18076. var v2 = vertices[ 0 ][ x + 1 ];
  18077. var v3 = this.vertices.length - 1;
  18078. var n1 = new THREE.Vector3( 0, 1, 0 );
  18079. var n2 = new THREE.Vector3( 0, 1, 0 );
  18080. var n3 = new THREE.Vector3( 0, 1, 0 );
  18081. var uv1 = uvs[ 0 ][ x ].clone();
  18082. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18083. var uv3 = new THREE.UV( uv2.u, 0 );
  18084. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18085. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18086. }
  18087. }
  18088. // bottom cap
  18089. if ( !openEnded && radiusBottom > 0 ) {
  18090. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18091. for ( x = 0; x < segmentsX; x ++ ) {
  18092. var v1 = vertices[ y ][ x + 1 ];
  18093. var v2 = vertices[ y ][ x ];
  18094. var v3 = this.vertices.length - 1;
  18095. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18096. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18097. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18098. var uv1 = uvs[ y ][ x + 1 ].clone();
  18099. var uv2 = uvs[ y ][ x ].clone();
  18100. var uv3 = new THREE.UV( uv2.u, 1 );
  18101. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18102. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18103. }
  18104. }
  18105. this.computeCentroids();
  18106. this.computeFaceNormals();
  18107. }
  18108. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18109. /**
  18110. * @author zz85 / http://www.lab4games.net/zz85/blog
  18111. *
  18112. * Creates extruded geometry from a path shape.
  18113. *
  18114. * parameters = {
  18115. *
  18116. * size: <float>, // size of the text
  18117. * height: <float>, // thickness to extrude text
  18118. * curveSegments: <int>, // number of points on the curves
  18119. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18120. amount: <int>, // Amount
  18121. *
  18122. * bevelEnabled: <bool>, // turn on bevel
  18123. * bevelThickness: <float>, // how deep into text bevel goes
  18124. * bevelSize: <float>, // how far from text outline is bevel
  18125. * bevelSegments: <int>, // number of bevel layers
  18126. *
  18127. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18128. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18129. * bendPath: <THREE.CurvePath> // 2d path for bend the shape around x/y plane
  18130. *
  18131. * material: <int> // material index for front and back faces
  18132. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18133. * uvGenerator: <Object> // object that provides UV generator functions
  18134. *
  18135. * }
  18136. **/
  18137. THREE.ExtrudeGeometry = function( shapes, options ) {
  18138. if ( typeof( shapes ) === "undefined" ) {
  18139. shapes = [];
  18140. return;
  18141. }
  18142. THREE.Geometry.call( this );
  18143. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18144. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18145. this.addShapeList( shapes, options );
  18146. this.computeCentroids();
  18147. this.computeFaceNormals();
  18148. // can't really use automatic vertex normals
  18149. // as then front and back sides get smoothed too
  18150. // should do separate smoothing just for sides
  18151. //this.computeVertexNormals();
  18152. //console.log( "took", ( Date.now() - startTime ) );
  18153. };
  18154. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18155. THREE.ExtrudeGeometry.prototype.addShapeList = function(shapes, options) {
  18156. var sl = shapes.length;
  18157. for ( var s = 0; s < sl; s ++ ) {
  18158. var shape = shapes[ s ];
  18159. this.addShape( shape, options );
  18160. }
  18161. };
  18162. THREE.ExtrudeGeometry.prototype.addShape = function( shape, options ) {
  18163. var amount = options.amount !== undefined ? options.amount : 100;
  18164. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18165. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18166. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18167. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18168. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18169. var steps = options.steps !== undefined ? options.steps : 1;
  18170. var bendPath = options.bendPath;
  18171. var extrudePath = options.extrudePath;
  18172. var extrudePts, extrudeByPath = false;
  18173. var material = options.material;
  18174. var extrudeMaterial = options.extrudeMaterial;
  18175. // Use default WorldUVGenerator if no UV generators are specified.
  18176. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18177. var shapebb = this.shapebb;
  18178. //shapebb = shape.getBoundingBox();
  18179. var splineTube, binormal, normal, position2;
  18180. if ( extrudePath ) {
  18181. extrudePts = extrudePath.getSpacedPoints( steps );
  18182. extrudeByPath = true;
  18183. bevelEnabled = false; // bevels not supported for path extrusion
  18184. // SETUP TNB variables
  18185. // Reuse TNB from TubeGeomtry for now.
  18186. // TODO1 - have a .isClosed in spline?
  18187. splineTube = options.frames !== undefined ?
  18188. options.frames :
  18189. new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18190. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18191. binormal = new THREE.Vector3();
  18192. normal = new THREE.Vector3();
  18193. position2 = new THREE.Vector3();
  18194. }
  18195. // Safeguards if bevels are not enabled
  18196. if ( ! bevelEnabled ) {
  18197. bevelSegments = 0;
  18198. bevelThickness = 0;
  18199. bevelSize = 0;
  18200. }
  18201. // Variables initalization
  18202. var ahole, h, hl; // looping of holes
  18203. var scope = this;
  18204. var bevelPoints = [];
  18205. var shapesOffset = this.vertices.length;
  18206. if ( bendPath ) {
  18207. shape.addWrapPath( bendPath );
  18208. }
  18209. var shapePoints = shape.extractPoints();
  18210. var vertices = shapePoints.shape;
  18211. var holes = shapePoints.holes;
  18212. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18213. if ( reverse ) {
  18214. vertices = vertices.reverse();
  18215. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18216. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18217. ahole = holes[ h ];
  18218. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18219. holes[ h ] = ahole.reverse();
  18220. }
  18221. }
  18222. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18223. }
  18224. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18225. //var faces = THREE.Shape.Utils.triangulate2( vertices, holes );
  18226. // Would it be better to move points after triangulation?
  18227. // shapePoints = shape.extractAllPointsWithBend( curveSegments, bendPath );
  18228. // vertices = shapePoints.shape;
  18229. // holes = shapePoints.holes;
  18230. //console.log(faces);
  18231. ////
  18232. /// Handle Vertices
  18233. ////
  18234. var contour = vertices; // vertices has all points but contour has only points of circumference
  18235. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18236. ahole = holes[ h ];
  18237. vertices = vertices.concat( ahole );
  18238. }
  18239. function scalePt2 ( pt, vec, size ) {
  18240. if ( !vec ) console.log( "die" );
  18241. return vec.clone().multiplyScalar( size ).addSelf( pt );
  18242. }
  18243. var b, bs, t, z,
  18244. vert, vlen = vertices.length,
  18245. face, flen = faces.length,
  18246. cont, clen = contour.length;
  18247. //------
  18248. // Find directions for point movement
  18249. //
  18250. var RAD_TO_DEGREES = 180 / Math.PI;
  18251. function getBevelVec( pt_i, pt_j, pt_k ) {
  18252. // Algorithm 2
  18253. return getBevelVec2( pt_i, pt_j, pt_k );
  18254. }
  18255. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18256. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18257. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18258. if ( anglea > angleb ) {
  18259. angleb += Math.PI * 2;
  18260. }
  18261. var anglec = ( anglea + angleb ) / 2;
  18262. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18263. var x = - Math.cos( anglec );
  18264. var y = - Math.sin( anglec );
  18265. var vec = new THREE.Vector2( x, y ); //.normalize();
  18266. return vec;
  18267. }
  18268. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18269. var a = THREE.ExtrudeGeometry.__v1,
  18270. b = THREE.ExtrudeGeometry.__v2,
  18271. v_hat = THREE.ExtrudeGeometry.__v3,
  18272. w_hat = THREE.ExtrudeGeometry.__v4,
  18273. p = THREE.ExtrudeGeometry.__v5,
  18274. q = THREE.ExtrudeGeometry.__v6,
  18275. v, w,
  18276. v_dot_w_hat, q_sub_p_dot_w_hat,
  18277. s, intersection;
  18278. // good reading for line-line intersection
  18279. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18280. // define a as vector j->i
  18281. // define b as vectot k->i
  18282. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18283. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18284. // get unit vectors
  18285. v = a.normalize();
  18286. w = b.normalize();
  18287. // normals from pt i
  18288. v_hat.set( -v.y, v.x );
  18289. w_hat.set( w.y, -w.x );
  18290. // pts from i
  18291. p.copy( pt_i ).addSelf( v_hat );
  18292. q.copy( pt_i ).addSelf( w_hat );
  18293. if ( p.equals( q ) ) {
  18294. //console.log("Warning: lines are straight");
  18295. return w_hat.clone();
  18296. }
  18297. // Points from j, k. helps prevents points cross overover most of the time
  18298. p.copy( pt_j ).addSelf( v_hat );
  18299. q.copy( pt_k ).addSelf( w_hat );
  18300. v_dot_w_hat = v.dot( w_hat );
  18301. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18302. // We should not reach these conditions
  18303. if ( v_dot_w_hat === 0 ) {
  18304. console.log( "Either infinite or no solutions!" );
  18305. if ( q_sub_p_dot_w_hat === 0 ) {
  18306. console.log( "Its finite solutions." );
  18307. } else {
  18308. console.log( "Too bad, no solutions." );
  18309. }
  18310. }
  18311. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18312. if ( s < 0 ) {
  18313. // in case of emergecy, revert to algorithm 1.
  18314. return getBevelVec1( pt_i, pt_j, pt_k );
  18315. }
  18316. intersection = v.multiplyScalar( s ).addSelf( p );
  18317. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18318. }
  18319. var contourMovements = [];
  18320. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18321. if ( j === il ) j = 0;
  18322. if ( k === il ) k = 0;
  18323. // (j)---(i)---(k)
  18324. // console.log('i,j,k', i, j , k)
  18325. var pt_i = contour[ i ];
  18326. var pt_j = contour[ j ];
  18327. var pt_k = contour[ k ];
  18328. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18329. }
  18330. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18331. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18332. ahole = holes[ h ];
  18333. oneHoleMovements = [];
  18334. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18335. if ( j === il ) j = 0;
  18336. if ( k === il ) k = 0;
  18337. // (j)---(i)---(k)
  18338. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18339. }
  18340. holesMovements.push( oneHoleMovements );
  18341. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18342. }
  18343. // Loop bevelSegments, 1 for the front, 1 for the back
  18344. for ( b = 0; b < bevelSegments; b ++ ) {
  18345. //for ( b = bevelSegments; b > 0; b -- ) {
  18346. t = b / bevelSegments;
  18347. z = bevelThickness * ( 1 - t );
  18348. //z = bevelThickness * t;
  18349. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18350. //bs = bevelSize * t ; // linear
  18351. // contract shape
  18352. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18353. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18354. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18355. v( vert.x, vert.y, - z );
  18356. }
  18357. // expand holes
  18358. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18359. ahole = holes[ h ];
  18360. oneHoleMovements = holesMovements[ h ];
  18361. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18362. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18363. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18364. v( vert.x, vert.y, -z );
  18365. }
  18366. }
  18367. }
  18368. bs = bevelSize;
  18369. // Back facing vertices
  18370. for ( i = 0; i < vlen; i ++ ) {
  18371. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18372. if ( !extrudeByPath ) {
  18373. v( vert.x, vert.y, 0 );
  18374. } else {
  18375. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18376. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18377. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18378. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  18379. v( position2.x, position2.y, position2.z );
  18380. }
  18381. }
  18382. // Add stepped vertices...
  18383. // Including front facing vertices
  18384. var s;
  18385. for ( s = 1; s <= steps; s ++ ) {
  18386. for ( i = 0; i < vlen; i ++ ) {
  18387. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18388. if ( !extrudeByPath ) {
  18389. v( vert.x, vert.y, amount / steps * s );
  18390. } else {
  18391. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18392. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18393. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18394. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  18395. v( position2.x, position2.y, position2.z );
  18396. }
  18397. }
  18398. }
  18399. // Add bevel segments planes
  18400. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18401. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18402. t = b / bevelSegments;
  18403. z = bevelThickness * ( 1 - t );
  18404. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18405. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18406. // contract shape
  18407. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18408. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18409. v( vert.x, vert.y, amount + z );
  18410. }
  18411. // expand holes
  18412. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18413. ahole = holes[ h ];
  18414. oneHoleMovements = holesMovements[ h ];
  18415. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18416. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18417. if ( !extrudeByPath ) {
  18418. v( vert.x, vert.y, amount + z );
  18419. } else {
  18420. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18421. }
  18422. }
  18423. }
  18424. }
  18425. ////
  18426. /// Handle Faces
  18427. ////
  18428. // Top and bottom faces
  18429. buildLidFaces();
  18430. // Sides faces
  18431. buildSideFaces();
  18432. ///// Internal functions
  18433. function buildLidFaces() {
  18434. if ( bevelEnabled ) {
  18435. var layer = 0 ; // steps + 1
  18436. var offset = vlen * layer;
  18437. // Bottom faces
  18438. for ( i = 0; i < flen; i ++ ) {
  18439. face = faces[ i ];
  18440. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18441. }
  18442. layer = steps + bevelSegments * 2;
  18443. offset = vlen * layer;
  18444. // Top faces
  18445. for ( i = 0; i < flen; i ++ ) {
  18446. face = faces[ i ];
  18447. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18448. }
  18449. } else {
  18450. // Bottom faces
  18451. for ( i = 0; i < flen; i++ ) {
  18452. face = faces[ i ];
  18453. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18454. }
  18455. // Top faces
  18456. for ( i = 0; i < flen; i ++ ) {
  18457. face = faces[ i ];
  18458. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18459. }
  18460. }
  18461. }
  18462. // Create faces for the z-sides of the shape
  18463. function buildSideFaces() {
  18464. var layeroffset = 0;
  18465. sidewalls( contour, layeroffset );
  18466. layeroffset += contour.length;
  18467. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18468. ahole = holes[ h ];
  18469. sidewalls( ahole, layeroffset );
  18470. //, true
  18471. layeroffset += ahole.length;
  18472. }
  18473. }
  18474. function sidewalls( contour, layeroffset ) {
  18475. var j, k;
  18476. i = contour.length;
  18477. while ( --i >= 0 ) {
  18478. j = i;
  18479. k = i - 1;
  18480. if ( k < 0 ) k = contour.length - 1;
  18481. //console.log('b', i,j, i-1, k,vertices.length);
  18482. var s = 0, sl = steps + bevelSegments * 2;
  18483. for ( s = 0; s < sl; s ++ ) {
  18484. var slen1 = vlen * s;
  18485. var slen2 = vlen * ( s + 1 );
  18486. var a = layeroffset + j + slen1,
  18487. b = layeroffset + k + slen1,
  18488. c = layeroffset + k + slen2,
  18489. d = layeroffset + j + slen2;
  18490. f4( a, b, c, d, contour, s, sl, j, k );
  18491. }
  18492. }
  18493. }
  18494. function v( x, y, z ) {
  18495. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18496. }
  18497. function f3( a, b, c, isBottom ) {
  18498. a += shapesOffset;
  18499. b += shapesOffset;
  18500. c += shapesOffset;
  18501. // normal, color, material
  18502. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18503. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c )
  18504. : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18505. scope.faceVertexUvs[ 0 ].push( uvs );
  18506. }
  18507. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18508. a += shapesOffset;
  18509. b += shapesOffset;
  18510. c += shapesOffset;
  18511. d += shapesOffset;
  18512. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18513. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18514. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18515. scope.faceVertexUvs[ 0 ].push( uvs );
  18516. }
  18517. };
  18518. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18519. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18520. var ax = geometry.vertices[ indexA ].x,
  18521. ay = geometry.vertices[ indexA ].y,
  18522. bx = geometry.vertices[ indexB ].x,
  18523. by = geometry.vertices[ indexB ].y,
  18524. cx = geometry.vertices[ indexC ].x,
  18525. cy = geometry.vertices[ indexC ].y;
  18526. return [
  18527. new THREE.UV( ax, ay ),
  18528. new THREE.UV( bx, by ),
  18529. new THREE.UV( cx, cy )
  18530. ];
  18531. },
  18532. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18533. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18534. },
  18535. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18536. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18537. contourIndex1, contourIndex2 ) {
  18538. var ax = geometry.vertices[ indexA ].x,
  18539. ay = geometry.vertices[ indexA ].y,
  18540. az = geometry.vertices[ indexA ].z,
  18541. bx = geometry.vertices[ indexB ].x,
  18542. by = geometry.vertices[ indexB ].y,
  18543. bz = geometry.vertices[ indexB ].z,
  18544. cx = geometry.vertices[ indexC ].x,
  18545. cy = geometry.vertices[ indexC ].y,
  18546. cz = geometry.vertices[ indexC ].z,
  18547. dx = geometry.vertices[ indexD ].x,
  18548. dy = geometry.vertices[ indexD ].y,
  18549. dz = geometry.vertices[ indexD ].z;
  18550. if ( Math.abs( ay - by ) < 0.01 ) {
  18551. return [
  18552. new THREE.UV( ax, 1 - az ),
  18553. new THREE.UV( bx, 1 - bz ),
  18554. new THREE.UV( cx, 1 - cz ),
  18555. new THREE.UV( dx, 1 - dz )
  18556. ];
  18557. } else {
  18558. return [
  18559. new THREE.UV( ay, 1 - az ),
  18560. new THREE.UV( by, 1 - bz ),
  18561. new THREE.UV( cy, 1 - cz ),
  18562. new THREE.UV( dy, 1 - dz )
  18563. ];
  18564. }
  18565. }
  18566. };
  18567. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18568. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18569. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18570. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18571. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18572. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18573. /**
  18574. * @author astrodud / http://astrodud.isgreat.org/
  18575. * @author zz85 / https://github.com/zz85
  18576. */
  18577. THREE.LatheGeometry = function ( points, steps, angle ) {
  18578. THREE.Geometry.call( this );
  18579. var _steps = steps || 12;
  18580. var _angle = angle || 2 * Math.PI;
  18581. var _newV = [];
  18582. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  18583. for ( var j = 0; j < points.length; j ++ ) {
  18584. _newV[ j ] = points[ j ].clone();
  18585. this.vertices.push( _newV[ j ] );
  18586. }
  18587. var i, il = _steps + 1;
  18588. for ( i = 0; i < il; i ++ ) {
  18589. for ( var j = 0; j < _newV.length; j ++ ) {
  18590. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  18591. this.vertices.push( _newV[ j ] );
  18592. }
  18593. }
  18594. for ( i = 0; i < _steps; i ++ ) {
  18595. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  18596. var a = i * kl + k;
  18597. var b = ( ( i + 1 ) % il ) * kl + k;
  18598. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  18599. var d = i * kl + ( k + 1 ) % kl;
  18600. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18601. this.faceVertexUvs[ 0 ].push( [
  18602. new THREE.UV( 1 - i / _steps, k / kl ),
  18603. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  18604. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  18605. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  18606. ] );
  18607. }
  18608. }
  18609. this.computeCentroids();
  18610. this.computeFaceNormals();
  18611. this.computeVertexNormals();
  18612. };
  18613. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18614. /**
  18615. * @author mrdoob / http://mrdoob.com/
  18616. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18617. */
  18618. THREE.PlaneGeometry = function ( width, height, segmentsWidth, segmentsheight ) {
  18619. THREE.Geometry.call( this );
  18620. var ix, iz,
  18621. width_half = width / 2,
  18622. height_half = height / 2,
  18623. gridX = segmentsWidth || 1,
  18624. gridZ = segmentsheight || 1,
  18625. gridX1 = gridX + 1,
  18626. gridZ1 = gridZ + 1,
  18627. segment_width = width / gridX,
  18628. segment_height = height / gridZ,
  18629. normal = new THREE.Vector3( 0, 0, 1 );
  18630. for ( iz = 0; iz < gridZ1; iz ++ ) {
  18631. for ( ix = 0; ix < gridX1; ix ++ ) {
  18632. var x = ix * segment_width - width_half;
  18633. var y = iz * segment_height - height_half;
  18634. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  18635. }
  18636. }
  18637. for ( iz = 0; iz < gridZ; iz ++ ) {
  18638. for ( ix = 0; ix < gridX; ix ++ ) {
  18639. var a = ix + gridX1 * iz;
  18640. var b = ix + gridX1 * ( iz + 1 );
  18641. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  18642. var d = ( ix + 1 ) + gridX1 * iz;
  18643. var face = new THREE.Face4( a, b, c, d );
  18644. face.normal.copy( normal );
  18645. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18646. this.faces.push( face );
  18647. this.faceVertexUvs[ 0 ].push( [
  18648. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  18649. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  18650. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  18651. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  18652. ] );
  18653. }
  18654. }
  18655. this.computeCentroids();
  18656. };
  18657. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18658. /**
  18659. * @author mrdoob / http://mrdoob.com/
  18660. */
  18661. THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength ) {
  18662. THREE.Geometry.call( this );
  18663. radius = radius || 50;
  18664. phiStart = phiStart !== undefined ? phiStart : 0;
  18665. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18666. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18667. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18668. var segmentsX = Math.max( 3, Math.floor( segmentsWidth ) || 8 );
  18669. var segmentsY = Math.max( 2, Math.floor( segmentsHeight ) || 6 );
  18670. var x, y, vertices = [], uvs = [];
  18671. for ( y = 0; y <= segmentsY; y ++ ) {
  18672. var verticesRow = [];
  18673. var uvsRow = [];
  18674. for ( x = 0; x <= segmentsX; x ++ ) {
  18675. var u = x / segmentsX;
  18676. var v = y / segmentsY;
  18677. var vertex = new THREE.Vector3();
  18678. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18679. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  18680. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18681. this.vertices.push( vertex );
  18682. verticesRow.push( this.vertices.length - 1 );
  18683. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18684. }
  18685. vertices.push( verticesRow );
  18686. uvs.push( uvsRow );
  18687. }
  18688. for ( y = 0; y < segmentsY; y ++ ) {
  18689. for ( x = 0; x < segmentsX; x ++ ) {
  18690. var v1 = vertices[ y ][ x + 1 ];
  18691. var v2 = vertices[ y ][ x ];
  18692. var v3 = vertices[ y + 1 ][ x ];
  18693. var v4 = vertices[ y + 1 ][ x + 1 ];
  18694. var n1 = this.vertices[ v1 ].clone().normalize();
  18695. var n2 = this.vertices[ v2 ].clone().normalize();
  18696. var n3 = this.vertices[ v3 ].clone().normalize();
  18697. var n4 = this.vertices[ v4 ].clone().normalize();
  18698. var uv1 = uvs[ y ][ x + 1 ].clone();
  18699. var uv2 = uvs[ y ][ x ].clone();
  18700. var uv3 = uvs[ y + 1 ][ x ].clone();
  18701. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  18702. if ( Math.abs( this.vertices[ v1 ].y ) == radius ) {
  18703. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  18704. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  18705. } else if ( Math.abs( this.vertices[ v3 ].y ) == radius ) {
  18706. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18707. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18708. } else {
  18709. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18710. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18711. }
  18712. }
  18713. }
  18714. this.computeCentroids();
  18715. this.computeFaceNormals();
  18716. this.boundingSphere = { radius: radius };
  18717. };
  18718. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18719. /**
  18720. * @author zz85 / http://www.lab4games.net/zz85/blog
  18721. * @author alteredq / http://alteredqualia.com/
  18722. *
  18723. * For creating 3D text geometry in three.js
  18724. *
  18725. * Text = 3D Text
  18726. *
  18727. * parameters = {
  18728. * size: <float>, // size of the text
  18729. * height: <float>, // thickness to extrude text
  18730. * curveSegments: <int>, // number of points on the curves
  18731. *
  18732. * font: <string>, // font name
  18733. * weight: <string>, // font weight (normal, bold)
  18734. * style: <string>, // font style (normal, italics)
  18735. *
  18736. * bevelEnabled: <bool>, // turn on bevel
  18737. * bevelThickness: <float>, // how deep into text bevel goes
  18738. * bevelSize: <float>, // how far from text outline is bevel
  18739. *
  18740. * bend: <bool> // bend according to hardcoded curve (generates bendPath)
  18741. * bendPath: <curve> // wraps text according to bend Path
  18742. * }
  18743. *
  18744. */
  18745. /* Usage Examples
  18746. // TextGeometry wrapper
  18747. var text3d = new TextGeometry( text, options );
  18748. // Complete manner
  18749. var textShapes = THREE.FontUtils.generateShapes( text, options );
  18750. var text3d = new ExtrudeGeometry( textShapes, options );
  18751. */
  18752. THREE.TextGeometry = function ( text, parameters ) {
  18753. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  18754. // translate parameters to ExtrudeGeometry API
  18755. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  18756. // defaults
  18757. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18758. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18759. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18760. if ( parameters.bend ) {
  18761. var b = textShapes[ textShapes.length - 1 ].getBoundingBox();
  18762. var max = b.maxX;
  18763. parameters.bendPath = new THREE.QuadraticBezierCurve(
  18764. new THREE.Vector2( 0, 0 ),
  18765. new THREE.Vector2( max / 2, 120 ),
  18766. new THREE.Vector2( max, 0 )
  18767. );
  18768. }
  18769. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  18770. };
  18771. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  18772. /**
  18773. * @author oosmoxiecode
  18774. * @author mrdoob / http://mrdoob.com/
  18775. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  18776. */
  18777. THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {
  18778. THREE.Geometry.call( this );
  18779. var scope = this;
  18780. this.radius = radius || 100;
  18781. this.tube = tube || 40;
  18782. this.segmentsR = segmentsR || 8;
  18783. this.segmentsT = segmentsT || 6;
  18784. this.arc = arc || Math.PI * 2;
  18785. var center = new THREE.Vector3(), uvs = [], normals = [];
  18786. for ( var j = 0; j <= this.segmentsR; j ++ ) {
  18787. for ( var i = 0; i <= this.segmentsT; i ++ ) {
  18788. var u = i / this.segmentsT * this.arc;
  18789. var v = j / this.segmentsR * Math.PI * 2;
  18790. center.x = this.radius * Math.cos( u );
  18791. center.y = this.radius * Math.sin( u );
  18792. var vertex = new THREE.Vector3();
  18793. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  18794. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  18795. vertex.z = this.tube * Math.sin( v );
  18796. this.vertices.push( vertex );
  18797. uvs.push( new THREE.UV( i / this.segmentsT, j / this.segmentsR ) );
  18798. normals.push( vertex.clone().subSelf( center ).normalize() );
  18799. }
  18800. }
  18801. for ( var j = 1; j <= this.segmentsR; j ++ ) {
  18802. for ( var i = 1; i <= this.segmentsT; i ++ ) {
  18803. var a = ( this.segmentsT + 1 ) * j + i - 1;
  18804. var b = ( this.segmentsT + 1 ) * ( j - 1 ) + i - 1;
  18805. var c = ( this.segmentsT + 1 ) * ( j - 1 ) + i;
  18806. var d = ( this.segmentsT + 1 ) * j + i;
  18807. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  18808. face.normal.addSelf( normals[ a ] );
  18809. face.normal.addSelf( normals[ b ] );
  18810. face.normal.addSelf( normals[ c ] );
  18811. face.normal.addSelf( normals[ d ] );
  18812. face.normal.normalize();
  18813. this.faces.push( face );
  18814. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  18815. }
  18816. }
  18817. this.computeCentroids();
  18818. };
  18819. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18820. /**
  18821. * @author oosmoxiecode
  18822. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  18823. */
  18824. THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {
  18825. THREE.Geometry.call( this );
  18826. var scope = this;
  18827. this.radius = radius || 200;
  18828. this.tube = tube || 40;
  18829. this.segmentsR = segmentsR || 64;
  18830. this.segmentsT = segmentsT || 8;
  18831. this.p = p || 2;
  18832. this.q = q || 3;
  18833. this.heightScale = heightScale || 1;
  18834. this.grid = new Array(this.segmentsR);
  18835. var tang = new THREE.Vector3();
  18836. var n = new THREE.Vector3();
  18837. var bitan = new THREE.Vector3();
  18838. for ( var i = 0; i < this.segmentsR; ++ i ) {
  18839. this.grid[ i ] = new Array( this.segmentsT );
  18840. for ( var j = 0; j < this.segmentsT; ++ j ) {
  18841. var u = i / this.segmentsR * 2 * this.p * Math.PI;
  18842. var v = j / this.segmentsT * 2 * Math.PI;
  18843. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  18844. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  18845. var cx, cy;
  18846. tang.sub( p2, p1 );
  18847. n.add( p2, p1 );
  18848. bitan.cross( tang, n );
  18849. n.cross( bitan, tang );
  18850. bitan.normalize();
  18851. n.normalize();
  18852. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18853. cy = this.tube * Math.sin( v );
  18854. p1.x += cx * n.x + cy * bitan.x;
  18855. p1.y += cx * n.y + cy * bitan.y;
  18856. p1.z += cx * n.z + cy * bitan.z;
  18857. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  18858. }
  18859. }
  18860. for ( var i = 0; i < this.segmentsR; ++ i ) {
  18861. for ( var j = 0; j < this.segmentsT; ++ j ) {
  18862. var ip = ( i + 1 ) % this.segmentsR;
  18863. var jp = ( j + 1 ) % this.segmentsT;
  18864. var a = this.grid[ i ][ j ];
  18865. var b = this.grid[ ip ][ j ];
  18866. var c = this.grid[ ip ][ jp ];
  18867. var d = this.grid[ i ][ jp ];
  18868. var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
  18869. var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
  18870. var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
  18871. var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );
  18872. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18873. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  18874. }
  18875. }
  18876. this.computeCentroids();
  18877. this.computeFaceNormals();
  18878. this.computeVertexNormals();
  18879. function vert( x, y, z ) {
  18880. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18881. }
  18882. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  18883. var cu = Math.cos( u );
  18884. var cv = Math.cos( v );
  18885. var su = Math.sin( u );
  18886. var quOverP = in_q / in_p * u;
  18887. var cs = Math.cos( quOverP );
  18888. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  18889. var ty = radius * ( 2 + cs ) * su * 0.5;
  18890. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  18891. return new THREE.Vector3( tx, ty, tz );
  18892. }
  18893. };
  18894. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18895. /**
  18896. * @author WestLangley / https://github.com/WestLangley
  18897. * @author zz85 / https://github.com/zz85
  18898. * @author miningold / https://github.com/miningold
  18899. *
  18900. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18901. *
  18902. * Creates a tube which extrudes along a 3d spline
  18903. *
  18904. * Uses parallel transport frames as described in
  18905. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18906. */
  18907. THREE.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {
  18908. THREE.Geometry.call( this );
  18909. this.path = path;
  18910. this.segments = segments || 64;
  18911. this.radius = radius || 1;
  18912. this.segmentsRadius = segmentsRadius || 8;
  18913. this.closed = closed || false;
  18914. if ( debug ) this.debug = new THREE.Object3D();
  18915. this.grid = [];
  18916. var scope = this,
  18917. tangent,
  18918. normal,
  18919. binormal,
  18920. numpoints = this.segments + 1,
  18921. x, y, z,
  18922. tx, ty, tz,
  18923. u, v,
  18924. cx, cy,
  18925. pos, pos2 = new THREE.Vector3(),
  18926. i, j,
  18927. ip, jp,
  18928. a, b, c, d,
  18929. uva, uvb, uvc, uvd;
  18930. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  18931. tangents = frames.tangents,
  18932. normals = frames.normals,
  18933. binormals = frames.binormals;
  18934. // proxy internals
  18935. this.tangents = tangents;
  18936. this.normals = normals;
  18937. this.binormals = binormals;
  18938. function vert( x, y, z ) {
  18939. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18940. }
  18941. // consruct the grid
  18942. for ( i = 0; i < numpoints; i++ ) {
  18943. this.grid[ i ] = [];
  18944. u = i / ( numpoints - 1 );
  18945. pos = path.getPointAt( u );
  18946. tangent = tangents[ i ];
  18947. normal = normals[ i ];
  18948. binormal = binormals[ i ];
  18949. if ( this.debug ) {
  18950. this.debug.add(new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff));
  18951. this.debug.add(new THREE.ArrowHelper(normal, pos, radius, 0xff0000));
  18952. this.debug.add(new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00));
  18953. }
  18954. for ( j = 0; j < this.segmentsRadius; j++ ) {
  18955. v = j / this.segmentsRadius * 2 * Math.PI;
  18956. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18957. cy = this.radius * Math.sin( v );
  18958. pos2.copy( pos );
  18959. pos2.x += cx * normal.x + cy * binormal.x;
  18960. pos2.y += cx * normal.y + cy * binormal.y;
  18961. pos2.z += cx * normal.z + cy * binormal.z;
  18962. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18963. }
  18964. }
  18965. // construct the mesh
  18966. for ( i = 0; i < this.segments; i++ ) {
  18967. for ( j = 0; j < this.segmentsRadius; j++ ) {
  18968. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  18969. jp = (j + 1) % this.segmentsRadius;
  18970. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18971. b = this.grid[ ip ][ j ];
  18972. c = this.grid[ ip ][ jp ];
  18973. d = this.grid[ i ][ jp ];
  18974. uva = new THREE.UV( i / this.segments, j / this.segmentsRadius );
  18975. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.segmentsRadius );
  18976. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.segmentsRadius );
  18977. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.segmentsRadius );
  18978. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18979. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  18980. }
  18981. }
  18982. this.computeCentroids();
  18983. this.computeFaceNormals();
  18984. this.computeVertexNormals();
  18985. };
  18986. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18987. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  18988. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  18989. var
  18990. tangent = new THREE.Vector3(),
  18991. normal = new THREE.Vector3(),
  18992. binormal = new THREE.Vector3(),
  18993. tangents = [],
  18994. normals = [],
  18995. binormals = [],
  18996. vec = new THREE.Vector3(),
  18997. mat = new THREE.Matrix4(),
  18998. numpoints = segments + 1,
  18999. theta,
  19000. epsilon = 0.0001,
  19001. smallest,
  19002. tx, ty, tz,
  19003. i, u, v;
  19004. // expose internals
  19005. this.tangents = tangents;
  19006. this.normals = normals;
  19007. this.binormals = binormals;
  19008. // compute the tangent vectors for each segment on the path
  19009. for ( i = 0; i < numpoints; i++ ) {
  19010. u = i / ( numpoints - 1 );
  19011. tangents[ i ] = path.getTangentAt( u );
  19012. tangents[ i ].normalize();
  19013. }
  19014. initialNormal3();
  19015. function initialNormal1(lastBinormal) {
  19016. // fixed start binormal. Has dangers of 0 vectors
  19017. normals[ 0 ] = new THREE.Vector3();
  19018. binormals[ 0 ] = new THREE.Vector3();
  19019. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19020. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  19021. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19022. }
  19023. function initialNormal2() {
  19024. // This uses the Frenet-Serret formula for deriving binormal
  19025. var t2 = path.getTangentAt( epsilon );
  19026. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  19027. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  19028. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19029. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19030. }
  19031. function initialNormal3() {
  19032. // select an initial normal vector perpenicular to the first tangent vector,
  19033. // and in the direction of the smallest tangent xyz component
  19034. normals[ 0 ] = new THREE.Vector3();
  19035. binormals[ 0 ] = new THREE.Vector3();
  19036. smallest = Number.MAX_VALUE;
  19037. tx = Math.abs( tangents[ 0 ].x );
  19038. ty = Math.abs( tangents[ 0 ].y );
  19039. tz = Math.abs( tangents[ 0 ].z );
  19040. if ( tx <= smallest ) {
  19041. smallest = tx;
  19042. normal.set( 1, 0, 0 );
  19043. }
  19044. if ( ty <= smallest ) {
  19045. smallest = ty;
  19046. normal.set( 0, 1, 0 );
  19047. }
  19048. if ( tz <= smallest ) {
  19049. normal.set( 0, 0, 1 );
  19050. }
  19051. vec.cross( tangents[ 0 ], normal ).normalize();
  19052. normals[ 0 ].cross( tangents[ 0 ], vec );
  19053. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  19054. }
  19055. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19056. for ( i = 1; i < numpoints; i++ ) {
  19057. normals[ i ] = normals[ i-1 ].clone();
  19058. binormals[ i ] = binormals[ i-1 ].clone();
  19059. vec.cross( tangents[ i-1 ], tangents[ i ] );
  19060. if ( vec.length() > epsilon ) {
  19061. vec.normalize();
  19062. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19063. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  19064. }
  19065. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19066. }
  19067. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19068. if ( closed ) {
  19069. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19070. theta /= ( numpoints - 1 );
  19071. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19072. theta = -theta;
  19073. }
  19074. for ( i = 1; i < numpoints; i++ ) {
  19075. // twist a little...
  19076. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  19077. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19078. }
  19079. }
  19080. };
  19081. /**
  19082. * @author clockworkgeek / https://github.com/clockworkgeek
  19083. * @author timothypratley / https://github.com/timothypratley
  19084. */
  19085. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19086. THREE.Geometry.call( this );
  19087. radius = radius || 1;
  19088. detail = detail || 0;
  19089. var that = this;
  19090. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19091. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19092. }
  19093. var midpoints = [], p = this.vertices;
  19094. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19095. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19096. }
  19097. this.mergeVertices();
  19098. // Apply radius
  19099. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19100. this.vertices[ i ].multiplyScalar( radius );
  19101. }
  19102. // Project vector onto sphere's surface
  19103. function prepare( vector ) {
  19104. var vertex = vector.normalize().clone();
  19105. vertex.index = that.vertices.push( vertex ) - 1;
  19106. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19107. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19108. var v = inclination( vector ) / Math.PI + 0.5;
  19109. vertex.uv = new THREE.UV( u, 1 - v );
  19110. return vertex;
  19111. }
  19112. // Approximate a curved face with recursively sub-divided triangles.
  19113. function make( v1, v2, v3, detail ) {
  19114. if ( detail < 1 ) {
  19115. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19116. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  19117. face.normal = face.centroid.clone().normalize();
  19118. that.faces.push( face );
  19119. var azi = azimuth( face.centroid );
  19120. that.faceVertexUvs[ 0 ].push( [
  19121. correctUV( v1.uv, v1, azi ),
  19122. correctUV( v2.uv, v2, azi ),
  19123. correctUV( v3.uv, v3, azi )
  19124. ] );
  19125. } else {
  19126. detail -= 1;
  19127. // split triangle into 4 smaller triangles
  19128. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19129. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19130. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19131. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19132. }
  19133. }
  19134. function midpoint( v1, v2 ) {
  19135. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19136. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19137. var mid = midpoints[ v1.index ][ v2.index ];
  19138. if ( mid === undefined ) {
  19139. // generate mean point and project to surface with prepare()
  19140. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19141. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  19142. );
  19143. }
  19144. return mid;
  19145. }
  19146. // Angle around the Y axis, counter-clockwise when looking from above.
  19147. function azimuth( vector ) {
  19148. return Math.atan2( vector.z, -vector.x );
  19149. }
  19150. // Angle above the XZ plane.
  19151. function inclination( vector ) {
  19152. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19153. }
  19154. // Texture fixing helper. Spheres have some odd behaviours.
  19155. function correctUV( uv, vector, azimuth ) {
  19156. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  19157. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  19158. return uv;
  19159. }
  19160. this.computeCentroids();
  19161. this.boundingSphere = { radius: radius };
  19162. };
  19163. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19164. /**
  19165. * @author timothypratley / https://github.com/timothypratley
  19166. */
  19167. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19168. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19169. var vertices = [
  19170. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19171. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19172. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19173. ];
  19174. var faces = [
  19175. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19176. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19177. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19178. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19179. ];
  19180. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19181. };
  19182. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19183. /**
  19184. * @author timothypratley / https://github.com/timothypratley
  19185. */
  19186. THREE.OctahedronGeometry = function ( radius, detail ) {
  19187. var vertices = [
  19188. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19189. ];
  19190. var faces = [
  19191. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19192. ];
  19193. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19194. };
  19195. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19196. /**
  19197. * @author timothypratley / https://github.com/timothypratley
  19198. */
  19199. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19200. var vertices = [
  19201. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19202. ];
  19203. var faces = [
  19204. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19205. ];
  19206. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19207. };
  19208. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19209. /**
  19210. * @author zz85 / https://github.com/zz85
  19211. * Parametric Surfaces Geometry
  19212. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19213. *
  19214. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19215. *
  19216. */
  19217. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19218. THREE.Geometry.call( this );
  19219. var verts = this.vertices;
  19220. var faces = this.faces;
  19221. var uvs = this.faceVertexUvs[ 0 ];
  19222. useTris = (useTris === undefined) ? false : useTris;
  19223. var i, il, j, p;
  19224. var u, v;
  19225. var stackCount = stacks + 1;
  19226. var sliceCount = slices + 1;
  19227. for ( i = 0; i <= stacks; i ++ ) {
  19228. v = i / stacks;
  19229. for ( j = 0; j <= slices; j ++ ) {
  19230. u = j / slices;
  19231. p = func( u, v );
  19232. verts.push( p );
  19233. }
  19234. }
  19235. var a, b, c, d;
  19236. var uva, uvb, uvc, uvd;
  19237. for ( i = 0; i < stacks; i ++ ) {
  19238. for ( j = 0; j < slices; j ++ ) {
  19239. a = i * sliceCount + j;
  19240. b = i * sliceCount + j + 1;
  19241. c = (i + 1) * sliceCount + j;
  19242. d = (i + 1) * sliceCount + j + 1;
  19243. uva = new THREE.UV( j / slices, i / stacks );
  19244. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  19245. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  19246. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19247. if ( useTris ) {
  19248. faces.push( new THREE.Face3( a, b, c ) );
  19249. faces.push( new THREE.Face3( b, d, c ) );
  19250. uvs.push( [ uva, uvb, uvc ] );
  19251. uvs.push( [ uvb, uvd, uvc ] );
  19252. } else {
  19253. faces.push( new THREE.Face4( a, b, d, c ) );
  19254. uvs.push( [ uva, uvb, uvd, uvc ] );
  19255. }
  19256. }
  19257. }
  19258. // console.log(this);
  19259. // magic bullet
  19260. // var diff = this.mergeVertices();
  19261. // console.log('removed ', diff, ' vertices by merging');
  19262. this.computeCentroids();
  19263. this.computeFaceNormals();
  19264. this.computeVertexNormals();
  19265. };
  19266. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19267. /**
  19268. * @author qiao / https://github.com/qiao
  19269. * @fileoverview This is a convex hull generator using the incremental method.
  19270. * The complexity is O(n^2) where n is the number of vertices.
  19271. * O(nlogn) algorithms do exist, but they are much more complicated.
  19272. *
  19273. * Benchmark:
  19274. *
  19275. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19276. *
  19277. * Num Vertices Time(ms)
  19278. *
  19279. * 10 1
  19280. * 20 3
  19281. * 30 19
  19282. * 40 48
  19283. * 50 107
  19284. */
  19285. THREE.ConvexGeometry = function( vertices ) {
  19286. THREE.Geometry.call( this );
  19287. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19288. for ( var i = 3; i < vertices.length; i++ ) {
  19289. addPoint( i );
  19290. }
  19291. function addPoint( vertexId ) {
  19292. var vertex = vertices[ vertexId ].clone();
  19293. var mag = vertex.length();
  19294. vertex.x += mag * randomOffset();
  19295. vertex.y += mag * randomOffset();
  19296. vertex.z += mag * randomOffset();
  19297. var hole = [];
  19298. for ( var f = 0; f < faces.length; ) {
  19299. var face = faces[ f ];
  19300. // for each face, if the vertex can see it,
  19301. // then we try to add the face's edges into the hole.
  19302. if ( visible( face, vertex ) ) {
  19303. for ( var e = 0; e < 3; e++ ) {
  19304. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19305. var boundary = true;
  19306. // remove duplicated edges.
  19307. for ( var h = 0; h < hole.length; h++ ) {
  19308. if ( equalEdge( hole[ h ], edge ) ) {
  19309. hole[ h ] = hole[ hole.length - 1 ];
  19310. hole.pop();
  19311. boundary = false;
  19312. break;
  19313. }
  19314. }
  19315. if ( boundary ) {
  19316. hole.push( edge );
  19317. }
  19318. }
  19319. // remove faces[ f ]
  19320. faces[ f ] = faces[ faces.length - 1 ];
  19321. faces.pop();
  19322. } else { // not visible
  19323. f++;
  19324. }
  19325. }
  19326. // construct the new faces formed by the edges of the hole and the vertex
  19327. for ( var h = 0; h < hole.length; h++ ) {
  19328. faces.push( [
  19329. hole[ h ][ 0 ],
  19330. hole[ h ][ 1 ],
  19331. vertexId
  19332. ] );
  19333. }
  19334. }
  19335. /**
  19336. * Whether the face is visible from the vertex
  19337. */
  19338. function visible( face, vertex ) {
  19339. var va = vertices[ face[ 0 ] ];
  19340. var vb = vertices[ face[ 1 ] ];
  19341. var vc = vertices[ face[ 2 ] ];
  19342. var n = normal( va, vb, vc );
  19343. // distance from face to origin
  19344. var dist = n.dot( va );
  19345. return n.dot( vertex ) >= dist;
  19346. }
  19347. /**
  19348. * Face normal
  19349. */
  19350. function normal( va, vb, vc ) {
  19351. var cb = new THREE.Vector3();
  19352. var ab = new THREE.Vector3();
  19353. cb.sub( vc, vb );
  19354. ab.sub( va, vb );
  19355. cb.crossSelf( ab );
  19356. if ( !cb.isZero() ) {
  19357. cb.normalize();
  19358. }
  19359. return cb;
  19360. }
  19361. /**
  19362. * Detect whether two edges are equal.
  19363. * Note that when constructing the convex hull, two same edges can only
  19364. * be of the negative direction.
  19365. */
  19366. function equalEdge( ea, eb ) {
  19367. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19368. }
  19369. /**
  19370. * Create a random offset between -1e-6 and 1e-6.
  19371. */
  19372. function randomOffset() {
  19373. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19374. }
  19375. /**
  19376. * XXX: Not sure if this is the correct approach. Need someone to review.
  19377. */
  19378. function vertexUv( vertex ) {
  19379. var mag = vertex.length();
  19380. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  19381. }
  19382. // Push vertices into `this.vertices`, skipping those inside the hull
  19383. var id = 0;
  19384. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19385. for ( var i = 0; i < faces.length; i++ ) {
  19386. var face = faces[ i ];
  19387. for ( var j = 0; j < 3; j++ ) {
  19388. if ( newId[ face[ j ] ] === undefined ) {
  19389. newId[ face[ j ] ] = id++;
  19390. this.vertices.push( vertices[ face[ j ] ] );
  19391. }
  19392. face[ j ] = newId[ face[ j ] ];
  19393. }
  19394. }
  19395. // Convert faces into instances of THREE.Face3
  19396. for ( var i = 0; i < faces.length; i++ ) {
  19397. this.faces.push( new THREE.Face3(
  19398. faces[ i ][ 0 ],
  19399. faces[ i ][ 1 ],
  19400. faces[ i ][ 2 ]
  19401. ) );
  19402. }
  19403. // Compute UVs
  19404. for ( var i = 0; i < this.faces.length; i++ ) {
  19405. var face = this.faces[ i ];
  19406. this.faceVertexUvs[ 0 ].push( [
  19407. vertexUv( this.vertices[ face.a ] ),
  19408. vertexUv( this.vertices[ face.b ] ),
  19409. vertexUv( this.vertices[ face.c ])
  19410. ] );
  19411. }
  19412. this.computeCentroids();
  19413. this.computeFaceNormals();
  19414. this.computeVertexNormals();
  19415. };
  19416. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19417. /**
  19418. * @author sroucheray / http://sroucheray.org/
  19419. * @author mrdoob / http://mrdoob.com/
  19420. */
  19421. THREE.AxisHelper = function () {
  19422. THREE.Object3D.call( this );
  19423. var lineGeometry = new THREE.Geometry();
  19424. lineGeometry.vertices.push( new THREE.Vector3() );
  19425. lineGeometry.vertices.push( new THREE.Vector3( 0, 100, 0 ) );
  19426. var coneGeometry = new THREE.CylinderGeometry( 0, 5, 25, 5, 1 );
  19427. var line, cone;
  19428. // x
  19429. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
  19430. line.rotation.z = - Math.PI / 2;
  19431. this.add( line );
  19432. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0xff0000 } ) );
  19433. cone.position.x = 100;
  19434. cone.rotation.z = - Math.PI / 2;
  19435. this.add( cone );
  19436. // y
  19437. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x00ff00 } ) );
  19438. this.add( line );
  19439. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x00ff00 } ) );
  19440. cone.position.y = 100;
  19441. this.add( cone );
  19442. // z
  19443. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
  19444. line.rotation.x = Math.PI / 2;
  19445. this.add( line );
  19446. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x0000ff } ) );
  19447. cone.position.z = 100;
  19448. cone.rotation.x = Math.PI / 2;
  19449. this.add( cone );
  19450. };
  19451. THREE.AxisHelper.prototype = Object.create( THREE.Object3D.prototype );
  19452. /**
  19453. * @author WestLangley / http://github.com/WestLangley
  19454. * @author zz85 / https://github.com/zz85
  19455. *
  19456. * Creates an arrow for visualizing directions
  19457. *
  19458. * Parameters:
  19459. * dir - Vector3
  19460. * origin - Vector3
  19461. * length - Number
  19462. * hex - color in hex value
  19463. */
  19464. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19465. THREE.Object3D.call( this );
  19466. if ( hex === undefined ) hex = 0xffff00;
  19467. if ( length === undefined ) length = 20;
  19468. var lineGeometry = new THREE.Geometry();
  19469. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19470. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19471. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19472. this.add( this.line );
  19473. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19474. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19475. this.cone.position.set( 0, 1, 0 );
  19476. this.add( this.cone );
  19477. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19478. this.setDirection( dir );
  19479. this.setLength( length );
  19480. };
  19481. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19482. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19483. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  19484. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  19485. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  19486. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  19487. };
  19488. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19489. this.scale.set( length, length, length );
  19490. };
  19491. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19492. this.line.material.color.setHex( hex );
  19493. this.cone.material.color.setHex( hex );
  19494. };
  19495. /**
  19496. * @author alteredq / http://alteredqualia.com/
  19497. *
  19498. * - shows frustum, line of sight and up of the camera
  19499. * - suitable for fast updates
  19500. * - based on frustum visualization in lightgl.js shadowmap example
  19501. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19502. */
  19503. THREE.CameraHelper = function ( camera ) {
  19504. THREE.Object3D.call( this );
  19505. var _this = this;
  19506. this.lineGeometry = new THREE.Geometry();
  19507. this.lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19508. this.pointMap = {};
  19509. // colors
  19510. var hexFrustum = 0xffaa00,
  19511. hexCone = 0xff0000,
  19512. hexUp = 0x00aaff,
  19513. hexTarget = 0xffffff,
  19514. hexCross = 0x333333;
  19515. // near
  19516. addLine( "n1", "n2", hexFrustum );
  19517. addLine( "n2", "n4", hexFrustum );
  19518. addLine( "n4", "n3", hexFrustum );
  19519. addLine( "n3", "n1", hexFrustum );
  19520. // far
  19521. addLine( "f1", "f2", hexFrustum );
  19522. addLine( "f2", "f4", hexFrustum );
  19523. addLine( "f4", "f3", hexFrustum );
  19524. addLine( "f3", "f1", hexFrustum );
  19525. // sides
  19526. addLine( "n1", "f1", hexFrustum );
  19527. addLine( "n2", "f2", hexFrustum );
  19528. addLine( "n3", "f3", hexFrustum );
  19529. addLine( "n4", "f4", hexFrustum );
  19530. // cone
  19531. addLine( "p", "n1", hexCone );
  19532. addLine( "p", "n2", hexCone );
  19533. addLine( "p", "n3", hexCone );
  19534. addLine( "p", "n4", hexCone );
  19535. // up
  19536. addLine( "u1", "u2", hexUp );
  19537. addLine( "u2", "u3", hexUp );
  19538. addLine( "u3", "u1", hexUp );
  19539. // target
  19540. addLine( "c", "t", hexTarget );
  19541. addLine( "p", "c", hexCross );
  19542. // cross
  19543. addLine( "cn1", "cn2", hexCross );
  19544. addLine( "cn3", "cn4", hexCross );
  19545. addLine( "cf1", "cf2", hexCross );
  19546. addLine( "cf3", "cf4", hexCross );
  19547. this.camera = camera;
  19548. function addLine( a, b, hex ) {
  19549. addPoint( a, hex );
  19550. addPoint( b, hex );
  19551. }
  19552. function addPoint( id, hex ) {
  19553. _this.lineGeometry.vertices.push( new THREE.Vector3() );
  19554. _this.lineGeometry.colors.push( new THREE.Color( hex ) );
  19555. if ( _this.pointMap[ id ] === undefined ) _this.pointMap[ id ] = [];
  19556. _this.pointMap[ id ].push( _this.lineGeometry.vertices.length - 1 );
  19557. }
  19558. this.update( camera );
  19559. this.lines = new THREE.Line( this.lineGeometry, this.lineMaterial, THREE.LinePieces );
  19560. this.add( this.lines );
  19561. };
  19562. THREE.CameraHelper.prototype = Object.create( THREE.Object3D.prototype );
  19563. THREE.CameraHelper.prototype.update = function () {
  19564. var camera = this.camera;
  19565. var w = 1;
  19566. var h = 1;
  19567. var _this = this;
  19568. // we need just camera projection matrix
  19569. // world matrix must be identity
  19570. THREE.CameraHelper.__c.projectionMatrix.copy( camera.projectionMatrix );
  19571. // center / target
  19572. setPoint( "c", 0, 0, -1 );
  19573. setPoint( "t", 0, 0, 1 );
  19574. // near
  19575. setPoint( "n1", -w, -h, -1 );
  19576. setPoint( "n2", w, -h, -1 );
  19577. setPoint( "n3", -w, h, -1 );
  19578. setPoint( "n4", w, h, -1 );
  19579. // far
  19580. setPoint( "f1", -w, -h, 1 );
  19581. setPoint( "f2", w, -h, 1 );
  19582. setPoint( "f3", -w, h, 1 );
  19583. setPoint( "f4", w, h, 1 );
  19584. // up
  19585. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19586. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19587. setPoint( "u3", 0, h * 2, -1 );
  19588. // cross
  19589. setPoint( "cf1", -w, 0, 1 );
  19590. setPoint( "cf2", w, 0, 1 );
  19591. setPoint( "cf3", 0, -h, 1 );
  19592. setPoint( "cf4", 0, h, 1 );
  19593. setPoint( "cn1", -w, 0, -1 );
  19594. setPoint( "cn2", w, 0, -1 );
  19595. setPoint( "cn3", 0, -h, -1 );
  19596. setPoint( "cn4", 0, h, -1 );
  19597. function setPoint( point, x, y, z ) {
  19598. THREE.CameraHelper.__v.set( x, y, z );
  19599. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19600. var points = _this.pointMap[ point ];
  19601. if ( points !== undefined ) {
  19602. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19603. var j = points[ i ];
  19604. _this.lineGeometry.vertices[ j ].copy( THREE.CameraHelper.__v );
  19605. }
  19606. }
  19607. }
  19608. this.lineGeometry.verticesNeedUpdate = true;
  19609. };
  19610. THREE.CameraHelper.__projector = new THREE.Projector();
  19611. THREE.CameraHelper.__v = new THREE.Vector3();
  19612. THREE.CameraHelper.__c = new THREE.Camera();
  19613. /*
  19614. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19615. *
  19616. * Subdivision Geometry Modifier
  19617. * using Catmull-Clark Subdivision Surfaces
  19618. * for creating smooth geometry meshes
  19619. *
  19620. * Note: a modifier modifies vertices and faces of geometry,
  19621. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  19622. *
  19623. * Readings:
  19624. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19625. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  19626. * http://xrt.wikidot.com/blog:31
  19627. * "Subdivision Surfaces in Character Animation"
  19628. *
  19629. * Supports:
  19630. * Closed and Open geometries.
  19631. *
  19632. * TODO:
  19633. * crease vertex and "semi-sharp" features
  19634. * selective subdivision
  19635. */
  19636. THREE.SubdivisionModifier = function( subdivisions ) {
  19637. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  19638. // Settings
  19639. this.useOldVertexColors = false;
  19640. this.supportUVs = true;
  19641. this.debug = false;
  19642. };
  19643. // Applies the "modify" pattern
  19644. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  19645. var repeats = this.subdivisions;
  19646. while ( repeats-- > 0 ) {
  19647. this.smooth( geometry );
  19648. }
  19649. };
  19650. // Performs an iteration of Catmull-Clark Subdivision
  19651. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  19652. //debug( 'running smooth' );
  19653. // New set of vertices, faces and uvs
  19654. var newVertices = [], newFaces = [], newUVs = [];
  19655. function v( x, y, z ) {
  19656. newVertices.push( new THREE.Vector3( x, y, z ) );
  19657. }
  19658. var scope = this;
  19659. function debug() {
  19660. if (scope.debug) console.log.apply(console, arguments);
  19661. }
  19662. function warn() {
  19663. if (console)
  19664. console.log.apply(console, arguments);
  19665. }
  19666. function f4( a, b, c, d, oldFace, orders, facei ) {
  19667. // TODO move vertex selection over here!
  19668. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  19669. if (scope.useOldVertexColors) {
  19670. newFace.vertexColors = [];
  19671. var color, tmpColor, order;
  19672. for (var i=0;i<4;i++) {
  19673. order = orders[i];
  19674. color = new THREE.Color(),
  19675. color.setRGB(0,0,0);
  19676. for (var j=0, jl=0; j<order.length;j++) {
  19677. tmpColor = oldFace.vertexColors[order[j]-1];
  19678. color.r += tmpColor.r;
  19679. color.g += tmpColor.g;
  19680. color.b += tmpColor.b;
  19681. }
  19682. color.r /= order.length;
  19683. color.g /= order.length;
  19684. color.b /= order.length;
  19685. newFace.vertexColors[i] = color;
  19686. }
  19687. }
  19688. newFaces.push( newFace );
  19689. if (scope.supportUVs) {
  19690. var aUv = [
  19691. getUV(a, ''),
  19692. getUV(b, facei),
  19693. getUV(c, facei),
  19694. getUV(d, facei)
  19695. ];
  19696. if (!aUv[0]) debug('a :( ', a+':'+facei);
  19697. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  19698. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  19699. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  19700. else
  19701. newUVs.push( aUv );
  19702. }
  19703. }
  19704. function edge_hash( a, b ) {
  19705. return Math.min( a, b ) + "_" + Math.max( a, b );
  19706. }
  19707. function computeEdgeFaces( geometry ) {
  19708. var i, il, v1, v2, j, k,
  19709. face, faceIndices, faceIndex,
  19710. edge,
  19711. hash,
  19712. edgeFaceMap = {};
  19713. function mapEdgeHash( hash, i ) {
  19714. if ( edgeFaceMap[ hash ] === undefined ) {
  19715. edgeFaceMap[ hash ] = [];
  19716. }
  19717. edgeFaceMap[ hash ].push( i );
  19718. }
  19719. // construct vertex -> face map
  19720. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  19721. face = geometry.faces[ i ];
  19722. if ( face instanceof THREE.Face3 ) {
  19723. hash = edge_hash( face.a, face.b );
  19724. mapEdgeHash( hash, i );
  19725. hash = edge_hash( face.b, face.c );
  19726. mapEdgeHash( hash, i );
  19727. hash = edge_hash( face.c, face.a );
  19728. mapEdgeHash( hash, i );
  19729. } else if ( face instanceof THREE.Face4 ) {
  19730. hash = edge_hash( face.a, face.b );
  19731. mapEdgeHash( hash, i );
  19732. hash = edge_hash( face.b, face.c );
  19733. mapEdgeHash( hash, i );
  19734. hash = edge_hash( face.c, face.d );
  19735. mapEdgeHash( hash, i );
  19736. hash = edge_hash( face.d, face.a );
  19737. mapEdgeHash( hash, i );
  19738. }
  19739. }
  19740. // extract faces
  19741. // var edges = [];
  19742. //
  19743. // var numOfEdges = 0;
  19744. // for (i in edgeFaceMap) {
  19745. // numOfEdges++;
  19746. //
  19747. // edge = edgeFaceMap[i];
  19748. // edges.push(edge);
  19749. //
  19750. // }
  19751. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  19752. return edgeFaceMap;
  19753. }
  19754. var originalPoints = oldGeometry.vertices;
  19755. var originalFaces = oldGeometry.faces;
  19756. var newPoints = originalPoints.concat(); // Vertices
  19757. var facePoints = [], edgePoints = {};
  19758. var sharpEdges = {}, sharpVertices = [], sharpFaces = [];
  19759. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  19760. var originalVerticesLength = originalPoints.length;
  19761. function getUV(vertexNo, oldFaceNo) {
  19762. var j,jl;
  19763. var key = vertexNo+':'+oldFaceNo;
  19764. var theUV = uvForVertices[key];
  19765. if (!theUV) {
  19766. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  19767. debug('face pt');
  19768. } else {
  19769. debug('edge pt');
  19770. }
  19771. warn('warning, UV not found for', key);
  19772. return null;
  19773. }
  19774. return theUV;
  19775. // Original faces -> Vertex Nos.
  19776. // new Facepoint -> Vertex Nos.
  19777. // edge Points
  19778. }
  19779. function addUV(vertexNo, oldFaceNo, value) {
  19780. var key = vertexNo+':'+oldFaceNo;
  19781. if (!(key in uvForVertices)) {
  19782. uvForVertices[key] = value;
  19783. } else {
  19784. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  19785. }
  19786. }
  19787. // Step 1
  19788. // For each face, add a face point
  19789. // Set each face point to be the centroid of all original points for the respective face.
  19790. // debug(oldGeometry);
  19791. var i, il, j, jl, face;
  19792. // For Uvs
  19793. var uvs = oldGeometry.faceVertexUvs[0];
  19794. var abcd = 'abcd', vertice;
  19795. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  19796. if (scope.supportUVs)
  19797. for (i=0, il = uvs.length; i<il; i++ ) {
  19798. for (j=0,jl=uvs[i].length;j<jl;j++) {
  19799. vertice = originalFaces[i][abcd.charAt(j)];
  19800. addUV(vertice, i, uvs[i][j]);
  19801. }
  19802. }
  19803. if (uvs.length == 0) scope.supportUVs = false;
  19804. // Additional UVs check, if we index original
  19805. var uvCount = 0;
  19806. for (var u in uvForVertices) {
  19807. uvCount++;
  19808. }
  19809. if (!uvCount) {
  19810. scope.supportUVs = false;
  19811. debug('no uvs');
  19812. }
  19813. debug('-- Original Faces + Vertices UVs completed', uvForVertices, 'vs', uvs.length);
  19814. var avgUv ;
  19815. for (i=0, il = originalFaces.length; i<il ;i++) {
  19816. face = originalFaces[ i ];
  19817. facePoints.push( face.centroid );
  19818. newPoints.push( face.centroid );
  19819. if (!scope.supportUVs) continue;
  19820. // Prepare subdivided uv
  19821. avgUv = new THREE.UV();
  19822. if ( face instanceof THREE.Face3 ) {
  19823. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  19824. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  19825. avgUv.u /= 3;
  19826. avgUv.v /= 3;
  19827. } else if ( face instanceof THREE.Face4 ) {
  19828. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  19829. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  19830. avgUv.u /= 4;
  19831. avgUv.v /= 4;
  19832. }
  19833. addUV(originalVerticesLength + i, '', avgUv);
  19834. }
  19835. debug('-- added UVs for new Faces', uvForVertices);
  19836. // Step 2
  19837. // For each edge, add an edge point.
  19838. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  19839. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index
  19840. var edge, faceIndexA, faceIndexB, avg;
  19841. // debug('edgeFaceMap', edgeFaceMap);
  19842. var edgeCount = 0;
  19843. var edgeVertex, edgeVertexA, edgeVertexB;
  19844. ////
  19845. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  19846. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  19847. function addVertexEdgeMap(vertex, edge) {
  19848. if (vertexEdgeMap[vertex]===undefined) {
  19849. vertexEdgeMap[vertex] = [];
  19850. }
  19851. vertexEdgeMap[vertex].push(edge);
  19852. }
  19853. function addVertexFaceMap(vertex, face, edge) {
  19854. if (vertexFaceMap[vertex]===undefined) {
  19855. vertexFaceMap[vertex] = {};
  19856. }
  19857. vertexFaceMap[vertex][face] = edge;
  19858. // vertexFaceMap[vertex][face] = null;
  19859. }
  19860. // Prepares vertexEdgeMap and vertexFaceMap
  19861. for (i in edgeFaceMap) { // This is for every edge
  19862. edge = edgeFaceMap[i];
  19863. edgeVertex = i.split('_');
  19864. edgeVertexA = edgeVertex[0];
  19865. edgeVertexB = edgeVertex[1];
  19866. // Maps an edgeVertex to connecting edges
  19867. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  19868. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  19869. for (j=0,jl=edge.length;j<jl;j++) {
  19870. face = edge[j];
  19871. addVertexFaceMap(edgeVertexA, face, i);
  19872. addVertexFaceMap(edgeVertexB, face, i);
  19873. }
  19874. if (edge.length < 2) {
  19875. // edge is "sharp";
  19876. sharpEdges[i] = true;
  19877. sharpVertices[edgeVertexA] = true;
  19878. sharpVertices[edgeVertexB] = true;
  19879. }
  19880. }
  19881. debug('vertexEdgeMap',vertexEdgeMap, 'vertexFaceMap', vertexFaceMap);
  19882. for (i in edgeFaceMap) {
  19883. edge = edgeFaceMap[i];
  19884. faceIndexA = edge[0]; // face index a
  19885. faceIndexB = edge[1]; // face index b
  19886. edgeVertex = i.split('_');
  19887. edgeVertexA = edgeVertex[0];
  19888. edgeVertexB = edgeVertex[1];
  19889. avg = new THREE.Vector3();
  19890. //debug(i, faceIndexB,facePoints[faceIndexB]);
  19891. if (sharpEdges[i]) {
  19892. //debug('warning, ', i, 'edge has only 1 connecting face', edge);
  19893. // For a sharp edge, average the edge end points.
  19894. avg.addSelf(originalPoints[edgeVertexA]);
  19895. avg.addSelf(originalPoints[edgeVertexB]);
  19896. avg.multiplyScalar(0.5);
  19897. sharpVertices[newPoints.length] = true;
  19898. } else {
  19899. avg.addSelf(facePoints[faceIndexA]);
  19900. avg.addSelf(facePoints[faceIndexB]);
  19901. avg.addSelf(originalPoints[edgeVertexA]);
  19902. avg.addSelf(originalPoints[edgeVertexB]);
  19903. avg.multiplyScalar(0.25);
  19904. }
  19905. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  19906. newPoints.push( avg );
  19907. edgeCount ++;
  19908. if (!scope.supportUVs) {
  19909. continue;
  19910. }
  19911. // debug('faceIndexAB', faceIndexA, faceIndexB, sharpEdges[i]);
  19912. // Prepare subdivided uv
  19913. avgUv = new THREE.UV();
  19914. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  19915. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  19916. avgUv.u /= 2;
  19917. avgUv.v /= 2;
  19918. addUV(edgePoints[i], faceIndexA, avgUv);
  19919. if (!sharpEdges[i]) {
  19920. avgUv = new THREE.UV();
  19921. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  19922. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  19923. avgUv.u /= 2;
  19924. avgUv.v /= 2;
  19925. addUV(edgePoints[i], faceIndexB, avgUv);
  19926. }
  19927. }
  19928. debug('-- Step 2 done');
  19929. // Step 3
  19930. // For each face point, add an edge for every edge of the face,
  19931. // connecting the face point to each edge point for the face.
  19932. var facePt, currentVerticeIndex;
  19933. var hashAB, hashBC, hashCD, hashDA, hashCA;
  19934. var abc123 = ['123', '12', '2', '23'];
  19935. var bca123 = ['123', '23', '3', '31'];
  19936. var cab123 = ['123', '31', '1', '12'];
  19937. var abc1234 = ['1234', '12', '2', '23'];
  19938. var bcd1234 = ['1234', '23', '3', '34'];
  19939. var cda1234 = ['1234', '34', '4', '41'];
  19940. var dab1234 = ['1234', '41', '1', '12'];
  19941. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  19942. facePt = facePoints[i];
  19943. face = originalFaces[i];
  19944. currentVerticeIndex = originalVerticesLength+ i;
  19945. if ( face instanceof THREE.Face3 ) {
  19946. // create 3 face4s
  19947. hashAB = edge_hash( face.a, face.b );
  19948. hashBC = edge_hash( face.b, face.c );
  19949. hashCA = edge_hash( face.c, face.a );
  19950. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  19951. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  19952. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  19953. } else if ( face instanceof THREE.Face4 ) {
  19954. // create 4 face4s
  19955. hashAB = edge_hash( face.a, face.b );
  19956. hashBC = edge_hash( face.b, face.c );
  19957. hashCD = edge_hash( face.c, face.d );
  19958. hashDA = edge_hash( face.d, face.a );
  19959. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  19960. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  19961. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  19962. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  19963. } else {
  19964. debug('face should be a face!', face);
  19965. }
  19966. }
  19967. newVertices = newPoints;
  19968. // debug('original ', oldGeometry.vertices.length, oldGeometry.faces.length );
  19969. // debug('new points', newPoints.length, 'faces', newFaces.length );
  19970. // Step 4
  19971. // For each original point P,
  19972. // take the average F of all n face points for faces touching P,
  19973. // and take the average R of all n edge midpoints for edges touching P,
  19974. // where each edge midpoint is the average of its two endpoint vertices.
  19975. // Move each original point to the point
  19976. var F = new THREE.Vector3();
  19977. var R = new THREE.Vector3();
  19978. var n;
  19979. for (i=0, il = originalPoints.length; i<il; i++) {
  19980. // (F + 2R + (n-3)P) / n
  19981. if (vertexEdgeMap[i]===undefined) continue;
  19982. F.set(0,0,0);
  19983. R.set(0,0,0);
  19984. var newPos = new THREE.Vector3(0,0,0);
  19985. var f =0;
  19986. for (j in vertexFaceMap[i]) {
  19987. F.addSelf(facePoints[j]);
  19988. f++;
  19989. }
  19990. var sharpEdgeCount = 0;
  19991. n = vertexEdgeMap[i].length;
  19992. for (j=0;j<n;j++) {
  19993. if (
  19994. sharpEdges[
  19995. edge_hash(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  19996. ]) {
  19997. sharpEdgeCount++;
  19998. }
  19999. }
  20000. if ( sharpEdgeCount==2 ) {
  20001. continue;
  20002. // Do not move vertex if there's 2 connecting sharp edges.
  20003. }
  20004. /*
  20005. if (sharpEdgeCount>2) {
  20006. // TODO
  20007. }
  20008. */
  20009. F.divideScalar(f);
  20010. for (j=0; j<n;j++) {
  20011. edge = vertexEdgeMap[i][j];
  20012. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20013. R.addSelf(midPt);
  20014. // R.addSelf(originalPoints[edge[0]]);
  20015. // R.addSelf(originalPoints[edge[1]]);
  20016. }
  20017. R.divideScalar(n);
  20018. newPos.addSelf(originalPoints[i]);
  20019. newPos.multiplyScalar(n - 3);
  20020. newPos.addSelf(F);
  20021. newPos.addSelf(R.multiplyScalar(2));
  20022. newPos.divideScalar(n);
  20023. newVertices[i] = newPos;
  20024. }
  20025. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  20026. newGeometry.vertices = newVertices;
  20027. newGeometry.faces = newFaces;
  20028. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  20029. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  20030. newGeometry.computeCentroids();
  20031. newGeometry.computeFaceNormals();
  20032. newGeometry.computeVertexNormals();
  20033. };
  20034. /**
  20035. * @author alteredq / http://alteredqualia.com/
  20036. */
  20037. THREE.ImmediateRenderObject = function ( ) {
  20038. THREE.Object3D.call( this );
  20039. this.render = function ( renderCallback ) { };
  20040. };
  20041. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20042. /**
  20043. * @author mikael emtinger / http://gomo.se/
  20044. * @author alteredq / http://alteredqualia.com/
  20045. */
  20046. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20047. THREE.Object3D.call( this );
  20048. this.lensFlares = [];
  20049. this.positionScreen = new THREE.Vector3();
  20050. this.customUpdateCallback = undefined;
  20051. if( texture !== undefined ) {
  20052. this.add( texture, size, distance, blending, color );
  20053. }
  20054. };
  20055. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20056. /*
  20057. * Add: adds another flare
  20058. */
  20059. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20060. if( size === undefined ) size = -1;
  20061. if( distance === undefined ) distance = 0;
  20062. if( opacity === undefined ) opacity = 1;
  20063. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20064. if( blending === undefined ) blending = THREE.NormalBlending;
  20065. distance = Math.min( distance, Math.max( 0, distance ) );
  20066. this.lensFlares.push( { texture: texture, // THREE.Texture
  20067. size: size, // size in pixels (-1 = use texture.width)
  20068. distance: distance, // distance (0-1) from light source (0=at light source)
  20069. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20070. scale: 1, // scale
  20071. rotation: 1, // rotation
  20072. opacity: opacity, // opacity
  20073. color: color, // color
  20074. blending: blending } ); // blending
  20075. };
  20076. /*
  20077. * Update lens flares update positions on all flares based on the screen position
  20078. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20079. */
  20080. THREE.LensFlare.prototype.updateLensFlares = function () {
  20081. var f, fl = this.lensFlares.length;
  20082. var flare;
  20083. var vecX = -this.positionScreen.x * 2;
  20084. var vecY = -this.positionScreen.y * 2;
  20085. for( f = 0; f < fl; f ++ ) {
  20086. flare = this.lensFlares[ f ];
  20087. flare.x = this.positionScreen.x + vecX * flare.distance;
  20088. flare.y = this.positionScreen.y + vecY * flare.distance;
  20089. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20090. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20091. }
  20092. };
  20093. /**
  20094. * @author alteredq / http://alteredqualia.com/
  20095. */
  20096. THREE.MorphBlendMesh = function( geometry, material ) {
  20097. THREE.Mesh.call( this, geometry, material );
  20098. this.animationsMap = {};
  20099. this.animationsList = [];
  20100. // prepare default animation
  20101. // (all frames played together in 1 second)
  20102. var numFrames = this.geometry.morphTargets.length;
  20103. var name = "__default";
  20104. var startFrame = 0;
  20105. var endFrame = numFrames - 1;
  20106. var fps = numFrames / 1;
  20107. this.createAnimation( name, startFrame, endFrame, fps );
  20108. this.setAnimationWeight( name, 1 );
  20109. };
  20110. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20111. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20112. var animation = {
  20113. startFrame: start,
  20114. endFrame: end,
  20115. length: end - start + 1,
  20116. fps: fps,
  20117. duration: ( end - start ) / fps,
  20118. lastFrame: 0,
  20119. currentFrame: 0,
  20120. active: false,
  20121. time: 0,
  20122. direction: 1,
  20123. weight: 1,
  20124. directionBackwards: false,
  20125. mirroredLoop: false
  20126. };
  20127. this.animationsMap[ name ] = animation;
  20128. this.animationsList.push( animation );
  20129. };
  20130. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20131. var pattern = /([a-z]+)(\d+)/;
  20132. var firstAnimation, frameRanges = {};
  20133. var geometry = this.geometry;
  20134. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20135. var morph = geometry.morphTargets[ i ];
  20136. var chunks = morph.name.match( pattern );
  20137. if ( chunks && chunks.length > 1 ) {
  20138. var name = chunks[ 1 ];
  20139. var num = chunks[ 2 ];
  20140. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20141. var range = frameRanges[ name ];
  20142. if ( i < range.start ) range.start = i;
  20143. if ( i > range.end ) range.end = i;
  20144. if ( ! firstAnimation ) firstAnimation = name;
  20145. }
  20146. }
  20147. for ( var name in frameRanges ) {
  20148. var range = frameRanges[ name ];
  20149. this.createAnimation( name, range.start, range.end, fps );
  20150. }
  20151. this.firstAnimation = firstAnimation;
  20152. };
  20153. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20154. var animation = this.animationsMap[ name ];
  20155. if ( animation ) {
  20156. animation.direction = 1;
  20157. animation.directionBackwards = false;
  20158. }
  20159. };
  20160. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20161. var animation = this.animationsMap[ name ];
  20162. if ( animation ) {
  20163. animation.direction = -1;
  20164. animation.directionBackwards = true;
  20165. }
  20166. };
  20167. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20168. var animation = this.animationsMap[ name ];
  20169. if ( animation ) {
  20170. animation.fps = fps;
  20171. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20172. }
  20173. };
  20174. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20175. var animation = this.animationsMap[ name ];
  20176. if ( animation ) {
  20177. animation.duration = duration;
  20178. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20179. }
  20180. };
  20181. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20182. var animation = this.animationsMap[ name ];
  20183. if ( animation ) {
  20184. animation.weight = weight;
  20185. }
  20186. };
  20187. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20188. var animation = this.animationsMap[ name ];
  20189. if ( animation ) {
  20190. animation.time = time;
  20191. }
  20192. };
  20193. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20194. var time = 0;
  20195. var animation = this.animationsMap[ name ];
  20196. if ( animation ) {
  20197. time = animation.time;
  20198. }
  20199. return time;
  20200. };
  20201. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20202. var duration = -1;
  20203. var animation = this.animationsMap[ name ];
  20204. if ( animation ) {
  20205. duration = animation.duration;
  20206. }
  20207. return duration;
  20208. };
  20209. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20210. var animation = this.animationsMap[ name ];
  20211. if ( animation ) {
  20212. animation.time = 0;
  20213. animation.active = true;
  20214. } else {
  20215. console.warn( "animation[" + name + "] undefined" );
  20216. }
  20217. };
  20218. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20219. var animation = this.animationsMap[ name ];
  20220. if ( animation ) {
  20221. animation.active = false;
  20222. }
  20223. };
  20224. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20225. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20226. var animation = this.animationsList[ i ];
  20227. if ( ! animation.active ) continue;
  20228. var frameTime = animation.duration / animation.length;
  20229. animation.time += animation.direction * delta;
  20230. if ( animation.mirroredLoop ) {
  20231. if ( animation.time > animation.duration || animation.time < 0 ) {
  20232. animation.direction *= -1;
  20233. if ( animation.time > animation.duration ) {
  20234. animation.time = animation.duration;
  20235. animation.directionBackwards = true;
  20236. }
  20237. if ( animation.time < 0 ) {
  20238. animation.time = 0;
  20239. animation.directionBackwards = false;
  20240. }
  20241. }
  20242. } else {
  20243. animation.time = animation.time % animation.duration;
  20244. if ( animation.time < 0 ) animation.time += animation.duration;
  20245. }
  20246. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20247. var weight = animation.weight;
  20248. if ( keyframe !== animation.currentFrame ) {
  20249. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20250. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20251. this.morphTargetInfluences[ keyframe ] = 0;
  20252. animation.lastFrame = animation.currentFrame;
  20253. animation.currentFrame = keyframe;
  20254. }
  20255. var mix = ( animation.time % frameTime ) / frameTime;
  20256. if ( animation.directionBackwards ) mix = 1 - mix;
  20257. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20258. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20259. }
  20260. };
  20261. /**
  20262. * @author mikael emtinger / http://gomo.se/
  20263. * @author alteredq / http://alteredqualia.com/
  20264. */
  20265. THREE.LensFlarePlugin = function ( ) {
  20266. var _gl, _renderer, _lensFlare = {};
  20267. this.init = function ( renderer ) {
  20268. _gl = renderer.context;
  20269. _renderer = renderer;
  20270. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20271. _lensFlare.faces = new Uint16Array( 6 );
  20272. var i = 0;
  20273. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20274. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20275. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20276. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20277. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20278. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20279. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20280. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20281. i = 0;
  20282. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20283. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20284. // buffers
  20285. _lensFlare.vertexBuffer = _gl.createBuffer();
  20286. _lensFlare.elementBuffer = _gl.createBuffer();
  20287. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20288. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20289. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20290. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20291. // textures
  20292. _lensFlare.tempTexture = _gl.createTexture();
  20293. _lensFlare.occlusionTexture = _gl.createTexture();
  20294. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20295. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20296. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20297. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20298. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20299. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20300. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20301. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20302. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20303. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20304. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20305. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20306. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20307. _lensFlare.hasVertexTexture = false;
  20308. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20309. } else {
  20310. _lensFlare.hasVertexTexture = true;
  20311. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20312. }
  20313. _lensFlare.attributes = {};
  20314. _lensFlare.uniforms = {};
  20315. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20316. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20317. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20318. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20319. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20320. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20321. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20322. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20323. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20324. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20325. _lensFlare.attributesEnabled = false;
  20326. };
  20327. /*
  20328. * Render lens flares
  20329. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20330. * reads these back and calculates occlusion.
  20331. * Then _lensFlare.update_lensFlares() is called to re-position and
  20332. * update transparency of flares. Then they are rendered.
  20333. *
  20334. */
  20335. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20336. var flares = scene.__webglFlares,
  20337. nFlares = flares.length;
  20338. if ( ! nFlares ) return;
  20339. var tempPosition = new THREE.Vector3();
  20340. var invAspect = viewportHeight / viewportWidth,
  20341. halfViewportWidth = viewportWidth * 0.5,
  20342. halfViewportHeight = viewportHeight * 0.5;
  20343. var size = 16 / viewportHeight,
  20344. scale = new THREE.Vector2( size * invAspect, size );
  20345. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20346. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20347. var uniforms = _lensFlare.uniforms,
  20348. attributes = _lensFlare.attributes;
  20349. // set _lensFlare program and reset blending
  20350. _gl.useProgram( _lensFlare.program );
  20351. if ( ! _lensFlare.attributesEnabled ) {
  20352. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20353. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20354. _lensFlare.attributesEnabled = true;
  20355. }
  20356. // loop through all lens flares to update their occlusion and positions
  20357. // setup gl and common used attribs/unforms
  20358. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20359. _gl.uniform1i( uniforms.map, 1 );
  20360. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20361. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20362. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20363. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20364. _gl.disable( _gl.CULL_FACE );
  20365. _gl.depthMask( false );
  20366. var i, j, jl, flare, sprite;
  20367. for ( i = 0; i < nFlares; i ++ ) {
  20368. size = 16 / viewportHeight;
  20369. scale.set( size * invAspect, size );
  20370. // calc object screen position
  20371. flare = flares[ i ];
  20372. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20373. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  20374. camera.projectionMatrix.multiplyVector3( tempPosition );
  20375. // setup arrays for gl programs
  20376. screenPosition.copy( tempPosition )
  20377. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20378. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20379. // screen cull
  20380. if ( _lensFlare.hasVertexTexture || (
  20381. screenPositionPixels.x > 0 &&
  20382. screenPositionPixels.x < viewportWidth &&
  20383. screenPositionPixels.y > 0 &&
  20384. screenPositionPixels.y < viewportHeight ) ) {
  20385. // save current RGB to temp texture
  20386. _gl.activeTexture( _gl.TEXTURE1 );
  20387. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20388. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20389. // render pink quad
  20390. _gl.uniform1i( uniforms.renderType, 0 );
  20391. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20392. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20393. _gl.disable( _gl.BLEND );
  20394. _gl.enable( _gl.DEPTH_TEST );
  20395. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20396. // copy result to occlusionMap
  20397. _gl.activeTexture( _gl.TEXTURE0 );
  20398. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20399. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20400. // restore graphics
  20401. _gl.uniform1i( uniforms.renderType, 1 );
  20402. _gl.disable( _gl.DEPTH_TEST );
  20403. _gl.activeTexture( _gl.TEXTURE1 );
  20404. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20405. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20406. // update object positions
  20407. flare.positionScreen.copy( screenPosition )
  20408. if ( flare.customUpdateCallback ) {
  20409. flare.customUpdateCallback( flare );
  20410. } else {
  20411. flare.updateLensFlares();
  20412. }
  20413. // render flares
  20414. _gl.uniform1i( uniforms.renderType, 2 );
  20415. _gl.enable( _gl.BLEND );
  20416. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20417. sprite = flare.lensFlares[ j ];
  20418. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20419. screenPosition.x = sprite.x;
  20420. screenPosition.y = sprite.y;
  20421. screenPosition.z = sprite.z;
  20422. size = sprite.size * sprite.scale / viewportHeight;
  20423. scale.x = size * invAspect;
  20424. scale.y = size;
  20425. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20426. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20427. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20428. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20429. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20430. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20431. _renderer.setTexture( sprite.texture, 1 );
  20432. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20433. }
  20434. }
  20435. }
  20436. }
  20437. // restore gl
  20438. _gl.enable( _gl.CULL_FACE );
  20439. _gl.enable( _gl.DEPTH_TEST );
  20440. _gl.depthMask( true );
  20441. };
  20442. function createProgram ( shader ) {
  20443. var program = _gl.createProgram();
  20444. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20445. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20446. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20447. _gl.shaderSource( vertexShader, shader.vertexShader );
  20448. _gl.compileShader( fragmentShader );
  20449. _gl.compileShader( vertexShader );
  20450. _gl.attachShader( program, fragmentShader );
  20451. _gl.attachShader( program, vertexShader );
  20452. _gl.linkProgram( program );
  20453. return program;
  20454. };
  20455. };/**
  20456. * @author alteredq / http://alteredqualia.com/
  20457. */
  20458. THREE.ShadowMapPlugin = function ( ) {
  20459. var _gl,
  20460. _renderer,
  20461. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin,
  20462. _frustum = new THREE.Frustum(),
  20463. _projScreenMatrix = new THREE.Matrix4(),
  20464. _min = new THREE.Vector3(),
  20465. _max = new THREE.Vector3();
  20466. this.init = function ( renderer ) {
  20467. _gl = renderer.context;
  20468. _renderer = renderer;
  20469. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20470. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20471. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20472. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20473. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20474. _depthMaterial._shadowPass = true;
  20475. _depthMaterialMorph._shadowPass = true;
  20476. _depthMaterialSkin._shadowPass = true;
  20477. };
  20478. this.render = function ( scene, camera ) {
  20479. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20480. this.update( scene, camera );
  20481. };
  20482. this.update = function ( scene, camera ) {
  20483. var i, il, j, jl, n,
  20484. shadowMap, shadowMatrix, shadowCamera,
  20485. program, buffer, material,
  20486. webglObject, object, light,
  20487. renderList,
  20488. lights = [],
  20489. k = 0,
  20490. fog = null;
  20491. // set GL state for depth map
  20492. _gl.clearColor( 1, 1, 1, 1 );
  20493. _gl.disable( _gl.BLEND );
  20494. _gl.enable( _gl.CULL_FACE );
  20495. if ( _renderer.shadowMapCullFrontFaces ) {
  20496. _gl.cullFace( _gl.FRONT );
  20497. } else {
  20498. _gl.cullFace( _gl.BACK );
  20499. }
  20500. _renderer.setDepthTest( true );
  20501. // preprocess lights
  20502. // - skip lights that are not casting shadows
  20503. // - create virtual lights for cascaded shadow maps
  20504. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20505. light = scene.__lights[ i ];
  20506. if ( ! light.castShadow ) continue;
  20507. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20508. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20509. var virtualLight;
  20510. if ( ! light.shadowCascadeArray[ n ] ) {
  20511. virtualLight = createVirtualLight( light, n );
  20512. virtualLight.originalCamera = camera;
  20513. var gyro = new THREE.Gyroscope();
  20514. gyro.position = light.shadowCascadeOffset;
  20515. gyro.add( virtualLight );
  20516. gyro.add( virtualLight.target );
  20517. camera.add( gyro );
  20518. light.shadowCascadeArray[ n ] = virtualLight;
  20519. console.log( "Created virtualLight", virtualLight );
  20520. } else {
  20521. virtualLight = light.shadowCascadeArray[ n ];
  20522. }
  20523. updateVirtualLight( light, n );
  20524. lights[ k ] = virtualLight;
  20525. k ++;
  20526. }
  20527. } else {
  20528. lights[ k ] = light;
  20529. k ++;
  20530. }
  20531. }
  20532. // render depth map
  20533. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20534. light = lights[ i ];
  20535. if ( ! light.shadowMap ) {
  20536. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  20537. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20538. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20539. light.shadowMatrix = new THREE.Matrix4();
  20540. }
  20541. if ( ! light.shadowCamera ) {
  20542. if ( light instanceof THREE.SpotLight ) {
  20543. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20544. } else if ( light instanceof THREE.DirectionalLight ) {
  20545. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20546. } else {
  20547. console.error( "Unsupported light type for shadow" );
  20548. continue;
  20549. }
  20550. scene.add( light.shadowCamera );
  20551. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20552. }
  20553. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20554. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20555. light.shadowCamera.add( light.cameraHelper );
  20556. }
  20557. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20558. updateShadowCamera( camera, light );
  20559. }
  20560. shadowMap = light.shadowMap;
  20561. shadowMatrix = light.shadowMatrix;
  20562. shadowCamera = light.shadowCamera;
  20563. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20564. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20565. shadowCamera.updateMatrixWorld();
  20566. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20567. if ( light.cameraHelper ) light.cameraHelper.lines.visible = light.shadowCameraVisible;
  20568. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20569. // compute shadow matrix
  20570. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20571. 0.0, 0.5, 0.0, 0.5,
  20572. 0.0, 0.0, 0.5, 0.5,
  20573. 0.0, 0.0, 0.0, 1.0 );
  20574. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  20575. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  20576. // update camera matrices and frustum
  20577. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  20578. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  20579. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  20580. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  20581. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20582. _frustum.setFromMatrix( _projScreenMatrix );
  20583. // render shadow map
  20584. _renderer.setRenderTarget( shadowMap );
  20585. _renderer.clear();
  20586. // set object matrices & frustum culling
  20587. renderList = scene.__webglObjects;
  20588. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20589. webglObject = renderList[ j ];
  20590. object = webglObject.object;
  20591. webglObject.render = false;
  20592. if ( object.visible && object.castShadow ) {
  20593. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20594. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20595. webglObject.render = true;
  20596. }
  20597. }
  20598. }
  20599. // render regular objects
  20600. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20601. webglObject = renderList[ j ];
  20602. if ( webglObject.render ) {
  20603. object = webglObject.object;
  20604. buffer = webglObject.buffer;
  20605. // culling is overriden globally for all objects
  20606. // while rendering depth map
  20607. if ( object.customDepthMaterial ) {
  20608. material = object.customDepthMaterial;
  20609. } else if ( object.geometry.morphTargets.length ) {
  20610. material = _depthMaterialMorph;
  20611. } else if ( object instanceof THREE.SkinnedMesh ) {
  20612. material = _depthMaterialSkin;
  20613. } else {
  20614. material = _depthMaterial;
  20615. }
  20616. if ( buffer instanceof THREE.BufferGeometry ) {
  20617. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20618. } else {
  20619. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20620. }
  20621. }
  20622. }
  20623. // set matrices and render immediate objects
  20624. renderList = scene.__webglObjectsImmediate;
  20625. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20626. webglObject = renderList[ j ];
  20627. object = webglObject.object;
  20628. if ( object.visible && object.castShadow ) {
  20629. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20630. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20631. }
  20632. }
  20633. }
  20634. // restore GL state
  20635. var clearColor = _renderer.getClearColor(),
  20636. clearAlpha = _renderer.getClearAlpha();
  20637. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20638. _gl.enable( _gl.BLEND );
  20639. if ( _renderer.shadowMapCullFrontFaces ) {
  20640. _gl.cullFace( _gl.BACK );
  20641. }
  20642. };
  20643. function createVirtualLight( light, cascade ) {
  20644. var virtualLight = new THREE.DirectionalLight();
  20645. virtualLight.isVirtual = true;
  20646. virtualLight.onlyShadow = true;
  20647. virtualLight.castShadow = true;
  20648. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20649. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20650. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20651. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20652. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20653. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20654. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20655. virtualLight.shadowDarkness = light.shadowDarkness;
  20656. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20657. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20658. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20659. virtualLight.pointsWorld = [];
  20660. virtualLight.pointsFrustum = [];
  20661. var pointsWorld = virtualLight.pointsWorld,
  20662. pointsFrustum = virtualLight.pointsFrustum;
  20663. for ( var i = 0; i < 8; i ++ ) {
  20664. pointsWorld[ i ] = new THREE.Vector3();
  20665. pointsFrustum[ i ] = new THREE.Vector3();
  20666. }
  20667. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20668. var farZ = light.shadowCascadeFarZ[ cascade ];
  20669. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20670. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20671. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20672. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20673. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20674. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20675. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20676. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20677. return virtualLight;
  20678. }
  20679. // Synchronize virtual light with the original light
  20680. function updateVirtualLight( light, cascade ) {
  20681. var virtualLight = light.shadowCascadeArray[ cascade ];
  20682. virtualLight.position.copy( light.position );
  20683. virtualLight.target.position.copy( light.target.position );
  20684. virtualLight.lookAt( virtualLight.target );
  20685. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20686. virtualLight.shadowDarkness = light.shadowDarkness;
  20687. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20688. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20689. var farZ = light.shadowCascadeFarZ[ cascade ];
  20690. var pointsFrustum = virtualLight.pointsFrustum;
  20691. pointsFrustum[ 0 ].z = nearZ;
  20692. pointsFrustum[ 1 ].z = nearZ;
  20693. pointsFrustum[ 2 ].z = nearZ;
  20694. pointsFrustum[ 3 ].z = nearZ;
  20695. pointsFrustum[ 4 ].z = farZ;
  20696. pointsFrustum[ 5 ].z = farZ;
  20697. pointsFrustum[ 6 ].z = farZ;
  20698. pointsFrustum[ 7 ].z = farZ;
  20699. }
  20700. // Fit shadow camera's ortho frustum to camera frustum
  20701. function updateShadowCamera( camera, light ) {
  20702. var shadowCamera = light.shadowCamera,
  20703. pointsFrustum = light.pointsFrustum,
  20704. pointsWorld = light.pointsWorld;
  20705. _min.set( Infinity, Infinity, Infinity );
  20706. _max.set( -Infinity, -Infinity, -Infinity );
  20707. for ( var i = 0; i < 8; i ++ ) {
  20708. var p = pointsWorld[ i ];
  20709. p.copy( pointsFrustum[ i ] );
  20710. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  20711. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  20712. if ( p.x < _min.x ) _min.x = p.x;
  20713. if ( p.x > _max.x ) _max.x = p.x;
  20714. if ( p.y < _min.y ) _min.y = p.y;
  20715. if ( p.y > _max.y ) _max.y = p.y;
  20716. if ( p.z < _min.z ) _min.z = p.z;
  20717. if ( p.z > _max.z ) _max.z = p.z;
  20718. }
  20719. shadowCamera.left = _min.x;
  20720. shadowCamera.right = _max.x;
  20721. shadowCamera.top = _max.y;
  20722. shadowCamera.bottom = _min.y;
  20723. // can't really fit near/far
  20724. //shadowCamera.near = _min.z;
  20725. //shadowCamera.far = _max.z;
  20726. shadowCamera.updateProjectionMatrix();
  20727. }
  20728. };
  20729. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  20730. /**
  20731. * @author mikael emtinger / http://gomo.se/
  20732. * @author alteredq / http://alteredqualia.com/
  20733. */
  20734. THREE.SpritePlugin = function ( ) {
  20735. var _gl, _renderer, _sprite = {};
  20736. this.init = function ( renderer ) {
  20737. _gl = renderer.context;
  20738. _renderer = renderer;
  20739. _sprite.vertices = new Float32Array( 8 + 8 );
  20740. _sprite.faces = new Uint16Array( 6 );
  20741. var i = 0;
  20742. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  20743. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  20744. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  20745. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  20746. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  20747. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  20748. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  20749. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  20750. i = 0;
  20751. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  20752. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  20753. _sprite.vertexBuffer = _gl.createBuffer();
  20754. _sprite.elementBuffer = _gl.createBuffer();
  20755. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20756. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  20757. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20758. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  20759. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  20760. _sprite.attributes = {};
  20761. _sprite.uniforms = {};
  20762. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  20763. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  20764. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  20765. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  20766. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  20767. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  20768. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  20769. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  20770. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  20771. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  20772. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  20773. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  20774. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  20775. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  20776. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  20777. _sprite.attributesEnabled = false;
  20778. };
  20779. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20780. var sprites = scene.__webglSprites,
  20781. nSprites = sprites.length;
  20782. if ( ! nSprites ) return;
  20783. var attributes = _sprite.attributes,
  20784. uniforms = _sprite.uniforms;
  20785. var invAspect = viewportHeight / viewportWidth;
  20786. var halfViewportWidth = viewportWidth * 0.5,
  20787. halfViewportHeight = viewportHeight * 0.5;
  20788. var mergeWith3D = true;
  20789. // setup gl
  20790. _gl.useProgram( _sprite.program );
  20791. if ( ! _sprite.attributesEnabled ) {
  20792. _gl.enableVertexAttribArray( attributes.position );
  20793. _gl.enableVertexAttribArray( attributes.uv );
  20794. _sprite.attributesEnabled = true;
  20795. }
  20796. _gl.disable( _gl.CULL_FACE );
  20797. _gl.enable( _gl.BLEND );
  20798. _gl.depthMask( true );
  20799. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20800. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20801. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20802. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20803. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  20804. _gl.activeTexture( _gl.TEXTURE0 );
  20805. _gl.uniform1i( uniforms.map, 0 );
  20806. // update positions and sort
  20807. var i, sprite, screenPosition, size, scale = [];
  20808. for( i = 0; i < nSprites; i ++ ) {
  20809. sprite = sprites[ i ];
  20810. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  20811. if( ! sprite.useScreenCoordinates ) {
  20812. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  20813. sprite.z = - sprite._modelViewMatrix.elements[14];
  20814. } else {
  20815. sprite.z = - sprite.position.z;
  20816. }
  20817. }
  20818. sprites.sort( painterSort );
  20819. // render all sprites
  20820. for( i = 0; i < nSprites; i ++ ) {
  20821. sprite = sprites[ i ];
  20822. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  20823. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  20824. if ( sprite.useScreenCoordinates ) {
  20825. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  20826. _gl.uniform3f( uniforms.screenPosition, ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  20827. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  20828. Math.max( 0, Math.min( 1, sprite.position.z ) ) );
  20829. } else {
  20830. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  20831. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  20832. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  20833. }
  20834. size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
  20835. scale[ 0 ] = size * invAspect * sprite.scale.x;
  20836. scale[ 1 ] = size * sprite.scale.y;
  20837. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  20838. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  20839. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  20840. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20841. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20842. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20843. _gl.uniform2fv( uniforms.scale, scale );
  20844. if ( sprite.mergeWith3D && !mergeWith3D ) {
  20845. _gl.enable( _gl.DEPTH_TEST );
  20846. mergeWith3D = true;
  20847. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  20848. _gl.disable( _gl.DEPTH_TEST );
  20849. mergeWith3D = false;
  20850. }
  20851. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20852. _renderer.setTexture( sprite.map, 0 );
  20853. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20854. }
  20855. }
  20856. // restore gl
  20857. _gl.enable( _gl.CULL_FACE );
  20858. _gl.enable( _gl.DEPTH_TEST );
  20859. _gl.depthMask( true );
  20860. };
  20861. function createProgram ( shader ) {
  20862. var program = _gl.createProgram();
  20863. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20864. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20865. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20866. _gl.shaderSource( vertexShader, shader.vertexShader );
  20867. _gl.compileShader( fragmentShader );
  20868. _gl.compileShader( vertexShader );
  20869. _gl.attachShader( program, fragmentShader );
  20870. _gl.attachShader( program, vertexShader );
  20871. _gl.linkProgram( program );
  20872. return program;
  20873. };
  20874. function painterSort ( a, b ) {
  20875. return b.z - a.z;
  20876. };
  20877. };/**
  20878. * @author alteredq / http://alteredqualia.com/
  20879. */
  20880. THREE.DepthPassPlugin = function ( ) {
  20881. this.enabled = false;
  20882. this.renderTarget = null;
  20883. var _gl,
  20884. _renderer,
  20885. _depthMaterial, _depthMaterialMorph,
  20886. _frustum = new THREE.Frustum(),
  20887. _projScreenMatrix = new THREE.Matrix4();
  20888. this.init = function ( renderer ) {
  20889. _gl = renderer.context;
  20890. _renderer = renderer;
  20891. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20892. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20893. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20894. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20895. _depthMaterial._shadowPass = true;
  20896. _depthMaterialMorph._shadowPass = true;
  20897. };
  20898. this.render = function ( scene, camera ) {
  20899. if ( ! this.enabled ) return;
  20900. this.update( scene, camera );
  20901. };
  20902. this.update = function ( scene, camera ) {
  20903. var i, il, j, jl, n,
  20904. program, buffer, material,
  20905. webglObject, object, light,
  20906. renderList,
  20907. fog = null;
  20908. // set GL state for depth map
  20909. _gl.clearColor( 1, 1, 1, 1 );
  20910. _gl.disable( _gl.BLEND );
  20911. _renderer.setDepthTest( true );
  20912. // update scene
  20913. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20914. // update camera matrices and frustum
  20915. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  20916. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  20917. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  20918. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  20919. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  20920. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  20921. _frustum.setFromMatrix( _projScreenMatrix );
  20922. // render depth map
  20923. _renderer.setRenderTarget( this.renderTarget );
  20924. _renderer.clear();
  20925. // set object matrices & frustum culling
  20926. renderList = scene.__webglObjects;
  20927. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20928. webglObject = renderList[ j ];
  20929. object = webglObject.object;
  20930. webglObject.render = false;
  20931. if ( object.visible ) {
  20932. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20933. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  20934. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  20935. webglObject.render = true;
  20936. }
  20937. }
  20938. }
  20939. // render regular objects
  20940. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20941. webglObject = renderList[ j ];
  20942. if ( webglObject.render ) {
  20943. object = webglObject.object;
  20944. buffer = webglObject.buffer;
  20945. if ( object.material ) _renderer.setMaterialFaces( object.material );
  20946. if ( object.customDepthMaterial ) {
  20947. material = object.customDepthMaterial;
  20948. } else if ( object.geometry.morphTargets.length ) {
  20949. material = _depthMaterialMorph;
  20950. } else {
  20951. material = _depthMaterial;
  20952. }
  20953. if ( buffer instanceof THREE.BufferGeometry ) {
  20954. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  20955. } else {
  20956. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  20957. }
  20958. }
  20959. }
  20960. // set matrices and render immediate objects
  20961. renderList = scene.__webglObjectsImmediate;
  20962. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20963. webglObject = renderList[ j ];
  20964. object = webglObject.object;
  20965. if ( object.visible && object.castShadow ) {
  20966. /*
  20967. if ( object.matrixAutoUpdate ) {
  20968. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  20969. }
  20970. */
  20971. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  20972. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  20973. }
  20974. }
  20975. // restore GL state
  20976. var clearColor = _renderer.getClearColor(),
  20977. clearAlpha = _renderer.getClearAlpha();
  20978. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20979. _gl.enable( _gl.BLEND );
  20980. };
  20981. };
  20982. /**
  20983. * @author mikael emtinger / http://gomo.se/
  20984. *
  20985. */
  20986. THREE.ShaderFlares = {
  20987. 'lensFlareVertexTexture': {
  20988. vertexShader: [
  20989. "uniform vec3 screenPosition;",
  20990. "uniform vec2 scale;",
  20991. "uniform float rotation;",
  20992. "uniform int renderType;",
  20993. "uniform sampler2D occlusionMap;",
  20994. "attribute vec2 position;",
  20995. "attribute vec2 uv;",
  20996. "varying vec2 vUV;",
  20997. "varying float vVisibility;",
  20998. "void main() {",
  20999. "vUV = uv;",
  21000. "vec2 pos = position;",
  21001. "if( renderType == 2 ) {",
  21002. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21003. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21004. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21005. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21006. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21007. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21008. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21009. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21010. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21011. "vVisibility = ( visibility.r / 9.0 ) *",
  21012. "( 1.0 - visibility.g / 9.0 ) *",
  21013. "( visibility.b / 9.0 ) *",
  21014. "( 1.0 - visibility.a / 9.0 );",
  21015. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21016. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21017. "}",
  21018. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21019. "}"
  21020. ].join( "\n" ),
  21021. fragmentShader: [
  21022. "precision mediump float;",
  21023. "uniform sampler2D map;",
  21024. "uniform float opacity;",
  21025. "uniform int renderType;",
  21026. "uniform vec3 color;",
  21027. "varying vec2 vUV;",
  21028. "varying float vVisibility;",
  21029. "void main() {",
  21030. // pink square
  21031. "if( renderType == 0 ) {",
  21032. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21033. // restore
  21034. "} else if( renderType == 1 ) {",
  21035. "gl_FragColor = texture2D( map, vUV );",
  21036. // flare
  21037. "} else {",
  21038. "vec4 texture = texture2D( map, vUV );",
  21039. "texture.a *= opacity * vVisibility;",
  21040. "gl_FragColor = texture;",
  21041. "gl_FragColor.rgb *= color;",
  21042. "}",
  21043. "}"
  21044. ].join( "\n" )
  21045. },
  21046. 'lensFlare': {
  21047. vertexShader: [
  21048. "uniform vec3 screenPosition;",
  21049. "uniform vec2 scale;",
  21050. "uniform float rotation;",
  21051. "uniform int renderType;",
  21052. "attribute vec2 position;",
  21053. "attribute vec2 uv;",
  21054. "varying vec2 vUV;",
  21055. "void main() {",
  21056. "vUV = uv;",
  21057. "vec2 pos = position;",
  21058. "if( renderType == 2 ) {",
  21059. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21060. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21061. "}",
  21062. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21063. "}"
  21064. ].join( "\n" ),
  21065. fragmentShader: [
  21066. "precision mediump float;",
  21067. "uniform sampler2D map;",
  21068. "uniform sampler2D occlusionMap;",
  21069. "uniform float opacity;",
  21070. "uniform int renderType;",
  21071. "uniform vec3 color;",
  21072. "varying vec2 vUV;",
  21073. "void main() {",
  21074. // pink square
  21075. "if( renderType == 0 ) {",
  21076. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21077. // restore
  21078. "} else if( renderType == 1 ) {",
  21079. "gl_FragColor = texture2D( map, vUV );",
  21080. // flare
  21081. "} else {",
  21082. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21083. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21084. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21085. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21086. "visibility = ( 1.0 - visibility / 4.0 );",
  21087. "vec4 texture = texture2D( map, vUV );",
  21088. "texture.a *= opacity * visibility;",
  21089. "gl_FragColor = texture;",
  21090. "gl_FragColor.rgb *= color;",
  21091. "}",
  21092. "}"
  21093. ].join( "\n" )
  21094. }
  21095. };
  21096. /**
  21097. * @author mikael emtinger / http://gomo.se/
  21098. *
  21099. */
  21100. THREE.ShaderSprite = {
  21101. 'sprite': {
  21102. vertexShader: [
  21103. "uniform int useScreenCoordinates;",
  21104. "uniform int affectedByDistance;",
  21105. "uniform vec3 screenPosition;",
  21106. "uniform mat4 modelViewMatrix;",
  21107. "uniform mat4 projectionMatrix;",
  21108. "uniform float rotation;",
  21109. "uniform vec2 scale;",
  21110. "uniform vec2 alignment;",
  21111. "uniform vec2 uvOffset;",
  21112. "uniform vec2 uvScale;",
  21113. "attribute vec2 position;",
  21114. "attribute vec2 uv;",
  21115. "varying vec2 vUV;",
  21116. "void main() {",
  21117. "vUV = uvOffset + uv * uvScale;",
  21118. "vec2 alignedPosition = position + alignment;",
  21119. "vec2 rotatedPosition;",
  21120. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21121. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21122. "vec4 finalPosition;",
  21123. "if( useScreenCoordinates != 0 ) {",
  21124. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21125. "} else {",
  21126. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21127. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  21128. "}",
  21129. "gl_Position = finalPosition;",
  21130. "}"
  21131. ].join( "\n" ),
  21132. fragmentShader: [
  21133. "precision mediump float;",
  21134. "uniform vec3 color;",
  21135. "uniform sampler2D map;",
  21136. "uniform float opacity;",
  21137. "varying vec2 vUV;",
  21138. "void main() {",
  21139. "vec4 texture = texture2D( map, vUV );",
  21140. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21141. "}"
  21142. ].join( "\n" )
  21143. }
  21144. };