three.js 824 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '54dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. // Shims for "startsWith", "endsWith", and "trim" for browsers where this is not yet implemented
  16. // not sure we should have this, or at least not have it here
  17. // http://stackoverflow.com/questions/646628/javascript-startswith
  18. // http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript
  19. // http://wiki.ecmascript.org/doku.php?id=harmony%3astring_extras
  20. String.prototype.startsWith = String.prototype.startsWith || function ( str ) {
  21. return this.slice( 0, str.length ) === str;
  22. };
  23. String.prototype.endsWith = String.prototype.endsWith || function ( str ) {
  24. var t = String( str );
  25. var index = this.lastIndexOf( t );
  26. return ( -1 < index && index ) === (this.length - t.length);
  27. };
  28. String.prototype.trim = String.prototype.trim || function () {
  29. return this.replace( /^\s+|\s+$/g, '' );
  30. };
  31. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  32. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  33. // requestAnimationFrame polyfill by Erik Möller
  34. // fixes from Paul Irish and Tino Zijdel
  35. ( function () {
  36. var lastTime = 0;
  37. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  38. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  39. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  40. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  41. }
  42. if ( window.requestAnimationFrame === undefined ) {
  43. window.requestAnimationFrame = function ( callback, element ) {
  44. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  45. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  46. lastTime = currTime + timeToCall;
  47. return id;
  48. };
  49. }
  50. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  51. }() );
  52. // MATERIAL CONSTANTS
  53. // side
  54. THREE.FrontSide = 0;
  55. THREE.BackSide = 1;
  56. THREE.DoubleSide = 2;
  57. // shading
  58. THREE.NoShading = 0;
  59. THREE.FlatShading = 1;
  60. THREE.SmoothShading = 2;
  61. // colors
  62. THREE.NoColors = 0;
  63. THREE.FaceColors = 1;
  64. THREE.VertexColors = 2;
  65. // blending modes
  66. THREE.NoBlending = 0;
  67. THREE.NormalBlending = 1;
  68. THREE.AdditiveBlending = 2;
  69. THREE.SubtractiveBlending = 3;
  70. THREE.MultiplyBlending = 4;
  71. THREE.CustomBlending = 5;
  72. // custom blending equations
  73. // (numbers start from 100 not to clash with other
  74. // mappings to OpenGL constants defined in Texture.js)
  75. THREE.AddEquation = 100;
  76. THREE.SubtractEquation = 101;
  77. THREE.ReverseSubtractEquation = 102;
  78. // custom blending destination factors
  79. THREE.ZeroFactor = 200;
  80. THREE.OneFactor = 201;
  81. THREE.SrcColorFactor = 202;
  82. THREE.OneMinusSrcColorFactor = 203;
  83. THREE.SrcAlphaFactor = 204;
  84. THREE.OneMinusSrcAlphaFactor = 205;
  85. THREE.DstAlphaFactor = 206;
  86. THREE.OneMinusDstAlphaFactor = 207;
  87. // custom blending source factors
  88. //THREE.ZeroFactor = 200;
  89. //THREE.OneFactor = 201;
  90. //THREE.SrcAlphaFactor = 204;
  91. //THREE.OneMinusSrcAlphaFactor = 205;
  92. //THREE.DstAlphaFactor = 206;
  93. //THREE.OneMinusDstAlphaFactor = 207;
  94. THREE.DstColorFactor = 208;
  95. THREE.OneMinusDstColorFactor = 209;
  96. THREE.SrcAlphaSaturateFactor = 210;
  97. // TEXTURE CONSTANTS
  98. THREE.MultiplyOperation = 0;
  99. THREE.MixOperation = 1;
  100. THREE.AddOperation = 2;
  101. // Mapping modes
  102. THREE.UVMapping = function () {};
  103. THREE.CubeReflectionMapping = function () {};
  104. THREE.CubeRefractionMapping = function () {};
  105. THREE.SphericalReflectionMapping = function () {};
  106. THREE.SphericalRefractionMapping = function () {};
  107. // Wrapping modes
  108. THREE.RepeatWrapping = 1000;
  109. THREE.ClampToEdgeWrapping = 1001;
  110. THREE.MirroredRepeatWrapping = 1002;
  111. // Filters
  112. THREE.NearestFilter = 1003;
  113. THREE.NearestMipMapNearestFilter = 1004;
  114. THREE.NearestMipMapLinearFilter = 1005;
  115. THREE.LinearFilter = 1006;
  116. THREE.LinearMipMapNearestFilter = 1007;
  117. THREE.LinearMipMapLinearFilter = 1008;
  118. // Data types
  119. THREE.UnsignedByteType = 1009;
  120. THREE.ByteType = 1010;
  121. THREE.ShortType = 1011;
  122. THREE.UnsignedShortType = 1012;
  123. THREE.IntType = 1013;
  124. THREE.UnsignedIntType = 1014;
  125. THREE.FloatType = 1015;
  126. // Pixel types
  127. //THREE.UnsignedByteType = 1009;
  128. THREE.UnsignedShort4444Type = 1016;
  129. THREE.UnsignedShort5551Type = 1017;
  130. THREE.UnsignedShort565Type = 1018;
  131. // Pixel formats
  132. THREE.AlphaFormat = 1019;
  133. THREE.RGBFormat = 1020;
  134. THREE.RGBAFormat = 1021;
  135. THREE.LuminanceFormat = 1022;
  136. THREE.LuminanceAlphaFormat = 1023;
  137. // Compressed texture formats
  138. THREE.RGB_S3TC_DXT1_Format = 2001;
  139. THREE.RGBA_S3TC_DXT1_Format = 2002;
  140. THREE.RGBA_S3TC_DXT3_Format = 2003;
  141. THREE.RGBA_S3TC_DXT5_Format = 2004;
  142. /*
  143. // Potential future PVRTC compressed texture formats
  144. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  145. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  146. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  147. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  148. */
  149. /**
  150. * @author alteredq / http://alteredqualia.com/
  151. */
  152. THREE.Clock = function ( autoStart ) {
  153. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  154. this.startTime = 0;
  155. this.oldTime = 0;
  156. this.elapsedTime = 0;
  157. this.running = false;
  158. };
  159. THREE.Clock.prototype.start = function () {
  160. this.startTime = Date.now();
  161. this.oldTime = this.startTime;
  162. this.running = true;
  163. };
  164. THREE.Clock.prototype.stop = function () {
  165. this.getElapsedTime();
  166. this.running = false;
  167. };
  168. THREE.Clock.prototype.getElapsedTime = function () {
  169. this.getDelta();
  170. return this.elapsedTime;
  171. };
  172. THREE.Clock.prototype.getDelta = function () {
  173. var diff = 0;
  174. if ( this.autoStart && ! this.running ) {
  175. this.start();
  176. }
  177. if ( this.running ) {
  178. var newTime = Date.now();
  179. diff = 0.001 * ( newTime - this.oldTime );
  180. this.oldTime = newTime;
  181. this.elapsedTime += diff;
  182. }
  183. return diff;
  184. };/**
  185. * @author mrdoob / http://mrdoob.com/
  186. */
  187. THREE.Color = function ( hex ) {
  188. if ( hex !== undefined ) this.setHex( hex );
  189. return this;
  190. };
  191. THREE.Color.prototype = {
  192. constructor: THREE.Color,
  193. r: 1, g: 1, b: 1,
  194. copy: function ( color ) {
  195. this.r = color.r;
  196. this.g = color.g;
  197. this.b = color.b;
  198. return this;
  199. },
  200. copyGammaToLinear: function ( color ) {
  201. this.r = color.r * color.r;
  202. this.g = color.g * color.g;
  203. this.b = color.b * color.b;
  204. return this;
  205. },
  206. copyLinearToGamma: function ( color ) {
  207. this.r = Math.sqrt( color.r );
  208. this.g = Math.sqrt( color.g );
  209. this.b = Math.sqrt( color.b );
  210. return this;
  211. },
  212. convertGammaToLinear: function () {
  213. var r = this.r, g = this.g, b = this.b;
  214. this.r = r * r;
  215. this.g = g * g;
  216. this.b = b * b;
  217. return this;
  218. },
  219. convertLinearToGamma: function () {
  220. this.r = Math.sqrt( this.r );
  221. this.g = Math.sqrt( this.g );
  222. this.b = Math.sqrt( this.b );
  223. return this;
  224. },
  225. setRGB: function ( r, g, b ) {
  226. this.r = r;
  227. this.g = g;
  228. this.b = b;
  229. return this;
  230. },
  231. setHSV: function ( h, s, v ) {
  232. // based on MochiKit implementation by Bob Ippolito
  233. // h,s,v ranges are < 0.0 - 1.0 >
  234. var i, f, p, q, t;
  235. if ( v === 0 ) {
  236. this.r = this.g = this.b = 0;
  237. } else {
  238. i = Math.floor( h * 6 );
  239. f = ( h * 6 ) - i;
  240. p = v * ( 1 - s );
  241. q = v * ( 1 - ( s * f ) );
  242. t = v * ( 1 - ( s * ( 1 - f ) ) );
  243. if ( i === 0 ) {
  244. this.r = v;
  245. this.g = t;
  246. this.b = p;
  247. } else if ( i === 1 ) {
  248. this.r = q;
  249. this.g = v;
  250. this.b = p;
  251. } else if ( i === 2 ) {
  252. this.r = p;
  253. this.g = v;
  254. this.b = t;
  255. } else if ( i === 3 ) {
  256. this.r = p;
  257. this.g = q;
  258. this.b = v;
  259. } else if ( i === 4 ) {
  260. this.r = t;
  261. this.g = p;
  262. this.b = v;
  263. } else if ( i === 5 ) {
  264. this.r = v;
  265. this.g = p;
  266. this.b = q;
  267. }
  268. }
  269. return this;
  270. },
  271. getHex: function () {
  272. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  273. },
  274. setHex: function ( hex ) {
  275. hex = Math.floor( hex );
  276. this.r = ( hex >> 16 & 255 ) / 255;
  277. this.g = ( hex >> 8 & 255 ) / 255;
  278. this.b = ( hex & 255 ) / 255;
  279. return this;
  280. },
  281. getHexString: function () {
  282. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  283. },
  284. getContextStyle: function () {
  285. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  286. },
  287. setContextStyle: function ( style ) {
  288. var color = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/i.exec( style );
  289. this.r = parseInt( color[ 1 ], 10 ) / 255;
  290. this.g = parseInt( color[ 2 ], 10 ) / 255;
  291. this.b = parseInt( color[ 3 ], 10 ) / 255;
  292. return this;
  293. },
  294. getHSV: function ( hsv ) {
  295. // based on MochiKit implementation by Bob Ippolito
  296. // h,s,v ranges are < 0.0 - 1.0 >
  297. var r = this.r;
  298. var g = this.g;
  299. var b = this.b;
  300. var max = Math.max( Math.max( r, g ), b );
  301. var min = Math.min( Math.min( r, g ), b );
  302. var hue;
  303. var saturation;
  304. var value = max;
  305. if ( min === max ) {
  306. hue = 0;
  307. saturation = 0;
  308. } else {
  309. var delta = ( max - min );
  310. saturation = delta / max;
  311. if ( r === max ) {
  312. hue = ( g - b ) / delta;
  313. } else if ( g === max ) {
  314. hue = 2 + ( ( b - r ) / delta );
  315. } else {
  316. hue = 4 + ( ( r - g ) / delta );
  317. }
  318. hue /= 6;
  319. if ( hue < 0 ) {
  320. hue += 1;
  321. }
  322. if ( hue > 1 ) {
  323. hue -= 1;
  324. }
  325. }
  326. if ( hsv === undefined ) {
  327. hsv = { h: 0, s: 0, v: 0 };
  328. }
  329. hsv.h = hue;
  330. hsv.s = saturation;
  331. hsv.v = value;
  332. return hsv;
  333. },
  334. lerpSelf: function ( color, alpha ) {
  335. this.r += ( color.r - this.r ) * alpha;
  336. this.g += ( color.g - this.g ) * alpha;
  337. this.b += ( color.b - this.b ) * alpha;
  338. return this;
  339. },
  340. clone: function () {
  341. return new THREE.Color().setRGB( this.r, this.g, this.b );
  342. }
  343. };
  344. /**
  345. * @author mrdoob / http://mrdoob.com/
  346. * @author philogb / http://blog.thejit.org/
  347. * @author egraether / http://egraether.com/
  348. * @author zz85 / http://www.lab4games.net/zz85/blog
  349. */
  350. THREE.Vector2 = function ( x, y ) {
  351. this.x = x || 0;
  352. this.y = y || 0;
  353. };
  354. THREE.Vector2.prototype = {
  355. constructor: THREE.Vector2,
  356. set: function ( x, y ) {
  357. this.x = x;
  358. this.y = y;
  359. return this;
  360. },
  361. copy: function ( v ) {
  362. this.x = v.x;
  363. this.y = v.y;
  364. return this;
  365. },
  366. add: function ( a, b ) {
  367. this.x = a.x + b.x;
  368. this.y = a.y + b.y;
  369. return this;
  370. },
  371. addSelf: function ( v ) {
  372. this.x += v.x;
  373. this.y += v.y;
  374. return this;
  375. },
  376. sub: function ( a, b ) {
  377. this.x = a.x - b.x;
  378. this.y = a.y - b.y;
  379. return this;
  380. },
  381. subSelf: function ( v ) {
  382. this.x -= v.x;
  383. this.y -= v.y;
  384. return this;
  385. },
  386. multiplyScalar: function ( s ) {
  387. this.x *= s;
  388. this.y *= s;
  389. return this;
  390. },
  391. divideScalar: function ( s ) {
  392. if ( s ) {
  393. this.x /= s;
  394. this.y /= s;
  395. } else {
  396. this.set( 0, 0 );
  397. }
  398. return this;
  399. },
  400. negate: function() {
  401. return this.multiplyScalar( - 1 );
  402. },
  403. dot: function ( v ) {
  404. return this.x * v.x + this.y * v.y;
  405. },
  406. lengthSq: function () {
  407. return this.x * this.x + this.y * this.y;
  408. },
  409. length: function () {
  410. return Math.sqrt( this.lengthSq() );
  411. },
  412. normalize: function () {
  413. return this.divideScalar( this.length() );
  414. },
  415. distanceTo: function ( v ) {
  416. return Math.sqrt( this.distanceToSquared( v ) );
  417. },
  418. distanceToSquared: function ( v ) {
  419. var dx = this.x - v.x, dy = this.y - v.y;
  420. return dx * dx + dy * dy;
  421. },
  422. setLength: function ( l ) {
  423. return this.normalize().multiplyScalar( l );
  424. },
  425. lerpSelf: function ( v, alpha ) {
  426. this.x += ( v.x - this.x ) * alpha;
  427. this.y += ( v.y - this.y ) * alpha;
  428. return this;
  429. },
  430. equals: function( v ) {
  431. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  432. },
  433. clone: function () {
  434. return new THREE.Vector2( this.x, this.y );
  435. }
  436. };
  437. /**
  438. * @author mrdoob / http://mrdoob.com/
  439. * @author kile / http://kile.stravaganza.org/
  440. * @author philogb / http://blog.thejit.org/
  441. * @author mikael emtinger / http://gomo.se/
  442. * @author egraether / http://egraether.com/
  443. * @author WestLangley / http://github.com/WestLangley
  444. */
  445. THREE.Vector3 = function ( x, y, z ) {
  446. this.x = x || 0;
  447. this.y = y || 0;
  448. this.z = z || 0;
  449. };
  450. THREE.Vector3.prototype = {
  451. constructor: THREE.Vector3,
  452. set: function ( x, y, z ) {
  453. this.x = x;
  454. this.y = y;
  455. this.z = z;
  456. return this;
  457. },
  458. setX: function ( x ) {
  459. this.x = x;
  460. return this;
  461. },
  462. setY: function ( y ) {
  463. this.y = y;
  464. return this;
  465. },
  466. setZ: function ( z ) {
  467. this.z = z;
  468. return this;
  469. },
  470. copy: function ( v ) {
  471. this.x = v.x;
  472. this.y = v.y;
  473. this.z = v.z;
  474. return this;
  475. },
  476. add: function ( a, b ) {
  477. this.x = a.x + b.x;
  478. this.y = a.y + b.y;
  479. this.z = a.z + b.z;
  480. return this;
  481. },
  482. addSelf: function ( v ) {
  483. this.x += v.x;
  484. this.y += v.y;
  485. this.z += v.z;
  486. return this;
  487. },
  488. addScalar: function ( s ) {
  489. this.x += s;
  490. this.y += s;
  491. this.z += s;
  492. return this;
  493. },
  494. sub: function ( a, b ) {
  495. this.x = a.x - b.x;
  496. this.y = a.y - b.y;
  497. this.z = a.z - b.z;
  498. return this;
  499. },
  500. subSelf: function ( v ) {
  501. this.x -= v.x;
  502. this.y -= v.y;
  503. this.z -= v.z;
  504. return this;
  505. },
  506. multiply: function ( a, b ) {
  507. this.x = a.x * b.x;
  508. this.y = a.y * b.y;
  509. this.z = a.z * b.z;
  510. return this;
  511. },
  512. multiplySelf: function ( v ) {
  513. this.x *= v.x;
  514. this.y *= v.y;
  515. this.z *= v.z;
  516. return this;
  517. },
  518. multiplyScalar: function ( s ) {
  519. this.x *= s;
  520. this.y *= s;
  521. this.z *= s;
  522. return this;
  523. },
  524. divideSelf: function ( v ) {
  525. this.x /= v.x;
  526. this.y /= v.y;
  527. this.z /= v.z;
  528. return this;
  529. },
  530. divideScalar: function ( s ) {
  531. if ( s ) {
  532. this.x /= s;
  533. this.y /= s;
  534. this.z /= s;
  535. } else {
  536. this.x = 0;
  537. this.y = 0;
  538. this.z = 0;
  539. }
  540. return this;
  541. },
  542. negate: function() {
  543. return this.multiplyScalar( - 1 );
  544. },
  545. dot: function ( v ) {
  546. return this.x * v.x + this.y * v.y + this.z * v.z;
  547. },
  548. lengthSq: function () {
  549. return this.x * this.x + this.y * this.y + this.z * this.z;
  550. },
  551. length: function () {
  552. return Math.sqrt( this.lengthSq() );
  553. },
  554. lengthManhattan: function () {
  555. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  556. },
  557. normalize: function () {
  558. return this.divideScalar( this.length() );
  559. },
  560. setLength: function ( l ) {
  561. return this.normalize().multiplyScalar( l );
  562. },
  563. lerpSelf: function ( v, alpha ) {
  564. this.x += ( v.x - this.x ) * alpha;
  565. this.y += ( v.y - this.y ) * alpha;
  566. this.z += ( v.z - this.z ) * alpha;
  567. return this;
  568. },
  569. cross: function ( a, b ) {
  570. this.x = a.y * b.z - a.z * b.y;
  571. this.y = a.z * b.x - a.x * b.z;
  572. this.z = a.x * b.y - a.y * b.x;
  573. return this;
  574. },
  575. crossSelf: function ( v ) {
  576. var x = this.x, y = this.y, z = this.z;
  577. this.x = y * v.z - z * v.y;
  578. this.y = z * v.x - x * v.z;
  579. this.z = x * v.y - y * v.x;
  580. return this;
  581. },
  582. angleTo: function ( v ) {
  583. return Math.acos( this.dot( v ) / this.length() / v.length() );
  584. },
  585. distanceTo: function ( v ) {
  586. return Math.sqrt( this.distanceToSquared( v ) );
  587. },
  588. distanceToSquared: function ( v ) {
  589. return new THREE.Vector3().sub( this, v ).lengthSq();
  590. },
  591. getPositionFromMatrix: function ( m ) {
  592. this.x = m.elements[12];
  593. this.y = m.elements[13];
  594. this.z = m.elements[14];
  595. return this;
  596. },
  597. setEulerFromRotationMatrix: function ( m, order ) {
  598. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  599. // clamp, to handle numerical problems
  600. function clamp( x ) {
  601. return Math.min( Math.max( x, -1 ), 1 );
  602. }
  603. var te = m.elements;
  604. var m11 = te[0], m12 = te[4], m13 = te[8];
  605. var m21 = te[1], m22 = te[5], m23 = te[9];
  606. var m31 = te[2], m32 = te[6], m33 = te[10];
  607. if ( order === undefined || order === 'XYZ' ) {
  608. this.y = Math.asin( clamp( m13 ) );
  609. if ( Math.abs( m13 ) < 0.99999 ) {
  610. this.x = Math.atan2( - m23, m33 );
  611. this.z = Math.atan2( - m12, m11 );
  612. } else {
  613. this.x = Math.atan2( m32, m22 );
  614. this.z = 0;
  615. }
  616. } else if ( order === 'YXZ' ) {
  617. this.x = Math.asin( - clamp( m23 ) );
  618. if ( Math.abs( m23 ) < 0.99999 ) {
  619. this.y = Math.atan2( m13, m33 );
  620. this.z = Math.atan2( m21, m22 );
  621. } else {
  622. this.y = Math.atan2( - m31, m11 );
  623. this.z = 0;
  624. }
  625. } else if ( order === 'ZXY' ) {
  626. this.x = Math.asin( clamp( m32 ) );
  627. if ( Math.abs( m32 ) < 0.99999 ) {
  628. this.y = Math.atan2( - m31, m33 );
  629. this.z = Math.atan2( - m12, m22 );
  630. } else {
  631. this.y = 0;
  632. this.z = Math.atan2( m21, m11 );
  633. }
  634. } else if ( order === 'ZYX' ) {
  635. this.y = Math.asin( - clamp( m31 ) );
  636. if ( Math.abs( m31 ) < 0.99999 ) {
  637. this.x = Math.atan2( m32, m33 );
  638. this.z = Math.atan2( m21, m11 );
  639. } else {
  640. this.x = 0;
  641. this.z = Math.atan2( - m12, m22 );
  642. }
  643. } else if ( order === 'YZX' ) {
  644. this.z = Math.asin( clamp( m21 ) );
  645. if ( Math.abs( m21 ) < 0.99999 ) {
  646. this.x = Math.atan2( - m23, m22 );
  647. this.y = Math.atan2( - m31, m11 );
  648. } else {
  649. this.x = 0;
  650. this.y = Math.atan2( m13, m33 );
  651. }
  652. } else if ( order === 'XZY' ) {
  653. this.z = Math.asin( - clamp( m12 ) );
  654. if ( Math.abs( m12 ) < 0.99999 ) {
  655. this.x = Math.atan2( m32, m22 );
  656. this.y = Math.atan2( m13, m11 );
  657. } else {
  658. this.x = Math.atan2( - m23, m33 );
  659. this.y = 0;
  660. }
  661. }
  662. return this;
  663. },
  664. setEulerFromQuaternion: function ( q, order ) {
  665. // q is assumed to be normalized
  666. // clamp, to handle numerical problems
  667. function clamp( x ) {
  668. return Math.min( Math.max( x, -1 ), 1 );
  669. }
  670. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  671. var sqx = q.x * q.x;
  672. var sqy = q.y * q.y;
  673. var sqz = q.z * q.z;
  674. var sqw = q.w * q.w;
  675. if ( order === undefined || order === 'XYZ' ) {
  676. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  677. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  678. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  679. } else if ( order === 'YXZ' ) {
  680. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  681. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  682. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  683. } else if ( order === 'ZXY' ) {
  684. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  685. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  686. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  687. } else if ( order === 'ZYX' ) {
  688. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  689. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  690. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  691. } else if ( order === 'YZX' ) {
  692. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  693. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  694. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  695. } else if ( order === 'XZY' ) {
  696. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  697. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  698. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  699. }
  700. return this;
  701. },
  702. getScaleFromMatrix: function ( m ) {
  703. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  704. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  705. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  706. this.x = sx;
  707. this.y = sy;
  708. this.z = sz;
  709. return this;
  710. },
  711. equals: function ( v ) {
  712. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  713. },
  714. clone: function () {
  715. return new THREE.Vector3( this.x, this.y, this.z );
  716. }
  717. };
  718. /**
  719. * @author supereggbert / http://www.paulbrunt.co.uk/
  720. * @author philogb / http://blog.thejit.org/
  721. * @author mikael emtinger / http://gomo.se/
  722. * @author egraether / http://egraether.com/
  723. * @author WestLangley / http://github.com/WestLangley
  724. */
  725. THREE.Vector4 = function ( x, y, z, w ) {
  726. this.x = x || 0;
  727. this.y = y || 0;
  728. this.z = z || 0;
  729. this.w = ( w !== undefined ) ? w : 1;
  730. };
  731. THREE.Vector4.prototype = {
  732. constructor: THREE.Vector4,
  733. set: function ( x, y, z, w ) {
  734. this.x = x;
  735. this.y = y;
  736. this.z = z;
  737. this.w = w;
  738. return this;
  739. },
  740. copy: function ( v ) {
  741. this.x = v.x;
  742. this.y = v.y;
  743. this.z = v.z;
  744. this.w = ( v.w !== undefined ) ? v.w : 1;
  745. return this;
  746. },
  747. add: function ( a, b ) {
  748. this.x = a.x + b.x;
  749. this.y = a.y + b.y;
  750. this.z = a.z + b.z;
  751. this.w = a.w + b.w;
  752. return this;
  753. },
  754. addSelf: function ( v ) {
  755. this.x += v.x;
  756. this.y += v.y;
  757. this.z += v.z;
  758. this.w += v.w;
  759. return this;
  760. },
  761. sub: function ( a, b ) {
  762. this.x = a.x - b.x;
  763. this.y = a.y - b.y;
  764. this.z = a.z - b.z;
  765. this.w = a.w - b.w;
  766. return this;
  767. },
  768. subSelf: function ( v ) {
  769. this.x -= v.x;
  770. this.y -= v.y;
  771. this.z -= v.z;
  772. this.w -= v.w;
  773. return this;
  774. },
  775. multiplyScalar: function ( s ) {
  776. this.x *= s;
  777. this.y *= s;
  778. this.z *= s;
  779. this.w *= s;
  780. return this;
  781. },
  782. divideScalar: function ( s ) {
  783. if ( s ) {
  784. this.x /= s;
  785. this.y /= s;
  786. this.z /= s;
  787. this.w /= s;
  788. } else {
  789. this.x = 0;
  790. this.y = 0;
  791. this.z = 0;
  792. this.w = 1;
  793. }
  794. return this;
  795. },
  796. negate: function() {
  797. return this.multiplyScalar( -1 );
  798. },
  799. dot: function ( v ) {
  800. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  801. },
  802. lengthSq: function () {
  803. return this.dot( this );
  804. },
  805. length: function () {
  806. return Math.sqrt( this.lengthSq() );
  807. },
  808. lengthManhattan: function () {
  809. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  810. },
  811. normalize: function () {
  812. return this.divideScalar( this.length() );
  813. },
  814. setLength: function ( l ) {
  815. return this.normalize().multiplyScalar( l );
  816. },
  817. lerpSelf: function ( v, alpha ) {
  818. this.x += ( v.x - this.x ) * alpha;
  819. this.y += ( v.y - this.y ) * alpha;
  820. this.z += ( v.z - this.z ) * alpha;
  821. this.w += ( v.w - this.w ) * alpha;
  822. return this;
  823. },
  824. clone: function () {
  825. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  826. },
  827. setAxisAngleFromQuaternion: function ( q ) {
  828. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  829. // q is assumed to be normalized
  830. this.w = 2 * Math.acos( q.w );
  831. var s = Math.sqrt( 1 - q.w * q.w );
  832. if ( s < 0.0001 ) {
  833. this.x = 1;
  834. this.y = 0;
  835. this.z = 0;
  836. } else {
  837. this.x = q.x / s;
  838. this.y = q.y / s;
  839. this.z = q.z / s;
  840. }
  841. return this;
  842. },
  843. setAxisAngleFromRotationMatrix: function ( m ) {
  844. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  845. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  846. var angle, x, y, z, // variables for result
  847. epsilon = 0.01, // margin to allow for rounding errors
  848. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  849. te = m.elements,
  850. m11 = te[0], m12 = te[4], m13 = te[8],
  851. m21 = te[1], m22 = te[5], m23 = te[9],
  852. m31 = te[2], m32 = te[6], m33 = te[10];
  853. if ( ( Math.abs( m12 - m21 ) < epsilon )
  854. && ( Math.abs( m13 - m31 ) < epsilon )
  855. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  856. // singularity found
  857. // first check for identity matrix which must have +1 for all terms
  858. // in leading diagonal and zero in other terms
  859. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  860. && ( Math.abs( m13 + m31 ) < epsilon2 )
  861. && ( Math.abs( m23 + m32 ) < epsilon2 )
  862. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  863. // this singularity is identity matrix so angle = 0
  864. this.set( 1, 0, 0, 0 );
  865. return this; // zero angle, arbitrary axis
  866. }
  867. // otherwise this singularity is angle = 180
  868. angle = Math.PI;
  869. var xx = ( m11 + 1 ) / 2;
  870. var yy = ( m22 + 1 ) / 2;
  871. var zz = ( m33 + 1 ) / 2;
  872. var xy = ( m12 + m21 ) / 4;
  873. var xz = ( m13 + m31 ) / 4;
  874. var yz = ( m23 + m32 ) / 4;
  875. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  876. if ( xx < epsilon ) {
  877. x = 0;
  878. y = 0.707106781;
  879. z = 0.707106781;
  880. } else {
  881. x = Math.sqrt( xx );
  882. y = xy / x;
  883. z = xz / x;
  884. }
  885. } else if ( yy > zz ) { // m22 is the largest diagonal term
  886. if ( yy < epsilon ) {
  887. x = 0.707106781;
  888. y = 0;
  889. z = 0.707106781;
  890. } else {
  891. y = Math.sqrt( yy );
  892. x = xy / y;
  893. z = yz / y;
  894. }
  895. } else { // m33 is the largest diagonal term so base result on this
  896. if ( zz < epsilon ) {
  897. x = 0.707106781;
  898. y = 0.707106781;
  899. z = 0;
  900. } else {
  901. z = Math.sqrt( zz );
  902. x = xz / z;
  903. y = yz / z;
  904. }
  905. }
  906. this.set( x, y, z, angle );
  907. return this; // return 180 deg rotation
  908. }
  909. // as we have reached here there are no singularities so we can handle normally
  910. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  911. + ( m13 - m31 ) * ( m13 - m31 )
  912. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  913. if ( Math.abs( s ) < 0.001 ) s = 1;
  914. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  915. // caught by singularity test above, but I've left it in just in case
  916. this.x = ( m32 - m23 ) / s;
  917. this.y = ( m13 - m31 ) / s;
  918. this.z = ( m21 - m12 ) / s;
  919. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  920. return this;
  921. }
  922. };
  923. /**
  924. * @author alteredq / http://alteredqualia.com/
  925. * @author WestLangley / http://github.com/WestLangley
  926. */
  927. THREE.Matrix3 = function () {
  928. this.elements = new Float32Array(9);
  929. };
  930. THREE.Matrix3.prototype = {
  931. constructor: THREE.Matrix3,
  932. multiplyVector3: function ( v ) {
  933. var te = this.elements;
  934. var vx = v.x, vy = v.y, vz = v.z;
  935. v.x = te[0] * vx + te[3] * vy + te[6] * vz;
  936. v.y = te[1] * vx + te[4] * vy + te[7] * vz;
  937. v.z = te[2] * vx + te[5] * vy + te[8] * vz;
  938. return v;
  939. },
  940. multiplyVector3Array: function ( a ) {
  941. var tmp = THREE.Matrix3.__v1;
  942. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  943. tmp.x = a[ i ];
  944. tmp.y = a[ i + 1 ];
  945. tmp.z = a[ i + 2 ];
  946. this.multiplyVector3( tmp );
  947. a[ i ] = tmp.x;
  948. a[ i + 1 ] = tmp.y;
  949. a[ i + 2 ] = tmp.z;
  950. }
  951. return a;
  952. },
  953. getInverse: function ( matrix ) {
  954. // input: THREE.Matrix4
  955. // ( based on http://code.google.com/p/webgl-mjs/ )
  956. var me = matrix.elements;
  957. var a11 = me[10] * me[5] - me[6] * me[9];
  958. var a21 = - me[10] * me[1] + me[2] * me[9];
  959. var a31 = me[6] * me[1] - me[2] * me[5];
  960. var a12 = - me[10] * me[4] + me[6] * me[8];
  961. var a22 = me[10] * me[0] - me[2] * me[8];
  962. var a32 = - me[6] * me[0] + me[2] * me[4];
  963. var a13 = me[9] * me[4] - me[5] * me[8];
  964. var a23 = - me[9] * me[0] + me[1] * me[8];
  965. var a33 = me[5] * me[0] - me[1] * me[4];
  966. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  967. // no inverse
  968. if ( det === 0 ) {
  969. console.warn( "Matrix3.getInverse(): determinant == 0" );
  970. }
  971. var idet = 1.0 / det;
  972. var m = this.elements;
  973. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  974. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  975. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  976. return this;
  977. },
  978. transpose: function () {
  979. var tmp, m = this.elements;
  980. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  981. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  982. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  983. return this;
  984. },
  985. transposeIntoArray: function ( r ) {
  986. var m = this.m;
  987. r[ 0 ] = m[ 0 ];
  988. r[ 1 ] = m[ 3 ];
  989. r[ 2 ] = m[ 6 ];
  990. r[ 3 ] = m[ 1 ];
  991. r[ 4 ] = m[ 4 ];
  992. r[ 5 ] = m[ 7 ];
  993. r[ 6 ] = m[ 2 ];
  994. r[ 7 ] = m[ 5 ];
  995. r[ 8 ] = m[ 8 ];
  996. return this;
  997. }
  998. };
  999. THREE.Matrix3.__v1 = new THREE.Vector3();/**
  1000. * @author mrdoob / http://mrdoob.com/
  1001. * @author supereggbert / http://www.paulbrunt.co.uk/
  1002. * @author philogb / http://blog.thejit.org/
  1003. * @author jordi_ros / http://plattsoft.com
  1004. * @author D1plo1d / http://github.com/D1plo1d
  1005. * @author alteredq / http://alteredqualia.com/
  1006. * @author mikael emtinger / http://gomo.se/
  1007. * @author timknip / http://www.floorplanner.com/
  1008. */
  1009. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1010. this.elements = new Float32Array( 16 );
  1011. this.set(
  1012. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1013. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1014. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1015. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1016. );
  1017. };
  1018. THREE.Matrix4.prototype = {
  1019. constructor: THREE.Matrix4,
  1020. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1021. var te = this.elements;
  1022. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1023. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1024. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1025. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1026. return this;
  1027. },
  1028. identity: function () {
  1029. this.set(
  1030. 1, 0, 0, 0,
  1031. 0, 1, 0, 0,
  1032. 0, 0, 1, 0,
  1033. 0, 0, 0, 1
  1034. );
  1035. return this;
  1036. },
  1037. copy: function ( m ) {
  1038. var me = m.elements;
  1039. this.set(
  1040. me[0], me[4], me[8], me[12],
  1041. me[1], me[5], me[9], me[13],
  1042. me[2], me[6], me[10], me[14],
  1043. me[3], me[7], me[11], me[15]
  1044. );
  1045. return this;
  1046. },
  1047. lookAt: function ( eye, target, up ) {
  1048. var te = this.elements;
  1049. var x = THREE.Matrix4.__v1;
  1050. var y = THREE.Matrix4.__v2;
  1051. var z = THREE.Matrix4.__v3;
  1052. z.sub( eye, target ).normalize();
  1053. if ( z.length() === 0 ) {
  1054. z.z = 1;
  1055. }
  1056. x.cross( up, z ).normalize();
  1057. if ( x.length() === 0 ) {
  1058. z.x += 0.0001;
  1059. x.cross( up, z ).normalize();
  1060. }
  1061. y.cross( z, x );
  1062. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1063. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1064. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1065. return this;
  1066. },
  1067. multiply: function ( a, b ) {
  1068. var ae = a.elements;
  1069. var be = b.elements;
  1070. var te = this.elements;
  1071. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1072. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1073. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1074. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1075. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1076. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1077. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1078. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1079. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1080. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1081. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1082. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1083. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1084. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1085. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1086. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1087. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1088. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1089. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1090. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1091. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1092. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1093. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1094. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1095. return this;
  1096. },
  1097. multiplySelf: function ( m ) {
  1098. return this.multiply( this, m );
  1099. },
  1100. multiplyToArray: function ( a, b, r ) {
  1101. var te = this.elements;
  1102. this.multiply( a, b );
  1103. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1104. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1105. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1106. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1107. return this;
  1108. },
  1109. multiplyScalar: function ( s ) {
  1110. var te = this.elements;
  1111. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1112. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1113. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1114. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1115. return this;
  1116. },
  1117. multiplyVector3: function ( v ) {
  1118. var te = this.elements;
  1119. var vx = v.x, vy = v.y, vz = v.z;
  1120. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1121. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1122. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1123. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1124. return v;
  1125. },
  1126. multiplyVector4: function ( v ) {
  1127. var te = this.elements;
  1128. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1129. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1130. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1131. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1132. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1133. return v;
  1134. },
  1135. multiplyVector3Array: function ( a ) {
  1136. var tmp = THREE.Matrix4.__v1;
  1137. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1138. tmp.x = a[ i ];
  1139. tmp.y = a[ i + 1 ];
  1140. tmp.z = a[ i + 2 ];
  1141. this.multiplyVector3( tmp );
  1142. a[ i ] = tmp.x;
  1143. a[ i + 1 ] = tmp.y;
  1144. a[ i + 2 ] = tmp.z;
  1145. }
  1146. return a;
  1147. },
  1148. rotateAxis: function ( v ) {
  1149. var te = this.elements;
  1150. var vx = v.x, vy = v.y, vz = v.z;
  1151. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1152. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1153. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1154. v.normalize();
  1155. return v;
  1156. },
  1157. crossVector: function ( a ) {
  1158. var te = this.elements;
  1159. var v = new THREE.Vector4();
  1160. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1161. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1162. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1163. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1164. return v;
  1165. },
  1166. determinant: function () {
  1167. var te = this.elements;
  1168. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1169. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1170. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1171. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1172. //TODO: make this more efficient
  1173. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1174. return (
  1175. n14 * n23 * n32 * n41-
  1176. n13 * n24 * n32 * n41-
  1177. n14 * n22 * n33 * n41+
  1178. n12 * n24 * n33 * n41+
  1179. n13 * n22 * n34 * n41-
  1180. n12 * n23 * n34 * n41-
  1181. n14 * n23 * n31 * n42+
  1182. n13 * n24 * n31 * n42+
  1183. n14 * n21 * n33 * n42-
  1184. n11 * n24 * n33 * n42-
  1185. n13 * n21 * n34 * n42+
  1186. n11 * n23 * n34 * n42+
  1187. n14 * n22 * n31 * n43-
  1188. n12 * n24 * n31 * n43-
  1189. n14 * n21 * n32 * n43+
  1190. n11 * n24 * n32 * n43+
  1191. n12 * n21 * n34 * n43-
  1192. n11 * n22 * n34 * n43-
  1193. n13 * n22 * n31 * n44+
  1194. n12 * n23 * n31 * n44+
  1195. n13 * n21 * n32 * n44-
  1196. n11 * n23 * n32 * n44-
  1197. n12 * n21 * n33 * n44+
  1198. n11 * n22 * n33 * n44
  1199. );
  1200. },
  1201. transpose: function () {
  1202. var te = this.elements;
  1203. var tmp;
  1204. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1205. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1206. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1207. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1208. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1209. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1210. return this;
  1211. },
  1212. flattenToArray: function ( flat ) {
  1213. var te = this.elements;
  1214. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1215. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1216. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1217. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1218. return flat;
  1219. },
  1220. flattenToArrayOffset: function( flat, offset ) {
  1221. var te = this.elements;
  1222. flat[ offset ] = te[0];
  1223. flat[ offset + 1 ] = te[1];
  1224. flat[ offset + 2 ] = te[2];
  1225. flat[ offset + 3 ] = te[3];
  1226. flat[ offset + 4 ] = te[4];
  1227. flat[ offset + 5 ] = te[5];
  1228. flat[ offset + 6 ] = te[6];
  1229. flat[ offset + 7 ] = te[7];
  1230. flat[ offset + 8 ] = te[8];
  1231. flat[ offset + 9 ] = te[9];
  1232. flat[ offset + 10 ] = te[10];
  1233. flat[ offset + 11 ] = te[11];
  1234. flat[ offset + 12 ] = te[12];
  1235. flat[ offset + 13 ] = te[13];
  1236. flat[ offset + 14 ] = te[14];
  1237. flat[ offset + 15 ] = te[15];
  1238. return flat;
  1239. },
  1240. getPosition: function () {
  1241. var te = this.elements;
  1242. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1243. },
  1244. setPosition: function ( v ) {
  1245. var te = this.elements;
  1246. te[12] = v.x;
  1247. te[13] = v.y;
  1248. te[14] = v.z;
  1249. return this;
  1250. },
  1251. getColumnX: function () {
  1252. var te = this.elements;
  1253. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1254. },
  1255. getColumnY: function () {
  1256. var te = this.elements;
  1257. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1258. },
  1259. getColumnZ: function() {
  1260. var te = this.elements;
  1261. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1262. },
  1263. getInverse: function ( m ) {
  1264. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1265. var te = this.elements;
  1266. var me = m.elements;
  1267. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1268. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1269. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1270. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1271. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1272. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1273. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1274. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1275. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1276. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1277. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1278. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1279. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1280. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1281. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1282. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1283. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1284. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1285. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1286. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1287. this.multiplyScalar( 1 / m.determinant() );
  1288. return this;
  1289. },
  1290. setRotationFromEuler: function ( v, order ) {
  1291. var te = this.elements;
  1292. var x = v.x, y = v.y, z = v.z;
  1293. var a = Math.cos( x ), b = Math.sin( x );
  1294. var c = Math.cos( y ), d = Math.sin( y );
  1295. var e = Math.cos( z ), f = Math.sin( z );
  1296. if ( order === undefined || order === 'XYZ' ) {
  1297. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1298. te[0] = c * e;
  1299. te[4] = - c * f;
  1300. te[8] = d;
  1301. te[1] = af + be * d;
  1302. te[5] = ae - bf * d;
  1303. te[9] = - b * c;
  1304. te[2] = bf - ae * d;
  1305. te[6] = be + af * d;
  1306. te[10] = a * c;
  1307. } else if ( order === 'YXZ' ) {
  1308. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1309. te[0] = ce + df * b;
  1310. te[4] = de * b - cf;
  1311. te[8] = a * d;
  1312. te[1] = a * f;
  1313. te[5] = a * e;
  1314. te[9] = - b;
  1315. te[2] = cf * b - de;
  1316. te[6] = df + ce * b;
  1317. te[10] = a * c;
  1318. } else if ( order === 'ZXY' ) {
  1319. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1320. te[0] = ce - df * b;
  1321. te[4] = - a * f;
  1322. te[8] = de + cf * b;
  1323. te[1] = cf + de * b;
  1324. te[5] = a * e;
  1325. te[9] = df - ce * b;
  1326. te[2] = - a * d;
  1327. te[6] = b;
  1328. te[10] = a * c;
  1329. } else if ( order === 'ZYX' ) {
  1330. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1331. te[0] = c * e;
  1332. te[4] = be * d - af;
  1333. te[8] = ae * d + bf;
  1334. te[1] = c * f;
  1335. te[5] = bf * d + ae;
  1336. te[9] = af * d - be;
  1337. te[2] = - d;
  1338. te[6] = b * c;
  1339. te[10] = a * c;
  1340. } else if ( order === 'YZX' ) {
  1341. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1342. te[0] = c * e;
  1343. te[4] = bd - ac * f;
  1344. te[8] = bc * f + ad;
  1345. te[1] = f;
  1346. te[5] = a * e;
  1347. te[9] = - b * e;
  1348. te[2] = - d * e;
  1349. te[6] = ad * f + bc;
  1350. te[10] = ac - bd * f;
  1351. } else if ( order === 'XZY' ) {
  1352. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1353. te[0] = c * e;
  1354. te[4] = - f;
  1355. te[8] = d * e;
  1356. te[1] = ac * f + bd;
  1357. te[5] = a * e;
  1358. te[9] = ad * f - bc;
  1359. te[2] = bc * f - ad;
  1360. te[6] = b * e;
  1361. te[10] = bd * f + ac;
  1362. }
  1363. return this;
  1364. },
  1365. setRotationFromQuaternion: function ( q ) {
  1366. var te = this.elements;
  1367. var x = q.x, y = q.y, z = q.z, w = q.w;
  1368. var x2 = x + x, y2 = y + y, z2 = z + z;
  1369. var xx = x * x2, xy = x * y2, xz = x * z2;
  1370. var yy = y * y2, yz = y * z2, zz = z * z2;
  1371. var wx = w * x2, wy = w * y2, wz = w * z2;
  1372. te[0] = 1 - ( yy + zz );
  1373. te[4] = xy - wz;
  1374. te[8] = xz + wy;
  1375. te[1] = xy + wz;
  1376. te[5] = 1 - ( xx + zz );
  1377. te[9] = yz - wx;
  1378. te[2] = xz - wy;
  1379. te[6] = yz + wx;
  1380. te[10] = 1 - ( xx + yy );
  1381. return this;
  1382. },
  1383. compose: function ( translation, rotation, scale ) {
  1384. var te = this.elements;
  1385. var mRotation = THREE.Matrix4.__m1;
  1386. var mScale = THREE.Matrix4.__m2;
  1387. mRotation.identity();
  1388. mRotation.setRotationFromQuaternion( rotation );
  1389. mScale.makeScale( scale.x, scale.y, scale.z );
  1390. this.multiply( mRotation, mScale );
  1391. te[12] = translation.x;
  1392. te[13] = translation.y;
  1393. te[14] = translation.z;
  1394. return this;
  1395. },
  1396. decompose: function ( translation, rotation, scale ) {
  1397. var te = this.elements;
  1398. // grab the axis vectors
  1399. var x = THREE.Matrix4.__v1;
  1400. var y = THREE.Matrix4.__v2;
  1401. var z = THREE.Matrix4.__v3;
  1402. x.set( te[0], te[1], te[2] );
  1403. y.set( te[4], te[5], te[6] );
  1404. z.set( te[8], te[9], te[10] );
  1405. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1406. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1407. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1408. scale.x = x.length();
  1409. scale.y = y.length();
  1410. scale.z = z.length();
  1411. translation.x = te[12];
  1412. translation.y = te[13];
  1413. translation.z = te[14];
  1414. // scale the rotation part
  1415. var matrix = THREE.Matrix4.__m1;
  1416. matrix.copy( this );
  1417. matrix.elements[0] /= scale.x;
  1418. matrix.elements[1] /= scale.x;
  1419. matrix.elements[2] /= scale.x;
  1420. matrix.elements[4] /= scale.y;
  1421. matrix.elements[5] /= scale.y;
  1422. matrix.elements[6] /= scale.y;
  1423. matrix.elements[8] /= scale.z;
  1424. matrix.elements[9] /= scale.z;
  1425. matrix.elements[10] /= scale.z;
  1426. rotation.setFromRotationMatrix( matrix );
  1427. return [ translation, rotation, scale ];
  1428. },
  1429. extractPosition: function ( m ) {
  1430. var te = this.elements;
  1431. var me = m.elements;
  1432. te[12] = me[12];
  1433. te[13] = me[13];
  1434. te[14] = me[14];
  1435. return this;
  1436. },
  1437. extractRotation: function ( m ) {
  1438. var te = this.elements;
  1439. var me = m.elements;
  1440. var vector = THREE.Matrix4.__v1;
  1441. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1442. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1443. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1444. te[0] = me[0] * scaleX;
  1445. te[1] = me[1] * scaleX;
  1446. te[2] = me[2] * scaleX;
  1447. te[4] = me[4] * scaleY;
  1448. te[5] = me[5] * scaleY;
  1449. te[6] = me[6] * scaleY;
  1450. te[8] = me[8] * scaleZ;
  1451. te[9] = me[9] * scaleZ;
  1452. te[10] = me[10] * scaleZ;
  1453. return this;
  1454. },
  1455. //
  1456. translate: function ( v ) {
  1457. var te = this.elements;
  1458. var x = v.x, y = v.y, z = v.z;
  1459. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1460. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1461. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1462. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1463. return this;
  1464. },
  1465. rotateX: function ( angle ) {
  1466. var te = this.elements;
  1467. var m12 = te[4];
  1468. var m22 = te[5];
  1469. var m32 = te[6];
  1470. var m42 = te[7];
  1471. var m13 = te[8];
  1472. var m23 = te[9];
  1473. var m33 = te[10];
  1474. var m43 = te[11];
  1475. var c = Math.cos( angle );
  1476. var s = Math.sin( angle );
  1477. te[4] = c * m12 + s * m13;
  1478. te[5] = c * m22 + s * m23;
  1479. te[6] = c * m32 + s * m33;
  1480. te[7] = c * m42 + s * m43;
  1481. te[8] = c * m13 - s * m12;
  1482. te[9] = c * m23 - s * m22;
  1483. te[10] = c * m33 - s * m32;
  1484. te[11] = c * m43 - s * m42;
  1485. return this;
  1486. },
  1487. rotateY: function ( angle ) {
  1488. var te = this.elements;
  1489. var m11 = te[0];
  1490. var m21 = te[1];
  1491. var m31 = te[2];
  1492. var m41 = te[3];
  1493. var m13 = te[8];
  1494. var m23 = te[9];
  1495. var m33 = te[10];
  1496. var m43 = te[11];
  1497. var c = Math.cos( angle );
  1498. var s = Math.sin( angle );
  1499. te[0] = c * m11 - s * m13;
  1500. te[1] = c * m21 - s * m23;
  1501. te[2] = c * m31 - s * m33;
  1502. te[3] = c * m41 - s * m43;
  1503. te[8] = c * m13 + s * m11;
  1504. te[9] = c * m23 + s * m21;
  1505. te[10] = c * m33 + s * m31;
  1506. te[11] = c * m43 + s * m41;
  1507. return this;
  1508. },
  1509. rotateZ: function ( angle ) {
  1510. var te = this.elements;
  1511. var m11 = te[0];
  1512. var m21 = te[1];
  1513. var m31 = te[2];
  1514. var m41 = te[3];
  1515. var m12 = te[4];
  1516. var m22 = te[5];
  1517. var m32 = te[6];
  1518. var m42 = te[7];
  1519. var c = Math.cos( angle );
  1520. var s = Math.sin( angle );
  1521. te[0] = c * m11 + s * m12;
  1522. te[1] = c * m21 + s * m22;
  1523. te[2] = c * m31 + s * m32;
  1524. te[3] = c * m41 + s * m42;
  1525. te[4] = c * m12 - s * m11;
  1526. te[5] = c * m22 - s * m21;
  1527. te[6] = c * m32 - s * m31;
  1528. te[7] = c * m42 - s * m41;
  1529. return this;
  1530. },
  1531. rotateByAxis: function ( axis, angle ) {
  1532. var te = this.elements;
  1533. // optimize by checking axis
  1534. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1535. return this.rotateX( angle );
  1536. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1537. return this.rotateY( angle );
  1538. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1539. return this.rotateZ( angle );
  1540. }
  1541. var x = axis.x, y = axis.y, z = axis.z;
  1542. var n = Math.sqrt(x * x + y * y + z * z);
  1543. x /= n;
  1544. y /= n;
  1545. z /= n;
  1546. var xx = x * x, yy = y * y, zz = z * z;
  1547. var c = Math.cos( angle );
  1548. var s = Math.sin( angle );
  1549. var oneMinusCosine = 1 - c;
  1550. var xy = x * y * oneMinusCosine;
  1551. var xz = x * z * oneMinusCosine;
  1552. var yz = y * z * oneMinusCosine;
  1553. var xs = x * s;
  1554. var ys = y * s;
  1555. var zs = z * s;
  1556. var r11 = xx + (1 - xx) * c;
  1557. var r21 = xy + zs;
  1558. var r31 = xz - ys;
  1559. var r12 = xy - zs;
  1560. var r22 = yy + (1 - yy) * c;
  1561. var r32 = yz + xs;
  1562. var r13 = xz + ys;
  1563. var r23 = yz - xs;
  1564. var r33 = zz + (1 - zz) * c;
  1565. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1566. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1567. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1568. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1569. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1570. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1571. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1572. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1573. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1574. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1575. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1576. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1577. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1578. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1579. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1580. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1581. return this;
  1582. },
  1583. scale: function ( v ) {
  1584. var te = this.elements;
  1585. var x = v.x, y = v.y, z = v.z;
  1586. te[0] *= x; te[4] *= y; te[8] *= z;
  1587. te[1] *= x; te[5] *= y; te[9] *= z;
  1588. te[2] *= x; te[6] *= y; te[10] *= z;
  1589. te[3] *= x; te[7] *= y; te[11] *= z;
  1590. return this;
  1591. },
  1592. getMaxScaleOnAxis: function () {
  1593. var te = this.elements;
  1594. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  1595. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  1596. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  1597. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  1598. },
  1599. //
  1600. makeTranslation: function ( x, y, z ) {
  1601. this.set(
  1602. 1, 0, 0, x,
  1603. 0, 1, 0, y,
  1604. 0, 0, 1, z,
  1605. 0, 0, 0, 1
  1606. );
  1607. return this;
  1608. },
  1609. makeRotationX: function ( theta ) {
  1610. var c = Math.cos( theta ), s = Math.sin( theta );
  1611. this.set(
  1612. 1, 0, 0, 0,
  1613. 0, c, -s, 0,
  1614. 0, s, c, 0,
  1615. 0, 0, 0, 1
  1616. );
  1617. return this;
  1618. },
  1619. makeRotationY: function ( theta ) {
  1620. var c = Math.cos( theta ), s = Math.sin( theta );
  1621. this.set(
  1622. c, 0, s, 0,
  1623. 0, 1, 0, 0,
  1624. -s, 0, c, 0,
  1625. 0, 0, 0, 1
  1626. );
  1627. return this;
  1628. },
  1629. makeRotationZ: function ( theta ) {
  1630. var c = Math.cos( theta ), s = Math.sin( theta );
  1631. this.set(
  1632. c, -s, 0, 0,
  1633. s, c, 0, 0,
  1634. 0, 0, 1, 0,
  1635. 0, 0, 0, 1
  1636. );
  1637. return this;
  1638. },
  1639. makeRotationAxis: function ( axis, angle ) {
  1640. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1641. var c = Math.cos( angle );
  1642. var s = Math.sin( angle );
  1643. var t = 1 - c;
  1644. var x = axis.x, y = axis.y, z = axis.z;
  1645. var tx = t * x, ty = t * y;
  1646. this.set(
  1647. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1648. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1649. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1650. 0, 0, 0, 1
  1651. );
  1652. return this;
  1653. },
  1654. makeScale: function ( x, y, z ) {
  1655. this.set(
  1656. x, 0, 0, 0,
  1657. 0, y, 0, 0,
  1658. 0, 0, z, 0,
  1659. 0, 0, 0, 1
  1660. );
  1661. return this;
  1662. },
  1663. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1664. var te = this.elements;
  1665. var x = 2 * near / ( right - left );
  1666. var y = 2 * near / ( top - bottom );
  1667. var a = ( right + left ) / ( right - left );
  1668. var b = ( top + bottom ) / ( top - bottom );
  1669. var c = - ( far + near ) / ( far - near );
  1670. var d = - 2 * far * near / ( far - near );
  1671. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1672. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1673. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1674. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1675. return this;
  1676. },
  1677. makePerspective: function ( fov, aspect, near, far ) {
  1678. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1679. var ymin = - ymax;
  1680. var xmin = ymin * aspect;
  1681. var xmax = ymax * aspect;
  1682. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1683. },
  1684. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1685. var te = this.elements;
  1686. var w = right - left;
  1687. var h = top - bottom;
  1688. var p = far - near;
  1689. var x = ( right + left ) / w;
  1690. var y = ( top + bottom ) / h;
  1691. var z = ( far + near ) / p;
  1692. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1693. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1694. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1695. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1696. return this;
  1697. },
  1698. clone: function () {
  1699. var te = this.elements;
  1700. return new THREE.Matrix4(
  1701. te[0], te[4], te[8], te[12],
  1702. te[1], te[5], te[9], te[13],
  1703. te[2], te[6], te[10], te[14],
  1704. te[3], te[7], te[11], te[15]
  1705. );
  1706. }
  1707. };
  1708. THREE.Matrix4.__v1 = new THREE.Vector3();
  1709. THREE.Matrix4.__v2 = new THREE.Vector3();
  1710. THREE.Matrix4.__v3 = new THREE.Vector3();
  1711. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1712. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1713. /**
  1714. * https://github.com/mrdoob/eventtarget.js/
  1715. */
  1716. THREE.EventTarget = function () {
  1717. var listeners = {};
  1718. this.addEventListener = function ( type, listener ) {
  1719. if ( listeners[ type ] === undefined ) {
  1720. listeners[ type ] = [];
  1721. }
  1722. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1723. listeners[ type ].push( listener );
  1724. }
  1725. };
  1726. this.dispatchEvent = function ( event ) {
  1727. var listenerArray = listeners[ event.type ];
  1728. if ( listenerArray !== undefined ) {
  1729. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  1730. listenerArray[ i ]( event );
  1731. }
  1732. }
  1733. };
  1734. this.removeEventListener = function ( type, listener ) {
  1735. var index = listeners[ type ].indexOf( listener );
  1736. if ( index !== - 1 ) {
  1737. listeners[ type ].splice( index, 1 );
  1738. }
  1739. };
  1740. };
  1741. /**
  1742. * @author mrdoob / http://mrdoob.com/
  1743. * @author alteredq / http://alteredqualia.com/
  1744. */
  1745. THREE.Frustum = function ( ) {
  1746. this.planes = [
  1747. new THREE.Vector4(),
  1748. new THREE.Vector4(),
  1749. new THREE.Vector4(),
  1750. new THREE.Vector4(),
  1751. new THREE.Vector4(),
  1752. new THREE.Vector4()
  1753. ];
  1754. };
  1755. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  1756. var plane;
  1757. var planes = this.planes;
  1758. var me = m.elements;
  1759. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  1760. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  1761. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  1762. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  1763. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  1764. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  1765. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  1766. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  1767. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  1768. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  1769. for ( var i = 0; i < 6; i ++ ) {
  1770. plane = planes[ i ];
  1771. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  1772. }
  1773. };
  1774. THREE.Frustum.prototype.contains = function ( object ) {
  1775. var distance = 0.0;
  1776. var planes = this.planes;
  1777. var matrix = object.matrixWorld;
  1778. var me = matrix.elements;
  1779. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  1780. for ( var i = 0; i < 6; i ++ ) {
  1781. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  1782. if ( distance <= radius ) return false;
  1783. }
  1784. return true;
  1785. };
  1786. THREE.Frustum.__v1 = new THREE.Vector3();
  1787. /**
  1788. * @author mrdoob / http://mrdoob.com/
  1789. */
  1790. ( function ( THREE ) {
  1791. THREE.Ray = function ( origin, direction, near, far ) {
  1792. this.origin = origin || new THREE.Vector3();
  1793. this.direction = direction || new THREE.Vector3();
  1794. this.near = near || 0;
  1795. this.far = far || Infinity;
  1796. };
  1797. var originCopy = new THREE.Vector3();
  1798. var localOriginCopy = new THREE.Vector3();
  1799. var localDirectionCopy = new THREE.Vector3();
  1800. var vector = new THREE.Vector3();
  1801. var normal = new THREE.Vector3();
  1802. var intersectPoint = new THREE.Vector3();
  1803. var inverseMatrix = new THREE.Matrix4();
  1804. var descSort = function ( a, b ) {
  1805. return a.distance - b.distance;
  1806. };
  1807. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  1808. var distanceFromIntersection = function ( origin, direction, position ) {
  1809. v0.sub( position, origin );
  1810. var dot = v0.dot( direction );
  1811. var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  1812. var distance = position.distanceTo( intersect );
  1813. return distance;
  1814. };
  1815. // http://www.blackpawn.com/texts/pointinpoly/default.html
  1816. var pointInFace3 = function ( p, a, b, c ) {
  1817. v0.sub( c, a );
  1818. v1.sub( b, a );
  1819. v2.sub( p, a );
  1820. var dot00 = v0.dot( v0 );
  1821. var dot01 = v0.dot( v1 );
  1822. var dot02 = v0.dot( v2 );
  1823. var dot11 = v1.dot( v1 );
  1824. var dot12 = v1.dot( v2 );
  1825. var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  1826. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  1827. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  1828. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  1829. };
  1830. var intersectObject = function ( object, ray, intersects ) {
  1831. if ( object instanceof THREE.Particle ) {
  1832. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1833. if ( distance > object.scale.x ) {
  1834. return intersects;
  1835. }
  1836. intersects.push( {
  1837. distance: distance,
  1838. point: object.position,
  1839. face: null,
  1840. object: object
  1841. } );
  1842. } else if ( object instanceof THREE.Mesh ) {
  1843. // Checking boundingSphere
  1844. var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
  1845. // Checking distance to ray
  1846. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1847. if ( distance > scaledRadius) {
  1848. return intersects;
  1849. }
  1850. // Checking faces
  1851. var geometry = object.geometry;
  1852. var vertices = geometry.vertices;
  1853. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  1854. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  1855. var side = object.material.side;
  1856. var a, b, c, d;
  1857. var precision = ray.precision;
  1858. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  1859. originCopy.copy( ray.origin );
  1860. inverseMatrix.getInverse( object.matrixWorld );
  1861. localOriginCopy.copy( originCopy );
  1862. inverseMatrix.multiplyVector3( localOriginCopy );
  1863. localDirectionCopy.copy( ray.direction );
  1864. inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
  1865. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  1866. var face = geometry.faces[ f ];
  1867. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  1868. if ( material === undefined ) continue;
  1869. side = material.side;
  1870. vector.sub( face.centroid, localOriginCopy );
  1871. var normal = face.normal;
  1872. var dot = localDirectionCopy.dot( normal );
  1873. // bail if ray and plane are parallel
  1874. if ( Math.abs( dot ) < precision ) continue;
  1875. // calc distance to plane
  1876. var scalar = normal.dot( vector ) / dot;
  1877. // if negative distance, then plane is behind ray
  1878. if ( scalar < 0 ) continue;
  1879. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  1880. intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
  1881. if ( face instanceof THREE.Face3 ) {
  1882. a = vertices[ face.a ];
  1883. b = vertices[ face.b ];
  1884. c = vertices[ face.c ];
  1885. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  1886. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1887. distance = originCopy.distanceTo( point );
  1888. if ( distance < ray.near || distance > ray.far ) continue;
  1889. intersects.push( {
  1890. distance: distance,
  1891. point: point,
  1892. face: face,
  1893. faceIndex: f,
  1894. object: object
  1895. } );
  1896. }
  1897. } else if ( face instanceof THREE.Face4 ) {
  1898. a = vertices[ face.a ];
  1899. b = vertices[ face.b ];
  1900. c = vertices[ face.c ];
  1901. d = vertices[ face.d ];
  1902. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  1903. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1904. distance = originCopy.distanceTo( point );
  1905. if ( distance < ray.near || distance > ray.far ) continue;
  1906. intersects.push( {
  1907. distance: distance,
  1908. point: point,
  1909. face: face,
  1910. faceIndex: f,
  1911. object: object
  1912. } );
  1913. }
  1914. }
  1915. }
  1916. }
  1917. }
  1918. };
  1919. var intersectDescendants = function ( object, ray, intersects ) {
  1920. var descendants = object.getDescendants();
  1921. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  1922. intersectObject( descendants[ i ], ray, intersects );
  1923. }
  1924. };
  1925. //
  1926. THREE.Ray.prototype.precision = 0.0001;
  1927. THREE.Ray.prototype.set = function ( origin, direction ) {
  1928. this.origin = origin;
  1929. this.direction = direction;
  1930. };
  1931. THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
  1932. var intersects = [];
  1933. if ( recursive === true ) {
  1934. intersectDescendants( object, this, intersects );
  1935. }
  1936. intersectObject( object, this, intersects );
  1937. intersects.sort( descSort );
  1938. return intersects;
  1939. };
  1940. THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
  1941. var intersects = [];
  1942. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  1943. intersectObject( objects[ i ], this, intersects );
  1944. if ( recursive === true ) {
  1945. intersectDescendants( objects[ i ], this, intersects );
  1946. }
  1947. }
  1948. intersects.sort( descSort );
  1949. return intersects;
  1950. };
  1951. }( THREE ) );
  1952. /**
  1953. * @author mrdoob / http://mrdoob.com/
  1954. */
  1955. THREE.Rectangle = function () {
  1956. var _left = 0;
  1957. var _top = 0;
  1958. var _right = 0;
  1959. var _bottom = 0;
  1960. var _width = 0;
  1961. var _height = 0;
  1962. var _isEmpty = true;
  1963. function resize() {
  1964. _width = _right - _left;
  1965. _height = _bottom - _top;
  1966. }
  1967. this.getX = function () {
  1968. return _left;
  1969. };
  1970. this.getY = function () {
  1971. return _top;
  1972. };
  1973. this.getWidth = function () {
  1974. return _width;
  1975. };
  1976. this.getHeight = function () {
  1977. return _height;
  1978. };
  1979. this.getLeft = function() {
  1980. return _left;
  1981. };
  1982. this.getTop = function() {
  1983. return _top;
  1984. };
  1985. this.getRight = function() {
  1986. return _right;
  1987. };
  1988. this.getBottom = function() {
  1989. return _bottom;
  1990. };
  1991. this.set = function ( left, top, right, bottom ) {
  1992. _isEmpty = false;
  1993. _left = left; _top = top;
  1994. _right = right; _bottom = bottom;
  1995. resize();
  1996. };
  1997. this.addPoint = function ( x, y ) {
  1998. if ( _isEmpty === true ) {
  1999. _isEmpty = false;
  2000. _left = x; _top = y;
  2001. _right = x; _bottom = y;
  2002. resize();
  2003. } else {
  2004. _left = _left < x ? _left : x; // Math.min( _left, x );
  2005. _top = _top < y ? _top : y; // Math.min( _top, y );
  2006. _right = _right > x ? _right : x; // Math.max( _right, x );
  2007. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  2008. resize();
  2009. }
  2010. };
  2011. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  2012. if ( _isEmpty === true ) {
  2013. _isEmpty = false;
  2014. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  2015. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  2016. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  2017. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  2018. resize();
  2019. } else {
  2020. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  2021. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  2022. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  2023. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  2024. resize();
  2025. };
  2026. };
  2027. this.addRectangle = function ( r ) {
  2028. if ( _isEmpty === true ) {
  2029. _isEmpty = false;
  2030. _left = r.getLeft(); _top = r.getTop();
  2031. _right = r.getRight(); _bottom = r.getBottom();
  2032. resize();
  2033. } else {
  2034. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  2035. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  2036. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  2037. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  2038. resize();
  2039. }
  2040. };
  2041. this.inflate = function ( v ) {
  2042. _left -= v; _top -= v;
  2043. _right += v; _bottom += v;
  2044. resize();
  2045. };
  2046. this.minSelf = function ( r ) {
  2047. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  2048. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  2049. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  2050. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  2051. resize();
  2052. };
  2053. this.intersects = function ( r ) {
  2054. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  2055. if ( _right < r.getLeft() ) return false;
  2056. if ( _left > r.getRight() ) return false;
  2057. if ( _bottom < r.getTop() ) return false;
  2058. if ( _top > r.getBottom() ) return false;
  2059. return true;
  2060. };
  2061. this.empty = function () {
  2062. _isEmpty = true;
  2063. _left = 0; _top = 0;
  2064. _right = 0; _bottom = 0;
  2065. resize();
  2066. };
  2067. this.isEmpty = function () {
  2068. return _isEmpty;
  2069. };
  2070. };
  2071. /**
  2072. * @author alteredq / http://alteredqualia.com/
  2073. */
  2074. THREE.Math = {
  2075. // Clamp value to range <a, b>
  2076. clamp: function ( x, a, b ) {
  2077. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2078. },
  2079. // Clamp value to range <a, inf)
  2080. clampBottom: function ( x, a ) {
  2081. return x < a ? a : x;
  2082. },
  2083. // Linear mapping from range <a1, a2> to range <b1, b2>
  2084. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2085. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2086. },
  2087. // Random float from <0, 1> with 16 bits of randomness
  2088. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2089. random16: function () {
  2090. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2091. },
  2092. // Random integer from <low, high> interval
  2093. randInt: function ( low, high ) {
  2094. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2095. },
  2096. // Random float from <low, high> interval
  2097. randFloat: function ( low, high ) {
  2098. return low + Math.random() * ( high - low );
  2099. },
  2100. // Random float from <-range/2, range/2> interval
  2101. randFloatSpread: function ( range ) {
  2102. return range * ( 0.5 - Math.random() );
  2103. },
  2104. sign: function ( x ) {
  2105. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2106. }
  2107. };
  2108. /**
  2109. * @author mrdoob / http://mrdoob.com/
  2110. * @author mikael emtinger / http://gomo.se/
  2111. * @author alteredq / http://alteredqualia.com/
  2112. */
  2113. THREE.Object3D = function () {
  2114. THREE.Object3DLibrary.push( this );
  2115. this.id = THREE.Object3DIdCount ++;
  2116. this.name = '';
  2117. this.properties = {};
  2118. this.parent = undefined;
  2119. this.children = [];
  2120. this.up = new THREE.Vector3( 0, 1, 0 );
  2121. this.position = new THREE.Vector3();
  2122. this.rotation = new THREE.Vector3();
  2123. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  2124. this.scale = new THREE.Vector3( 1, 1, 1 );
  2125. this.renderDepth = null;
  2126. this.rotationAutoUpdate = true;
  2127. this.matrix = new THREE.Matrix4();
  2128. this.matrixWorld = new THREE.Matrix4();
  2129. this.matrixRotationWorld = new THREE.Matrix4();
  2130. this.matrixAutoUpdate = true;
  2131. this.matrixWorldNeedsUpdate = true;
  2132. this.quaternion = new THREE.Quaternion();
  2133. this.useQuaternion = false;
  2134. this.boundRadius = 0.0;
  2135. this.boundRadiusScale = 1.0;
  2136. this.visible = true;
  2137. this.castShadow = false;
  2138. this.receiveShadow = false;
  2139. this.frustumCulled = true;
  2140. this._vector = new THREE.Vector3();
  2141. };
  2142. THREE.Object3D.prototype = {
  2143. constructor: THREE.Object3D,
  2144. applyMatrix: function ( matrix ) {
  2145. this.matrix.multiply( matrix, this.matrix );
  2146. this.scale.getScaleFromMatrix( this.matrix );
  2147. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2148. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2149. this.position.getPositionFromMatrix( this.matrix );
  2150. },
  2151. translate: function ( distance, axis ) {
  2152. this.matrix.rotateAxis( axis );
  2153. this.position.addSelf( axis.multiplyScalar( distance ) );
  2154. },
  2155. translateX: function ( distance ) {
  2156. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2157. },
  2158. translateY: function ( distance ) {
  2159. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2160. },
  2161. translateZ: function ( distance ) {
  2162. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2163. },
  2164. localToWorld: function ( vector ) {
  2165. return this.matrixWorld.multiplyVector3( vector );
  2166. },
  2167. worldToLocal: function ( vector ) {
  2168. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2169. },
  2170. lookAt: function ( vector ) {
  2171. // TODO: Add hierarchy support.
  2172. this.matrix.lookAt( vector, this.position, this.up );
  2173. if ( this.rotationAutoUpdate ) {
  2174. if ( this.useQuaternion === false ) {
  2175. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2176. } else {
  2177. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  2178. }
  2179. }
  2180. },
  2181. add: function ( object ) {
  2182. if ( object === this ) {
  2183. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2184. return;
  2185. }
  2186. if ( object instanceof THREE.Object3D ) {
  2187. if ( object.parent !== undefined ) {
  2188. object.parent.remove( object );
  2189. }
  2190. object.parent = this;
  2191. this.children.push( object );
  2192. // add to scene
  2193. var scene = this;
  2194. while ( scene.parent !== undefined ) {
  2195. scene = scene.parent;
  2196. }
  2197. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2198. scene.__addObject( object );
  2199. }
  2200. }
  2201. },
  2202. remove: function ( object ) {
  2203. var index = this.children.indexOf( object );
  2204. if ( index !== - 1 ) {
  2205. object.parent = undefined;
  2206. this.children.splice( index, 1 );
  2207. // remove from scene
  2208. var scene = this;
  2209. while ( scene.parent !== undefined ) {
  2210. scene = scene.parent;
  2211. }
  2212. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2213. scene.__removeObject( object );
  2214. }
  2215. }
  2216. },
  2217. traverse: function ( callback ) {
  2218. callback( this );
  2219. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2220. this.children[ i ].traverse( callback );
  2221. }
  2222. },
  2223. getChildByName: function ( name, recursive ) {
  2224. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2225. var child = this.children[ i ];
  2226. if ( child.name === name ) {
  2227. return child;
  2228. }
  2229. if ( recursive === true ) {
  2230. child = child.getChildByName( name, recursive );
  2231. if ( child !== undefined ) {
  2232. return child;
  2233. }
  2234. }
  2235. }
  2236. return undefined;
  2237. },
  2238. getDescendants: function ( array ) {
  2239. if ( array === undefined ) array = [];
  2240. Array.prototype.push.apply( array, this.children );
  2241. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2242. this.children[ i ].getDescendants( array );
  2243. }
  2244. return array;
  2245. },
  2246. updateMatrix: function () {
  2247. this.matrix.setPosition( this.position );
  2248. if ( this.useQuaternion === false ) {
  2249. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2250. } else {
  2251. this.matrix.setRotationFromQuaternion( this.quaternion );
  2252. }
  2253. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2254. this.matrix.scale( this.scale );
  2255. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2256. }
  2257. this.matrixWorldNeedsUpdate = true;
  2258. },
  2259. updateMatrixWorld: function ( force ) {
  2260. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2261. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2262. if ( this.parent === undefined ) {
  2263. this.matrixWorld.copy( this.matrix );
  2264. } else {
  2265. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2266. }
  2267. this.matrixWorldNeedsUpdate = false;
  2268. force = true;
  2269. }
  2270. // update children
  2271. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2272. this.children[ i ].updateMatrixWorld( force );
  2273. }
  2274. },
  2275. clone: function ( object ) {
  2276. if ( object === undefined ) object = new THREE.Object3D();
  2277. object.name = this.name;
  2278. object.up.copy( this.up );
  2279. object.position.copy( this.position );
  2280. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  2281. object.eulerOrder = this.eulerOrder;
  2282. object.scale.copy( this.scale );
  2283. object.renderDepth = this.renderDepth;
  2284. object.rotationAutoUpdate = this.rotationAutoUpdate;
  2285. object.matrix.copy( this.matrix );
  2286. object.matrixWorld.copy( this.matrixWorld );
  2287. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  2288. object.matrixAutoUpdate = this.matrixAutoUpdate;
  2289. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  2290. object.quaternion.copy( this.quaternion );
  2291. object.useQuaternion = this.useQuaternion;
  2292. object.boundRadius = this.boundRadius;
  2293. object.boundRadiusScale = this.boundRadiusScale;
  2294. object.visible = this.visible;
  2295. object.castShadow = this.castShadow;
  2296. object.receiveShadow = this.receiveShadow;
  2297. object.frustumCulled = this.frustumCulled;
  2298. for ( var i = 0; i < this.children.length; i ++ ) {
  2299. var child = this.children[ i ];
  2300. object.add( child.clone() );
  2301. }
  2302. return object;
  2303. },
  2304. deallocate: function () {
  2305. var index = THREE.Object3DLibrary.indexOf( this );
  2306. if ( index !== -1 ) THREE.Object3DLibrary.splice( index, 1 );
  2307. }
  2308. };
  2309. THREE.Object3D.__m1 = new THREE.Matrix4();
  2310. THREE.Object3D.defaultEulerOrder = 'XYZ',
  2311. THREE.Object3DIdCount = 0;
  2312. THREE.Object3DLibrary = [];
  2313. /**
  2314. * @author mrdoob / http://mrdoob.com/
  2315. * @author supereggbert / http://www.paulbrunt.co.uk/
  2316. * @author julianwa / https://github.com/julianwa
  2317. */
  2318. THREE.Projector = function() {
  2319. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  2320. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  2321. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  2322. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  2323. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  2324. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  2325. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  2326. _vector3 = new THREE.Vector3(),
  2327. _vector4 = new THREE.Vector4(),
  2328. _viewProjectionMatrix = new THREE.Matrix4(),
  2329. _modelViewProjectionMatrix = new THREE.Matrix4(),
  2330. _normalMatrix = new THREE.Matrix3(),
  2331. _frustum = new THREE.Frustum(),
  2332. _clippedVertex1PositionScreen = new THREE.Vector4(),
  2333. _clippedVertex2PositionScreen = new THREE.Vector4(),
  2334. _face3VertexNormals;
  2335. this.projectVector = function ( vector, camera ) {
  2336. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2337. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2338. _viewProjectionMatrix.multiplyVector3( vector );
  2339. return vector;
  2340. };
  2341. this.unprojectVector = function ( vector, camera ) {
  2342. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  2343. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  2344. _viewProjectionMatrix.multiplyVector3( vector );
  2345. return vector;
  2346. };
  2347. this.pickingRay = function ( vector, camera ) {
  2348. var end, ray, t;
  2349. // set two vectors with opposing z values
  2350. vector.z = -1.0;
  2351. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  2352. this.unprojectVector( vector, camera );
  2353. this.unprojectVector( end, camera );
  2354. // find direction from vector to end
  2355. end.subSelf( vector ).normalize();
  2356. return new THREE.Ray( vector, end );
  2357. };
  2358. var projectGraph = function ( root, sortObjects ) {
  2359. _objectCount = 0;
  2360. _renderData.objects.length = 0;
  2361. _renderData.sprites.length = 0;
  2362. _renderData.lights.length = 0;
  2363. var projectObject = function ( parent ) {
  2364. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  2365. var object = parent.children[ c ];
  2366. if ( object.visible === false ) continue;
  2367. if ( object instanceof THREE.Light ) {
  2368. _renderData.lights.push( object );
  2369. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  2370. if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
  2371. _object = getNextObjectInPool();
  2372. _object.object = object;
  2373. if ( object.renderDepth !== null ) {
  2374. _object.z = object.renderDepth;
  2375. } else {
  2376. _vector3.copy( object.matrixWorld.getPosition() );
  2377. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2378. _object.z = _vector3.z;
  2379. }
  2380. _renderData.objects.push( _object );
  2381. }
  2382. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  2383. _object = getNextObjectInPool();
  2384. _object.object = object;
  2385. // TODO: Find an elegant and performant solution and remove this dupe code.
  2386. if ( object.renderDepth !== null ) {
  2387. _object.z = object.renderDepth;
  2388. } else {
  2389. _vector3.copy( object.matrixWorld.getPosition() );
  2390. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2391. _object.z = _vector3.z;
  2392. }
  2393. _renderData.sprites.push( _object );
  2394. } else {
  2395. _object = getNextObjectInPool();
  2396. _object.object = object;
  2397. if ( object.renderDepth !== null ) {
  2398. _object.z = object.renderDepth;
  2399. } else {
  2400. _vector3.copy( object.matrixWorld.getPosition() );
  2401. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2402. _object.z = _vector3.z;
  2403. }
  2404. _renderData.objects.push( _object );
  2405. }
  2406. projectObject( object );
  2407. }
  2408. };
  2409. projectObject( root );
  2410. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  2411. return _renderData;
  2412. };
  2413. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  2414. var near = camera.near, far = camera.far, visible = false,
  2415. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object, modelMatrix,
  2416. geometry, vertices, vertex, vertexPositionScreen,
  2417. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  2418. v1, v2, v3, v4, isFaceMaterial, objectMaterials, material, side;
  2419. _face3Count = 0;
  2420. _face4Count = 0;
  2421. _lineCount = 0;
  2422. _particleCount = 0;
  2423. _renderData.elements.length = 0;
  2424. scene.updateMatrixWorld();
  2425. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2426. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2427. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2428. _frustum.setFromMatrix( _viewProjectionMatrix );
  2429. _renderData = projectGraph( scene, sortObjects );
  2430. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  2431. object = _renderData.objects[ o ].object;
  2432. modelMatrix = object.matrixWorld;
  2433. _vertexCount = 0;
  2434. if ( object instanceof THREE.Mesh ) {
  2435. geometry = object.geometry;
  2436. vertices = geometry.vertices;
  2437. faces = geometry.faces;
  2438. faceVertexUvs = geometry.faceVertexUvs;
  2439. _normalMatrix.getInverse( modelMatrix );
  2440. _normalMatrix.transpose();
  2441. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2442. objectMaterials = isFaceMaterial === true ? object.material : null;
  2443. side = object.material.side;
  2444. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  2445. _vertex = getNextVertexInPool();
  2446. _vertex.positionWorld.copy( vertices[ v ] );
  2447. modelMatrix.multiplyVector3( _vertex.positionWorld );
  2448. _vertex.positionScreen.copy( _vertex.positionWorld );
  2449. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  2450. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  2451. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  2452. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  2453. }
  2454. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  2455. face = faces[ f ];
  2456. material = isFaceMaterial === true ? objectMaterials.materials[ face.materialIndex ] : object.material;
  2457. if ( material === undefined ) continue;
  2458. side = material.side;
  2459. if ( face instanceof THREE.Face3 ) {
  2460. v1 = _vertexPool[ face.a ];
  2461. v2 = _vertexPool[ face.b ];
  2462. v3 = _vertexPool[ face.c ];
  2463. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  2464. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2465. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  2466. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2467. _face = getNextFace3InPool();
  2468. _face.v1.copy( v1 );
  2469. _face.v2.copy( v2 );
  2470. _face.v3.copy( v3 );
  2471. } else {
  2472. continue;
  2473. }
  2474. } else {
  2475. continue;
  2476. }
  2477. } else if ( face instanceof THREE.Face4 ) {
  2478. v1 = _vertexPool[ face.a ];
  2479. v2 = _vertexPool[ face.b ];
  2480. v3 = _vertexPool[ face.c ];
  2481. v4 = _vertexPool[ face.d ];
  2482. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  2483. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2484. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  2485. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  2486. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  2487. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2488. _face = getNextFace4InPool();
  2489. _face.v1.copy( v1 );
  2490. _face.v2.copy( v2 );
  2491. _face.v3.copy( v3 );
  2492. _face.v4.copy( v4 );
  2493. } else {
  2494. continue;
  2495. }
  2496. } else {
  2497. continue;
  2498. }
  2499. }
  2500. _face.normalWorld.copy( face.normal );
  2501. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  2502. _normalMatrix.multiplyVector3( _face.normalWorld ).normalize();
  2503. _face.centroidWorld.copy( face.centroid );
  2504. modelMatrix.multiplyVector3( _face.centroidWorld );
  2505. _face.centroidScreen.copy( _face.centroidWorld );
  2506. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  2507. faceVertexNormals = face.vertexNormals;
  2508. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  2509. normal = _face.vertexNormalsWorld[ n ];
  2510. normal.copy( faceVertexNormals[ n ] );
  2511. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  2512. _normalMatrix.multiplyVector3( normal ).normalize();
  2513. }
  2514. _face.vertexNormalsLength = faceVertexNormals.length;
  2515. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  2516. uvs = faceVertexUvs[ c ][ f ];
  2517. if ( uvs === undefined ) continue;
  2518. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2519. _face.uvs[ c ][ u ] = uvs[ u ];
  2520. }
  2521. }
  2522. _face.color = face.color;
  2523. _face.material = material;
  2524. _face.z = _face.centroidScreen.z;
  2525. _renderData.elements.push( _face );
  2526. }
  2527. } else if ( object instanceof THREE.Line ) {
  2528. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  2529. vertices = object.geometry.vertices;
  2530. v1 = getNextVertexInPool();
  2531. v1.positionScreen.copy( vertices[ 0 ] );
  2532. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2533. // Handle LineStrip and LinePieces
  2534. var step = object.type === THREE.LinePieces ? 2 : 1;
  2535. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2536. v1 = getNextVertexInPool();
  2537. v1.positionScreen.copy( vertices[ v ] );
  2538. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2539. if ( ( v + 1 ) % step > 0 ) continue;
  2540. v2 = _vertexPool[ _vertexCount - 2 ];
  2541. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2542. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2543. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  2544. // Perform the perspective divide
  2545. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2546. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2547. _line = getNextLineInPool();
  2548. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2549. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2550. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2551. _line.material = object.material;
  2552. _renderData.elements.push( _line );
  2553. }
  2554. }
  2555. }
  2556. }
  2557. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2558. object = _renderData.sprites[ o ].object;
  2559. modelMatrix = object.matrixWorld;
  2560. if ( object instanceof THREE.Particle ) {
  2561. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  2562. _viewProjectionMatrix.multiplyVector4( _vector4 );
  2563. _vector4.z /= _vector4.w;
  2564. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2565. _particle = getNextParticleInPool();
  2566. _particle.object = object;
  2567. _particle.x = _vector4.x / _vector4.w;
  2568. _particle.y = _vector4.y / _vector4.w;
  2569. _particle.z = _vector4.z;
  2570. _particle.rotation = object.rotation.z;
  2571. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2572. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2573. _particle.material = object.material;
  2574. _renderData.elements.push( _particle );
  2575. }
  2576. }
  2577. }
  2578. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  2579. return _renderData;
  2580. };
  2581. // Pools
  2582. function getNextObjectInPool() {
  2583. if ( _objectCount === _objectPoolLength ) {
  2584. var object = new THREE.RenderableObject();
  2585. _objectPool.push( object );
  2586. _objectPoolLength ++;
  2587. _objectCount ++;
  2588. return object;
  2589. }
  2590. return _objectPool[ _objectCount ++ ];
  2591. }
  2592. function getNextVertexInPool() {
  2593. if ( _vertexCount === _vertexPoolLength ) {
  2594. var vertex = new THREE.RenderableVertex();
  2595. _vertexPool.push( vertex );
  2596. _vertexPoolLength ++;
  2597. _vertexCount ++;
  2598. return vertex;
  2599. }
  2600. return _vertexPool[ _vertexCount ++ ];
  2601. }
  2602. function getNextFace3InPool() {
  2603. if ( _face3Count === _face3PoolLength ) {
  2604. var face = new THREE.RenderableFace3();
  2605. _face3Pool.push( face );
  2606. _face3PoolLength ++;
  2607. _face3Count ++;
  2608. return face;
  2609. }
  2610. return _face3Pool[ _face3Count ++ ];
  2611. }
  2612. function getNextFace4InPool() {
  2613. if ( _face4Count === _face4PoolLength ) {
  2614. var face = new THREE.RenderableFace4();
  2615. _face4Pool.push( face );
  2616. _face4PoolLength ++;
  2617. _face4Count ++;
  2618. return face;
  2619. }
  2620. return _face4Pool[ _face4Count ++ ];
  2621. }
  2622. function getNextLineInPool() {
  2623. if ( _lineCount === _linePoolLength ) {
  2624. var line = new THREE.RenderableLine();
  2625. _linePool.push( line );
  2626. _linePoolLength ++;
  2627. _lineCount ++
  2628. return line;
  2629. }
  2630. return _linePool[ _lineCount ++ ];
  2631. }
  2632. function getNextParticleInPool() {
  2633. if ( _particleCount === _particlePoolLength ) {
  2634. var particle = new THREE.RenderableParticle();
  2635. _particlePool.push( particle );
  2636. _particlePoolLength ++;
  2637. _particleCount ++
  2638. return particle;
  2639. }
  2640. return _particlePool[ _particleCount ++ ];
  2641. }
  2642. //
  2643. function painterSort( a, b ) {
  2644. return b.z - a.z;
  2645. }
  2646. function clipLine( s1, s2 ) {
  2647. var alpha1 = 0, alpha2 = 1,
  2648. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2649. // Z = -1 and Z = +1, respectively.
  2650. bc1near = s1.z + s1.w,
  2651. bc2near = s2.z + s2.w,
  2652. bc1far = - s1.z + s1.w,
  2653. bc2far = - s2.z + s2.w;
  2654. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2655. // Both vertices lie entirely within all clip planes.
  2656. return true;
  2657. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2658. // Both vertices lie entirely outside one of the clip planes.
  2659. return false;
  2660. } else {
  2661. // The line segment spans at least one clip plane.
  2662. if ( bc1near < 0 ) {
  2663. // v1 lies outside the near plane, v2 inside
  2664. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2665. } else if ( bc2near < 0 ) {
  2666. // v2 lies outside the near plane, v1 inside
  2667. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2668. }
  2669. if ( bc1far < 0 ) {
  2670. // v1 lies outside the far plane, v2 inside
  2671. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2672. } else if ( bc2far < 0 ) {
  2673. // v2 lies outside the far plane, v2 inside
  2674. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2675. }
  2676. if ( alpha2 < alpha1 ) {
  2677. // The line segment spans two boundaries, but is outside both of them.
  2678. // (This can't happen when we're only clipping against just near/far but good
  2679. // to leave the check here for future usage if other clip planes are added.)
  2680. return false;
  2681. } else {
  2682. // Update the s1 and s2 vertices to match the clipped line segment.
  2683. s1.lerpSelf( s2, alpha1 );
  2684. s2.lerpSelf( s1, 1 - alpha2 );
  2685. return true;
  2686. }
  2687. }
  2688. }
  2689. };
  2690. /**
  2691. * @author mikael emtinger / http://gomo.se/
  2692. * @author alteredq / http://alteredqualia.com/
  2693. * @author WestLangley / http://github.com/WestLangley
  2694. */
  2695. THREE.Quaternion = function( x, y, z, w ) {
  2696. this.x = x || 0;
  2697. this.y = y || 0;
  2698. this.z = z || 0;
  2699. this.w = ( w !== undefined ) ? w : 1;
  2700. };
  2701. THREE.Quaternion.prototype = {
  2702. constructor: THREE.Quaternion,
  2703. set: function ( x, y, z, w ) {
  2704. this.x = x;
  2705. this.y = y;
  2706. this.z = z;
  2707. this.w = w;
  2708. return this;
  2709. },
  2710. copy: function ( q ) {
  2711. this.x = q.x;
  2712. this.y = q.y;
  2713. this.z = q.z;
  2714. this.w = q.w;
  2715. return this;
  2716. },
  2717. setFromEuler: function ( v, order ) {
  2718. // http://www.mathworks.com/matlabcentral/fileexchange/
  2719. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2720. // content/SpinCalc.m
  2721. var c1 = Math.cos( v.x / 2 );
  2722. var c2 = Math.cos( v.y / 2 );
  2723. var c3 = Math.cos( v.z / 2 );
  2724. var s1 = Math.sin( v.x / 2 );
  2725. var s2 = Math.sin( v.y / 2 );
  2726. var s3 = Math.sin( v.z / 2 );
  2727. if ( order === undefined || order === 'XYZ' ) {
  2728. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2729. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2730. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2731. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2732. } else if ( order === 'YXZ' ) {
  2733. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2734. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2735. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2736. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2737. } else if ( order === 'ZXY' ) {
  2738. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2739. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2740. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2741. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2742. } else if ( order === 'ZYX' ) {
  2743. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2744. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2745. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2746. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2747. } else if ( order === 'YZX' ) {
  2748. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2749. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2750. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2751. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2752. } else if ( order === 'XZY' ) {
  2753. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2754. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2755. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2756. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2757. }
  2758. return this;
  2759. },
  2760. setFromAxisAngle: function ( axis, angle ) {
  2761. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2762. // axis have to be normalized
  2763. var halfAngle = angle / 2,
  2764. s = Math.sin( halfAngle );
  2765. this.x = axis.x * s;
  2766. this.y = axis.y * s;
  2767. this.z = axis.z * s;
  2768. this.w = Math.cos( halfAngle );
  2769. return this;
  2770. },
  2771. setFromRotationMatrix: function ( m ) {
  2772. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2773. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2774. var te = m.elements,
  2775. m11 = te[0], m12 = te[4], m13 = te[8],
  2776. m21 = te[1], m22 = te[5], m23 = te[9],
  2777. m31 = te[2], m32 = te[6], m33 = te[10],
  2778. trace = m11 + m22 + m33,
  2779. s;
  2780. if( trace > 0 ) {
  2781. s = 0.5 / Math.sqrt( trace + 1.0 );
  2782. this.w = 0.25 / s;
  2783. this.x = ( m32 - m23 ) * s;
  2784. this.y = ( m13 - m31 ) * s;
  2785. this.z = ( m21 - m12 ) * s;
  2786. } else if ( m11 > m22 && m11 > m33 ) {
  2787. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2788. this.w = (m32 - m23 ) / s;
  2789. this.x = 0.25 * s;
  2790. this.y = (m12 + m21 ) / s;
  2791. this.z = (m13 + m31 ) / s;
  2792. } else if (m22 > m33) {
  2793. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2794. this.w = (m13 - m31 ) / s;
  2795. this.x = (m12 + m21 ) / s;
  2796. this.y = 0.25 * s;
  2797. this.z = (m23 + m32 ) / s;
  2798. } else {
  2799. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2800. this.w = ( m21 - m12 ) / s;
  2801. this.x = ( m13 + m31 ) / s;
  2802. this.y = ( m23 + m32 ) / s;
  2803. this.z = 0.25 * s;
  2804. }
  2805. return this;
  2806. },
  2807. inverse: function () {
  2808. this.conjugate().normalize();
  2809. return this;
  2810. },
  2811. conjugate: function () {
  2812. this.x *= -1;
  2813. this.y *= -1;
  2814. this.z *= -1;
  2815. return this;
  2816. },
  2817. length: function () {
  2818. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2819. },
  2820. normalize: function () {
  2821. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2822. if ( l === 0 ) {
  2823. this.x = 0;
  2824. this.y = 0;
  2825. this.z = 0;
  2826. this.w = 1;
  2827. } else {
  2828. l = 1 / l;
  2829. this.x = this.x * l;
  2830. this.y = this.y * l;
  2831. this.z = this.z * l;
  2832. this.w = this.w * l;
  2833. }
  2834. return this;
  2835. },
  2836. multiply: function ( a, b ) {
  2837. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2838. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2839. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2840. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2841. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2842. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2843. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2844. return this;
  2845. },
  2846. multiplySelf: function ( b ) {
  2847. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2848. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2849. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2850. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2851. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2852. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2853. return this;
  2854. },
  2855. multiplyVector3: function ( vector, dest ) {
  2856. if ( !dest ) { dest = vector; }
  2857. var x = vector.x, y = vector.y, z = vector.z,
  2858. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2859. // calculate quat * vector
  2860. var ix = qw * x + qy * z - qz * y,
  2861. iy = qw * y + qz * x - qx * z,
  2862. iz = qw * z + qx * y - qy * x,
  2863. iw = -qx * x - qy * y - qz * z;
  2864. // calculate result * inverse quat
  2865. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2866. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2867. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2868. return dest;
  2869. },
  2870. slerpSelf: function ( qb, t ) {
  2871. var x = this.x, y = this.y, z = this.z, w = this.w;
  2872. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2873. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2874. if ( cosHalfTheta < 0 ) {
  2875. this.w = -qb.w;
  2876. this.x = -qb.x;
  2877. this.y = -qb.y;
  2878. this.z = -qb.z;
  2879. cosHalfTheta = -cosHalfTheta;
  2880. } else {
  2881. this.copy( qb );
  2882. }
  2883. if ( cosHalfTheta >= 1.0 ) {
  2884. this.w = w;
  2885. this.x = x;
  2886. this.y = y;
  2887. this.z = z;
  2888. return this;
  2889. }
  2890. var halfTheta = Math.acos( cosHalfTheta );
  2891. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2892. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2893. this.w = 0.5 * ( w + this.w );
  2894. this.x = 0.5 * ( x + this.x );
  2895. this.y = 0.5 * ( y + this.y );
  2896. this.z = 0.5 * ( z + this.z );
  2897. return this;
  2898. }
  2899. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2900. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2901. this.w = ( w * ratioA + this.w * ratioB );
  2902. this.x = ( x * ratioA + this.x * ratioB );
  2903. this.y = ( y * ratioA + this.y * ratioB );
  2904. this.z = ( z * ratioA + this.z * ratioB );
  2905. return this;
  2906. },
  2907. clone: function () {
  2908. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2909. }
  2910. }
  2911. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2912. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2913. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2914. if ( cosHalfTheta < 0 ) {
  2915. qm.w = -qb.w;
  2916. qm.x = -qb.x;
  2917. qm.y = -qb.y;
  2918. qm.z = -qb.z;
  2919. cosHalfTheta = -cosHalfTheta;
  2920. } else {
  2921. qm.copy( qb );
  2922. }
  2923. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2924. qm.w = qa.w;
  2925. qm.x = qa.x;
  2926. qm.y = qa.y;
  2927. qm.z = qa.z;
  2928. return qm;
  2929. }
  2930. var halfTheta = Math.acos( cosHalfTheta );
  2931. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2932. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2933. qm.w = 0.5 * ( qa.w + qm.w );
  2934. qm.x = 0.5 * ( qa.x + qm.x );
  2935. qm.y = 0.5 * ( qa.y + qm.y );
  2936. qm.z = 0.5 * ( qa.z + qm.z );
  2937. return qm;
  2938. }
  2939. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2940. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2941. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2942. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2943. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2944. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2945. return qm;
  2946. }
  2947. /**
  2948. * @author mrdoob / http://mrdoob.com/
  2949. */
  2950. THREE.Vertex = function ( v ) {
  2951. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  2952. return v;
  2953. };
  2954. /**
  2955. * @author mrdoob / http://mrdoob.com/
  2956. * @author alteredq / http://alteredqualia.com/
  2957. */
  2958. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2959. this.a = a;
  2960. this.b = b;
  2961. this.c = c;
  2962. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2963. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2964. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2965. this.vertexColors = color instanceof Array ? color : [];
  2966. this.vertexTangents = [];
  2967. this.materialIndex = materialIndex;
  2968. this.centroid = new THREE.Vector3();
  2969. };
  2970. THREE.Face3.prototype = {
  2971. constructor: THREE.Face3,
  2972. clone: function () {
  2973. var face = new THREE.Face3( this.a, this.b, this.c );
  2974. face.normal.copy( this.normal );
  2975. face.color.copy( this.color );
  2976. face.centroid.copy( this.centroid );
  2977. face.materialIndex = this.materialIndex;
  2978. var i, il;
  2979. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2980. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2981. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2982. return face;
  2983. }
  2984. };
  2985. /**
  2986. * @author mrdoob / http://mrdoob.com/
  2987. * @author alteredq / http://alteredqualia.com/
  2988. */
  2989. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2990. this.a = a;
  2991. this.b = b;
  2992. this.c = c;
  2993. this.d = d;
  2994. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2995. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2996. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2997. this.vertexColors = color instanceof Array ? color : [];
  2998. this.vertexTangents = [];
  2999. this.materialIndex = materialIndex;
  3000. this.centroid = new THREE.Vector3();
  3001. };
  3002. THREE.Face4.prototype = {
  3003. constructor: THREE.Face4,
  3004. clone: function () {
  3005. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  3006. face.normal.copy( this.normal );
  3007. face.color.copy( this.color );
  3008. face.centroid.copy( this.centroid );
  3009. face.materialIndex = this.materialIndex;
  3010. var i, il;
  3011. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3012. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3013. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3014. return face;
  3015. }
  3016. };
  3017. /**
  3018. * @author mrdoob / http://mrdoob.com/
  3019. */
  3020. THREE.UV = function ( u, v ) {
  3021. this.u = u || 0;
  3022. this.v = v || 0;
  3023. };
  3024. THREE.UV.prototype = {
  3025. constructor: THREE.UV,
  3026. set: function ( u, v ) {
  3027. this.u = u;
  3028. this.v = v;
  3029. return this;
  3030. },
  3031. copy: function ( uv ) {
  3032. this.u = uv.u;
  3033. this.v = uv.v;
  3034. return this;
  3035. },
  3036. lerpSelf: function ( uv, alpha ) {
  3037. this.u += ( uv.u - this.u ) * alpha;
  3038. this.v += ( uv.v - this.v ) * alpha;
  3039. return this;
  3040. },
  3041. clone: function () {
  3042. return new THREE.UV( this.u, this.v );
  3043. }
  3044. };
  3045. /**
  3046. * @author mrdoob / http://mrdoob.com/
  3047. * @author kile / http://kile.stravaganza.org/
  3048. * @author alteredq / http://alteredqualia.com/
  3049. * @author mikael emtinger / http://gomo.se/
  3050. * @author zz85 / http://www.lab4games.net/zz85/blog
  3051. */
  3052. THREE.Geometry = function () {
  3053. THREE.GeometryLibrary.push( this );
  3054. this.id = THREE.GeometryIdCount ++;
  3055. this.name = '';
  3056. this.vertices = [];
  3057. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  3058. this.normals = []; // one-to-one vertex normals, used in Ribbon
  3059. this.faces = [];
  3060. this.faceUvs = [[]];
  3061. this.faceVertexUvs = [[]];
  3062. this.morphTargets = [];
  3063. this.morphColors = [];
  3064. this.morphNormals = [];
  3065. this.skinWeights = [];
  3066. this.skinIndices = [];
  3067. this.lineDistances = [];
  3068. this.boundingBox = null;
  3069. this.boundingSphere = null;
  3070. this.hasTangents = false;
  3071. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  3072. // update flags
  3073. this.verticesNeedUpdate = false;
  3074. this.elementsNeedUpdate = false;
  3075. this.uvsNeedUpdate = false;
  3076. this.normalsNeedUpdate = false;
  3077. this.tangentsNeedUpdate = false;
  3078. this.colorsNeedUpdate = false;
  3079. this.lineDistancesNeedUpdate = false;
  3080. this.buffersNeedUpdate = false;
  3081. };
  3082. THREE.Geometry.prototype = {
  3083. constructor : THREE.Geometry,
  3084. applyMatrix: function ( matrix ) {
  3085. var normalMatrix = new THREE.Matrix3();
  3086. normalMatrix.getInverse( matrix ).transpose();
  3087. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  3088. var vertex = this.vertices[ i ];
  3089. matrix.multiplyVector3( vertex );
  3090. }
  3091. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  3092. var face = this.faces[ i ];
  3093. normalMatrix.multiplyVector3( face.normal ).normalize();
  3094. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  3095. normalMatrix.multiplyVector3( face.vertexNormals[ j ] ).normalize();
  3096. }
  3097. matrix.multiplyVector3( face.centroid );
  3098. }
  3099. },
  3100. computeCentroids: function () {
  3101. var f, fl, face;
  3102. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3103. face = this.faces[ f ];
  3104. face.centroid.set( 0, 0, 0 );
  3105. if ( face instanceof THREE.Face3 ) {
  3106. face.centroid.addSelf( this.vertices[ face.a ] );
  3107. face.centroid.addSelf( this.vertices[ face.b ] );
  3108. face.centroid.addSelf( this.vertices[ face.c ] );
  3109. face.centroid.divideScalar( 3 );
  3110. } else if ( face instanceof THREE.Face4 ) {
  3111. face.centroid.addSelf( this.vertices[ face.a ] );
  3112. face.centroid.addSelf( this.vertices[ face.b ] );
  3113. face.centroid.addSelf( this.vertices[ face.c ] );
  3114. face.centroid.addSelf( this.vertices[ face.d ] );
  3115. face.centroid.divideScalar( 4 );
  3116. }
  3117. }
  3118. },
  3119. computeFaceNormals: function () {
  3120. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  3121. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  3122. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3123. face = this.faces[ f ];
  3124. vA = this.vertices[ face.a ];
  3125. vB = this.vertices[ face.b ];
  3126. vC = this.vertices[ face.c ];
  3127. cb.sub( vC, vB );
  3128. ab.sub( vA, vB );
  3129. cb.crossSelf( ab );
  3130. cb.normalize();
  3131. face.normal.copy( cb );
  3132. }
  3133. },
  3134. computeVertexNormals: function ( areaWeighted ) {
  3135. var v, vl, f, fl, face, vertices;
  3136. // create internal buffers for reuse when calling this method repeatedly
  3137. // (otherwise memory allocation / deallocation every frame is big resource hog)
  3138. if ( this.__tmpVertices === undefined ) {
  3139. this.__tmpVertices = new Array( this.vertices.length );
  3140. vertices = this.__tmpVertices;
  3141. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3142. vertices[ v ] = new THREE.Vector3();
  3143. }
  3144. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3145. face = this.faces[ f ];
  3146. if ( face instanceof THREE.Face3 ) {
  3147. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3148. } else if ( face instanceof THREE.Face4 ) {
  3149. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3150. }
  3151. }
  3152. } else {
  3153. vertices = this.__tmpVertices;
  3154. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3155. vertices[ v ].set( 0, 0, 0 );
  3156. }
  3157. }
  3158. if ( areaWeighted ) {
  3159. // vertex normals weighted by triangle areas
  3160. // http://www.iquilezles.org/www/articles/normals/normals.htm
  3161. var vA, vB, vC, vD;
  3162. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  3163. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  3164. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3165. face = this.faces[ f ];
  3166. if ( face instanceof THREE.Face3 ) {
  3167. vA = this.vertices[ face.a ];
  3168. vB = this.vertices[ face.b ];
  3169. vC = this.vertices[ face.c ];
  3170. cb.sub( vC, vB );
  3171. ab.sub( vA, vB );
  3172. cb.crossSelf( ab );
  3173. vertices[ face.a ].addSelf( cb );
  3174. vertices[ face.b ].addSelf( cb );
  3175. vertices[ face.c ].addSelf( cb );
  3176. } else if ( face instanceof THREE.Face4 ) {
  3177. vA = this.vertices[ face.a ];
  3178. vB = this.vertices[ face.b ];
  3179. vC = this.vertices[ face.c ];
  3180. vD = this.vertices[ face.d ];
  3181. // abd
  3182. db.sub( vD, vB );
  3183. ab.sub( vA, vB );
  3184. db.crossSelf( ab );
  3185. vertices[ face.a ].addSelf( db );
  3186. vertices[ face.b ].addSelf( db );
  3187. vertices[ face.d ].addSelf( db );
  3188. // bcd
  3189. dc.sub( vD, vC );
  3190. bc.sub( vB, vC );
  3191. dc.crossSelf( bc );
  3192. vertices[ face.b ].addSelf( dc );
  3193. vertices[ face.c ].addSelf( dc );
  3194. vertices[ face.d ].addSelf( dc );
  3195. }
  3196. }
  3197. } else {
  3198. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3199. face = this.faces[ f ];
  3200. if ( face instanceof THREE.Face3 ) {
  3201. vertices[ face.a ].addSelf( face.normal );
  3202. vertices[ face.b ].addSelf( face.normal );
  3203. vertices[ face.c ].addSelf( face.normal );
  3204. } else if ( face instanceof THREE.Face4 ) {
  3205. vertices[ face.a ].addSelf( face.normal );
  3206. vertices[ face.b ].addSelf( face.normal );
  3207. vertices[ face.c ].addSelf( face.normal );
  3208. vertices[ face.d ].addSelf( face.normal );
  3209. }
  3210. }
  3211. }
  3212. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3213. vertices[ v ].normalize();
  3214. }
  3215. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3216. face = this.faces[ f ];
  3217. if ( face instanceof THREE.Face3 ) {
  3218. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3219. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3220. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3221. } else if ( face instanceof THREE.Face4 ) {
  3222. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3223. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3224. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3225. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3226. }
  3227. }
  3228. },
  3229. computeMorphNormals: function () {
  3230. var i, il, f, fl, face;
  3231. // save original normals
  3232. // - create temp variables on first access
  3233. // otherwise just copy (for faster repeated calls)
  3234. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3235. face = this.faces[ f ];
  3236. if ( ! face.__originalFaceNormal ) {
  3237. face.__originalFaceNormal = face.normal.clone();
  3238. } else {
  3239. face.__originalFaceNormal.copy( face.normal );
  3240. }
  3241. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3242. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3243. if ( ! face.__originalVertexNormals[ i ] ) {
  3244. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3245. } else {
  3246. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3247. }
  3248. }
  3249. }
  3250. // use temp geometry to compute face and vertex normals for each morph
  3251. var tmpGeo = new THREE.Geometry();
  3252. tmpGeo.faces = this.faces;
  3253. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3254. // create on first access
  3255. if ( ! this.morphNormals[ i ] ) {
  3256. this.morphNormals[ i ] = {};
  3257. this.morphNormals[ i ].faceNormals = [];
  3258. this.morphNormals[ i ].vertexNormals = [];
  3259. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3260. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3261. var faceNormal, vertexNormals;
  3262. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3263. face = this.faces[ f ];
  3264. faceNormal = new THREE.Vector3();
  3265. if ( face instanceof THREE.Face3 ) {
  3266. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3267. } else {
  3268. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3269. }
  3270. dstNormalsFace.push( faceNormal );
  3271. dstNormalsVertex.push( vertexNormals );
  3272. }
  3273. }
  3274. var morphNormals = this.morphNormals[ i ];
  3275. // set vertices to morph target
  3276. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3277. // compute morph normals
  3278. tmpGeo.computeFaceNormals();
  3279. tmpGeo.computeVertexNormals();
  3280. // store morph normals
  3281. var faceNormal, vertexNormals;
  3282. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3283. face = this.faces[ f ];
  3284. faceNormal = morphNormals.faceNormals[ f ];
  3285. vertexNormals = morphNormals.vertexNormals[ f ];
  3286. faceNormal.copy( face.normal );
  3287. if ( face instanceof THREE.Face3 ) {
  3288. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3289. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3290. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3291. } else {
  3292. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3293. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3294. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3295. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3296. }
  3297. }
  3298. }
  3299. // restore original normals
  3300. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3301. face = this.faces[ f ];
  3302. face.normal = face.__originalFaceNormal;
  3303. face.vertexNormals = face.__originalVertexNormals;
  3304. }
  3305. },
  3306. computeTangents: function () {
  3307. // based on http://www.terathon.com/code/tangent.html
  3308. // tangents go to vertices
  3309. var f, fl, v, vl, i, il, vertexIndex,
  3310. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3311. x1, x2, y1, y2, z1, z2,
  3312. s1, s2, t1, t2, r, t, test,
  3313. tan1 = [], tan2 = [],
  3314. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3315. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3316. n = new THREE.Vector3(), w;
  3317. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3318. tan1[ v ] = new THREE.Vector3();
  3319. tan2[ v ] = new THREE.Vector3();
  3320. }
  3321. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  3322. vA = context.vertices[ a ];
  3323. vB = context.vertices[ b ];
  3324. vC = context.vertices[ c ];
  3325. uvA = uv[ ua ];
  3326. uvB = uv[ ub ];
  3327. uvC = uv[ uc ];
  3328. x1 = vB.x - vA.x;
  3329. x2 = vC.x - vA.x;
  3330. y1 = vB.y - vA.y;
  3331. y2 = vC.y - vA.y;
  3332. z1 = vB.z - vA.z;
  3333. z2 = vC.z - vA.z;
  3334. s1 = uvB.u - uvA.u;
  3335. s2 = uvC.u - uvA.u;
  3336. t1 = uvB.v - uvA.v;
  3337. t2 = uvC.v - uvA.v;
  3338. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3339. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  3340. ( t2 * y1 - t1 * y2 ) * r,
  3341. ( t2 * z1 - t1 * z2 ) * r );
  3342. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  3343. ( s1 * y2 - s2 * y1 ) * r,
  3344. ( s1 * z2 - s2 * z1 ) * r );
  3345. tan1[ a ].addSelf( sdir );
  3346. tan1[ b ].addSelf( sdir );
  3347. tan1[ c ].addSelf( sdir );
  3348. tan2[ a ].addSelf( tdir );
  3349. tan2[ b ].addSelf( tdir );
  3350. tan2[ c ].addSelf( tdir );
  3351. }
  3352. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3353. face = this.faces[ f ];
  3354. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  3355. if ( face instanceof THREE.Face3 ) {
  3356. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  3357. } else if ( face instanceof THREE.Face4 ) {
  3358. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  3359. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  3360. }
  3361. }
  3362. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  3363. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3364. face = this.faces[ f ];
  3365. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  3366. n.copy( face.vertexNormals[ i ] );
  3367. vertexIndex = face[ faceIndex[ i ] ];
  3368. t = tan1[ vertexIndex ];
  3369. // Gram-Schmidt orthogonalize
  3370. tmp.copy( t );
  3371. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3372. // Calculate handedness
  3373. tmp2.cross( face.vertexNormals[ i ], t );
  3374. test = tmp2.dot( tan2[ vertexIndex ] );
  3375. w = (test < 0.0) ? -1.0 : 1.0;
  3376. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  3377. }
  3378. }
  3379. this.hasTangents = true;
  3380. },
  3381. computeLineDistances: function ( ) {
  3382. var d = 0;
  3383. var vertices = this.vertices;
  3384. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  3385. if ( i > 0 ) {
  3386. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  3387. }
  3388. this.lineDistances[ i ] = d;
  3389. }
  3390. },
  3391. computeBoundingBox: function () {
  3392. if ( ! this.boundingBox ) {
  3393. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  3394. }
  3395. if ( this.vertices.length > 0 ) {
  3396. var position, firstPosition = this.vertices[ 0 ];
  3397. this.boundingBox.min.copy( firstPosition );
  3398. this.boundingBox.max.copy( firstPosition );
  3399. var min = this.boundingBox.min,
  3400. max = this.boundingBox.max;
  3401. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  3402. position = this.vertices[ v ];
  3403. if ( position.x < min.x ) {
  3404. min.x = position.x;
  3405. } else if ( position.x > max.x ) {
  3406. max.x = position.x;
  3407. }
  3408. if ( position.y < min.y ) {
  3409. min.y = position.y;
  3410. } else if ( position.y > max.y ) {
  3411. max.y = position.y;
  3412. }
  3413. if ( position.z < min.z ) {
  3414. min.z = position.z;
  3415. } else if ( position.z > max.z ) {
  3416. max.z = position.z;
  3417. }
  3418. }
  3419. } else {
  3420. this.boundingBox.min.set( 0, 0, 0 );
  3421. this.boundingBox.max.set( 0, 0, 0 );
  3422. }
  3423. },
  3424. computeBoundingSphere: function () {
  3425. var maxRadiusSq = 0;
  3426. if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
  3427. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  3428. var radiusSq = this.vertices[ i ].lengthSq();
  3429. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3430. }
  3431. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3432. },
  3433. /*
  3434. * Checks for duplicate vertices with hashmap.
  3435. * Duplicated vertices are removed
  3436. * and faces' vertices are updated.
  3437. */
  3438. mergeVertices: function () {
  3439. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  3440. var unique = [], changes = [];
  3441. var v, key;
  3442. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  3443. var precision = Math.pow( 10, precisionPoints );
  3444. var i,il, face;
  3445. var abcd = 'abcd', o, k, j, jl, u;
  3446. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  3447. v = this.vertices[ i ];
  3448. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  3449. if ( verticesMap[ key ] === undefined ) {
  3450. verticesMap[ key ] = i;
  3451. unique.push( this.vertices[ i ] );
  3452. changes[ i ] = unique.length - 1;
  3453. } else {
  3454. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3455. changes[ i ] = changes[ verticesMap[ key ] ];
  3456. }
  3457. };
  3458. // Start to patch face indices
  3459. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  3460. face = this.faces[ i ];
  3461. if ( face instanceof THREE.Face3 ) {
  3462. face.a = changes[ face.a ];
  3463. face.b = changes[ face.b ];
  3464. face.c = changes[ face.c ];
  3465. } else if ( face instanceof THREE.Face4 ) {
  3466. face.a = changes[ face.a ];
  3467. face.b = changes[ face.b ];
  3468. face.c = changes[ face.c ];
  3469. face.d = changes[ face.d ];
  3470. // check dups in (a, b, c, d) and convert to -> face3
  3471. o = [ face.a, face.b, face.c, face.d ];
  3472. for ( k = 3; k > 0; k -- ) {
  3473. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  3474. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  3475. o.splice( k, 1 );
  3476. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  3477. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  3478. u = this.faceVertexUvs[ j ][ i ];
  3479. if ( u ) u.splice( k, 1 );
  3480. }
  3481. this.faces[ i ].vertexColors = face.vertexColors;
  3482. break;
  3483. }
  3484. }
  3485. }
  3486. }
  3487. // Use unique set of vertices
  3488. var diff = this.vertices.length - unique.length;
  3489. this.vertices = unique;
  3490. return diff;
  3491. },
  3492. clone: function () {
  3493. var geometry = new THREE.Geometry();
  3494. var vertices = this.vertices;
  3495. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  3496. geometry.vertices.push( vertices[ i ].clone() );
  3497. }
  3498. var faces = this.faces;
  3499. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  3500. geometry.faces.push( faces[ i ].clone() );
  3501. }
  3502. var uvs = this.faceVertexUvs[ 0 ];
  3503. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  3504. var uv = uvs[ i ], uvCopy = [];
  3505. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  3506. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  3507. }
  3508. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  3509. }
  3510. return geometry;
  3511. },
  3512. deallocate: function () {
  3513. var index = THREE.GeometryLibrary.indexOf( this );
  3514. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3515. }
  3516. };
  3517. THREE.GeometryIdCount = 0;
  3518. THREE.GeometryLibrary = [];
  3519. /**
  3520. * @author alteredq / http://alteredqualia.com/
  3521. */
  3522. THREE.BufferGeometry = function () {
  3523. THREE.GeometryLibrary.push( this );
  3524. this.id = THREE.GeometryIdCount ++;
  3525. // attributes
  3526. this.attributes = {};
  3527. // attributes typed arrays are kept only if dynamic flag is set
  3528. this.dynamic = false;
  3529. // boundings
  3530. this.boundingBox = null;
  3531. this.boundingSphere = null;
  3532. this.hasTangents = false;
  3533. // for compatibility
  3534. this.morphTargets = [];
  3535. };
  3536. THREE.BufferGeometry.prototype = {
  3537. constructor : THREE.BufferGeometry,
  3538. applyMatrix: function ( matrix ) {
  3539. var positionArray;
  3540. var normalArray;
  3541. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  3542. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  3543. if ( positionArray !== undefined ) {
  3544. matrix.multiplyVector3Array( positionArray );
  3545. this.verticesNeedUpdate = true;
  3546. }
  3547. if ( normalArray !== undefined ) {
  3548. var normalMatrix = new THREE.Matrix3();
  3549. normalMatrix.getInverse( matrix ).transpose();
  3550. normalMatrix.multiplyVector3Array( normalArray );
  3551. this.normalizeNormals();
  3552. this.normalsNeedUpdate = true;
  3553. }
  3554. },
  3555. computeBoundingBox: function () {
  3556. if ( ! this.boundingBox ) {
  3557. this.boundingBox = {
  3558. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  3559. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  3560. };
  3561. }
  3562. var positions = this.attributes[ "position" ].array;
  3563. if ( positions ) {
  3564. var bb = this.boundingBox;
  3565. var x, y, z;
  3566. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3567. x = positions[ i ];
  3568. y = positions[ i + 1 ];
  3569. z = positions[ i + 2 ];
  3570. // bounding box
  3571. if ( x < bb.min.x ) {
  3572. bb.min.x = x;
  3573. } else if ( x > bb.max.x ) {
  3574. bb.max.x = x;
  3575. }
  3576. if ( y < bb.min.y ) {
  3577. bb.min.y = y;
  3578. } else if ( y > bb.max.y ) {
  3579. bb.max.y = y;
  3580. }
  3581. if ( z < bb.min.z ) {
  3582. bb.min.z = z;
  3583. } else if ( z > bb.max.z ) {
  3584. bb.max.z = z;
  3585. }
  3586. }
  3587. }
  3588. if ( positions === undefined || positions.length === 0 ) {
  3589. this.boundingBox.min.set( 0, 0, 0 );
  3590. this.boundingBox.max.set( 0, 0, 0 );
  3591. }
  3592. },
  3593. computeBoundingSphere: function () {
  3594. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  3595. var positions = this.attributes[ "position" ].array;
  3596. if ( positions ) {
  3597. var radiusSq, maxRadiusSq = 0;
  3598. var x, y, z;
  3599. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3600. x = positions[ i ];
  3601. y = positions[ i + 1 ];
  3602. z = positions[ i + 2 ];
  3603. radiusSq = x * x + y * y + z * z;
  3604. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3605. }
  3606. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3607. }
  3608. },
  3609. computeVertexNormals: function () {
  3610. if ( this.attributes[ "position" ] && this.attributes[ "index" ] ) {
  3611. var i, il;
  3612. var j, jl;
  3613. var nVertexElements = this.attributes[ "position" ].array.length;
  3614. if ( this.attributes[ "normal" ] === undefined ) {
  3615. this.attributes[ "normal" ] = {
  3616. itemSize: 3,
  3617. array: new Float32Array( nVertexElements ),
  3618. numItems: nVertexElements
  3619. };
  3620. } else {
  3621. // reset existing normals to zero
  3622. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  3623. this.attributes[ "normal" ].array[ i ] = 0;
  3624. }
  3625. }
  3626. var offsets = this.offsets;
  3627. var indices = this.attributes[ "index" ].array;
  3628. var positions = this.attributes[ "position" ].array;
  3629. var normals = this.attributes[ "normal" ].array;
  3630. var vA, vB, vC, x, y, z,
  3631. pA = new THREE.Vector3(),
  3632. pB = new THREE.Vector3(),
  3633. pC = new THREE.Vector3(),
  3634. cb = new THREE.Vector3(),
  3635. ab = new THREE.Vector3();
  3636. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3637. var start = offsets[ j ].start;
  3638. var count = offsets[ j ].count;
  3639. var index = offsets[ j ].index;
  3640. for ( i = start, il = start + count; i < il; i += 3 ) {
  3641. vA = index + indices[ i ];
  3642. vB = index + indices[ i + 1 ];
  3643. vC = index + indices[ i + 2 ];
  3644. x = positions[ vA * 3 ];
  3645. y = positions[ vA * 3 + 1 ];
  3646. z = positions[ vA * 3 + 2 ];
  3647. pA.set( x, y, z );
  3648. x = positions[ vB * 3 ];
  3649. y = positions[ vB * 3 + 1 ];
  3650. z = positions[ vB * 3 + 2 ];
  3651. pB.set( x, y, z );
  3652. x = positions[ vC * 3 ];
  3653. y = positions[ vC * 3 + 1 ];
  3654. z = positions[ vC * 3 + 2 ];
  3655. pC.set( x, y, z );
  3656. cb.sub( pC, pB );
  3657. ab.sub( pA, pB );
  3658. cb.crossSelf( ab );
  3659. normals[ vA * 3 ] += cb.x;
  3660. normals[ vA * 3 + 1 ] += cb.y;
  3661. normals[ vA * 3 + 2 ] += cb.z;
  3662. normals[ vB * 3 ] += cb.x;
  3663. normals[ vB * 3 + 1 ] += cb.y;
  3664. normals[ vB * 3 + 2 ] += cb.z;
  3665. normals[ vC * 3 ] += cb.x;
  3666. normals[ vC * 3 + 1 ] += cb.y;
  3667. normals[ vC * 3 + 2 ] += cb.z;
  3668. }
  3669. }
  3670. this.normalizeNormals();
  3671. this.normalsNeedUpdate = true;
  3672. }
  3673. },
  3674. normalizeNormals: function () {
  3675. var normals = this.attributes[ "normal" ].array;
  3676. var x, y, z, n;
  3677. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  3678. x = normals[ i ];
  3679. y = normals[ i + 1 ];
  3680. z = normals[ i + 2 ];
  3681. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  3682. normals[ i ] *= n;
  3683. normals[ i + 1 ] *= n;
  3684. normals[ i + 2 ] *= n;
  3685. }
  3686. },
  3687. computeTangents: function () {
  3688. // based on http://www.terathon.com/code/tangent.html
  3689. // (per vertex tangents)
  3690. if ( this.attributes[ "index" ] === undefined ||
  3691. this.attributes[ "position" ] === undefined ||
  3692. this.attributes[ "normal" ] === undefined ||
  3693. this.attributes[ "uv" ] === undefined ) {
  3694. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  3695. return;
  3696. }
  3697. var indices = this.attributes[ "index" ].array;
  3698. var positions = this.attributes[ "position" ].array;
  3699. var normals = this.attributes[ "normal" ].array;
  3700. var uvs = this.attributes[ "uv" ].array;
  3701. var nVertices = positions.length / 3;
  3702. if ( this.attributes[ "tangent" ] === undefined ) {
  3703. var nTangentElements = 4 * nVertices;
  3704. this.attributes[ "tangent" ] = {
  3705. itemSize: 4,
  3706. array: new Float32Array( nTangentElements ),
  3707. numItems: nTangentElements
  3708. };
  3709. }
  3710. var tangents = this.attributes[ "tangent" ].array;
  3711. var tan1 = [], tan2 = [];
  3712. for ( var k = 0; k < nVertices; k ++ ) {
  3713. tan1[ k ] = new THREE.Vector3();
  3714. tan2[ k ] = new THREE.Vector3();
  3715. }
  3716. var xA, yA, zA,
  3717. xB, yB, zB,
  3718. xC, yC, zC,
  3719. uA, vA,
  3720. uB, vB,
  3721. uC, vC,
  3722. x1, x2, y1, y2, z1, z2,
  3723. s1, s2, t1, t2, r;
  3724. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  3725. function handleTriangle( a, b, c ) {
  3726. xA = positions[ a * 3 ];
  3727. yA = positions[ a * 3 + 1 ];
  3728. zA = positions[ a * 3 + 2 ];
  3729. xB = positions[ b * 3 ];
  3730. yB = positions[ b * 3 + 1 ];
  3731. zB = positions[ b * 3 + 2 ];
  3732. xC = positions[ c * 3 ];
  3733. yC = positions[ c * 3 + 1 ];
  3734. zC = positions[ c * 3 + 2 ];
  3735. uA = uvs[ a * 2 ];
  3736. vA = uvs[ a * 2 + 1 ];
  3737. uB = uvs[ b * 2 ];
  3738. vB = uvs[ b * 2 + 1 ];
  3739. uC = uvs[ c * 2 ];
  3740. vC = uvs[ c * 2 + 1 ];
  3741. x1 = xB - xA;
  3742. x2 = xC - xA;
  3743. y1 = yB - yA;
  3744. y2 = yC - yA;
  3745. z1 = zB - zA;
  3746. z2 = zC - zA;
  3747. s1 = uB - uA;
  3748. s2 = uC - uA;
  3749. t1 = vB - vA;
  3750. t2 = vC - vA;
  3751. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3752. sdir.set(
  3753. ( t2 * x1 - t1 * x2 ) * r,
  3754. ( t2 * y1 - t1 * y2 ) * r,
  3755. ( t2 * z1 - t1 * z2 ) * r
  3756. );
  3757. tdir.set(
  3758. ( s1 * x2 - s2 * x1 ) * r,
  3759. ( s1 * y2 - s2 * y1 ) * r,
  3760. ( s1 * z2 - s2 * z1 ) * r
  3761. );
  3762. tan1[ a ].addSelf( sdir );
  3763. tan1[ b ].addSelf( sdir );
  3764. tan1[ c ].addSelf( sdir );
  3765. tan2[ a ].addSelf( tdir );
  3766. tan2[ b ].addSelf( tdir );
  3767. tan2[ c ].addSelf( tdir );
  3768. }
  3769. var i, il;
  3770. var j, jl;
  3771. var iA, iB, iC;
  3772. var offsets = this.offsets;
  3773. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3774. var start = offsets[ j ].start;
  3775. var count = offsets[ j ].count;
  3776. var index = offsets[ j ].index;
  3777. for ( i = start, il = start + count; i < il; i += 3 ) {
  3778. iA = index + indices[ i ];
  3779. iB = index + indices[ i + 1 ];
  3780. iC = index + indices[ i + 2 ];
  3781. handleTriangle( iA, iB, iC );
  3782. }
  3783. }
  3784. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  3785. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  3786. var w, t, test;
  3787. var nx, ny, nz;
  3788. function handleVertex( v ) {
  3789. n.x = normals[ v * 3 ];
  3790. n.y = normals[ v * 3 + 1 ];
  3791. n.z = normals[ v * 3 + 2 ];
  3792. n2.copy( n );
  3793. t = tan1[ v ];
  3794. // Gram-Schmidt orthogonalize
  3795. tmp.copy( t );
  3796. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3797. // Calculate handedness
  3798. tmp2.cross( n2, t );
  3799. test = tmp2.dot( tan2[ v ] );
  3800. w = ( test < 0.0 ) ? -1.0 : 1.0;
  3801. tangents[ v * 4 ] = tmp.x;
  3802. tangents[ v * 4 + 1 ] = tmp.y;
  3803. tangents[ v * 4 + 2 ] = tmp.z;
  3804. tangents[ v * 4 + 3 ] = w;
  3805. }
  3806. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3807. var start = offsets[ j ].start;
  3808. var count = offsets[ j ].count;
  3809. var index = offsets[ j ].index;
  3810. for ( i = start, il = start + count; i < il; i += 3 ) {
  3811. iA = index + indices[ i ];
  3812. iB = index + indices[ i + 1 ];
  3813. iC = index + indices[ i + 2 ];
  3814. handleVertex( iA );
  3815. handleVertex( iB );
  3816. handleVertex( iC );
  3817. }
  3818. }
  3819. this.hasTangents = true;
  3820. this.tangentsNeedUpdate = true;
  3821. },
  3822. deallocate: function () {
  3823. var index = THREE.GeometryLibrary.indexOf( this );
  3824. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3825. }
  3826. };
  3827. /**
  3828. * Spline from Tween.js, slightly optimized (and trashed)
  3829. * http://sole.github.com/tween.js/examples/05_spline.html
  3830. *
  3831. * @author mrdoob / http://mrdoob.com/
  3832. * @author alteredq / http://alteredqualia.com/
  3833. */
  3834. THREE.Spline = function ( points ) {
  3835. this.points = points;
  3836. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3837. point, intPoint, weight, w2, w3,
  3838. pa, pb, pc, pd;
  3839. this.initFromArray = function( a ) {
  3840. this.points = [];
  3841. for ( var i = 0; i < a.length; i++ ) {
  3842. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3843. }
  3844. };
  3845. this.getPoint = function ( k ) {
  3846. point = ( this.points.length - 1 ) * k;
  3847. intPoint = Math.floor( point );
  3848. weight = point - intPoint;
  3849. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3850. c[ 1 ] = intPoint;
  3851. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3852. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3853. pa = this.points[ c[ 0 ] ];
  3854. pb = this.points[ c[ 1 ] ];
  3855. pc = this.points[ c[ 2 ] ];
  3856. pd = this.points[ c[ 3 ] ];
  3857. w2 = weight * weight;
  3858. w3 = weight * w2;
  3859. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3860. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3861. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3862. return v3;
  3863. };
  3864. this.getControlPointsArray = function () {
  3865. var i, p, l = this.points.length,
  3866. coords = [];
  3867. for ( i = 0; i < l; i ++ ) {
  3868. p = this.points[ i ];
  3869. coords[ i ] = [ p.x, p.y, p.z ];
  3870. }
  3871. return coords;
  3872. };
  3873. // approximate length by summing linear segments
  3874. this.getLength = function ( nSubDivisions ) {
  3875. var i, index, nSamples, position,
  3876. point = 0, intPoint = 0, oldIntPoint = 0,
  3877. oldPosition = new THREE.Vector3(),
  3878. tmpVec = new THREE.Vector3(),
  3879. chunkLengths = [],
  3880. totalLength = 0;
  3881. // first point has 0 length
  3882. chunkLengths[ 0 ] = 0;
  3883. if ( !nSubDivisions ) nSubDivisions = 100;
  3884. nSamples = this.points.length * nSubDivisions;
  3885. oldPosition.copy( this.points[ 0 ] );
  3886. for ( i = 1; i < nSamples; i ++ ) {
  3887. index = i / nSamples;
  3888. position = this.getPoint( index );
  3889. tmpVec.copy( position );
  3890. totalLength += tmpVec.distanceTo( oldPosition );
  3891. oldPosition.copy( position );
  3892. point = ( this.points.length - 1 ) * index;
  3893. intPoint = Math.floor( point );
  3894. if ( intPoint != oldIntPoint ) {
  3895. chunkLengths[ intPoint ] = totalLength;
  3896. oldIntPoint = intPoint;
  3897. }
  3898. }
  3899. // last point ends with total length
  3900. chunkLengths[ chunkLengths.length ] = totalLength;
  3901. return { chunks: chunkLengths, total: totalLength };
  3902. };
  3903. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3904. var i, j,
  3905. index, indexCurrent, indexNext,
  3906. linearDistance, realDistance,
  3907. sampling, position,
  3908. newpoints = [],
  3909. tmpVec = new THREE.Vector3(),
  3910. sl = this.getLength();
  3911. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3912. for ( i = 1; i < this.points.length; i++ ) {
  3913. //tmpVec.copy( this.points[ i - 1 ] );
  3914. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3915. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3916. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3917. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3918. indexNext = i / ( this.points.length - 1 );
  3919. for ( j = 1; j < sampling - 1; j++ ) {
  3920. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3921. position = this.getPoint( index );
  3922. newpoints.push( tmpVec.copy( position ).clone() );
  3923. }
  3924. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3925. }
  3926. this.points = newpoints;
  3927. };
  3928. // Catmull-Rom
  3929. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3930. var v0 = ( p2 - p0 ) * 0.5,
  3931. v1 = ( p3 - p1 ) * 0.5;
  3932. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3933. };
  3934. };
  3935. /**
  3936. * @author mrdoob / http://mrdoob.com/
  3937. * @author mikael emtinger / http://gomo.se/
  3938. */
  3939. THREE.Camera = function () {
  3940. THREE.Object3D.call( this );
  3941. this.matrixWorldInverse = new THREE.Matrix4();
  3942. this.projectionMatrix = new THREE.Matrix4();
  3943. this.projectionMatrixInverse = new THREE.Matrix4();
  3944. };
  3945. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  3946. THREE.Camera.prototype.lookAt = function ( vector ) {
  3947. // TODO: Add hierarchy support.
  3948. this.matrix.lookAt( this.position, vector, this.up );
  3949. if ( this.rotationAutoUpdate === true ) {
  3950. if ( this.useQuaternion === false ) {
  3951. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3952. } else {
  3953. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3954. }
  3955. }
  3956. };
  3957. /**
  3958. * @author alteredq / http://alteredqualia.com/
  3959. */
  3960. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  3961. THREE.Camera.call( this );
  3962. this.left = left;
  3963. this.right = right;
  3964. this.top = top;
  3965. this.bottom = bottom;
  3966. this.near = ( near !== undefined ) ? near : 0.1;
  3967. this.far = ( far !== undefined ) ? far : 2000;
  3968. this.updateProjectionMatrix();
  3969. };
  3970. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  3971. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  3972. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  3973. };
  3974. /**
  3975. * @author mrdoob / http://mrdoob.com/
  3976. * @author greggman / http://games.greggman.com/
  3977. * @author zz85 / http://www.lab4games.net/zz85/blog
  3978. */
  3979. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  3980. THREE.Camera.call( this );
  3981. this.fov = fov !== undefined ? fov : 50;
  3982. this.aspect = aspect !== undefined ? aspect : 1;
  3983. this.near = near !== undefined ? near : 0.1;
  3984. this.far = far !== undefined ? far : 2000;
  3985. this.updateProjectionMatrix();
  3986. };
  3987. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  3988. /**
  3989. * Uses Focal Length (in mm) to estimate and set FOV
  3990. * 35mm (fullframe) camera is used if frame size is not specified;
  3991. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  3992. */
  3993. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  3994. if ( frameHeight === undefined ) frameHeight = 24;
  3995. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  3996. this.updateProjectionMatrix();
  3997. }
  3998. /**
  3999. * Sets an offset in a larger frustum. This is useful for multi-window or
  4000. * multi-monitor/multi-machine setups.
  4001. *
  4002. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  4003. * the monitors are in grid like this
  4004. *
  4005. * +---+---+---+
  4006. * | A | B | C |
  4007. * +---+---+---+
  4008. * | D | E | F |
  4009. * +---+---+---+
  4010. *
  4011. * then for each monitor you would call it like this
  4012. *
  4013. * var w = 1920;
  4014. * var h = 1080;
  4015. * var fullWidth = w * 3;
  4016. * var fullHeight = h * 2;
  4017. *
  4018. * --A--
  4019. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  4020. * --B--
  4021. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  4022. * --C--
  4023. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  4024. * --D--
  4025. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  4026. * --E--
  4027. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  4028. * --F--
  4029. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  4030. *
  4031. * Note there is no reason monitors have to be the same size or in a grid.
  4032. */
  4033. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  4034. this.fullWidth = fullWidth;
  4035. this.fullHeight = fullHeight;
  4036. this.x = x;
  4037. this.y = y;
  4038. this.width = width;
  4039. this.height = height;
  4040. this.updateProjectionMatrix();
  4041. };
  4042. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  4043. if ( this.fullWidth ) {
  4044. var aspect = this.fullWidth / this.fullHeight;
  4045. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  4046. var bottom = -top;
  4047. var left = aspect * bottom;
  4048. var right = aspect * top;
  4049. var width = Math.abs( right - left );
  4050. var height = Math.abs( top - bottom );
  4051. this.projectionMatrix.makeFrustum(
  4052. left + this.x * width / this.fullWidth,
  4053. left + ( this.x + this.width ) * width / this.fullWidth,
  4054. top - ( this.y + this.height ) * height / this.fullHeight,
  4055. top - this.y * height / this.fullHeight,
  4056. this.near,
  4057. this.far
  4058. );
  4059. } else {
  4060. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  4061. }
  4062. };
  4063. /**
  4064. * @author mrdoob / http://mrdoob.com/
  4065. * @author alteredq / http://alteredqualia.com/
  4066. */
  4067. THREE.Light = function ( hex ) {
  4068. THREE.Object3D.call( this );
  4069. this.color = new THREE.Color( hex );
  4070. };
  4071. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  4072. /**
  4073. * @author mrdoob / http://mrdoob.com/
  4074. */
  4075. THREE.AmbientLight = function ( hex ) {
  4076. THREE.Light.call( this, hex );
  4077. };
  4078. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  4079. /**
  4080. * @author mrdoob / http://mrdoob.com/
  4081. * @author alteredq / http://alteredqualia.com/
  4082. */
  4083. THREE.DirectionalLight = function ( hex, intensity ) {
  4084. THREE.Light.call( this, hex );
  4085. this.position = new THREE.Vector3( 0, 1, 0 );
  4086. this.target = new THREE.Object3D();
  4087. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4088. this.castShadow = false;
  4089. this.onlyShadow = false;
  4090. //
  4091. this.shadowCameraNear = 50;
  4092. this.shadowCameraFar = 5000;
  4093. this.shadowCameraLeft = -500;
  4094. this.shadowCameraRight = 500;
  4095. this.shadowCameraTop = 500;
  4096. this.shadowCameraBottom = -500;
  4097. this.shadowCameraVisible = false;
  4098. this.shadowBias = 0;
  4099. this.shadowDarkness = 0.5;
  4100. this.shadowMapWidth = 512;
  4101. this.shadowMapHeight = 512;
  4102. //
  4103. this.shadowCascade = false;
  4104. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  4105. this.shadowCascadeCount = 2;
  4106. this.shadowCascadeBias = [ 0, 0, 0 ];
  4107. this.shadowCascadeWidth = [ 512, 512, 512 ];
  4108. this.shadowCascadeHeight = [ 512, 512, 512 ];
  4109. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  4110. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  4111. this.shadowCascadeArray = [];
  4112. //
  4113. this.shadowMap = null;
  4114. this.shadowMapSize = null;
  4115. this.shadowCamera = null;
  4116. this.shadowMatrix = null;
  4117. };
  4118. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  4119. /**
  4120. * @author alteredq / http://alteredqualia.com/
  4121. */
  4122. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  4123. THREE.Light.call( this, skyColorHex );
  4124. this.groundColor = new THREE.Color( groundColorHex );
  4125. this.position = new THREE.Vector3( 0, 100, 0 );
  4126. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4127. };
  4128. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  4129. /**
  4130. * @author mrdoob / http://mrdoob.com/
  4131. */
  4132. THREE.PointLight = function ( hex, intensity, distance ) {
  4133. THREE.Light.call( this, hex );
  4134. this.position = new THREE.Vector3( 0, 0, 0 );
  4135. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4136. this.distance = ( distance !== undefined ) ? distance : 0;
  4137. };
  4138. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  4139. /**
  4140. * @author alteredq / http://alteredqualia.com/
  4141. */
  4142. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  4143. THREE.Light.call( this, hex );
  4144. this.position = new THREE.Vector3( 0, 1, 0 );
  4145. this.target = new THREE.Object3D();
  4146. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4147. this.distance = ( distance !== undefined ) ? distance : 0;
  4148. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  4149. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  4150. this.castShadow = false;
  4151. this.onlyShadow = false;
  4152. //
  4153. this.shadowCameraNear = 50;
  4154. this.shadowCameraFar = 5000;
  4155. this.shadowCameraFov = 50;
  4156. this.shadowCameraVisible = false;
  4157. this.shadowBias = 0;
  4158. this.shadowDarkness = 0.5;
  4159. this.shadowMapWidth = 512;
  4160. this.shadowMapHeight = 512;
  4161. //
  4162. this.shadowMap = null;
  4163. this.shadowMapSize = null;
  4164. this.shadowCamera = null;
  4165. this.shadowMatrix = null;
  4166. };
  4167. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  4168. /**
  4169. * @author alteredq / http://alteredqualia.com/
  4170. */
  4171. THREE.Loader = function ( showStatus ) {
  4172. this.showStatus = showStatus;
  4173. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  4174. this.onLoadStart = function () {};
  4175. this.onLoadProgress = function () {};
  4176. this.onLoadComplete = function () {};
  4177. };
  4178. THREE.Loader.prototype = {
  4179. constructor: THREE.Loader,
  4180. crossOrigin: 'anonymous',
  4181. addStatusElement: function () {
  4182. var e = document.createElement( "div" );
  4183. e.style.position = "absolute";
  4184. e.style.right = "0px";
  4185. e.style.top = "0px";
  4186. e.style.fontSize = "0.8em";
  4187. e.style.textAlign = "left";
  4188. e.style.background = "rgba(0,0,0,0.25)";
  4189. e.style.color = "#fff";
  4190. e.style.width = "120px";
  4191. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  4192. e.style.zIndex = 1000;
  4193. e.innerHTML = "Loading ...";
  4194. return e;
  4195. },
  4196. updateProgress: function ( progress ) {
  4197. var message = "Loaded ";
  4198. if ( progress.total ) {
  4199. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  4200. } else {
  4201. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  4202. }
  4203. this.statusDomElement.innerHTML = message;
  4204. },
  4205. extractUrlBase: function ( url ) {
  4206. var parts = url.split( '/' );
  4207. parts.pop();
  4208. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  4209. },
  4210. initMaterials: function ( materials, texturePath ) {
  4211. var array = [];
  4212. for ( var i = 0; i < materials.length; ++ i ) {
  4213. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  4214. }
  4215. return array;
  4216. },
  4217. needsTangents: function ( materials ) {
  4218. for( var i = 0, il = materials.length; i < il; i ++ ) {
  4219. var m = materials[ i ];
  4220. if ( m instanceof THREE.ShaderMaterial ) return true;
  4221. }
  4222. return false;
  4223. },
  4224. createMaterial: function ( m, texturePath ) {
  4225. var _this = this;
  4226. function is_pow2( n ) {
  4227. var l = Math.log( n ) / Math.LN2;
  4228. return Math.floor( l ) == l;
  4229. }
  4230. function nearest_pow2( n ) {
  4231. var l = Math.log( n ) / Math.LN2;
  4232. return Math.pow( 2, Math.round( l ) );
  4233. }
  4234. function load_image( where, url ) {
  4235. var image = new Image();
  4236. image.onload = function () {
  4237. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  4238. var width = nearest_pow2( this.width );
  4239. var height = nearest_pow2( this.height );
  4240. where.image.width = width;
  4241. where.image.height = height;
  4242. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  4243. } else {
  4244. where.image = this;
  4245. }
  4246. where.needsUpdate = true;
  4247. };
  4248. image.crossOrigin = _this.crossOrigin;
  4249. image.src = url;
  4250. }
  4251. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  4252. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  4253. var fullPath = texturePath + "/" + sourceFile;
  4254. if ( isCompressed ) {
  4255. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  4256. where[ name ] = texture;
  4257. } else {
  4258. var texture = document.createElement( 'canvas' );
  4259. where[ name ] = new THREE.Texture( texture );
  4260. }
  4261. where[ name ].sourceFile = sourceFile;
  4262. if( repeat ) {
  4263. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4264. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4265. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4266. }
  4267. if ( offset ) {
  4268. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4269. }
  4270. if ( wrap ) {
  4271. var wrapMap = {
  4272. "repeat": THREE.RepeatWrapping,
  4273. "mirror": THREE.MirroredRepeatWrapping
  4274. }
  4275. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4276. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4277. }
  4278. if ( anisotropy ) {
  4279. where[ name ].anisotropy = anisotropy;
  4280. }
  4281. if ( ! isCompressed ) {
  4282. load_image( where[ name ], fullPath );
  4283. }
  4284. }
  4285. function rgb2hex( rgb ) {
  4286. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4287. }
  4288. // defaults
  4289. var mtype = "MeshLambertMaterial";
  4290. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4291. // parameters from model file
  4292. if ( m.shading ) {
  4293. var shading = m.shading.toLowerCase();
  4294. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4295. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4296. }
  4297. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4298. mpars.blending = THREE[ m.blending ];
  4299. }
  4300. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4301. mpars.transparent = m.transparent;
  4302. }
  4303. if ( m.depthTest !== undefined ) {
  4304. mpars.depthTest = m.depthTest;
  4305. }
  4306. if ( m.depthWrite !== undefined ) {
  4307. mpars.depthWrite = m.depthWrite;
  4308. }
  4309. if ( m.visible !== undefined ) {
  4310. mpars.visible = m.visible;
  4311. }
  4312. if ( m.flipSided !== undefined ) {
  4313. mpars.side = THREE.BackSide;
  4314. }
  4315. if ( m.doubleSided !== undefined ) {
  4316. mpars.side = THREE.DoubleSide;
  4317. }
  4318. if ( m.wireframe !== undefined ) {
  4319. mpars.wireframe = m.wireframe;
  4320. }
  4321. if ( m.vertexColors !== undefined ) {
  4322. if ( m.vertexColors === "face" ) {
  4323. mpars.vertexColors = THREE.FaceColors;
  4324. } else if ( m.vertexColors ) {
  4325. mpars.vertexColors = THREE.VertexColors;
  4326. }
  4327. }
  4328. // colors
  4329. if ( m.colorDiffuse ) {
  4330. mpars.color = rgb2hex( m.colorDiffuse );
  4331. } else if ( m.DbgColor ) {
  4332. mpars.color = m.DbgColor;
  4333. }
  4334. if ( m.colorSpecular ) {
  4335. mpars.specular = rgb2hex( m.colorSpecular );
  4336. }
  4337. if ( m.colorAmbient ) {
  4338. mpars.ambient = rgb2hex( m.colorAmbient );
  4339. }
  4340. // modifiers
  4341. if ( m.transparency ) {
  4342. mpars.opacity = m.transparency;
  4343. }
  4344. if ( m.specularCoef ) {
  4345. mpars.shininess = m.specularCoef;
  4346. }
  4347. // textures
  4348. if ( m.mapDiffuse && texturePath ) {
  4349. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  4350. }
  4351. if ( m.mapLight && texturePath ) {
  4352. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  4353. }
  4354. if ( m.mapBump && texturePath ) {
  4355. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  4356. }
  4357. if ( m.mapNormal && texturePath ) {
  4358. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  4359. }
  4360. if ( m.mapSpecular && texturePath ) {
  4361. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  4362. }
  4363. //
  4364. if ( m.mapBumpScale ) {
  4365. mpars.bumpScale = m.mapBumpScale;
  4366. }
  4367. // special case for normal mapped material
  4368. if ( m.mapNormal ) {
  4369. var shader = THREE.ShaderUtils.lib[ "normal" ];
  4370. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  4371. uniforms[ "tNormal" ].value = mpars.normalMap;
  4372. if ( m.mapNormalFactor ) {
  4373. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  4374. }
  4375. if ( mpars.map ) {
  4376. uniforms[ "tDiffuse" ].value = mpars.map;
  4377. uniforms[ "enableDiffuse" ].value = true;
  4378. }
  4379. if ( mpars.specularMap ) {
  4380. uniforms[ "tSpecular" ].value = mpars.specularMap;
  4381. uniforms[ "enableSpecular" ].value = true;
  4382. }
  4383. if ( mpars.lightMap ) {
  4384. uniforms[ "tAO" ].value = mpars.lightMap;
  4385. uniforms[ "enableAO" ].value = true;
  4386. }
  4387. // for the moment don't handle displacement texture
  4388. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  4389. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  4390. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  4391. uniforms[ "uShininess" ].value = mpars.shininess;
  4392. if ( mpars.opacity !== undefined ) {
  4393. uniforms[ "uOpacity" ].value = mpars.opacity;
  4394. }
  4395. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  4396. var material = new THREE.ShaderMaterial( parameters );
  4397. } else {
  4398. var material = new THREE[ mtype ]( mpars );
  4399. }
  4400. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  4401. return material;
  4402. }
  4403. };
  4404. /**
  4405. * @author alteredq / http://alteredqualia.com/
  4406. */
  4407. THREE.BinaryLoader = function ( showStatus ) {
  4408. THREE.Loader.call( this, showStatus );
  4409. };
  4410. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  4411. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  4412. // - binary models consist of two files: JS and BIN
  4413. // - parameters
  4414. // - url (required)
  4415. // - callback (required)
  4416. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  4417. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  4418. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  4419. // todo: unify load API to for easier SceneLoader use
  4420. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  4421. binaryPath = binaryPath && ( typeof binaryPath === "string" ) ? binaryPath : this.extractUrlBase( url );
  4422. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  4423. this.onLoadStart();
  4424. // #1 load JS part via web worker
  4425. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  4426. };
  4427. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  4428. var xhr = new XMLHttpRequest();
  4429. xhr.onreadystatechange = function () {
  4430. if ( xhr.readyState == 4 ) {
  4431. if ( xhr.status == 200 || xhr.status == 0 ) {
  4432. var json = JSON.parse( xhr.responseText );
  4433. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  4434. } else {
  4435. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4436. }
  4437. }
  4438. };
  4439. xhr.open( "GET", url, true );
  4440. xhr.send( null );
  4441. };
  4442. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  4443. var xhr = new XMLHttpRequest(),
  4444. url = binaryPath + "/" + json.buffers;
  4445. var length = 0;
  4446. xhr.onreadystatechange = function () {
  4447. if ( xhr.readyState == 4 ) {
  4448. if ( xhr.status == 200 || xhr.status == 0 ) {
  4449. var buffer = xhr.response;
  4450. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  4451. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  4452. } else {
  4453. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4454. }
  4455. } else if ( xhr.readyState == 3 ) {
  4456. if ( callbackProgress ) {
  4457. if ( length == 0 ) {
  4458. length = xhr.getResponseHeader( "Content-Length" );
  4459. }
  4460. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4461. }
  4462. } else if ( xhr.readyState == 2 ) {
  4463. length = xhr.getResponseHeader( "Content-Length" );
  4464. }
  4465. };
  4466. xhr.open( "GET", url, true );
  4467. xhr.responseType = "arraybuffer";
  4468. xhr.send( null );
  4469. };
  4470. // Binary AJAX parser
  4471. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, jsonMaterials ) {
  4472. var Model = function ( texturePath ) {
  4473. var scope = this,
  4474. currentOffset = 0,
  4475. md,
  4476. normals = [],
  4477. uvs = [],
  4478. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  4479. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  4480. tri_size, quad_size,
  4481. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  4482. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  4483. THREE.Geometry.call( this );
  4484. md = parseMetaData( data, currentOffset );
  4485. currentOffset += md.header_bytes;
  4486. /*
  4487. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4488. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  4489. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4490. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4491. */
  4492. // buffers sizes
  4493. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  4494. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  4495. len_tri_flat = md.ntri_flat * ( tri_size );
  4496. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  4497. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  4498. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  4499. len_quad_flat = md.nquad_flat * ( quad_size );
  4500. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  4501. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  4502. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  4503. // read buffers
  4504. currentOffset += init_vertices( currentOffset );
  4505. currentOffset += init_normals( currentOffset );
  4506. currentOffset += handlePadding( md.nnormals * 3 );
  4507. currentOffset += init_uvs( currentOffset );
  4508. start_tri_flat = currentOffset;
  4509. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  4510. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  4511. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  4512. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  4513. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  4514. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  4515. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  4516. // have to first process faces with uvs
  4517. // so that face and uv indices match
  4518. init_triangles_flat_uv( start_tri_flat_uv );
  4519. init_triangles_smooth_uv( start_tri_smooth_uv );
  4520. init_quads_flat_uv( start_quad_flat_uv );
  4521. init_quads_smooth_uv( start_quad_smooth_uv );
  4522. // now we can process untextured faces
  4523. init_triangles_flat( start_tri_flat );
  4524. init_triangles_smooth( start_tri_smooth );
  4525. init_quads_flat( start_quad_flat );
  4526. init_quads_smooth( start_quad_smooth );
  4527. this.computeCentroids();
  4528. this.computeFaceNormals();
  4529. function handlePadding( n ) {
  4530. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  4531. };
  4532. function parseMetaData( data, offset ) {
  4533. var metaData = {
  4534. 'signature' :parseString( data, offset, 12 ),
  4535. 'header_bytes' :parseUChar8( data, offset + 12 ),
  4536. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  4537. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  4538. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  4539. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  4540. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  4541. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  4542. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  4543. 'nvertices' :parseUInt32( data, offset + 20 ),
  4544. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  4545. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  4546. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  4547. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  4548. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  4549. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  4550. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  4551. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  4552. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  4553. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  4554. };
  4555. /*
  4556. console.log( "signature: " + metaData.signature );
  4557. console.log( "header_bytes: " + metaData.header_bytes );
  4558. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  4559. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  4560. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  4561. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  4562. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  4563. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  4564. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  4565. console.log( "nvertices: " + metaData.nvertices );
  4566. console.log( "nnormals: " + metaData.nnormals );
  4567. console.log( "nuvs: " + metaData.nuvs );
  4568. console.log( "ntri_flat: " + metaData.ntri_flat );
  4569. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  4570. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  4571. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  4572. console.log( "nquad_flat: " + metaData.nquad_flat );
  4573. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  4574. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  4575. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  4576. var total = metaData.header_bytes
  4577. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  4578. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  4579. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  4580. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  4581. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  4582. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  4583. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  4584. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  4585. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  4586. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  4587. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  4588. console.log( "total bytes: " + total );
  4589. */
  4590. return metaData;
  4591. };
  4592. function parseString( data, offset, length ) {
  4593. var charArray = new Uint8Array( data, offset, length );
  4594. var text = "";
  4595. for ( var i = 0; i < length; i ++ ) {
  4596. text += String.fromCharCode( charArray[ offset + i ] );
  4597. }
  4598. return text;
  4599. };
  4600. function parseUChar8( data, offset ) {
  4601. var charArray = new Uint8Array( data, offset, 1 );
  4602. return charArray[ 0 ];
  4603. };
  4604. function parseUInt32( data, offset ) {
  4605. var intArray = new Uint32Array( data, offset, 1 );
  4606. return intArray[ 0 ];
  4607. };
  4608. function init_vertices( start ) {
  4609. var nElements = md.nvertices;
  4610. var coordArray = new Float32Array( data, start, nElements * 3 );
  4611. var i, x, y, z;
  4612. for( i = 0; i < nElements; i ++ ) {
  4613. x = coordArray[ i * 3 ];
  4614. y = coordArray[ i * 3 + 1 ];
  4615. z = coordArray[ i * 3 + 2 ];
  4616. vertex( scope, x, y, z );
  4617. }
  4618. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  4619. };
  4620. function init_normals( start ) {
  4621. var nElements = md.nnormals;
  4622. if ( nElements ) {
  4623. var normalArray = new Int8Array( data, start, nElements * 3 );
  4624. var i, x, y, z;
  4625. for( i = 0; i < nElements; i ++ ) {
  4626. x = normalArray[ i * 3 ];
  4627. y = normalArray[ i * 3 + 1 ];
  4628. z = normalArray[ i * 3 + 2 ];
  4629. normals.push( x/127, y/127, z/127 );
  4630. }
  4631. }
  4632. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  4633. };
  4634. function init_uvs( start ) {
  4635. var nElements = md.nuvs;
  4636. if ( nElements ) {
  4637. var uvArray = new Float32Array( data, start, nElements * 2 );
  4638. var i, u, v;
  4639. for( i = 0; i < nElements; i ++ ) {
  4640. u = uvArray[ i * 2 ];
  4641. v = uvArray[ i * 2 + 1 ];
  4642. uvs.push( u, v );
  4643. }
  4644. }
  4645. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  4646. };
  4647. function init_uvs3( nElements, offset ) {
  4648. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  4649. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  4650. for( i = 0; i < nElements; i ++ ) {
  4651. uva = uvIndexBuffer[ i * 3 ];
  4652. uvb = uvIndexBuffer[ i * 3 + 1 ];
  4653. uvc = uvIndexBuffer[ i * 3 + 2 ];
  4654. u1 = uvs[ uva*2 ];
  4655. v1 = uvs[ uva*2 + 1 ];
  4656. u2 = uvs[ uvb*2 ];
  4657. v2 = uvs[ uvb*2 + 1 ];
  4658. u3 = uvs[ uvc*2 ];
  4659. v3 = uvs[ uvc*2 + 1 ];
  4660. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  4661. }
  4662. };
  4663. function init_uvs4( nElements, offset ) {
  4664. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  4665. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  4666. for( i = 0; i < nElements; i ++ ) {
  4667. uva = uvIndexBuffer[ i * 4 ];
  4668. uvb = uvIndexBuffer[ i * 4 + 1 ];
  4669. uvc = uvIndexBuffer[ i * 4 + 2 ];
  4670. uvd = uvIndexBuffer[ i * 4 + 3 ];
  4671. u1 = uvs[ uva*2 ];
  4672. v1 = uvs[ uva*2 + 1 ];
  4673. u2 = uvs[ uvb*2 ];
  4674. v2 = uvs[ uvb*2 + 1 ];
  4675. u3 = uvs[ uvc*2 ];
  4676. v3 = uvs[ uvc*2 + 1 ];
  4677. u4 = uvs[ uvd*2 ];
  4678. v4 = uvs[ uvd*2 + 1 ];
  4679. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  4680. }
  4681. };
  4682. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  4683. var i, a, b, c, m;
  4684. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4685. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4686. for( i = 0; i < nElements; i ++ ) {
  4687. a = vertexIndexBuffer[ i * 3 ];
  4688. b = vertexIndexBuffer[ i * 3 + 1 ];
  4689. c = vertexIndexBuffer[ i * 3 + 2 ];
  4690. m = materialIndexBuffer[ i ];
  4691. f3( scope, a, b, c, m );
  4692. }
  4693. };
  4694. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  4695. var i, a, b, c, d, m;
  4696. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4697. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4698. for( i = 0; i < nElements; i ++ ) {
  4699. a = vertexIndexBuffer[ i * 4 ];
  4700. b = vertexIndexBuffer[ i * 4 + 1 ];
  4701. c = vertexIndexBuffer[ i * 4 + 2 ];
  4702. d = vertexIndexBuffer[ i * 4 + 3 ];
  4703. m = materialIndexBuffer[ i ];
  4704. f4( scope, a, b, c, d, m );
  4705. }
  4706. };
  4707. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4708. var i, a, b, c, m;
  4709. var na, nb, nc;
  4710. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4711. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  4712. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4713. for( i = 0; i < nElements; i ++ ) {
  4714. a = vertexIndexBuffer[ i * 3 ];
  4715. b = vertexIndexBuffer[ i * 3 + 1 ];
  4716. c = vertexIndexBuffer[ i * 3 + 2 ];
  4717. na = normalIndexBuffer[ i * 3 ];
  4718. nb = normalIndexBuffer[ i * 3 + 1 ];
  4719. nc = normalIndexBuffer[ i * 3 + 2 ];
  4720. m = materialIndexBuffer[ i ];
  4721. f3n( scope, normals, a, b, c, m, na, nb, nc );
  4722. }
  4723. };
  4724. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4725. var i, a, b, c, d, m;
  4726. var na, nb, nc, nd;
  4727. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4728. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  4729. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4730. for( i = 0; i < nElements; i ++ ) {
  4731. a = vertexIndexBuffer[ i * 4 ];
  4732. b = vertexIndexBuffer[ i * 4 + 1 ];
  4733. c = vertexIndexBuffer[ i * 4 + 2 ];
  4734. d = vertexIndexBuffer[ i * 4 + 3 ];
  4735. na = normalIndexBuffer[ i * 4 ];
  4736. nb = normalIndexBuffer[ i * 4 + 1 ];
  4737. nc = normalIndexBuffer[ i * 4 + 2 ];
  4738. nd = normalIndexBuffer[ i * 4 + 3 ];
  4739. m = materialIndexBuffer[ i ];
  4740. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  4741. }
  4742. };
  4743. function init_triangles_flat( start ) {
  4744. var nElements = md.ntri_flat;
  4745. if ( nElements ) {
  4746. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4747. init_faces3_flat( nElements, start, offsetMaterials );
  4748. }
  4749. };
  4750. function init_triangles_flat_uv( start ) {
  4751. var nElements = md.ntri_flat_uv;
  4752. if ( nElements ) {
  4753. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4754. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4755. init_faces3_flat( nElements, start, offsetMaterials );
  4756. init_uvs3( nElements, offsetUvs );
  4757. }
  4758. };
  4759. function init_triangles_smooth( start ) {
  4760. var nElements = md.ntri_smooth;
  4761. if ( nElements ) {
  4762. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4763. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4764. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4765. }
  4766. };
  4767. function init_triangles_smooth_uv( start ) {
  4768. var nElements = md.ntri_smooth_uv;
  4769. if ( nElements ) {
  4770. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4771. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4772. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4773. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4774. init_uvs3( nElements, offsetUvs );
  4775. }
  4776. };
  4777. function init_quads_flat( start ) {
  4778. var nElements = md.nquad_flat;
  4779. if ( nElements ) {
  4780. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4781. init_faces4_flat( nElements, start, offsetMaterials );
  4782. }
  4783. };
  4784. function init_quads_flat_uv( start ) {
  4785. var nElements = md.nquad_flat_uv;
  4786. if ( nElements ) {
  4787. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4788. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4789. init_faces4_flat( nElements, start, offsetMaterials );
  4790. init_uvs4( nElements, offsetUvs );
  4791. }
  4792. };
  4793. function init_quads_smooth( start ) {
  4794. var nElements = md.nquad_smooth;
  4795. if ( nElements ) {
  4796. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4797. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4798. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4799. }
  4800. };
  4801. function init_quads_smooth_uv( start ) {
  4802. var nElements = md.nquad_smooth_uv;
  4803. if ( nElements ) {
  4804. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4805. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4806. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4807. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4808. init_uvs4( nElements, offsetUvs );
  4809. }
  4810. };
  4811. };
  4812. function vertex ( scope, x, y, z ) {
  4813. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  4814. };
  4815. function f3 ( scope, a, b, c, mi ) {
  4816. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  4817. };
  4818. function f4 ( scope, a, b, c, d, mi ) {
  4819. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  4820. };
  4821. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  4822. var nax = normals[ na*3 ],
  4823. nay = normals[ na*3 + 1 ],
  4824. naz = normals[ na*3 + 2 ],
  4825. nbx = normals[ nb*3 ],
  4826. nby = normals[ nb*3 + 1 ],
  4827. nbz = normals[ nb*3 + 2 ],
  4828. ncx = normals[ nc*3 ],
  4829. ncy = normals[ nc*3 + 1 ],
  4830. ncz = normals[ nc*3 + 2 ];
  4831. scope.faces.push( new THREE.Face3( a, b, c,
  4832. [new THREE.Vector3( nax, nay, naz ),
  4833. new THREE.Vector3( nbx, nby, nbz ),
  4834. new THREE.Vector3( ncx, ncy, ncz )],
  4835. null,
  4836. mi ) );
  4837. };
  4838. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  4839. var nax = normals[ na*3 ],
  4840. nay = normals[ na*3 + 1 ],
  4841. naz = normals[ na*3 + 2 ],
  4842. nbx = normals[ nb*3 ],
  4843. nby = normals[ nb*3 + 1 ],
  4844. nbz = normals[ nb*3 + 2 ],
  4845. ncx = normals[ nc*3 ],
  4846. ncy = normals[ nc*3 + 1 ],
  4847. ncz = normals[ nc*3 + 2 ],
  4848. ndx = normals[ nd*3 ],
  4849. ndy = normals[ nd*3 + 1 ],
  4850. ndz = normals[ nd*3 + 2 ];
  4851. scope.faces.push( new THREE.Face4( a, b, c, d,
  4852. [new THREE.Vector3( nax, nay, naz ),
  4853. new THREE.Vector3( nbx, nby, nbz ),
  4854. new THREE.Vector3( ncx, ncy, ncz ),
  4855. new THREE.Vector3( ndx, ndy, ndz )],
  4856. null,
  4857. mi ) );
  4858. };
  4859. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  4860. where.push( [
  4861. new THREE.UV( u1, v1 ),
  4862. new THREE.UV( u2, v2 ),
  4863. new THREE.UV( u3, v3 )
  4864. ] );
  4865. };
  4866. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  4867. where.push( [
  4868. new THREE.UV( u1, v1 ),
  4869. new THREE.UV( u2, v2 ),
  4870. new THREE.UV( u3, v3 ),
  4871. new THREE.UV( u4, v4 )
  4872. ] );
  4873. };
  4874. Model.prototype = Object.create( THREE.Geometry.prototype );
  4875. var geometry = new Model( texturePath );
  4876. var materials = this.initMaterials( jsonMaterials, texturePath );
  4877. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  4878. callback( geometry, materials );
  4879. };
  4880. /**
  4881. * @author mrdoob / http://mrdoob.com/
  4882. */
  4883. THREE.ImageLoader = function () {
  4884. THREE.EventTarget.call( this );
  4885. this.crossOrigin = null;
  4886. };
  4887. THREE.ImageLoader.prototype = {
  4888. constructor: THREE.ImageLoader,
  4889. load: function ( url, image ) {
  4890. var scope = this;
  4891. if ( image === undefined ) image = new Image();
  4892. image.addEventListener( 'load', function () {
  4893. scope.dispatchEvent( { type: 'load', content: image } );
  4894. }, false );
  4895. image.addEventListener( 'error', function () {
  4896. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4897. }, false );
  4898. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  4899. image.src = url;
  4900. }
  4901. }
  4902. /**
  4903. * @author mrdoob / http://mrdoob.com/
  4904. * @author alteredq / http://alteredqualia.com/
  4905. */
  4906. THREE.JSONLoader = function ( showStatus ) {
  4907. THREE.Loader.call( this, showStatus );
  4908. this.withCredentials = false;
  4909. };
  4910. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  4911. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  4912. var scope = this;
  4913. // todo: unify load API to for easier SceneLoader use
  4914. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  4915. this.onLoadStart();
  4916. this.loadAjaxJSON( this, url, callback, texturePath );
  4917. };
  4918. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  4919. var xhr = new XMLHttpRequest();
  4920. var length = 0;
  4921. xhr.withCredentials = this.withCredentials;
  4922. xhr.onreadystatechange = function () {
  4923. if ( xhr.readyState === xhr.DONE ) {
  4924. if ( xhr.status === 200 || xhr.status === 0 ) {
  4925. if ( xhr.responseText ) {
  4926. var json = JSON.parse( xhr.responseText );
  4927. context.createModel( json, callback, texturePath );
  4928. } else {
  4929. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  4930. }
  4931. // in context of more complex asset initialization
  4932. // do not block on single failed file
  4933. // maybe should go even one more level up
  4934. context.onLoadComplete();
  4935. } else {
  4936. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4937. }
  4938. } else if ( xhr.readyState === xhr.LOADING ) {
  4939. if ( callbackProgress ) {
  4940. if ( length === 0 ) {
  4941. length = xhr.getResponseHeader( "Content-Length" );
  4942. }
  4943. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4944. }
  4945. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  4946. length = xhr.getResponseHeader( "Content-Length" );
  4947. }
  4948. };
  4949. xhr.open( "GET", url, true );
  4950. xhr.send( null );
  4951. };
  4952. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  4953. var scope = this,
  4954. geometry = new THREE.Geometry(),
  4955. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  4956. parseModel( scale );
  4957. parseSkin();
  4958. parseMorphing( scale );
  4959. geometry.computeCentroids();
  4960. geometry.computeFaceNormals();
  4961. function parseModel( scale ) {
  4962. function isBitSet( value, position ) {
  4963. return value & ( 1 << position );
  4964. }
  4965. var i, j, fi,
  4966. offset, zLength, nVertices,
  4967. colorIndex, normalIndex, uvIndex, materialIndex,
  4968. type,
  4969. isQuad,
  4970. hasMaterial,
  4971. hasFaceUv, hasFaceVertexUv,
  4972. hasFaceNormal, hasFaceVertexNormal,
  4973. hasFaceColor, hasFaceVertexColor,
  4974. vertex, face, color, normal,
  4975. uvLayer, uvs, u, v,
  4976. faces = json.faces,
  4977. vertices = json.vertices,
  4978. normals = json.normals,
  4979. colors = json.colors,
  4980. nUvLayers = 0;
  4981. // disregard empty arrays
  4982. for ( i = 0; i < json.uvs.length; i++ ) {
  4983. if ( json.uvs[ i ].length ) nUvLayers ++;
  4984. }
  4985. for ( i = 0; i < nUvLayers; i++ ) {
  4986. geometry.faceUvs[ i ] = [];
  4987. geometry.faceVertexUvs[ i ] = [];
  4988. }
  4989. offset = 0;
  4990. zLength = vertices.length;
  4991. while ( offset < zLength ) {
  4992. vertex = new THREE.Vector3();
  4993. vertex.x = vertices[ offset ++ ] * scale;
  4994. vertex.y = vertices[ offset ++ ] * scale;
  4995. vertex.z = vertices[ offset ++ ] * scale;
  4996. geometry.vertices.push( vertex );
  4997. }
  4998. offset = 0;
  4999. zLength = faces.length;
  5000. while ( offset < zLength ) {
  5001. type = faces[ offset ++ ];
  5002. isQuad = isBitSet( type, 0 );
  5003. hasMaterial = isBitSet( type, 1 );
  5004. hasFaceUv = isBitSet( type, 2 );
  5005. hasFaceVertexUv = isBitSet( type, 3 );
  5006. hasFaceNormal = isBitSet( type, 4 );
  5007. hasFaceVertexNormal = isBitSet( type, 5 );
  5008. hasFaceColor = isBitSet( type, 6 );
  5009. hasFaceVertexColor = isBitSet( type, 7 );
  5010. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5011. if ( isQuad ) {
  5012. face = new THREE.Face4();
  5013. face.a = faces[ offset ++ ];
  5014. face.b = faces[ offset ++ ];
  5015. face.c = faces[ offset ++ ];
  5016. face.d = faces[ offset ++ ];
  5017. nVertices = 4;
  5018. } else {
  5019. face = new THREE.Face3();
  5020. face.a = faces[ offset ++ ];
  5021. face.b = faces[ offset ++ ];
  5022. face.c = faces[ offset ++ ];
  5023. nVertices = 3;
  5024. }
  5025. if ( hasMaterial ) {
  5026. materialIndex = faces[ offset ++ ];
  5027. face.materialIndex = materialIndex;
  5028. }
  5029. // to get face <=> uv index correspondence
  5030. fi = geometry.faces.length;
  5031. if ( hasFaceUv ) {
  5032. for ( i = 0; i < nUvLayers; i++ ) {
  5033. uvLayer = json.uvs[ i ];
  5034. uvIndex = faces[ offset ++ ];
  5035. u = uvLayer[ uvIndex * 2 ];
  5036. v = uvLayer[ uvIndex * 2 + 1 ];
  5037. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5038. }
  5039. }
  5040. if ( hasFaceVertexUv ) {
  5041. for ( i = 0; i < nUvLayers; i++ ) {
  5042. uvLayer = json.uvs[ i ];
  5043. uvs = [];
  5044. for ( j = 0; j < nVertices; j ++ ) {
  5045. uvIndex = faces[ offset ++ ];
  5046. u = uvLayer[ uvIndex * 2 ];
  5047. v = uvLayer[ uvIndex * 2 + 1 ];
  5048. uvs[ j ] = new THREE.UV( u, v );
  5049. }
  5050. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5051. }
  5052. }
  5053. if ( hasFaceNormal ) {
  5054. normalIndex = faces[ offset ++ ] * 3;
  5055. normal = new THREE.Vector3();
  5056. normal.x = normals[ normalIndex ++ ];
  5057. normal.y = normals[ normalIndex ++ ];
  5058. normal.z = normals[ normalIndex ];
  5059. face.normal = normal;
  5060. }
  5061. if ( hasFaceVertexNormal ) {
  5062. for ( i = 0; i < nVertices; i++ ) {
  5063. normalIndex = faces[ offset ++ ] * 3;
  5064. normal = new THREE.Vector3();
  5065. normal.x = normals[ normalIndex ++ ];
  5066. normal.y = normals[ normalIndex ++ ];
  5067. normal.z = normals[ normalIndex ];
  5068. face.vertexNormals.push( normal );
  5069. }
  5070. }
  5071. if ( hasFaceColor ) {
  5072. colorIndex = faces[ offset ++ ];
  5073. color = new THREE.Color( colors[ colorIndex ] );
  5074. face.color = color;
  5075. }
  5076. if ( hasFaceVertexColor ) {
  5077. for ( i = 0; i < nVertices; i++ ) {
  5078. colorIndex = faces[ offset ++ ];
  5079. color = new THREE.Color( colors[ colorIndex ] );
  5080. face.vertexColors.push( color );
  5081. }
  5082. }
  5083. geometry.faces.push( face );
  5084. }
  5085. };
  5086. function parseSkin() {
  5087. var i, l, x, y, z, w, a, b, c, d;
  5088. if ( json.skinWeights ) {
  5089. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5090. x = json.skinWeights[ i ];
  5091. y = json.skinWeights[ i + 1 ];
  5092. z = 0;
  5093. w = 0;
  5094. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5095. }
  5096. }
  5097. if ( json.skinIndices ) {
  5098. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5099. a = json.skinIndices[ i ];
  5100. b = json.skinIndices[ i + 1 ];
  5101. c = 0;
  5102. d = 0;
  5103. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5104. }
  5105. }
  5106. geometry.bones = json.bones;
  5107. geometry.animation = json.animation;
  5108. };
  5109. function parseMorphing( scale ) {
  5110. if ( json.morphTargets !== undefined ) {
  5111. var i, l, v, vl, dstVertices, srcVertices;
  5112. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5113. geometry.morphTargets[ i ] = {};
  5114. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5115. geometry.morphTargets[ i ].vertices = [];
  5116. dstVertices = geometry.morphTargets[ i ].vertices;
  5117. srcVertices = json.morphTargets [ i ].vertices;
  5118. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5119. var vertex = new THREE.Vector3();
  5120. vertex.x = srcVertices[ v ] * scale;
  5121. vertex.y = srcVertices[ v + 1 ] * scale;
  5122. vertex.z = srcVertices[ v + 2 ] * scale;
  5123. dstVertices.push( vertex );
  5124. }
  5125. }
  5126. }
  5127. if ( json.morphColors !== undefined ) {
  5128. var i, l, c, cl, dstColors, srcColors, color;
  5129. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5130. geometry.morphColors[ i ] = {};
  5131. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5132. geometry.morphColors[ i ].colors = [];
  5133. dstColors = geometry.morphColors[ i ].colors;
  5134. srcColors = json.morphColors [ i ].colors;
  5135. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5136. color = new THREE.Color( 0xffaa00 );
  5137. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5138. dstColors.push( color );
  5139. }
  5140. }
  5141. }
  5142. };
  5143. var materials = this.initMaterials( json.materials, texturePath );
  5144. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5145. callback( geometry, materials );
  5146. };
  5147. /**
  5148. * @author mrdoob / http://mrdoob.com/
  5149. */
  5150. THREE.LoadingMonitor = function () {
  5151. THREE.EventTarget.call( this );
  5152. var scope = this;
  5153. var loaded = 0;
  5154. var total = 0;
  5155. var onLoad = function ( event ) {
  5156. loaded ++;
  5157. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5158. if ( loaded === total ) {
  5159. scope.dispatchEvent( { type: 'load' } );
  5160. }
  5161. };
  5162. this.add = function ( loader ) {
  5163. total ++;
  5164. loader.addEventListener( 'load', onLoad, false );
  5165. };
  5166. };
  5167. /**
  5168. * @author alteredq / http://alteredqualia.com/
  5169. */
  5170. THREE.SceneLoader = function () {
  5171. this.onLoadStart = function () {};
  5172. this.onLoadProgress = function() {};
  5173. this.onLoadComplete = function () {};
  5174. this.callbackSync = function () {};
  5175. this.callbackProgress = function () {};
  5176. this.geometryHandlerMap = {};
  5177. this.hierarchyHandlerMap = {};
  5178. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5179. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  5180. };
  5181. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5182. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5183. var scope = this;
  5184. var xhr = new XMLHttpRequest();
  5185. xhr.onreadystatechange = function () {
  5186. if ( xhr.readyState === 4 ) {
  5187. if ( xhr.status === 200 || xhr.status === 0 ) {
  5188. var json = JSON.parse( xhr.responseText );
  5189. scope.parse( json, callbackFinished, url );
  5190. } else {
  5191. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5192. }
  5193. }
  5194. };
  5195. xhr.open( "GET", url, true );
  5196. xhr.send( null );
  5197. };
  5198. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5199. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5200. };
  5201. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5202. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5203. };
  5204. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5205. var scope = this;
  5206. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5207. var dg, dm, dc, df, dt,
  5208. g, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  5209. geometry, material, camera, fog,
  5210. texture, images,
  5211. light, hex, intensity,
  5212. counter_models, counter_textures,
  5213. total_models, total_textures,
  5214. result;
  5215. var target_array = [];
  5216. var data = json;
  5217. // async geometry loaders
  5218. for ( var typeID in this.geometryHandlerMap ) {
  5219. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5220. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5221. }
  5222. // async hierachy loaders
  5223. for ( var typeID in this.hierarchyHandlerMap ) {
  5224. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5225. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5226. }
  5227. counter_models = 0;
  5228. counter_textures = 0;
  5229. result = {
  5230. scene: new THREE.Scene(),
  5231. geometries: {},
  5232. face_materials: {},
  5233. materials: {},
  5234. textures: {},
  5235. objects: {},
  5236. cameras: {},
  5237. lights: {},
  5238. fogs: {},
  5239. empties: {}
  5240. };
  5241. if ( data.transform ) {
  5242. var position = data.transform.position,
  5243. rotation = data.transform.rotation,
  5244. scale = data.transform.scale;
  5245. if ( position )
  5246. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5247. if ( rotation )
  5248. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5249. if ( scale )
  5250. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5251. if ( position || rotation || scale ) {
  5252. result.scene.updateMatrix();
  5253. result.scene.updateMatrixWorld();
  5254. }
  5255. }
  5256. function get_url( source_url, url_type ) {
  5257. if ( url_type == "relativeToHTML" ) {
  5258. return source_url;
  5259. } else {
  5260. return urlBase + "/" + source_url;
  5261. }
  5262. };
  5263. // toplevel loader function, delegates to handle_children
  5264. function handle_objects() {
  5265. handle_children( result.scene, data.objects );
  5266. }
  5267. // handle all the children from the loaded json and attach them to given parent
  5268. function handle_children( parent, children ) {
  5269. for ( var dd in children ) {
  5270. // check by id if child has already been handled,
  5271. // if not, create new object
  5272. if ( result.objects[ dd ] === undefined ) {
  5273. var o = children[ dd ];
  5274. var object = null;
  5275. // meshes
  5276. if ( o.type && ( o.type in scope.hierarchyHandlerMap ) && o.loading === undefined ) {
  5277. var loaderParameters = {};
  5278. for ( var parType in g ) {
  5279. if ( parType !== "type" && parType !== "url" ) {
  5280. loaderParameters[ parType ] = g[ parType ];
  5281. }
  5282. }
  5283. material = result.materials[ o.material ];
  5284. o.loading = true;
  5285. var loader = scope.hierarchyHandlerMap[ o.type ][ "loaderObject" ];
  5286. // OBJLoader
  5287. if ( loader.addEventListener ) {
  5288. loader.addEventListener( 'load', create_callback_hierachy( dd, parent, material, o ) );
  5289. loader.load( get_url( o.url, data.urlBaseType ) );
  5290. } else {
  5291. // ColladaLoader
  5292. if ( loader.options ) {
  5293. loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ) );
  5294. // UTF8Loader
  5295. } else {
  5296. loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ), loaderParameters );
  5297. }
  5298. }
  5299. } else if ( o.geometry !== undefined ) {
  5300. geometry = result.geometries[ o.geometry ];
  5301. // geometry already loaded
  5302. if ( geometry ) {
  5303. var needsTangents = false;
  5304. material = result.materials[ o.material ];
  5305. needsTangents = material instanceof THREE.ShaderMaterial;
  5306. p = o.position;
  5307. r = o.rotation;
  5308. q = o.quaternion;
  5309. s = o.scale;
  5310. m = o.matrix;
  5311. // turn off quaternions, for the moment
  5312. q = 0;
  5313. // use materials from the model file
  5314. // if there is no material specified in the object
  5315. if ( ! o.material ) {
  5316. material = new THREE.MeshFaceMaterial( result.face_materials[ o.geometry ] );
  5317. }
  5318. // use materials from the model file
  5319. // if there is just empty face material
  5320. // (must create new material as each model has its own face material)
  5321. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  5322. material = new THREE.MeshFaceMaterial( result.face_materials[ o.geometry ] );
  5323. }
  5324. if ( material instanceof THREE.MeshFaceMaterial ) {
  5325. for ( var i = 0; i < material.materials.length; i ++ ) {
  5326. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  5327. }
  5328. }
  5329. if ( needsTangents ) {
  5330. geometry.computeTangents();
  5331. }
  5332. if ( o.skin ) {
  5333. object = new THREE.SkinnedMesh( geometry, material );
  5334. } else if ( o.morph ) {
  5335. object = new THREE.MorphAnimMesh( geometry, material );
  5336. if ( o.duration !== undefined ) {
  5337. object.duration = o.duration;
  5338. }
  5339. if ( o.time !== undefined ) {
  5340. object.time = o.time;
  5341. }
  5342. if ( o.mirroredLoop !== undefined ) {
  5343. object.mirroredLoop = o.mirroredLoop;
  5344. }
  5345. if ( material.morphNormals ) {
  5346. geometry.computeMorphNormals();
  5347. }
  5348. } else {
  5349. object = new THREE.Mesh( geometry, material );
  5350. }
  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. // lights
  5377. } else if ( o.type === "DirectionalLight" || o.type === "PointLight" || o.type === "AmbientLight" ) {
  5378. hex = ( o.color !== undefined ) ? o.color : 0xffffff;
  5379. intensity = ( o.intensity !== undefined ) ? o.intensity : 1;
  5380. if ( o.type === "DirectionalLight" ) {
  5381. p = o.direction;
  5382. light = new THREE.DirectionalLight( hex, intensity );
  5383. light.position.set( p[0], p[1], p[2] );
  5384. if ( o.target ) {
  5385. target_array.push( { "object": light, "targetName" : o.target } );
  5386. // kill existing default target
  5387. // otherwise it gets added to scene when parent gets added
  5388. light.target = null;
  5389. }
  5390. } else if ( o.type === "PointLight" ) {
  5391. p = o.position;
  5392. d = o.distance;
  5393. light = new THREE.PointLight( hex, intensity, d );
  5394. light.position.set( p[0], p[1], p[2] );
  5395. } else if ( o.type === "AmbientLight" ) {
  5396. light = new THREE.AmbientLight( hex );
  5397. }
  5398. parent.add( light );
  5399. light.name = dd;
  5400. result.lights[ dd ] = light;
  5401. result.objects[ dd ] = light;
  5402. // cameras
  5403. } else if ( o.type === "PerspectiveCamera" || o.type === "OrthographicCamera" ) {
  5404. if ( o.type === "PerspectiveCamera" ) {
  5405. camera = new THREE.PerspectiveCamera( o.fov, o.aspect, o.near, o.far );
  5406. } else if ( o.type === "OrthographicCamera" ) {
  5407. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  5408. }
  5409. p = o.position;
  5410. camera.position.set( p[0], p[1], p[2] );
  5411. parent.add( camera );
  5412. camera.name = dd;
  5413. result.cameras[ dd ] = camera;
  5414. result.objects[ dd ] = camera;
  5415. // pure Object3D
  5416. } else {
  5417. p = o.position;
  5418. r = o.rotation;
  5419. q = o.quaternion;
  5420. s = o.scale;
  5421. // turn off quaternions, for the moment
  5422. q = 0;
  5423. object = new THREE.Object3D();
  5424. object.name = dd;
  5425. object.position.set( p[0], p[1], p[2] );
  5426. if ( q ) {
  5427. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5428. object.useQuaternion = true;
  5429. } else {
  5430. object.rotation.set( r[0], r[1], r[2] );
  5431. }
  5432. object.scale.set( s[0], s[1], s[2] );
  5433. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  5434. parent.add( object );
  5435. result.objects[ dd ] = object;
  5436. result.empties[ dd ] = object;
  5437. }
  5438. if ( object ) {
  5439. if ( o.properties !== undefined ) {
  5440. for ( var key in o.properties ) {
  5441. var value = o.properties[ key ];
  5442. object.properties[ key ] = value;
  5443. }
  5444. }
  5445. if ( o.children !== undefined ) {
  5446. handle_children( object, o.children );
  5447. }
  5448. }
  5449. }
  5450. }
  5451. };
  5452. function handle_mesh( geo, mat, id ) {
  5453. result.geometries[ id ] = geo;
  5454. result.face_materials[ id ] = mat;
  5455. handle_objects();
  5456. };
  5457. function handle_hierarchy( node, id, parent, material, o ) {
  5458. var p = o.position;
  5459. var r = o.rotation;
  5460. var q = o.quaternion;
  5461. var s = o.scale;
  5462. node.position.set( p[0], p[1], p[2] );
  5463. if ( q ) {
  5464. node.quaternion.set( q[0], q[1], q[2], q[3] );
  5465. node.useQuaternion = true;
  5466. } else {
  5467. node.rotation.set( r[0], r[1], r[2] );
  5468. }
  5469. node.scale.set( s[0], s[1], s[2] );
  5470. if ( material ) {
  5471. node.traverse( function ( child ) {
  5472. child.material = material;
  5473. } );
  5474. }
  5475. parent.add( node );
  5476. result.objects[ id ] = node;
  5477. handle_objects();
  5478. };
  5479. function create_callback_geometry( id ) {
  5480. return function( geo, mat ) {
  5481. handle_mesh( geo, mat, id );
  5482. counter_models -= 1;
  5483. scope.onLoadComplete();
  5484. async_callback_gate();
  5485. }
  5486. };
  5487. function create_callback_hierachy( id, parent, material, obj ) {
  5488. return function( event ) {
  5489. var result;
  5490. // loaders which use EventTarget
  5491. if ( event.content ) {
  5492. result = event.content;
  5493. // ColladaLoader
  5494. } else if ( event.dae ) {
  5495. result = event.scene;
  5496. // UTF8Loader
  5497. } else {
  5498. result = event;
  5499. }
  5500. handle_hierarchy( result, id, parent, material, obj );
  5501. counter_models -= 1;
  5502. scope.onLoadComplete();
  5503. async_callback_gate();
  5504. }
  5505. };
  5506. function create_callback_embed( id ) {
  5507. return function( geo, mat ) {
  5508. result.geometries[ id ] = geo;
  5509. result.face_materials[ id ] = mat;
  5510. }
  5511. };
  5512. function async_callback_gate() {
  5513. var progress = {
  5514. totalModels : total_models,
  5515. totalTextures : total_textures,
  5516. loadedModels : total_models - counter_models,
  5517. loadedTextures : total_textures - counter_textures
  5518. };
  5519. scope.callbackProgress( progress, result );
  5520. scope.onLoadProgress();
  5521. if ( counter_models === 0 && counter_textures === 0 ) {
  5522. finalize();
  5523. callbackFinished( result );
  5524. }
  5525. };
  5526. function finalize() {
  5527. // take care of targets which could be asynchronously loaded objects
  5528. for ( var i = 0; i < target_array.length; i ++ ) {
  5529. var ta = target_array[ i ];
  5530. var target = result.objects[ ta.targetName ];
  5531. if ( target ) {
  5532. ta.object.target = target;
  5533. } else {
  5534. // if there was error and target of specified name doesn't exist in the scene file
  5535. // create instead dummy target
  5536. // (target must be added to scene explicitly as parent is already added)
  5537. ta.object.target = new THREE.Object3D();
  5538. result.scene.add( ta.object.target );
  5539. }
  5540. ta.object.target.properties.targetInverse = ta.object;
  5541. }
  5542. };
  5543. var callbackTexture = function ( count ) {
  5544. counter_textures -= count;
  5545. async_callback_gate();
  5546. scope.onLoadComplete();
  5547. };
  5548. // must use this instead of just directly calling callbackTexture
  5549. // because of closure in the calling context loop
  5550. var generateTextureCallback = function ( count ) {
  5551. return function() {
  5552. callbackTexture( count );
  5553. };
  5554. };
  5555. // first go synchronous elements
  5556. // fogs
  5557. for ( df in data.fogs ) {
  5558. f = data.fogs[ df ];
  5559. if ( f.type === "linear" ) {
  5560. fog = new THREE.Fog( 0x000000, f.near, f.far );
  5561. } else if ( f.type === "exp2" ) {
  5562. fog = new THREE.FogExp2( 0x000000, f.density );
  5563. }
  5564. c = f.color;
  5565. fog.color.setRGB( c[0], c[1], c[2] );
  5566. result.fogs[ df ] = fog;
  5567. }
  5568. // now come potentially asynchronous elements
  5569. // geometries
  5570. // count how many geometries will be loaded asynchronously
  5571. for ( dg in data.geometries ) {
  5572. g = data.geometries[ dg ];
  5573. if ( g.type in this.geometryHandlerMap ) {
  5574. counter_models += 1;
  5575. scope.onLoadStart();
  5576. }
  5577. }
  5578. // count how many hierarchies will be loaded asynchronously
  5579. for ( var dd in data.objects ) {
  5580. var o = data.objects[ dd ];
  5581. if ( o.type && ( o.type in this.hierarchyHandlerMap ) ) {
  5582. counter_models += 1;
  5583. scope.onLoadStart();
  5584. }
  5585. }
  5586. total_models = counter_models;
  5587. for ( dg in data.geometries ) {
  5588. g = data.geometries[ dg ];
  5589. if ( g.type === "cube" ) {
  5590. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.widthSegments, g.heightSegments, g.depthSegments );
  5591. result.geometries[ dg ] = geometry;
  5592. } else if ( g.type === "plane" ) {
  5593. geometry = new THREE.PlaneGeometry( g.width, g.height, g.widthSegments, g.heightSegments );
  5594. result.geometries[ dg ] = geometry;
  5595. } else if ( g.type === "sphere" ) {
  5596. geometry = new THREE.SphereGeometry( g.radius, g.widthSegments, g.heightSegments );
  5597. result.geometries[ dg ] = geometry;
  5598. } else if ( g.type === "cylinder" ) {
  5599. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  5600. result.geometries[ dg ] = geometry;
  5601. } else if ( g.type === "torus" ) {
  5602. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  5603. result.geometries[ dg ] = geometry;
  5604. } else if ( g.type === "icosahedron" ) {
  5605. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  5606. result.geometries[ dg ] = geometry;
  5607. } else if ( g.type in this.geometryHandlerMap ) {
  5608. var loaderParameters = {};
  5609. for ( var parType in g ) {
  5610. if ( parType !== "type" && parType !== "url" ) {
  5611. loaderParameters[ parType ] = g[ parType ];
  5612. }
  5613. }
  5614. var loader = this.geometryHandlerMap[ g.type ][ "loaderObject" ];
  5615. loader.load( get_url( g.url, data.urlBaseType ), create_callback_geometry( dg ), loaderParameters );
  5616. } else if ( g.type === "embedded" ) {
  5617. var modelJson = data.embeds[ g.id ],
  5618. texture_path = "";
  5619. // pass metadata along to jsonLoader so it knows the format version
  5620. modelJson.metadata = data.metadata;
  5621. if ( modelJson ) {
  5622. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  5623. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  5624. }
  5625. }
  5626. }
  5627. // textures
  5628. // count how many textures will be loaded asynchronously
  5629. for ( dt in data.textures ) {
  5630. tt = data.textures[ dt ];
  5631. if ( tt.url instanceof Array ) {
  5632. counter_textures += tt.url.length;
  5633. for( var n = 0; n < tt.url.length; n ++ ) {
  5634. scope.onLoadStart();
  5635. }
  5636. } else {
  5637. counter_textures += 1;
  5638. scope.onLoadStart();
  5639. }
  5640. }
  5641. total_textures = counter_textures;
  5642. for ( dt in data.textures ) {
  5643. tt = data.textures[ dt ];
  5644. if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined ) {
  5645. tt.mapping = new THREE[ tt.mapping ]();
  5646. }
  5647. if ( tt.url instanceof Array ) {
  5648. var count = tt.url.length;
  5649. var url_array = [];
  5650. for( var i = 0; i < count; i ++ ) {
  5651. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  5652. }
  5653. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  5654. if ( isCompressed ) {
  5655. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5656. } else {
  5657. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5658. }
  5659. } else {
  5660. var isCompressed = tt.url.toLowerCase().endsWith( ".dds" );
  5661. var fullUrl = get_url( tt.url, data.urlBaseType );
  5662. var textureCallback = generateTextureCallback( 1 );
  5663. if ( isCompressed ) {
  5664. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, tt.mapping, textureCallback );
  5665. } else {
  5666. texture = THREE.ImageUtils.loadTexture( fullUrl, tt.mapping, textureCallback );
  5667. }
  5668. if ( THREE[ tt.minFilter ] !== undefined )
  5669. texture.minFilter = THREE[ tt.minFilter ];
  5670. if ( THREE[ tt.magFilter ] !== undefined )
  5671. texture.magFilter = THREE[ tt.magFilter ];
  5672. if ( tt.anisotropy ) texture.anisotropy = tt.anisotropy;
  5673. if ( tt.repeat ) {
  5674. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  5675. if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  5676. if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  5677. }
  5678. if ( tt.offset ) {
  5679. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  5680. }
  5681. // handle wrap after repeat so that default repeat can be overriden
  5682. if ( tt.wrap ) {
  5683. var wrapMap = {
  5684. "repeat" : THREE.RepeatWrapping,
  5685. "mirror" : THREE.MirroredRepeatWrapping
  5686. }
  5687. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  5688. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  5689. }
  5690. }
  5691. result.textures[ dt ] = texture;
  5692. }
  5693. // materials
  5694. for ( dm in data.materials ) {
  5695. m = data.materials[ dm ];
  5696. for ( pp in m.parameters ) {
  5697. if ( pp === "envMap" || pp === "map" || pp === "lightMap" || pp === "bumpMap" ) {
  5698. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  5699. } else if ( pp === "shading" ) {
  5700. m.parameters[ pp ] = ( m.parameters[ pp ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  5701. } else if ( pp === "side" ) {
  5702. if ( m.parameters[ pp ] == "double" ) {
  5703. m.parameters[ pp ] = THREE.DoubleSide;
  5704. } else if ( m.parameters[ pp ] == "back" ) {
  5705. m.parameters[ pp ] = THREE.BackSide;
  5706. } else {
  5707. m.parameters[ pp ] = THREE.FrontSide;
  5708. }
  5709. } else if ( pp === "blending" ) {
  5710. m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  5711. } else if ( pp === "combine" ) {
  5712. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  5713. } else if ( pp === "vertexColors" ) {
  5714. if ( m.parameters[ pp ] == "face" ) {
  5715. m.parameters[ pp ] = THREE.FaceColors;
  5716. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  5717. } else if ( m.parameters[ pp ] ) {
  5718. m.parameters[ pp ] = THREE.VertexColors;
  5719. }
  5720. } else if ( pp === "wrapRGB" ) {
  5721. var v3 = m.parameters[ pp ];
  5722. m.parameters[ pp ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  5723. }
  5724. }
  5725. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  5726. m.parameters.transparent = true;
  5727. }
  5728. if ( m.parameters.normalMap ) {
  5729. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5730. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5731. var diffuse = m.parameters.color;
  5732. var specular = m.parameters.specular;
  5733. var ambient = m.parameters.ambient;
  5734. var shininess = m.parameters.shininess;
  5735. uniforms[ "tNormal" ].value = result.textures[ m.parameters.normalMap ];
  5736. if ( m.parameters.normalScale ) {
  5737. uniforms[ "uNormalScale" ].value.set( m.parameters.normalScale[ 0 ], m.parameters.normalScale[ 1 ] );
  5738. }
  5739. if ( m.parameters.map ) {
  5740. uniforms[ "tDiffuse" ].value = m.parameters.map;
  5741. uniforms[ "enableDiffuse" ].value = true;
  5742. }
  5743. if ( m.parameters.envMap ) {
  5744. uniforms[ "tCube" ].value = m.parameters.envMap;
  5745. uniforms[ "enableReflection" ].value = true;
  5746. uniforms[ "uReflectivity" ].value = m.parameters.reflectivity;
  5747. }
  5748. if ( m.parameters.lightMap ) {
  5749. uniforms[ "tAO" ].value = m.parameters.lightMap;
  5750. uniforms[ "enableAO" ].value = true;
  5751. }
  5752. if ( m.parameters.specularMap ) {
  5753. uniforms[ "tSpecular" ].value = result.textures[ m.parameters.specularMap ];
  5754. uniforms[ "enableSpecular" ].value = true;
  5755. }
  5756. if ( m.parameters.displacementMap ) {
  5757. uniforms[ "tDisplacement" ].value = result.textures[ m.parameters.displacementMap ];
  5758. uniforms[ "enableDisplacement" ].value = true;
  5759. uniforms[ "uDisplacementBias" ].value = m.parameters.displacementBias;
  5760. uniforms[ "uDisplacementScale" ].value = m.parameters.displacementScale;
  5761. }
  5762. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  5763. uniforms[ "uSpecularColor" ].value.setHex( specular );
  5764. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  5765. uniforms[ "uShininess" ].value = shininess;
  5766. if ( m.parameters.opacity ) {
  5767. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  5768. }
  5769. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5770. material = new THREE.ShaderMaterial( parameters );
  5771. } else {
  5772. material = new THREE[ m.type ]( m.parameters );
  5773. }
  5774. result.materials[ dm ] = material;
  5775. }
  5776. // second pass through all materials to initialize MeshFaceMaterials
  5777. // that could be referring to other materials out of order
  5778. for ( dm in data.materials ) {
  5779. m = data.materials[ dm ];
  5780. if ( m.parameters.materials ) {
  5781. var materialArray = [];
  5782. for ( var i = 0; i < m.parameters.materials.length; i ++ ) {
  5783. var label = m.parameters.materials[ i ];
  5784. materialArray.push( result.materials[ label ] );
  5785. }
  5786. result.materials[ dm ].materials = materialArray;
  5787. }
  5788. }
  5789. // objects ( synchronous init of procedural primitives )
  5790. handle_objects();
  5791. // defaults
  5792. if ( result.cameras && data.defaults.camera ) {
  5793. result.currentCamera = result.cameras[ data.defaults.camera ];
  5794. }
  5795. if ( result.fogs && data.defaults.fog ) {
  5796. result.scene.fog = result.fogs[ data.defaults.fog ];
  5797. }
  5798. c = data.defaults.bgcolor;
  5799. result.bgColor = new THREE.Color();
  5800. result.bgColor.setRGB( c[0], c[1], c[2] );
  5801. result.bgColorAlpha = data.defaults.bgalpha;
  5802. // synchronous callback
  5803. scope.callbackSync( result );
  5804. // just in case there are no async elements
  5805. async_callback_gate();
  5806. };
  5807. /**
  5808. * @author mrdoob / http://mrdoob.com/
  5809. */
  5810. THREE.TextureLoader = function () {
  5811. THREE.EventTarget.call( this );
  5812. this.crossOrigin = null;
  5813. };
  5814. THREE.TextureLoader.prototype = {
  5815. constructor: THREE.TextureLoader,
  5816. load: function ( url ) {
  5817. var scope = this;
  5818. var image = new Image();
  5819. image.addEventListener( 'load', function () {
  5820. var texture = new THREE.Texture( image );
  5821. texture.needsUpdate = true;
  5822. scope.dispatchEvent( { type: 'load', content: texture } );
  5823. }, false );
  5824. image.addEventListener( 'error', function () {
  5825. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5826. }, false );
  5827. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5828. image.src = url;
  5829. }
  5830. }
  5831. /**
  5832. * @author mrdoob / http://mrdoob.com/
  5833. * @author alteredq / http://alteredqualia.com/
  5834. */
  5835. THREE.Material = function () {
  5836. THREE.MaterialLibrary.push( this );
  5837. this.id = THREE.MaterialIdCount ++;
  5838. this.name = '';
  5839. this.side = THREE.FrontSide;
  5840. this.opacity = 1;
  5841. this.transparent = false;
  5842. this.blending = THREE.NormalBlending;
  5843. this.blendSrc = THREE.SrcAlphaFactor;
  5844. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  5845. this.blendEquation = THREE.AddEquation;
  5846. this.depthTest = true;
  5847. this.depthWrite = true;
  5848. this.polygonOffset = false;
  5849. this.polygonOffsetFactor = 0;
  5850. this.polygonOffsetUnits = 0;
  5851. this.alphaTest = 0;
  5852. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  5853. this.visible = true;
  5854. this.needsUpdate = true;
  5855. };
  5856. THREE.Material.prototype.setValues = function ( values ) {
  5857. if ( values === undefined ) return;
  5858. for ( var key in values ) {
  5859. var newValue = values[ key ];
  5860. if ( newValue === undefined ) {
  5861. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5862. continue;
  5863. }
  5864. if ( key in this ) {
  5865. var currentValue = this[ key ];
  5866. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  5867. currentValue.copy( newValue );
  5868. } else if ( currentValue instanceof THREE.Color && typeof( newValue ) === "number" ) {
  5869. currentValue.setHex( newValue );
  5870. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  5871. currentValue.copy( newValue );
  5872. } else {
  5873. this[ key ] = newValue;
  5874. }
  5875. }
  5876. }
  5877. };
  5878. THREE.Material.prototype.clone = function ( material ) {
  5879. if ( material === undefined ) material = new THREE.Material();
  5880. material.name = this.name;
  5881. material.side = this.side;
  5882. material.opacity = this.opacity;
  5883. material.transparent = this.transparent;
  5884. material.blending = this.blending;
  5885. material.blendSrc = this.blendSrc;
  5886. material.blendDst = this.blendDst;
  5887. material.blendEquation = this.blendEquation;
  5888. material.depthTest = this.depthTest;
  5889. material.depthWrite = this.depthWrite;
  5890. material.polygonOffset = this.polygonOffset;
  5891. material.polygonOffsetFactor = this.polygonOffsetFactor;
  5892. material.polygonOffsetUnits = this.polygonOffsetUnits;
  5893. material.alphaTest = this.alphaTest;
  5894. material.overdraw = this.overdraw;
  5895. material.visible = this.visible;
  5896. return material;
  5897. };
  5898. THREE.Material.prototype.deallocate = function () {
  5899. var index = THREE.MaterialLibrary.indexOf( this );
  5900. if ( index !== -1 ) THREE.MaterialLibrary.splice( index, 1 );
  5901. };
  5902. THREE.MaterialIdCount = 0;
  5903. THREE.MaterialLibrary = [];
  5904. /**
  5905. * @author mrdoob / http://mrdoob.com/
  5906. * @author alteredq / http://alteredqualia.com/
  5907. *
  5908. * parameters = {
  5909. * color: <hex>,
  5910. * opacity: <float>,
  5911. *
  5912. * blending: THREE.NormalBlending,
  5913. * depthTest: <bool>,
  5914. * depthWrite: <bool>,
  5915. *
  5916. * linewidth: <float>,
  5917. * linecap: "round",
  5918. * linejoin: "round",
  5919. *
  5920. * vertexColors: <bool>
  5921. *
  5922. * fog: <bool>
  5923. * }
  5924. */
  5925. THREE.LineBasicMaterial = function ( parameters ) {
  5926. THREE.Material.call( this );
  5927. this.color = new THREE.Color( 0xffffff );
  5928. this.linewidth = 1;
  5929. this.linecap = 'round';
  5930. this.linejoin = 'round';
  5931. this.vertexColors = false;
  5932. this.fog = true;
  5933. this.setValues( parameters );
  5934. };
  5935. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  5936. THREE.LineBasicMaterial.prototype.clone = function () {
  5937. var material = new THREE.LineBasicMaterial();
  5938. THREE.Material.prototype.clone.call( this, material );
  5939. material.color.copy( this.color );
  5940. material.linewidth = this.linewidth;
  5941. material.linecap = this.linecap;
  5942. material.linejoin = this.linejoin;
  5943. material.vertexColors = this.vertexColors;
  5944. material.fog = this.fog;
  5945. return material;
  5946. };
  5947. /**
  5948. * @author alteredq / http://alteredqualia.com/
  5949. *
  5950. * parameters = {
  5951. * color: <hex>,
  5952. * opacity: <float>,
  5953. *
  5954. * blending: THREE.NormalBlending,
  5955. * depthTest: <bool>,
  5956. * depthWrite: <bool>,
  5957. *
  5958. * linewidth: <float>,
  5959. *
  5960. * scale: <float>,
  5961. * dashSize: <float>,
  5962. * gapSize: <float>,
  5963. *
  5964. * vertexColors: <bool>
  5965. *
  5966. * fog: <bool>
  5967. * }
  5968. */
  5969. THREE.LineDashedMaterial = function ( parameters ) {
  5970. THREE.Material.call( this );
  5971. this.color = new THREE.Color( 0xffffff );
  5972. this.linewidth = 1;
  5973. this.scale = 1;
  5974. this.dashSize = 3;
  5975. this.gapSize = 1;
  5976. this.vertexColors = false;
  5977. this.fog = true;
  5978. this.setValues( parameters );
  5979. };
  5980. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  5981. THREE.LineDashedMaterial.prototype.clone = function () {
  5982. var material = new THREE.LineDashedMaterial();
  5983. THREE.Material.prototype.clone.call( this, material );
  5984. material.color.copy( this.color );
  5985. material.linewidth = this.linewidth;
  5986. material.scale = this.scale;
  5987. material.dashSize = this.dashSize;
  5988. material.gapSize = this.gapSize;
  5989. material.vertexColors = this.vertexColors;
  5990. material.fog = this.fog;
  5991. return material;
  5992. };
  5993. /**
  5994. * @author mrdoob / http://mrdoob.com/
  5995. * @author alteredq / http://alteredqualia.com/
  5996. *
  5997. * parameters = {
  5998. * color: <hex>,
  5999. * opacity: <float>,
  6000. * map: new THREE.Texture( <Image> ),
  6001. *
  6002. * lightMap: new THREE.Texture( <Image> ),
  6003. *
  6004. * specularMap: new THREE.Texture( <Image> ),
  6005. *
  6006. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6007. * combine: THREE.Multiply,
  6008. * reflectivity: <float>,
  6009. * refractionRatio: <float>,
  6010. *
  6011. * shading: THREE.SmoothShading,
  6012. * blending: THREE.NormalBlending,
  6013. * depthTest: <bool>,
  6014. * depthWrite: <bool>,
  6015. *
  6016. * wireframe: <boolean>,
  6017. * wireframeLinewidth: <float>,
  6018. *
  6019. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6020. *
  6021. * skinning: <bool>,
  6022. * morphTargets: <bool>,
  6023. *
  6024. * fog: <bool>
  6025. * }
  6026. */
  6027. THREE.MeshBasicMaterial = function ( parameters ) {
  6028. THREE.Material.call( this );
  6029. this.color = new THREE.Color( 0xffffff ); // emissive
  6030. this.map = null;
  6031. this.lightMap = null;
  6032. this.specularMap = null;
  6033. this.envMap = null;
  6034. this.combine = THREE.MultiplyOperation;
  6035. this.reflectivity = 1;
  6036. this.refractionRatio = 0.98;
  6037. this.fog = true;
  6038. this.shading = THREE.SmoothShading;
  6039. this.wireframe = false;
  6040. this.wireframeLinewidth = 1;
  6041. this.wireframeLinecap = 'round';
  6042. this.wireframeLinejoin = 'round';
  6043. this.vertexColors = THREE.NoColors;
  6044. this.skinning = false;
  6045. this.morphTargets = false;
  6046. this.setValues( parameters );
  6047. };
  6048. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6049. THREE.MeshBasicMaterial.prototype.clone = function () {
  6050. var material = new THREE.MeshBasicMaterial();
  6051. THREE.Material.prototype.clone.call( this, material );
  6052. material.color.copy( this.color );
  6053. material.map = this.map;
  6054. material.lightMap = this.lightMap;
  6055. material.specularMap = this.specularMap;
  6056. material.envMap = this.envMap;
  6057. material.combine = this.combine;
  6058. material.reflectivity = this.reflectivity;
  6059. material.refractionRatio = this.refractionRatio;
  6060. material.fog = this.fog;
  6061. material.shading = this.shading;
  6062. material.wireframe = this.wireframe;
  6063. material.wireframeLinewidth = this.wireframeLinewidth;
  6064. material.wireframeLinecap = this.wireframeLinecap;
  6065. material.wireframeLinejoin = this.wireframeLinejoin;
  6066. material.vertexColors = this.vertexColors;
  6067. material.skinning = this.skinning;
  6068. material.morphTargets = this.morphTargets;
  6069. return material;
  6070. };
  6071. /**
  6072. * @author mrdoob / http://mrdoob.com/
  6073. * @author alteredq / http://alteredqualia.com/
  6074. *
  6075. * parameters = {
  6076. * color: <hex>,
  6077. * ambient: <hex>,
  6078. * emissive: <hex>,
  6079. * opacity: <float>,
  6080. *
  6081. * map: new THREE.Texture( <Image> ),
  6082. *
  6083. * lightMap: new THREE.Texture( <Image> ),
  6084. *
  6085. * specularMap: new THREE.Texture( <Image> ),
  6086. *
  6087. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6088. * combine: THREE.Multiply,
  6089. * reflectivity: <float>,
  6090. * refractionRatio: <float>,
  6091. *
  6092. * shading: THREE.SmoothShading,
  6093. * blending: THREE.NormalBlending,
  6094. * depthTest: <bool>,
  6095. * depthWrite: <bool>,
  6096. *
  6097. * wireframe: <boolean>,
  6098. * wireframeLinewidth: <float>,
  6099. *
  6100. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6101. *
  6102. * skinning: <bool>,
  6103. * morphTargets: <bool>,
  6104. * morphNormals: <bool>,
  6105. *
  6106. * fog: <bool>
  6107. * }
  6108. */
  6109. THREE.MeshLambertMaterial = function ( parameters ) {
  6110. THREE.Material.call( this );
  6111. this.color = new THREE.Color( 0xffffff ); // diffuse
  6112. this.ambient = new THREE.Color( 0xffffff );
  6113. this.emissive = new THREE.Color( 0x000000 );
  6114. this.wrapAround = false;
  6115. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6116. this.map = null;
  6117. this.lightMap = null;
  6118. this.specularMap = null;
  6119. this.envMap = null;
  6120. this.combine = THREE.MultiplyOperation;
  6121. this.reflectivity = 1;
  6122. this.refractionRatio = 0.98;
  6123. this.fog = true;
  6124. this.shading = THREE.SmoothShading;
  6125. this.wireframe = false;
  6126. this.wireframeLinewidth = 1;
  6127. this.wireframeLinecap = 'round';
  6128. this.wireframeLinejoin = 'round';
  6129. this.vertexColors = THREE.NoColors;
  6130. this.skinning = false;
  6131. this.morphTargets = false;
  6132. this.morphNormals = false;
  6133. this.setValues( parameters );
  6134. };
  6135. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6136. THREE.MeshLambertMaterial.prototype.clone = function () {
  6137. var material = new THREE.MeshLambertMaterial();
  6138. THREE.Material.prototype.clone.call( this, material );
  6139. material.color.copy( this.color );
  6140. material.ambient.copy( this.ambient );
  6141. material.emissive.copy( this.emissive );
  6142. material.wrapAround = this.wrapAround;
  6143. material.wrapRGB.copy( this.wrapRGB );
  6144. material.map = this.map;
  6145. material.lightMap = this.lightMap;
  6146. material.specularMap = this.specularMap;
  6147. material.envMap = this.envMap;
  6148. material.combine = this.combine;
  6149. material.reflectivity = this.reflectivity;
  6150. material.refractionRatio = this.refractionRatio;
  6151. material.fog = this.fog;
  6152. material.shading = this.shading;
  6153. material.wireframe = this.wireframe;
  6154. material.wireframeLinewidth = this.wireframeLinewidth;
  6155. material.wireframeLinecap = this.wireframeLinecap;
  6156. material.wireframeLinejoin = this.wireframeLinejoin;
  6157. material.vertexColors = this.vertexColors;
  6158. material.skinning = this.skinning;
  6159. material.morphTargets = this.morphTargets;
  6160. material.morphNormals = this.morphNormals;
  6161. return material;
  6162. };
  6163. /**
  6164. * @author mrdoob / http://mrdoob.com/
  6165. * @author alteredq / http://alteredqualia.com/
  6166. *
  6167. * parameters = {
  6168. * color: <hex>,
  6169. * ambient: <hex>,
  6170. * emissive: <hex>,
  6171. * specular: <hex>,
  6172. * shininess: <float>,
  6173. * opacity: <float>,
  6174. *
  6175. * map: new THREE.Texture( <Image> ),
  6176. *
  6177. * lightMap: new THREE.Texture( <Image> ),
  6178. *
  6179. * bumpMap: new THREE.Texture( <Image> ),
  6180. * bumpScale: <float>,
  6181. *
  6182. * normalMap: new THREE.Texture( <Image> ),
  6183. * normalScale: <Vector2>,
  6184. *
  6185. * specularMap: new THREE.Texture( <Image> ),
  6186. *
  6187. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6188. * combine: THREE.Multiply,
  6189. * reflectivity: <float>,
  6190. * refractionRatio: <float>,
  6191. *
  6192. * shading: THREE.SmoothShading,
  6193. * blending: THREE.NormalBlending,
  6194. * depthTest: <bool>,
  6195. * depthWrite: <bool>,
  6196. *
  6197. * wireframe: <boolean>,
  6198. * wireframeLinewidth: <float>,
  6199. *
  6200. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6201. *
  6202. * skinning: <bool>,
  6203. * morphTargets: <bool>,
  6204. * morphNormals: <bool>,
  6205. *
  6206. * fog: <bool>
  6207. * }
  6208. */
  6209. THREE.MeshPhongMaterial = function ( parameters ) {
  6210. THREE.Material.call( this );
  6211. this.color = new THREE.Color( 0xffffff ); // diffuse
  6212. this.ambient = new THREE.Color( 0xffffff );
  6213. this.emissive = new THREE.Color( 0x000000 );
  6214. this.specular = new THREE.Color( 0x111111 );
  6215. this.shininess = 30;
  6216. this.metal = false;
  6217. this.perPixel = true;
  6218. this.wrapAround = false;
  6219. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6220. this.map = null;
  6221. this.lightMap = null;
  6222. this.bumpMap = null;
  6223. this.bumpScale = 1;
  6224. this.normalMap = null;
  6225. this.normalScale = new THREE.Vector2( 1, 1 );
  6226. this.specularMap = null;
  6227. this.envMap = null;
  6228. this.combine = THREE.MultiplyOperation;
  6229. this.reflectivity = 1;
  6230. this.refractionRatio = 0.98;
  6231. this.fog = true;
  6232. this.shading = THREE.SmoothShading;
  6233. this.wireframe = false;
  6234. this.wireframeLinewidth = 1;
  6235. this.wireframeLinecap = 'round';
  6236. this.wireframeLinejoin = 'round';
  6237. this.vertexColors = THREE.NoColors;
  6238. this.skinning = false;
  6239. this.morphTargets = false;
  6240. this.morphNormals = false;
  6241. this.setValues( parameters );
  6242. };
  6243. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6244. THREE.MeshPhongMaterial.prototype.clone = function () {
  6245. var material = new THREE.MeshPhongMaterial();
  6246. THREE.Material.prototype.clone.call( this, material );
  6247. material.color.copy( this.color );
  6248. material.ambient.copy( this.ambient );
  6249. material.emissive.copy( this.emissive );
  6250. material.specular.copy( this.specular );
  6251. material.shininess = this.shininess;
  6252. material.metal = this.metal;
  6253. material.perPixel = this.perPixel;
  6254. material.wrapAround = this.wrapAround;
  6255. material.wrapRGB.copy( this.wrapRGB );
  6256. material.map = this.map;
  6257. material.lightMap = this.lightMap;
  6258. material.bumpMap = this.bumpMap;
  6259. material.bumpScale = this.bumpScale;
  6260. material.normalMap = this.normalMap;
  6261. material.normalScale.copy( this.normalScale );
  6262. material.specularMap = this.specularMap;
  6263. material.envMap = this.envMap;
  6264. material.combine = this.combine;
  6265. material.reflectivity = this.reflectivity;
  6266. material.refractionRatio = this.refractionRatio;
  6267. material.fog = this.fog;
  6268. material.shading = this.shading;
  6269. material.wireframe = this.wireframe;
  6270. material.wireframeLinewidth = this.wireframeLinewidth;
  6271. material.wireframeLinecap = this.wireframeLinecap;
  6272. material.wireframeLinejoin = this.wireframeLinejoin;
  6273. material.vertexColors = this.vertexColors;
  6274. material.skinning = this.skinning;
  6275. material.morphTargets = this.morphTargets;
  6276. material.morphNormals = this.morphNormals;
  6277. return material;
  6278. };
  6279. /**
  6280. * @author mrdoob / http://mrdoob.com/
  6281. * @author alteredq / http://alteredqualia.com/
  6282. *
  6283. * parameters = {
  6284. * opacity: <float>,
  6285. *
  6286. * blending: THREE.NormalBlending,
  6287. * depthTest: <bool>,
  6288. * depthWrite: <bool>,
  6289. *
  6290. * wireframe: <boolean>,
  6291. * wireframeLinewidth: <float>
  6292. * }
  6293. */
  6294. THREE.MeshDepthMaterial = function ( parameters ) {
  6295. THREE.Material.call( this );
  6296. this.wireframe = false;
  6297. this.wireframeLinewidth = 1;
  6298. this.setValues( parameters );
  6299. };
  6300. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6301. THREE.MeshDepthMaterial.prototype.clone = function () {
  6302. var material = new THREE.LineBasicMaterial();
  6303. THREE.Material.prototype.clone.call( this, material );
  6304. material.wireframe = this.wireframe;
  6305. material.wireframeLinewidth = this.wireframeLinewidth;
  6306. return material;
  6307. };
  6308. /**
  6309. * @author mrdoob / http://mrdoob.com/
  6310. *
  6311. * parameters = {
  6312. * opacity: <float>,
  6313. *
  6314. * shading: THREE.FlatShading,
  6315. * blending: THREE.NormalBlending,
  6316. * depthTest: <bool>,
  6317. * depthWrite: <bool>,
  6318. *
  6319. * wireframe: <boolean>,
  6320. * wireframeLinewidth: <float>
  6321. * }
  6322. */
  6323. THREE.MeshNormalMaterial = function ( parameters ) {
  6324. THREE.Material.call( this, parameters );
  6325. this.shading = THREE.FlatShading;
  6326. this.wireframe = false;
  6327. this.wireframeLinewidth = 1;
  6328. this.setValues( parameters );
  6329. };
  6330. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6331. THREE.MeshNormalMaterial.prototype.clone = function () {
  6332. var material = new THREE.MeshNormalMaterial();
  6333. THREE.Material.prototype.clone.call( this, material );
  6334. material.shading = this.shading;
  6335. material.wireframe = this.wireframe;
  6336. material.wireframeLinewidth = this.wireframeLinewidth;
  6337. return material;
  6338. };
  6339. /**
  6340. * @author mrdoob / http://mrdoob.com/
  6341. */
  6342. THREE.MeshFaceMaterial = function ( materials ) {
  6343. this.materials = materials instanceof Array ? materials : [];
  6344. };
  6345. THREE.MeshFaceMaterial.prototype.clone = function () {
  6346. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  6347. };
  6348. /**
  6349. * @author mrdoob / http://mrdoob.com/
  6350. * @author alteredq / http://alteredqualia.com/
  6351. *
  6352. * parameters = {
  6353. * color: <hex>,
  6354. * opacity: <float>,
  6355. * map: new THREE.Texture( <Image> ),
  6356. *
  6357. * size: <float>,
  6358. *
  6359. * blending: THREE.NormalBlending,
  6360. * depthTest: <bool>,
  6361. * depthWrite: <bool>,
  6362. *
  6363. * vertexColors: <bool>,
  6364. *
  6365. * fog: <bool>
  6366. * }
  6367. */
  6368. THREE.ParticleBasicMaterial = function ( parameters ) {
  6369. THREE.Material.call( this );
  6370. this.color = new THREE.Color( 0xffffff );
  6371. this.map = null;
  6372. this.size = 1;
  6373. this.sizeAttenuation = true;
  6374. this.vertexColors = false;
  6375. this.fog = true;
  6376. this.setValues( parameters );
  6377. };
  6378. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6379. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6380. var material = new THREE.ParticleBasicMaterial();
  6381. THREE.Material.prototype.clone.call( this, material );
  6382. material.color.copy( this.color );
  6383. material.map = this.map;
  6384. material.size = this.size;
  6385. material.sizeAttenuation = this.sizeAttenuation;
  6386. material.vertexColors = this.vertexColors;
  6387. material.fog = this.fog;
  6388. return material;
  6389. };
  6390. /**
  6391. * @author mrdoob / http://mrdoob.com/
  6392. *
  6393. * parameters = {
  6394. * color: <hex>,
  6395. * program: <function>,
  6396. * opacity: <float>,
  6397. * blending: THREE.NormalBlending
  6398. * }
  6399. */
  6400. THREE.ParticleCanvasMaterial = function ( parameters ) {
  6401. THREE.Material.call( this );
  6402. this.color = new THREE.Color( 0xffffff );
  6403. this.program = function ( context, color ) {};
  6404. this.setValues( parameters );
  6405. };
  6406. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  6407. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  6408. var material = new THREE.ParticleCanvasMaterial();
  6409. THREE.Material.prototype.clone.call( this, material );
  6410. material.color.copy( this.color );
  6411. material.program = this.program;
  6412. return material;
  6413. };
  6414. /**
  6415. * @author mrdoob / http://mrdoob.com/
  6416. */
  6417. THREE.ParticleDOMMaterial = function ( element ) {
  6418. this.element = element;
  6419. };
  6420. THREE.ParticleDOMMaterial.prototype.clone = function(){
  6421. return new THREE.ParticleDOMMaterial( this.element );
  6422. };
  6423. /**
  6424. * @author alteredq / http://alteredqualia.com/
  6425. *
  6426. * parameters = {
  6427. * fragmentShader: <string>,
  6428. * vertexShader: <string>,
  6429. *
  6430. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  6431. *
  6432. * defines: { "label" : "value" },
  6433. *
  6434. * shading: THREE.SmoothShading,
  6435. * blending: THREE.NormalBlending,
  6436. * depthTest: <bool>,
  6437. * depthWrite: <bool>,
  6438. *
  6439. * wireframe: <boolean>,
  6440. * wireframeLinewidth: <float>,
  6441. *
  6442. * lights: <bool>,
  6443. *
  6444. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6445. *
  6446. * skinning: <bool>,
  6447. * morphTargets: <bool>,
  6448. * morphNormals: <bool>,
  6449. *
  6450. * fog: <bool>
  6451. * }
  6452. */
  6453. THREE.ShaderMaterial = function ( parameters ) {
  6454. THREE.Material.call( this );
  6455. this.fragmentShader = "void main() {}";
  6456. this.vertexShader = "void main() {}";
  6457. this.uniforms = {};
  6458. this.defines = {};
  6459. this.attributes = null;
  6460. this.shading = THREE.SmoothShading;
  6461. this.wireframe = false;
  6462. this.wireframeLinewidth = 1;
  6463. this.fog = false; // set to use scene fog
  6464. this.lights = false; // set to use scene lights
  6465. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  6466. this.skinning = false; // set to use skinning attribute streams
  6467. this.morphTargets = false; // set to use morph targets
  6468. this.morphNormals = false; // set to use morph normals
  6469. this.setValues( parameters );
  6470. };
  6471. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  6472. THREE.ShaderMaterial.prototype.clone = function () {
  6473. var material = new THREE.ShaderMaterial();
  6474. THREE.Material.prototype.clone.call( this, material );
  6475. material.fragmentShader = this.fragmentShader;
  6476. material.vertexShader = this.vertexShader;
  6477. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  6478. material.attributes = this.attributes;
  6479. material.defines = this.defines;
  6480. material.shading = this.shading;
  6481. material.wireframe = this.wireframe;
  6482. material.wireframeLinewidth = this.wireframeLinewidth;
  6483. material.fog = this.fog;
  6484. material.lights = this.lights;
  6485. material.vertexColors = this.vertexColors;
  6486. material.skinning = this.skinning;
  6487. material.morphTargets = this.morphTargets;
  6488. material.morphNormals = this.morphNormals;
  6489. return material;
  6490. };
  6491. /**
  6492. * @author alteredq / http://alteredqualia.com/
  6493. *
  6494. * parameters = {
  6495. * color: <hex>,
  6496. * opacity: <float>,
  6497. * map: new THREE.Texture( <Image> ),
  6498. *
  6499. * blending: THREE.NormalBlending,
  6500. * depthTest: <bool>,
  6501. * depthWrite: <bool>,
  6502. *
  6503. * useScreenCoordinates: <bool>,
  6504. * sizeAttenuation: <bool>,
  6505. * scaleByViewport: <bool>,
  6506. * alignment: THREE.SpriteAlignment.center,
  6507. *
  6508. * uvOffset: new THREE.Vector2(),
  6509. * uvScale: new THREE.Vector2(),
  6510. *
  6511. * fog: <bool>
  6512. * }
  6513. */
  6514. THREE.SpriteMaterial = function ( parameters ) {
  6515. THREE.Material.call( this );
  6516. // defaults
  6517. this.color = new THREE.Color( 0xffffff );
  6518. this.map = new THREE.Texture();
  6519. this.useScreenCoordinates = true;
  6520. this.depthTest = !this.useScreenCoordinates;
  6521. this.sizeAttenuation = !this.useScreenCoordinates;
  6522. this.scaleByViewport = !this.sizeAttenuation;
  6523. this.alignment = THREE.SpriteAlignment.center.clone();
  6524. this.fog = false;
  6525. this.uvOffset = new THREE.Vector2( 0, 0 );
  6526. this.uvScale = new THREE.Vector2( 1, 1 );
  6527. // set parameters
  6528. this.setValues( parameters );
  6529. // override coupled defaults if not specified explicitly by parameters
  6530. parameters = parameters || {};
  6531. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  6532. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  6533. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  6534. };
  6535. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  6536. THREE.SpriteMaterial.prototype.clone = function () {
  6537. var material = new THREE.SpriteMaterial();
  6538. THREE.Material.prototype.clone.call( this, material );
  6539. material.color.copy( this.color );
  6540. material.map = this.map;
  6541. material.useScreenCoordinates = this.useScreenCoordinates;
  6542. material.sizeAttenuation = this.sizeAttenuation;
  6543. material.scaleByViewport = this.scaleByViewport;
  6544. material.alignment.copy( this.alignment );
  6545. material.uvOffset.copy( this.uvOffset );
  6546. material.uvScale.copy( this.uvScale );
  6547. material.fog = this.fog;
  6548. return material;
  6549. };
  6550. // Alignment enums
  6551. THREE.SpriteAlignment = {};
  6552. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  6553. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  6554. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  6555. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  6556. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  6557. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  6558. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  6559. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  6560. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  6561. /**
  6562. * @author mrdoob / http://mrdoob.com/
  6563. * @author alteredq / http://alteredqualia.com/
  6564. * @author szimek / https://github.com/szimek/
  6565. */
  6566. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  6567. THREE.TextureLibrary.push( this );
  6568. this.id = THREE.TextureIdCount ++;
  6569. this.name = '';
  6570. this.image = image;
  6571. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  6572. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  6573. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  6574. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  6575. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  6576. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6577. this.format = format !== undefined ? format : THREE.RGBAFormat;
  6578. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  6579. this.offset = new THREE.Vector2( 0, 0 );
  6580. this.repeat = new THREE.Vector2( 1, 1 );
  6581. this.generateMipmaps = true;
  6582. this.premultiplyAlpha = false;
  6583. this.flipY = true;
  6584. this.needsUpdate = false;
  6585. this.onUpdate = null;
  6586. };
  6587. THREE.Texture.prototype = {
  6588. constructor: THREE.Texture,
  6589. clone: function () {
  6590. var texture = new THREE.Texture();
  6591. texture.image = this.image;
  6592. texture.mapping = this.mapping;
  6593. texture.wrapS = this.wrapS;
  6594. texture.wrapT = this.wrapT;
  6595. texture.magFilter = this.magFilter;
  6596. texture.minFilter = this.minFilter;
  6597. texture.anisotropy = this.anisotropy;
  6598. texture.format = this.format;
  6599. texture.type = this.type;
  6600. texture.offset.copy( this.offset );
  6601. texture.repeat.copy( this.repeat );
  6602. texture.generateMipmaps = this.generateMipmaps;
  6603. texture.premultiplyAlpha = this.premultiplyAlpha;
  6604. texture.flipY = this.flipY;
  6605. return texture;
  6606. },
  6607. deallocate: function () {
  6608. var index = THREE.TextureLibrary.indexOf( this );
  6609. if ( index !== -1 ) THREE.TextureLibrary.splice( index, 1 );
  6610. }
  6611. };
  6612. THREE.TextureIdCount = 0;
  6613. THREE.TextureLibrary = [];
  6614. /**
  6615. * @author alteredq / http://alteredqualia.com/
  6616. */
  6617. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6618. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6619. this.image = { width: width, height: height };
  6620. this.mipmaps = mipmaps;
  6621. };
  6622. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  6623. THREE.CompressedTexture.prototype.clone = function () {
  6624. var texture = new THREE.CompressedTexture();
  6625. texture.image = this.image;
  6626. texture.mipmaps = this.mipmaps;
  6627. texture.format = this.format;
  6628. texture.type = this.type;
  6629. texture.mapping = this.mapping;
  6630. texture.wrapS = this.wrapS;
  6631. texture.wrapT = this.wrapT;
  6632. texture.magFilter = this.magFilter;
  6633. texture.minFilter = this.minFilter;
  6634. texture.anisotropy = this.anisotropy;
  6635. texture.offset.copy( this.offset );
  6636. texture.repeat.copy( this.repeat );
  6637. return texture;
  6638. };
  6639. /**
  6640. * @author alteredq / http://alteredqualia.com/
  6641. */
  6642. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6643. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6644. this.image = { data: data, width: width, height: height };
  6645. };
  6646. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  6647. THREE.DataTexture.prototype.clone = function () {
  6648. 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 );
  6649. clonedTexture.offset.copy( this.offset );
  6650. clonedTexture.repeat.copy( this.repeat );
  6651. return clonedTexture;
  6652. };
  6653. /**
  6654. * @author mrdoob / http://mrdoob.com/
  6655. */
  6656. THREE.Particle = function ( material ) {
  6657. THREE.Object3D.call( this );
  6658. this.material = material;
  6659. };
  6660. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  6661. THREE.Particle.prototype.clone = function ( object ) {
  6662. if ( object === undefined ) object = new THREE.Particle( this.material );
  6663. THREE.Object3D.prototype.clone.call( this, object );
  6664. return object;
  6665. };
  6666. /**
  6667. * @author alteredq / http://alteredqualia.com/
  6668. */
  6669. THREE.ParticleSystem = function ( geometry, material ) {
  6670. THREE.Object3D.call( this );
  6671. this.geometry = geometry;
  6672. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  6673. this.sortParticles = false;
  6674. if ( this.geometry ) {
  6675. // calc bound radius
  6676. if( this.geometry.boundingSphere === null ) {
  6677. this.geometry.computeBoundingSphere();
  6678. }
  6679. this.boundRadius = geometry.boundingSphere.radius;
  6680. }
  6681. this.frustumCulled = false;
  6682. };
  6683. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  6684. THREE.ParticleSystem.prototype.clone = function ( object ) {
  6685. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  6686. object.sortParticles = this.sortParticles;
  6687. THREE.Object3D.prototype.clone.call( this, object );
  6688. return object;
  6689. };
  6690. /**
  6691. * @author mrdoob / http://mrdoob.com/
  6692. */
  6693. THREE.Line = function ( geometry, material, type ) {
  6694. THREE.Object3D.call( this );
  6695. this.geometry = geometry;
  6696. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6697. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  6698. if ( this.geometry ) {
  6699. if ( ! this.geometry.boundingSphere ) {
  6700. this.geometry.computeBoundingSphere();
  6701. }
  6702. }
  6703. };
  6704. THREE.LineStrip = 0;
  6705. THREE.LinePieces = 1;
  6706. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  6707. THREE.Line.prototype.clone = function ( object ) {
  6708. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  6709. THREE.Object3D.prototype.clone.call( this, object );
  6710. return object;
  6711. };
  6712. /**
  6713. * @author mrdoob / http://mrdoob.com/
  6714. * @author alteredq / http://alteredqualia.com/
  6715. * @author mikael emtinger / http://gomo.se/
  6716. */
  6717. THREE.Mesh = function ( geometry, material ) {
  6718. THREE.Object3D.call( this );
  6719. this.geometry = geometry;
  6720. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  6721. if ( this.geometry ) {
  6722. // calc bound radius
  6723. if ( this.geometry.boundingSphere === null ) {
  6724. this.geometry.computeBoundingSphere();
  6725. }
  6726. this.boundRadius = geometry.boundingSphere.radius;
  6727. // setup morph targets
  6728. if ( this.geometry.morphTargets.length ) {
  6729. this.morphTargetBase = -1;
  6730. this.morphTargetForcedOrder = [];
  6731. this.morphTargetInfluences = [];
  6732. this.morphTargetDictionary = {};
  6733. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  6734. this.morphTargetInfluences.push( 0 );
  6735. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  6736. }
  6737. }
  6738. }
  6739. }
  6740. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  6741. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  6742. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  6743. return this.morphTargetDictionary[ name ];
  6744. }
  6745. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  6746. return 0;
  6747. };
  6748. THREE.Mesh.prototype.clone = function ( object ) {
  6749. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  6750. THREE.Object3D.prototype.clone.call( this, object );
  6751. return object;
  6752. };
  6753. /**
  6754. * @author mikael emtinger / http://gomo.se/
  6755. * @author alteredq / http://alteredqualia.com/
  6756. */
  6757. THREE.Bone = function( belongsToSkin ) {
  6758. THREE.Object3D.call( this );
  6759. this.skin = belongsToSkin;
  6760. this.skinMatrix = new THREE.Matrix4();
  6761. };
  6762. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  6763. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  6764. // update local
  6765. if ( this.matrixAutoUpdate ) {
  6766. forceUpdate |= this.updateMatrix();
  6767. }
  6768. // update skin matrix
  6769. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  6770. if( parentSkinMatrix ) {
  6771. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  6772. } else {
  6773. this.skinMatrix.copy( this.matrix );
  6774. }
  6775. this.matrixWorldNeedsUpdate = false;
  6776. forceUpdate = true;
  6777. }
  6778. // update children
  6779. var child, i, l = this.children.length;
  6780. for ( i = 0; i < l; i ++ ) {
  6781. this.children[ i ].update( this.skinMatrix, forceUpdate );
  6782. }
  6783. };
  6784. /**
  6785. * @author mikael emtinger / http://gomo.se/
  6786. * @author alteredq / http://alteredqualia.com/
  6787. */
  6788. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  6789. THREE.Mesh.call( this, geometry, material );
  6790. //
  6791. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  6792. // init bones
  6793. this.identityMatrix = new THREE.Matrix4();
  6794. this.bones = [];
  6795. this.boneMatrices = [];
  6796. var b, bone, gbone, p, q, s;
  6797. if ( this.geometry && this.geometry.bones !== undefined ) {
  6798. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  6799. gbone = this.geometry.bones[ b ];
  6800. p = gbone.pos;
  6801. q = gbone.rotq;
  6802. s = gbone.scl;
  6803. bone = this.addBone();
  6804. bone.name = gbone.name;
  6805. bone.position.set( p[0], p[1], p[2] );
  6806. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  6807. bone.useQuaternion = true;
  6808. if ( s !== undefined ) {
  6809. bone.scale.set( s[0], s[1], s[2] );
  6810. } else {
  6811. bone.scale.set( 1, 1, 1 );
  6812. }
  6813. }
  6814. for ( b = 0; b < this.bones.length; b ++ ) {
  6815. gbone = this.geometry.bones[ b ];
  6816. bone = this.bones[ b ];
  6817. if ( gbone.parent === -1 ) {
  6818. this.add( bone );
  6819. } else {
  6820. this.bones[ gbone.parent ].add( bone );
  6821. }
  6822. }
  6823. //
  6824. var nBones = this.bones.length;
  6825. if ( this.useVertexTexture ) {
  6826. // layout (1 matrix = 4 pixels)
  6827. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  6828. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  6829. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  6830. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  6831. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  6832. var size;
  6833. if ( nBones > 256 )
  6834. size = 64;
  6835. else if ( nBones > 64 )
  6836. size = 32;
  6837. else if ( nBones > 16 )
  6838. size = 16;
  6839. else
  6840. size = 8;
  6841. this.boneTextureWidth = size;
  6842. this.boneTextureHeight = size;
  6843. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  6844. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  6845. this.boneTexture.minFilter = THREE.NearestFilter;
  6846. this.boneTexture.magFilter = THREE.NearestFilter;
  6847. this.boneTexture.generateMipmaps = false;
  6848. this.boneTexture.flipY = false;
  6849. } else {
  6850. this.boneMatrices = new Float32Array( 16 * nBones );
  6851. }
  6852. this.pose();
  6853. }
  6854. };
  6855. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  6856. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  6857. if ( bone === undefined ) {
  6858. bone = new THREE.Bone( this );
  6859. }
  6860. this.bones.push( bone );
  6861. return bone;
  6862. };
  6863. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  6864. this.matrixAutoUpdate && this.updateMatrix();
  6865. // update matrixWorld
  6866. if ( this.matrixWorldNeedsUpdate || force ) {
  6867. if ( this.parent ) {
  6868. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  6869. } else {
  6870. this.matrixWorld.copy( this.matrix );
  6871. }
  6872. this.matrixWorldNeedsUpdate = false;
  6873. force = true;
  6874. }
  6875. // update children
  6876. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6877. var child = this.children[ i ];
  6878. if ( child instanceof THREE.Bone ) {
  6879. child.update( this.identityMatrix, false );
  6880. } else {
  6881. child.updateMatrixWorld( true );
  6882. }
  6883. }
  6884. // make a snapshot of the bones' rest position
  6885. if ( this.boneInverses == undefined ) {
  6886. this.boneInverses = [];
  6887. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6888. var inverse = new THREE.Matrix4();
  6889. inverse.getInverse( this.bones[ b ].skinMatrix );
  6890. this.boneInverses.push( inverse );
  6891. }
  6892. }
  6893. // flatten bone matrices to array
  6894. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6895. // compute the offset between the current and the original transform;
  6896. //TODO: we could get rid of this multiplication step if the skinMatrix
  6897. // was already representing the offset; however, this requires some
  6898. // major changes to the animation system
  6899. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  6900. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  6901. }
  6902. if ( this.useVertexTexture ) {
  6903. this.boneTexture.needsUpdate = true;
  6904. }
  6905. };
  6906. THREE.SkinnedMesh.prototype.pose = function() {
  6907. this.updateMatrixWorld( true );
  6908. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  6909. // normalize weights
  6910. var sw = this.geometry.skinWeights[ i ];
  6911. var scale = 1.0 / sw.lengthManhattan();
  6912. if ( scale !== Infinity ) {
  6913. sw.multiplyScalar( scale );
  6914. } else {
  6915. sw.set( 1 ); // this will be normalized by the shader anyway
  6916. }
  6917. }
  6918. };
  6919. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  6920. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  6921. THREE.Mesh.prototype.clone.call( this, object );
  6922. return object;
  6923. };
  6924. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  6925. /**
  6926. * @author alteredq / http://alteredqualia.com/
  6927. */
  6928. THREE.MorphAnimMesh = function ( geometry, material ) {
  6929. THREE.Mesh.call( this, geometry, material );
  6930. // API
  6931. this.duration = 1000; // milliseconds
  6932. this.mirroredLoop = false;
  6933. this.time = 0;
  6934. // internals
  6935. this.lastKeyframe = 0;
  6936. this.currentKeyframe = 0;
  6937. this.direction = 1;
  6938. this.directionBackwards = false;
  6939. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  6940. };
  6941. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  6942. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  6943. this.startKeyframe = start;
  6944. this.endKeyframe = end;
  6945. this.length = this.endKeyframe - this.startKeyframe + 1;
  6946. };
  6947. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  6948. this.direction = 1;
  6949. this.directionBackwards = false;
  6950. };
  6951. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  6952. this.direction = -1;
  6953. this.directionBackwards = true;
  6954. };
  6955. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  6956. var geometry = this.geometry;
  6957. if ( ! geometry.animations ) geometry.animations = {};
  6958. var firstAnimation, animations = geometry.animations;
  6959. var pattern = /([a-z]+)(\d+)/;
  6960. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  6961. var morph = geometry.morphTargets[ i ];
  6962. var parts = morph.name.match( pattern );
  6963. if ( parts && parts.length > 1 ) {
  6964. var label = parts[ 1 ];
  6965. var num = parts[ 2 ];
  6966. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  6967. var animation = animations[ label ];
  6968. if ( i < animation.start ) animation.start = i;
  6969. if ( i > animation.end ) animation.end = i;
  6970. if ( ! firstAnimation ) firstAnimation = label;
  6971. }
  6972. }
  6973. geometry.firstAnimation = firstAnimation;
  6974. };
  6975. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  6976. if ( ! this.geometry.animations ) this.geometry.animations = {};
  6977. this.geometry.animations[ label ] = { start: start, end: end };
  6978. };
  6979. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  6980. var animation = this.geometry.animations[ label ];
  6981. if ( animation ) {
  6982. this.setFrameRange( animation.start, animation.end );
  6983. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  6984. this.time = 0;
  6985. } else {
  6986. console.warn( "animation[" + label + "] undefined" );
  6987. }
  6988. };
  6989. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  6990. var frameTime = this.duration / this.length;
  6991. this.time += this.direction * delta;
  6992. if ( this.mirroredLoop ) {
  6993. if ( this.time > this.duration || this.time < 0 ) {
  6994. this.direction *= -1;
  6995. if ( this.time > this.duration ) {
  6996. this.time = this.duration;
  6997. this.directionBackwards = true;
  6998. }
  6999. if ( this.time < 0 ) {
  7000. this.time = 0;
  7001. this.directionBackwards = false;
  7002. }
  7003. }
  7004. } else {
  7005. this.time = this.time % this.duration;
  7006. if ( this.time < 0 ) this.time += this.duration;
  7007. }
  7008. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7009. if ( keyframe !== this.currentKeyframe ) {
  7010. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7011. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7012. this.morphTargetInfluences[ keyframe ] = 0;
  7013. this.lastKeyframe = this.currentKeyframe;
  7014. this.currentKeyframe = keyframe;
  7015. }
  7016. var mix = ( this.time % frameTime ) / frameTime;
  7017. if ( this.directionBackwards ) {
  7018. mix = 1 - mix;
  7019. }
  7020. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7021. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7022. };
  7023. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7024. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7025. object.duration = this.duration;
  7026. object.mirroredLoop = this.mirroredLoop;
  7027. object.time = this.time;
  7028. object.lastKeyframe = this.lastKeyframe;
  7029. object.currentKeyframe = this.currentKeyframe;
  7030. object.direction = this.direction;
  7031. object.directionBackwards = this.directionBackwards;
  7032. THREE.Mesh.prototype.clone.call( this, object );
  7033. return object;
  7034. };
  7035. /**
  7036. * @author alteredq / http://alteredqualia.com/
  7037. */
  7038. THREE.Ribbon = function ( geometry, material ) {
  7039. THREE.Object3D.call( this );
  7040. this.geometry = geometry;
  7041. this.material = material;
  7042. };
  7043. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7044. THREE.Ribbon.prototype.clone = function ( object ) {
  7045. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7046. THREE.Object3D.prototype.clone.call( this, object );
  7047. return object;
  7048. };
  7049. /**
  7050. * @author mikael emtinger / http://gomo.se/
  7051. * @author alteredq / http://alteredqualia.com/
  7052. * @author mrdoob / http://mrdoob.com/
  7053. */
  7054. THREE.LOD = function () {
  7055. THREE.Object3D.call( this );
  7056. this.LODs = [];
  7057. };
  7058. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7059. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7060. if ( visibleAtDistance === undefined ) {
  7061. visibleAtDistance = 0;
  7062. }
  7063. visibleAtDistance = Math.abs( visibleAtDistance );
  7064. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7065. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7066. break;
  7067. }
  7068. }
  7069. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7070. this.add( object3D );
  7071. };
  7072. THREE.LOD.prototype.update = function ( camera ) {
  7073. if ( this.LODs.length > 1 ) {
  7074. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7075. var inverse = camera.matrixWorldInverse;
  7076. 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] );
  7077. this.LODs[ 0 ].object3D.visible = true;
  7078. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7079. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7080. this.LODs[ l - 1 ].object3D.visible = false;
  7081. this.LODs[ l ].object3D.visible = true;
  7082. } else {
  7083. break;
  7084. }
  7085. }
  7086. for( ; l < this.LODs.length; l ++ ) {
  7087. this.LODs[ l ].object3D.visible = false;
  7088. }
  7089. }
  7090. };
  7091. THREE.LOD.prototype.clone = function () {
  7092. // TODO
  7093. };
  7094. /**
  7095. * @author mikael emtinger / http://gomo.se/
  7096. * @author alteredq / http://alteredqualia.com/
  7097. */
  7098. THREE.Sprite = function ( material ) {
  7099. THREE.Object3D.call( this );
  7100. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7101. this.rotation3d = this.rotation;
  7102. this.rotation = 0;
  7103. };
  7104. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7105. /*
  7106. * Custom update matrix
  7107. */
  7108. THREE.Sprite.prototype.updateMatrix = function () {
  7109. this.matrix.setPosition( this.position );
  7110. this.rotation3d.set( 0, 0, this.rotation );
  7111. this.matrix.setRotationFromEuler( this.rotation3d );
  7112. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7113. this.matrix.scale( this.scale );
  7114. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  7115. }
  7116. this.matrixWorldNeedsUpdate = true;
  7117. };
  7118. THREE.Sprite.prototype.clone = function ( object ) {
  7119. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7120. THREE.Object3D.prototype.clone.call( this, object );
  7121. return object;
  7122. };
  7123. /**
  7124. * @author mrdoob / http://mrdoob.com/
  7125. */
  7126. THREE.Scene = function () {
  7127. THREE.Object3D.call( this );
  7128. this.fog = null;
  7129. this.overrideMaterial = null;
  7130. this.matrixAutoUpdate = false;
  7131. this.__objects = [];
  7132. this.__lights = [];
  7133. this.__objectsAdded = [];
  7134. this.__objectsRemoved = [];
  7135. };
  7136. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7137. THREE.Scene.prototype.__addObject = function ( object ) {
  7138. if ( object instanceof THREE.Light ) {
  7139. if ( this.__lights.indexOf( object ) === - 1 ) {
  7140. this.__lights.push( object );
  7141. }
  7142. if ( object.target && object.target.parent === undefined ) {
  7143. this.add( object.target );
  7144. }
  7145. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7146. if ( this.__objects.indexOf( object ) === - 1 ) {
  7147. this.__objects.push( object );
  7148. this.__objectsAdded.push( object );
  7149. // check if previously removed
  7150. var i = this.__objectsRemoved.indexOf( object );
  7151. if ( i !== -1 ) {
  7152. this.__objectsRemoved.splice( i, 1 );
  7153. }
  7154. }
  7155. }
  7156. for ( var c = 0; c < object.children.length; c ++ ) {
  7157. this.__addObject( object.children[ c ] );
  7158. }
  7159. };
  7160. THREE.Scene.prototype.__removeObject = function ( object ) {
  7161. if ( object instanceof THREE.Light ) {
  7162. var i = this.__lights.indexOf( object );
  7163. if ( i !== -1 ) {
  7164. this.__lights.splice( i, 1 );
  7165. }
  7166. } else if ( !( object instanceof THREE.Camera ) ) {
  7167. var i = this.__objects.indexOf( object );
  7168. if( i !== -1 ) {
  7169. this.__objects.splice( i, 1 );
  7170. this.__objectsRemoved.push( object );
  7171. // check if previously added
  7172. var ai = this.__objectsAdded.indexOf( object );
  7173. if ( ai !== -1 ) {
  7174. this.__objectsAdded.splice( ai, 1 );
  7175. }
  7176. }
  7177. }
  7178. for ( var c = 0; c < object.children.length; c ++ ) {
  7179. this.__removeObject( object.children[ c ] );
  7180. }
  7181. };
  7182. /**
  7183. * @author mrdoob / http://mrdoob.com/
  7184. * @author alteredq / http://alteredqualia.com/
  7185. */
  7186. THREE.Fog = function ( hex, near, far ) {
  7187. this.name = '';
  7188. this.color = new THREE.Color( hex );
  7189. this.near = ( near !== undefined ) ? near : 1;
  7190. this.far = ( far !== undefined ) ? far : 1000;
  7191. };
  7192. THREE.Fog.prototype.clone = function () {
  7193. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7194. };
  7195. /**
  7196. * @author mrdoob / http://mrdoob.com/
  7197. * @author alteredq / http://alteredqualia.com/
  7198. */
  7199. THREE.FogExp2 = function ( hex, density ) {
  7200. this.name = '';
  7201. this.color = new THREE.Color( hex );
  7202. this.density = ( density !== undefined ) ? density : 0.00025;
  7203. };
  7204. THREE.FogExp2.prototype.clone = function () {
  7205. return new THREE.FogExp2( this.color.getHex(), this.density );
  7206. };
  7207. /**
  7208. * @author mrdoob / http://mrdoob.com/
  7209. */
  7210. THREE.CanvasRenderer = function ( parameters ) {
  7211. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7212. parameters = parameters || {};
  7213. var _this = this,
  7214. _renderData, _elements, _lights,
  7215. _projector = new THREE.Projector(),
  7216. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  7217. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7218. _context = _canvas.getContext( '2d' ),
  7219. _clearColor = new THREE.Color( 0x000000 ),
  7220. _clearOpacity = 0,
  7221. _contextGlobalAlpha = 1,
  7222. _contextGlobalCompositeOperation = 0,
  7223. _contextStrokeStyle = null,
  7224. _contextFillStyle = null,
  7225. _contextLineWidth = null,
  7226. _contextLineCap = null,
  7227. _contextLineJoin = null,
  7228. _v1, _v2, _v3, _v4,
  7229. _v5 = new THREE.RenderableVertex(),
  7230. _v6 = new THREE.RenderableVertex(),
  7231. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7232. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7233. _color = new THREE.Color(),
  7234. _color1 = new THREE.Color(),
  7235. _color2 = new THREE.Color(),
  7236. _color3 = new THREE.Color(),
  7237. _color4 = new THREE.Color(),
  7238. _diffuseColor = new THREE.Color(),
  7239. _emissiveColor = new THREE.Color(),
  7240. _patterns = {}, _imagedatas = {},
  7241. _near, _far,
  7242. _image, _uvs,
  7243. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7244. _clipRect = new THREE.Rectangle(),
  7245. _clearRect = new THREE.Rectangle(),
  7246. _bboxRect = new THREE.Rectangle(),
  7247. _enableLighting = false,
  7248. _ambientLight = new THREE.Color(),
  7249. _directionalLights = new THREE.Color(),
  7250. _pointLights = new THREE.Color(),
  7251. _pi2 = Math.PI * 2,
  7252. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7253. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7254. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7255. _pixelMap = document.createElement( 'canvas' );
  7256. _pixelMap.width = _pixelMap.height = 2;
  7257. _pixelMapContext = _pixelMap.getContext( '2d' );
  7258. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7259. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7260. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7261. _pixelMapData = _pixelMapImage.data;
  7262. _gradientMap = document.createElement( 'canvas' );
  7263. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7264. _gradientMapContext = _gradientMap.getContext( '2d' );
  7265. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7266. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7267. _gradientMapQuality --; // Fix UVs
  7268. this.domElement = _canvas;
  7269. this.autoClear = true;
  7270. this.sortObjects = true;
  7271. this.sortElements = true;
  7272. this.info = {
  7273. render: {
  7274. vertices: 0,
  7275. faces: 0
  7276. }
  7277. }
  7278. this.setSize = function ( width, height ) {
  7279. _canvasWidth = width;
  7280. _canvasHeight = height;
  7281. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7282. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7283. _canvas.width = _canvasWidth;
  7284. _canvas.height = _canvasHeight;
  7285. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7286. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7287. _contextGlobalAlpha = 1;
  7288. _contextGlobalCompositeOperation = 0;
  7289. _contextStrokeStyle = null;
  7290. _contextFillStyle = null;
  7291. _contextLineWidth = null;
  7292. _contextLineCap = null;
  7293. _contextLineJoin = null;
  7294. };
  7295. this.setClearColor = function ( color, opacity ) {
  7296. _clearColor.copy( color );
  7297. _clearOpacity = opacity !== undefined ? opacity : 1;
  7298. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7299. };
  7300. this.setClearColorHex = function ( hex, opacity ) {
  7301. _clearColor.setHex( hex );
  7302. _clearOpacity = opacity !== undefined ? opacity : 1;
  7303. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7304. };
  7305. this.getMaxAnisotropy = function () {
  7306. return 0;
  7307. };
  7308. this.clear = function () {
  7309. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7310. if ( _clearRect.isEmpty() === false ) {
  7311. _clearRect.minSelf( _clipRect );
  7312. _clearRect.inflate( 2 );
  7313. if ( _clearOpacity < 1 ) {
  7314. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7315. }
  7316. if ( _clearOpacity > 0 ) {
  7317. setBlending( THREE.NormalBlending );
  7318. setOpacity( 1 );
  7319. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7320. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7321. }
  7322. _clearRect.empty();
  7323. }
  7324. };
  7325. this.render = function ( scene, camera ) {
  7326. if ( camera instanceof THREE.Camera === false ) {
  7327. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7328. return;
  7329. }
  7330. var e, el, element, material;
  7331. this.autoClear === true
  7332. ? this.clear()
  7333. : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7334. _this.info.render.vertices = 0;
  7335. _this.info.render.faces = 0;
  7336. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  7337. _elements = _renderData.elements;
  7338. _lights = _renderData.lights;
  7339. /* DEBUG
  7340. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7341. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  7342. */
  7343. _enableLighting = _lights.length > 0;
  7344. if ( _enableLighting === true ) {
  7345. calculateLights();
  7346. }
  7347. for ( e = 0, el = _elements.length; e < el; e++ ) {
  7348. element = _elements[ e ];
  7349. material = element.material;
  7350. if ( material === undefined || material.visible === false ) continue;
  7351. _bboxRect.empty();
  7352. if ( element instanceof THREE.RenderableParticle ) {
  7353. _v1 = element;
  7354. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7355. renderParticle( _v1, element, material, scene );
  7356. } else if ( element instanceof THREE.RenderableLine ) {
  7357. _v1 = element.v1; _v2 = element.v2;
  7358. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7359. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7360. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7361. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7362. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7363. renderLine( _v1, _v2, element, material, scene );
  7364. }
  7365. } else if ( element instanceof THREE.RenderableFace3 ) {
  7366. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7367. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7368. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7369. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7370. if ( material.overdraw === true ) {
  7371. expand( _v1.positionScreen, _v2.positionScreen );
  7372. expand( _v2.positionScreen, _v3.positionScreen );
  7373. expand( _v3.positionScreen, _v1.positionScreen );
  7374. }
  7375. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  7376. _v2.positionScreen.x, _v2.positionScreen.y,
  7377. _v3.positionScreen.x, _v3.positionScreen.y );
  7378. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7379. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7380. }
  7381. } else if ( element instanceof THREE.RenderableFace4 ) {
  7382. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7383. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7384. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7385. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7386. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7387. _v5.positionScreen.copy( _v2.positionScreen );
  7388. _v6.positionScreen.copy( _v4.positionScreen );
  7389. if ( material.overdraw === true ) {
  7390. expand( _v1.positionScreen, _v2.positionScreen );
  7391. expand( _v2.positionScreen, _v4.positionScreen );
  7392. expand( _v4.positionScreen, _v1.positionScreen );
  7393. expand( _v3.positionScreen, _v5.positionScreen );
  7394. expand( _v3.positionScreen, _v6.positionScreen );
  7395. }
  7396. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7397. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7398. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  7399. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  7400. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7401. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  7402. }
  7403. }
  7404. /* DEBUG
  7405. _context.lineWidth = 1;
  7406. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  7407. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  7408. */
  7409. _clearRect.addRectangle( _bboxRect );
  7410. }
  7411. /* DEBUG
  7412. _context.lineWidth = 1;
  7413. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  7414. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  7415. */
  7416. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  7417. //
  7418. function calculateLights() {
  7419. _ambientLight.setRGB( 0, 0, 0 );
  7420. _directionalLights.setRGB( 0, 0, 0 );
  7421. _pointLights.setRGB( 0, 0, 0 );
  7422. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7423. var light = _lights[ l ];
  7424. var lightColor = light.color;
  7425. if ( light instanceof THREE.AmbientLight ) {
  7426. _ambientLight.r += lightColor.r;
  7427. _ambientLight.g += lightColor.g;
  7428. _ambientLight.b += lightColor.b;
  7429. } else if ( light instanceof THREE.DirectionalLight ) {
  7430. // for particles
  7431. _directionalLights.r += lightColor.r;
  7432. _directionalLights.g += lightColor.g;
  7433. _directionalLights.b += lightColor.b;
  7434. } else if ( light instanceof THREE.PointLight ) {
  7435. // for particles
  7436. _pointLights.r += lightColor.r;
  7437. _pointLights.g += lightColor.g;
  7438. _pointLights.b += lightColor.b;
  7439. }
  7440. }
  7441. }
  7442. function calculateLight( position, normal, color ) {
  7443. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7444. var light = _lights[ l ];
  7445. var lightColor = light.color;
  7446. if ( light instanceof THREE.DirectionalLight ) {
  7447. var lightPosition = light.matrixWorld.getPosition().normalize();
  7448. var amount = normal.dot( lightPosition );
  7449. if ( amount <= 0 ) continue;
  7450. amount *= light.intensity;
  7451. color.r += lightColor.r * amount;
  7452. color.g += lightColor.g * amount;
  7453. color.b += lightColor.b * amount;
  7454. } else if ( light instanceof THREE.PointLight ) {
  7455. var lightPosition = light.matrixWorld.getPosition();
  7456. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  7457. if ( amount <= 0 ) continue;
  7458. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  7459. if ( amount == 0 ) continue;
  7460. amount *= light.intensity;
  7461. color.r += lightColor.r * amount;
  7462. color.g += lightColor.g * amount;
  7463. color.b += lightColor.b * amount;
  7464. }
  7465. }
  7466. }
  7467. function renderParticle( v1, element, material, scene ) {
  7468. setOpacity( material.opacity );
  7469. setBlending( material.blending );
  7470. var width, height, scaleX, scaleY,
  7471. bitmap, bitmapWidth, bitmapHeight;
  7472. if ( material instanceof THREE.ParticleBasicMaterial ) {
  7473. if ( material.map === null ) {
  7474. scaleX = element.object.scale.x;
  7475. scaleY = element.object.scale.y;
  7476. // TODO: Be able to disable this
  7477. scaleX *= element.scale.x * _canvasWidthHalf;
  7478. scaleY *= element.scale.y * _canvasHeightHalf;
  7479. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  7480. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7481. return;
  7482. }
  7483. setFillStyle( material.color.getContextStyle() );
  7484. _context.save();
  7485. _context.translate( v1.x, v1.y );
  7486. _context.rotate( - element.rotation );
  7487. _context.scale( scaleX, scaleY );
  7488. _context.fillRect( -1, -1, 2, 2 );
  7489. _context.restore();
  7490. } else {
  7491. bitmap = material.map.image;
  7492. bitmapWidth = bitmap.width >> 1;
  7493. bitmapHeight = bitmap.height >> 1;
  7494. scaleX = element.scale.x * _canvasWidthHalf;
  7495. scaleY = element.scale.y * _canvasHeightHalf;
  7496. width = scaleX * bitmapWidth;
  7497. height = scaleY * bitmapHeight;
  7498. // TODO: Rotations break this...
  7499. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7500. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7501. return;
  7502. }
  7503. _context.save();
  7504. _context.translate( v1.x, v1.y );
  7505. _context.rotate( - element.rotation );
  7506. _context.scale( scaleX, - scaleY );
  7507. _context.translate( - bitmapWidth, - bitmapHeight );
  7508. _context.drawImage( bitmap, 0, 0 );
  7509. _context.restore();
  7510. }
  7511. /* DEBUG
  7512. setStrokeStyle( 'rgb(255,255,0)' );
  7513. _context.beginPath();
  7514. _context.moveTo( v1.x - 10, v1.y );
  7515. _context.lineTo( v1.x + 10, v1.y );
  7516. _context.moveTo( v1.x, v1.y - 10 );
  7517. _context.lineTo( v1.x, v1.y + 10 );
  7518. _context.stroke();
  7519. */
  7520. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  7521. width = element.scale.x * _canvasWidthHalf;
  7522. height = element.scale.y * _canvasHeightHalf;
  7523. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7524. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7525. return;
  7526. }
  7527. setStrokeStyle( material.color.getContextStyle() );
  7528. setFillStyle( material.color.getContextStyle() );
  7529. _context.save();
  7530. _context.translate( v1.x, v1.y );
  7531. _context.rotate( - element.rotation );
  7532. _context.scale( width, height );
  7533. material.program( _context );
  7534. _context.restore();
  7535. }
  7536. }
  7537. function renderLine( v1, v2, element, material, scene ) {
  7538. setOpacity( material.opacity );
  7539. setBlending( material.blending );
  7540. _context.beginPath();
  7541. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  7542. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  7543. if ( material instanceof THREE.LineBasicMaterial ) {
  7544. setLineWidth( material.linewidth );
  7545. setLineCap( material.linecap );
  7546. setLineJoin( material.linejoin );
  7547. setStrokeStyle( material.color.getContextStyle() );
  7548. _context.stroke();
  7549. _bboxRect.inflate( material.linewidth * 2 );
  7550. }
  7551. }
  7552. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  7553. _this.info.render.vertices += 3;
  7554. _this.info.render.faces ++;
  7555. setOpacity( material.opacity );
  7556. setBlending( material.blending );
  7557. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7558. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7559. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7560. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  7561. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  7562. _diffuseColor.copy( material.color );
  7563. _emissiveColor.copy( material.emissive );
  7564. if ( material.vertexColors === THREE.FaceColors ) {
  7565. _diffuseColor.r *= element.color.r;
  7566. _diffuseColor.g *= element.color.g;
  7567. _diffuseColor.b *= element.color.b;
  7568. }
  7569. if ( _enableLighting === true ) {
  7570. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  7571. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  7572. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  7573. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  7574. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7575. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7576. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  7577. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7578. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7579. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7580. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7581. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7582. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7583. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7584. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7585. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7586. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7587. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7588. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7589. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7590. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7591. } else {
  7592. _color.r = _ambientLight.r;
  7593. _color.g = _ambientLight.g;
  7594. _color.b = _ambientLight.b;
  7595. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7596. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7597. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7598. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7599. material.wireframe === true
  7600. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7601. : fillPath( _color );
  7602. }
  7603. } else {
  7604. material.wireframe === true
  7605. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7606. : fillPath( material.color );
  7607. }
  7608. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7609. if ( material.map !== null ) {
  7610. if ( material.map.mapping instanceof THREE.UVMapping ) {
  7611. _uvs = element.uvs[ 0 ];
  7612. 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 );
  7613. }
  7614. } else if ( material.envMap !== null ) {
  7615. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  7616. var cameraMatrix = camera.matrixWorldInverse;
  7617. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  7618. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7619. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7620. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  7621. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7622. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7623. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  7624. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7625. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7626. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  7627. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  7628. }*/
  7629. } else {
  7630. _color.copy( material.color );
  7631. if ( material.vertexColors === THREE.FaceColors ) {
  7632. _color.r *= element.color.r;
  7633. _color.g *= element.color.g;
  7634. _color.b *= element.color.b;
  7635. }
  7636. material.wireframe === true
  7637. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7638. : fillPath( _color );
  7639. }
  7640. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7641. _near = camera.near;
  7642. _far = camera.far;
  7643. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7644. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7645. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7646. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7647. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7648. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7649. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7650. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7651. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7652. _color.r = normalToComponent( element.normalWorld.x );
  7653. _color.g = normalToComponent( element.normalWorld.y );
  7654. _color.b = normalToComponent( element.normalWorld.z );
  7655. material.wireframe === true
  7656. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7657. : fillPath( _color );
  7658. }
  7659. }
  7660. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  7661. _this.info.render.vertices += 4;
  7662. _this.info.render.faces ++;
  7663. setOpacity( material.opacity );
  7664. setBlending( material.blending );
  7665. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  7666. // Let renderFace3() handle this
  7667. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  7668. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  7669. return;
  7670. }
  7671. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7672. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7673. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7674. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  7675. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  7676. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  7677. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7678. _diffuseColor.copy( material.color );
  7679. _emissiveColor.copy( material.emissive );
  7680. if ( material.vertexColors === THREE.FaceColors ) {
  7681. _diffuseColor.r *= element.color.r;
  7682. _diffuseColor.g *= element.color.g;
  7683. _diffuseColor.b *= element.color.b;
  7684. }
  7685. if ( _enableLighting === true ) {
  7686. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  7687. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  7688. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  7689. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  7690. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7691. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7692. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  7693. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  7694. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7695. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7696. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7697. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7698. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7699. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7700. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7701. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7702. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7703. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  7704. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  7705. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  7706. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7707. // TODO: UVs are incorrect, v4->v3?
  7708. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7709. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7710. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7711. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7712. } else {
  7713. _color.r = _ambientLight.r;
  7714. _color.g = _ambientLight.g;
  7715. _color.b = _ambientLight.b;
  7716. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7717. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7718. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7719. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7720. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7721. material.wireframe === true
  7722. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7723. : fillPath( _color );
  7724. }
  7725. } else {
  7726. _color.r = _diffuseColor.r + _emissiveColor.r;
  7727. _color.g = _diffuseColor.g + _emissiveColor.g;
  7728. _color.b = _diffuseColor.b + _emissiveColor.b;
  7729. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7730. material.wireframe === true
  7731. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7732. : fillPath( _color );
  7733. }
  7734. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  7735. _color.copy( material.color );
  7736. if ( material.vertexColors === THREE.FaceColors ) {
  7737. _color.r *= element.color.r;
  7738. _color.g *= element.color.g;
  7739. _color.b *= element.color.b;
  7740. }
  7741. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7742. material.wireframe === true
  7743. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7744. : fillPath( _color );
  7745. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7746. _color.r = normalToComponent( element.normalWorld.x );
  7747. _color.g = normalToComponent( element.normalWorld.y );
  7748. _color.b = normalToComponent( element.normalWorld.z );
  7749. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7750. material.wireframe === true
  7751. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7752. : fillPath( _color );
  7753. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7754. _near = camera.near;
  7755. _far = camera.far;
  7756. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7757. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7758. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  7759. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7760. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7761. // TODO: UVs are incorrect, v4->v3?
  7762. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7763. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7764. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7765. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7766. }
  7767. }
  7768. //
  7769. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  7770. _context.beginPath();
  7771. _context.moveTo( x0, y0 );
  7772. _context.lineTo( x1, y1 );
  7773. _context.lineTo( x2, y2 );
  7774. _context.closePath();
  7775. }
  7776. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  7777. _context.beginPath();
  7778. _context.moveTo( x0, y0 );
  7779. _context.lineTo( x1, y1 );
  7780. _context.lineTo( x2, y2 );
  7781. _context.lineTo( x3, y3 );
  7782. _context.closePath();
  7783. }
  7784. function strokePath( color, linewidth, linecap, linejoin ) {
  7785. setLineWidth( linewidth );
  7786. setLineCap( linecap );
  7787. setLineJoin( linejoin );
  7788. setStrokeStyle( color.getContextStyle() );
  7789. _context.stroke();
  7790. _bboxRect.inflate( linewidth * 2 );
  7791. }
  7792. function fillPath( color ) {
  7793. setFillStyle( color.getContextStyle() );
  7794. _context.fill();
  7795. }
  7796. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  7797. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  7798. if ( texture.needsUpdate === true ) {
  7799. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  7800. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  7801. _patterns[ texture.id ] = _context.createPattern(
  7802. texture.image, repeatX === true && repeatY === true
  7803. ? 'repeat'
  7804. : repeatX === true && repeatY === false
  7805. ? 'repeat-x'
  7806. : repeatX === false && repeatY === true
  7807. ? 'repeat-y'
  7808. : 'no-repeat'
  7809. );
  7810. texture.needsUpdate = false;
  7811. }
  7812. _patterns[ texture.id ] === undefined
  7813. ? setFillStyle( 'rgba(0,0,0,1)' )
  7814. : setFillStyle( _patterns[ texture.id ] );
  7815. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7816. var a, b, c, d, e, f, det, idet,
  7817. offsetX = texture.offset.x / texture.repeat.x,
  7818. offsetY = texture.offset.y / texture.repeat.y,
  7819. width = texture.image.width * texture.repeat.x,
  7820. height = texture.image.height * texture.repeat.y;
  7821. u0 = ( u0 + offsetX ) * width;
  7822. v0 = ( 1.0 - v0 + offsetY ) * height;
  7823. u1 = ( u1 + offsetX ) * width;
  7824. v1 = ( 1.0 - v1 + offsetY ) * height;
  7825. u2 = ( u2 + offsetX ) * width;
  7826. v2 = ( 1.0 - v2 + offsetY ) * height;
  7827. x1 -= x0; y1 -= y0;
  7828. x2 -= x0; y2 -= y0;
  7829. u1 -= u0; v1 -= v0;
  7830. u2 -= u0; v2 -= v0;
  7831. det = u1 * v2 - u2 * v1;
  7832. if ( det === 0 ) {
  7833. if ( _imagedatas[ texture.id ] === undefined ) {
  7834. var canvas = document.createElement( 'canvas' )
  7835. canvas.width = texture.image.width;
  7836. canvas.height = texture.image.height;
  7837. var context = canvas.getContext( '2d' );
  7838. context.drawImage( texture.image, 0, 0 );
  7839. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  7840. }
  7841. var data = _imagedatas[ texture.id ];
  7842. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  7843. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  7844. fillPath( _color );
  7845. return;
  7846. }
  7847. idet = 1 / det;
  7848. a = ( v2 * x1 - v1 * x2 ) * idet;
  7849. b = ( v2 * y1 - v1 * y2 ) * idet;
  7850. c = ( u1 * x2 - u2 * x1 ) * idet;
  7851. d = ( u1 * y2 - u2 * y1 ) * idet;
  7852. e = x0 - a * u0 - c * v0;
  7853. f = y0 - b * u0 - d * v0;
  7854. _context.save();
  7855. _context.transform( a, b, c, d, e, f );
  7856. _context.fill();
  7857. _context.restore();
  7858. }
  7859. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  7860. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7861. var a, b, c, d, e, f, det, idet,
  7862. width = image.width - 1,
  7863. height = image.height - 1;
  7864. u0 *= width; v0 *= height;
  7865. u1 *= width; v1 *= height;
  7866. u2 *= width; v2 *= height;
  7867. x1 -= x0; y1 -= y0;
  7868. x2 -= x0; y2 -= y0;
  7869. u1 -= u0; v1 -= v0;
  7870. u2 -= u0; v2 -= v0;
  7871. det = u1 * v2 - u2 * v1;
  7872. idet = 1 / det;
  7873. a = ( v2 * x1 - v1 * x2 ) * idet;
  7874. b = ( v2 * y1 - v1 * y2 ) * idet;
  7875. c = ( u1 * x2 - u2 * x1 ) * idet;
  7876. d = ( u1 * y2 - u2 * y1 ) * idet;
  7877. e = x0 - a * u0 - c * v0;
  7878. f = y0 - b * u0 - d * v0;
  7879. _context.save();
  7880. _context.transform( a, b, c, d, e, f );
  7881. _context.clip();
  7882. _context.drawImage( image, 0, 0 );
  7883. _context.restore();
  7884. }
  7885. function getGradientTexture( color1, color2, color3, color4 ) {
  7886. // http://mrdoob.com/blog/post/710
  7887. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  7888. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  7889. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  7890. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  7891. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  7892. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  7893. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  7894. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  7895. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  7896. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  7897. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  7898. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  7899. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  7900. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  7901. return _gradientMap;
  7902. }
  7903. function smoothstep( value, min, max ) {
  7904. var x = ( value - min ) / ( max - min );
  7905. return x * x * ( 3 - 2 * x );
  7906. }
  7907. function normalToComponent( normal ) {
  7908. var component = ( normal + 1 ) * 0.5;
  7909. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  7910. }
  7911. // Hide anti-alias gaps
  7912. function expand( v1, v2 ) {
  7913. var x = v2.x - v1.x, y = v2.y - v1.y,
  7914. det = x * x + y * y, idet;
  7915. if ( det === 0 ) return;
  7916. idet = 1 / Math.sqrt( det );
  7917. x *= idet; y *= idet;
  7918. v2.x += x; v2.y += y;
  7919. v1.x -= x; v1.y -= y;
  7920. }
  7921. };
  7922. // Context cached methods.
  7923. function setOpacity( value ) {
  7924. if ( _contextGlobalAlpha !== value ) {
  7925. _context.globalAlpha = value;
  7926. _contextGlobalAlpha = value;
  7927. }
  7928. }
  7929. function setBlending( value ) {
  7930. if ( _contextGlobalCompositeOperation !== value ) {
  7931. if ( value === THREE.NormalBlending ) {
  7932. _context.globalCompositeOperation = 'source-over';
  7933. } else if ( value === THREE.AdditiveBlending ) {
  7934. _context.globalCompositeOperation = 'lighter';
  7935. } else if ( value === THREE.SubtractiveBlending ) {
  7936. _context.globalCompositeOperation = 'darker';
  7937. }
  7938. _contextGlobalCompositeOperation = value;
  7939. }
  7940. }
  7941. function setLineWidth( value ) {
  7942. if ( _contextLineWidth !== value ) {
  7943. _context.lineWidth = value;
  7944. _contextLineWidth = value;
  7945. }
  7946. }
  7947. function setLineCap( value ) {
  7948. // "butt", "round", "square"
  7949. if ( _contextLineCap !== value ) {
  7950. _context.lineCap = value;
  7951. _contextLineCap = value;
  7952. }
  7953. }
  7954. function setLineJoin( value ) {
  7955. // "round", "bevel", "miter"
  7956. if ( _contextLineJoin !== value ) {
  7957. _context.lineJoin = value;
  7958. _contextLineJoin = value;
  7959. }
  7960. }
  7961. function setStrokeStyle( value ) {
  7962. if ( _contextStrokeStyle !== value ) {
  7963. _context.strokeStyle = value;
  7964. _contextStrokeStyle = value;
  7965. }
  7966. }
  7967. function setFillStyle( value ) {
  7968. if ( _contextFillStyle !== value ) {
  7969. _context.fillStyle = value;
  7970. _contextFillStyle = value;
  7971. }
  7972. }
  7973. };
  7974. /**
  7975. * @author alteredq / http://alteredqualia.com/
  7976. * @author mrdoob / http://mrdoob.com/
  7977. * @author mikael emtinger / http://gomo.se/
  7978. */
  7979. THREE.ShaderChunk = {
  7980. // FOG
  7981. fog_pars_fragment: [
  7982. "#ifdef USE_FOG",
  7983. "uniform vec3 fogColor;",
  7984. "#ifdef FOG_EXP2",
  7985. "uniform float fogDensity;",
  7986. "#else",
  7987. "uniform float fogNear;",
  7988. "uniform float fogFar;",
  7989. "#endif",
  7990. "#endif"
  7991. ].join("\n"),
  7992. fog_fragment: [
  7993. "#ifdef USE_FOG",
  7994. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  7995. "#ifdef FOG_EXP2",
  7996. "const float LOG2 = 1.442695;",
  7997. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  7998. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  7999. "#else",
  8000. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8001. "#endif",
  8002. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8003. "#endif"
  8004. ].join("\n"),
  8005. // ENVIRONMENT MAP
  8006. envmap_pars_fragment: [
  8007. "#ifdef USE_ENVMAP",
  8008. "uniform float reflectivity;",
  8009. "uniform samplerCube envMap;",
  8010. "uniform float flipEnvMap;",
  8011. "uniform int combine;",
  8012. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8013. "uniform bool useRefract;",
  8014. "uniform float refractionRatio;",
  8015. "#else",
  8016. "varying vec3 vReflect;",
  8017. "#endif",
  8018. "#endif"
  8019. ].join("\n"),
  8020. envmap_fragment: [
  8021. "#ifdef USE_ENVMAP",
  8022. "vec3 reflectVec;",
  8023. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8024. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8025. "if ( useRefract ) {",
  8026. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8027. "} else { ",
  8028. "reflectVec = reflect( cameraToVertex, normal );",
  8029. "}",
  8030. "#else",
  8031. "reflectVec = vReflect;",
  8032. "#endif",
  8033. "#ifdef DOUBLE_SIDED",
  8034. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8035. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8036. "#else",
  8037. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8038. "#endif",
  8039. "#ifdef GAMMA_INPUT",
  8040. "cubeColor.xyz *= cubeColor.xyz;",
  8041. "#endif",
  8042. "if ( combine == 1 ) {",
  8043. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8044. "} else if ( combine == 2 ) {",
  8045. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8046. "} else {",
  8047. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8048. "}",
  8049. "#endif"
  8050. ].join("\n"),
  8051. envmap_pars_vertex: [
  8052. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8053. "varying vec3 vReflect;",
  8054. "uniform float refractionRatio;",
  8055. "uniform bool useRefract;",
  8056. "#endif"
  8057. ].join("\n"),
  8058. worldpos_vertex : [
  8059. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8060. "#ifdef USE_SKINNING",
  8061. "vec4 worldPosition = modelMatrix * skinned;",
  8062. "#endif",
  8063. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8064. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8065. "#endif",
  8066. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8067. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8068. "#endif",
  8069. "#endif"
  8070. ].join("\n"),
  8071. envmap_vertex : [
  8072. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8073. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8074. "worldNormal = normalize( worldNormal );",
  8075. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8076. "if ( useRefract ) {",
  8077. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8078. "} else {",
  8079. "vReflect = reflect( cameraToVertex, worldNormal );",
  8080. "}",
  8081. "#endif"
  8082. ].join("\n"),
  8083. // COLOR MAP (particles)
  8084. map_particle_pars_fragment: [
  8085. "#ifdef USE_MAP",
  8086. "uniform sampler2D map;",
  8087. "#endif"
  8088. ].join("\n"),
  8089. map_particle_fragment: [
  8090. "#ifdef USE_MAP",
  8091. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8092. "#endif"
  8093. ].join("\n"),
  8094. // COLOR MAP (triangles)
  8095. map_pars_vertex: [
  8096. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8097. "varying vec2 vUv;",
  8098. "uniform vec4 offsetRepeat;",
  8099. "#endif"
  8100. ].join("\n"),
  8101. map_pars_fragment: [
  8102. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8103. "varying vec2 vUv;",
  8104. "#endif",
  8105. "#ifdef USE_MAP",
  8106. "uniform sampler2D map;",
  8107. "#endif",
  8108. ].join("\n"),
  8109. map_vertex: [
  8110. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8111. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8112. "#endif"
  8113. ].join("\n"),
  8114. map_fragment: [
  8115. "#ifdef USE_MAP",
  8116. "#ifdef GAMMA_INPUT",
  8117. "vec4 texelColor = texture2D( map, vUv );",
  8118. "texelColor.xyz *= texelColor.xyz;",
  8119. "gl_FragColor = gl_FragColor * texelColor;",
  8120. "#else",
  8121. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  8122. "#endif",
  8123. "#endif"
  8124. ].join("\n"),
  8125. // LIGHT MAP
  8126. lightmap_pars_fragment: [
  8127. "#ifdef USE_LIGHTMAP",
  8128. "varying vec2 vUv2;",
  8129. "uniform sampler2D lightMap;",
  8130. "#endif"
  8131. ].join("\n"),
  8132. lightmap_pars_vertex: [
  8133. "#ifdef USE_LIGHTMAP",
  8134. "varying vec2 vUv2;",
  8135. "#endif"
  8136. ].join("\n"),
  8137. lightmap_fragment: [
  8138. "#ifdef USE_LIGHTMAP",
  8139. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8140. "#endif"
  8141. ].join("\n"),
  8142. lightmap_vertex: [
  8143. "#ifdef USE_LIGHTMAP",
  8144. "vUv2 = uv2;",
  8145. "#endif"
  8146. ].join("\n"),
  8147. // BUMP MAP
  8148. bumpmap_pars_fragment: [
  8149. "#ifdef USE_BUMPMAP",
  8150. "uniform sampler2D bumpMap;",
  8151. "uniform float bumpScale;",
  8152. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8153. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8154. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8155. "vec2 dHdxy_fwd() {",
  8156. "vec2 dSTdx = dFdx( vUv );",
  8157. "vec2 dSTdy = dFdy( vUv );",
  8158. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8159. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8160. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8161. "return vec2( dBx, dBy );",
  8162. "}",
  8163. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8164. "vec3 vSigmaX = dFdx( surf_pos );",
  8165. "vec3 vSigmaY = dFdy( surf_pos );",
  8166. "vec3 vN = surf_norm;", // normalized
  8167. "vec3 R1 = cross( vSigmaY, vN );",
  8168. "vec3 R2 = cross( vN, vSigmaX );",
  8169. "float fDet = dot( vSigmaX, R1 );",
  8170. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8171. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8172. "}",
  8173. "#endif"
  8174. ].join("\n"),
  8175. // NORMAL MAP
  8176. normalmap_pars_fragment: [
  8177. "#ifdef USE_NORMALMAP",
  8178. "uniform sampler2D normalMap;",
  8179. "uniform vec2 normalScale;",
  8180. // Per-Pixel Tangent Space Normal Mapping
  8181. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8182. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8183. "vec3 q0 = dFdx( eye_pos.xyz );",
  8184. "vec3 q1 = dFdy( eye_pos.xyz );",
  8185. "vec2 st0 = dFdx( vUv.st );",
  8186. "vec2 st1 = dFdy( vUv.st );",
  8187. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8188. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8189. "vec3 N = normalize( surf_norm );",
  8190. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8191. "mapN.xy = normalScale * mapN.xy;",
  8192. "mat3 tsn = mat3( S, T, N );",
  8193. "return normalize( tsn * mapN );",
  8194. "}",
  8195. "#endif"
  8196. ].join("\n"),
  8197. // SPECULAR MAP
  8198. specularmap_pars_fragment: [
  8199. "#ifdef USE_SPECULARMAP",
  8200. "uniform sampler2D specularMap;",
  8201. "#endif"
  8202. ].join("\n"),
  8203. specularmap_fragment: [
  8204. "float specularStrength;",
  8205. "#ifdef USE_SPECULARMAP",
  8206. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8207. "specularStrength = texelSpecular.r;",
  8208. "#else",
  8209. "specularStrength = 1.0;",
  8210. "#endif"
  8211. ].join("\n"),
  8212. // LIGHTS LAMBERT
  8213. lights_lambert_pars_vertex: [
  8214. "uniform vec3 ambient;",
  8215. "uniform vec3 diffuse;",
  8216. "uniform vec3 emissive;",
  8217. "uniform vec3 ambientLightColor;",
  8218. "#if MAX_DIR_LIGHTS > 0",
  8219. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8220. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8221. "#endif",
  8222. "#if MAX_HEMI_LIGHTS > 0",
  8223. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8224. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8225. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8226. "#endif",
  8227. "#if MAX_POINT_LIGHTS > 0",
  8228. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8229. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8230. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8231. "#endif",
  8232. "#if MAX_SPOT_LIGHTS > 0",
  8233. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8234. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8235. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8236. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8237. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8238. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8239. "#endif",
  8240. "#ifdef WRAP_AROUND",
  8241. "uniform vec3 wrapRGB;",
  8242. "#endif"
  8243. ].join("\n"),
  8244. lights_lambert_vertex: [
  8245. "vLightFront = vec3( 0.0 );",
  8246. "#ifdef DOUBLE_SIDED",
  8247. "vLightBack = vec3( 0.0 );",
  8248. "#endif",
  8249. "transformedNormal = normalize( transformedNormal );",
  8250. "#if MAX_DIR_LIGHTS > 0",
  8251. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8252. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8253. "vec3 dirVector = normalize( lDirection.xyz );",
  8254. "float dotProduct = dot( transformedNormal, dirVector );",
  8255. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8256. "#ifdef DOUBLE_SIDED",
  8257. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8258. "#ifdef WRAP_AROUND",
  8259. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8260. "#endif",
  8261. "#endif",
  8262. "#ifdef WRAP_AROUND",
  8263. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8264. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8265. "#ifdef DOUBLE_SIDED",
  8266. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8267. "#endif",
  8268. "#endif",
  8269. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8270. "#ifdef DOUBLE_SIDED",
  8271. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8272. "#endif",
  8273. "}",
  8274. "#endif",
  8275. "#if MAX_POINT_LIGHTS > 0",
  8276. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8277. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8278. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8279. "float lDistance = 1.0;",
  8280. "if ( pointLightDistance[ i ] > 0.0 )",
  8281. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8282. "lVector = normalize( lVector );",
  8283. "float dotProduct = dot( transformedNormal, lVector );",
  8284. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8285. "#ifdef DOUBLE_SIDED",
  8286. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8287. "#ifdef WRAP_AROUND",
  8288. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8289. "#endif",
  8290. "#endif",
  8291. "#ifdef WRAP_AROUND",
  8292. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8293. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8294. "#ifdef DOUBLE_SIDED",
  8295. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  8296. "#endif",
  8297. "#endif",
  8298. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  8299. "#ifdef DOUBLE_SIDED",
  8300. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  8301. "#endif",
  8302. "}",
  8303. "#endif",
  8304. "#if MAX_SPOT_LIGHTS > 0",
  8305. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8306. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8307. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8308. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  8309. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8310. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8311. "float lDistance = 1.0;",
  8312. "if ( spotLightDistance[ i ] > 0.0 )",
  8313. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8314. "lVector = normalize( lVector );",
  8315. "float dotProduct = dot( transformedNormal, lVector );",
  8316. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8317. "#ifdef DOUBLE_SIDED",
  8318. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8319. "#ifdef WRAP_AROUND",
  8320. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8321. "#endif",
  8322. "#endif",
  8323. "#ifdef WRAP_AROUND",
  8324. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8325. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  8326. "#ifdef DOUBLE_SIDED",
  8327. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  8328. "#endif",
  8329. "#endif",
  8330. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  8331. "#ifdef DOUBLE_SIDED",
  8332. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  8333. "#endif",
  8334. "}",
  8335. "}",
  8336. "#endif",
  8337. "#if MAX_HEMI_LIGHTS > 0",
  8338. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8339. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8340. "vec3 lVector = normalize( lDirection.xyz );",
  8341. "float dotProduct = dot( transformedNormal, lVector );",
  8342. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8343. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  8344. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8345. "#ifdef DOUBLE_SIDED",
  8346. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  8347. "#endif",
  8348. "}",
  8349. "#endif",
  8350. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  8351. "#ifdef DOUBLE_SIDED",
  8352. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  8353. "#endif"
  8354. ].join("\n"),
  8355. // LIGHTS PHONG
  8356. lights_phong_pars_vertex: [
  8357. "#ifndef PHONG_PER_PIXEL",
  8358. "#if MAX_POINT_LIGHTS > 0",
  8359. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8360. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8361. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8362. "#endif",
  8363. "#if MAX_SPOT_LIGHTS > 0",
  8364. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8365. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8366. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8367. "#endif",
  8368. "#endif",
  8369. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8370. "varying vec3 vWorldPosition;",
  8371. "#endif"
  8372. ].join("\n"),
  8373. lights_phong_vertex: [
  8374. "#ifndef PHONG_PER_PIXEL",
  8375. "#if MAX_POINT_LIGHTS > 0",
  8376. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8377. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8378. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8379. "float lDistance = 1.0;",
  8380. "if ( pointLightDistance[ i ] > 0.0 )",
  8381. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8382. "vPointLight[ i ] = vec4( lVector, lDistance );",
  8383. "}",
  8384. "#endif",
  8385. "#if MAX_SPOT_LIGHTS > 0",
  8386. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8387. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8388. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8389. "float lDistance = 1.0;",
  8390. "if ( spotLightDistance[ i ] > 0.0 )",
  8391. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8392. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  8393. "}",
  8394. "#endif",
  8395. "#endif",
  8396. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8397. "vWorldPosition = worldPosition.xyz;",
  8398. "#endif"
  8399. ].join("\n"),
  8400. lights_phong_pars_fragment: [
  8401. "uniform vec3 ambientLightColor;",
  8402. "#if MAX_DIR_LIGHTS > 0",
  8403. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8404. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8405. "#endif",
  8406. "#if MAX_HEMI_LIGHTS > 0",
  8407. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8408. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8409. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8410. "#endif",
  8411. "#if MAX_POINT_LIGHTS > 0",
  8412. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8413. "#ifdef PHONG_PER_PIXEL",
  8414. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8415. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8416. "#else",
  8417. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8418. "#endif",
  8419. "#endif",
  8420. "#if MAX_SPOT_LIGHTS > 0",
  8421. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8422. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8423. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8424. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8425. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8426. "#ifdef PHONG_PER_PIXEL",
  8427. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8428. "#else",
  8429. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8430. "#endif",
  8431. "#endif",
  8432. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8433. "varying vec3 vWorldPosition;",
  8434. "#endif",
  8435. "#ifdef WRAP_AROUND",
  8436. "uniform vec3 wrapRGB;",
  8437. "#endif",
  8438. "varying vec3 vViewPosition;",
  8439. "varying vec3 vNormal;"
  8440. ].join("\n"),
  8441. lights_phong_fragment: [
  8442. "vec3 normal = normalize( vNormal );",
  8443. "vec3 viewPosition = normalize( vViewPosition );",
  8444. "#ifdef DOUBLE_SIDED",
  8445. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8446. "#endif",
  8447. "#ifdef USE_NORMALMAP",
  8448. "normal = perturbNormal2Arb( -viewPosition, normal );",
  8449. "#elif defined( USE_BUMPMAP )",
  8450. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  8451. "#endif",
  8452. "#if MAX_POINT_LIGHTS > 0",
  8453. "vec3 pointDiffuse = vec3( 0.0 );",
  8454. "vec3 pointSpecular = vec3( 0.0 );",
  8455. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8456. "#ifdef PHONG_PER_PIXEL",
  8457. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8458. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8459. "float lDistance = 1.0;",
  8460. "if ( pointLightDistance[ i ] > 0.0 )",
  8461. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8462. "lVector = normalize( lVector );",
  8463. "#else",
  8464. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  8465. "float lDistance = vPointLight[ i ].w;",
  8466. "#endif",
  8467. // diffuse
  8468. "float dotProduct = dot( normal, lVector );",
  8469. "#ifdef WRAP_AROUND",
  8470. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  8471. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8472. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  8473. "#else",
  8474. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  8475. "#endif",
  8476. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  8477. // specular
  8478. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  8479. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  8480. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  8481. "#ifdef PHYSICALLY_BASED_SHADING",
  8482. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8483. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8484. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  8485. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  8486. "#else",
  8487. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  8488. "#endif",
  8489. "}",
  8490. "#endif",
  8491. "#if MAX_SPOT_LIGHTS > 0",
  8492. "vec3 spotDiffuse = vec3( 0.0 );",
  8493. "vec3 spotSpecular = vec3( 0.0 );",
  8494. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8495. "#ifdef PHONG_PER_PIXEL",
  8496. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8497. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8498. "float lDistance = 1.0;",
  8499. "if ( spotLightDistance[ i ] > 0.0 )",
  8500. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8501. "lVector = normalize( lVector );",
  8502. "#else",
  8503. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  8504. "float lDistance = vSpotLight[ i ].w;",
  8505. "#endif",
  8506. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  8507. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8508. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8509. // diffuse
  8510. "float dotProduct = dot( normal, lVector );",
  8511. "#ifdef WRAP_AROUND",
  8512. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  8513. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8514. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  8515. "#else",
  8516. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  8517. "#endif",
  8518. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  8519. // specular
  8520. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  8521. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  8522. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  8523. "#ifdef PHYSICALLY_BASED_SHADING",
  8524. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8525. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8526. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  8527. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  8528. "#else",
  8529. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  8530. "#endif",
  8531. "}",
  8532. "}",
  8533. "#endif",
  8534. "#if MAX_DIR_LIGHTS > 0",
  8535. "vec3 dirDiffuse = vec3( 0.0 );",
  8536. "vec3 dirSpecular = vec3( 0.0 );" ,
  8537. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8538. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8539. "vec3 dirVector = normalize( lDirection.xyz );",
  8540. // diffuse
  8541. "float dotProduct = dot( normal, dirVector );",
  8542. "#ifdef WRAP_AROUND",
  8543. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  8544. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8545. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  8546. "#else",
  8547. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  8548. "#endif",
  8549. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  8550. // specular
  8551. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  8552. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  8553. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  8554. "#ifdef PHYSICALLY_BASED_SHADING",
  8555. /*
  8556. // fresnel term from skin shader
  8557. "const float F0 = 0.128;",
  8558. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  8559. "float exponential = pow( base, 5.0 );",
  8560. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  8561. */
  8562. /*
  8563. // fresnel term from fresnel shader
  8564. "const float mFresnelBias = 0.08;",
  8565. "const float mFresnelScale = 0.3;",
  8566. "const float mFresnelPower = 5.0;",
  8567. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  8568. */
  8569. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8570. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8571. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  8572. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  8573. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  8574. "#else",
  8575. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  8576. "#endif",
  8577. "}",
  8578. "#endif",
  8579. "#if MAX_HEMI_LIGHTS > 0",
  8580. "vec3 hemiDiffuse = vec3( 0.0 );",
  8581. "vec3 hemiSpecular = vec3( 0.0 );" ,
  8582. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8583. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8584. "vec3 lVector = normalize( lDirection.xyz );",
  8585. // diffuse
  8586. "float dotProduct = dot( normal, lVector );",
  8587. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8588. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8589. "hemiDiffuse += diffuse * hemiColor;",
  8590. // specular (sky light)
  8591. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  8592. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  8593. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  8594. // specular (ground light)
  8595. "vec3 lVectorGround = -lVector;",
  8596. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  8597. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  8598. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  8599. "#ifdef PHYSICALLY_BASED_SHADING",
  8600. "float dotProductGround = dot( normal, lVectorGround );",
  8601. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8602. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8603. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  8604. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  8605. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  8606. "#else",
  8607. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  8608. "#endif",
  8609. "}",
  8610. "#endif",
  8611. "vec3 totalDiffuse = vec3( 0.0 );",
  8612. "vec3 totalSpecular = vec3( 0.0 );",
  8613. "#if MAX_DIR_LIGHTS > 0",
  8614. "totalDiffuse += dirDiffuse;",
  8615. "totalSpecular += dirSpecular;",
  8616. "#endif",
  8617. "#if MAX_HEMI_LIGHTS > 0",
  8618. "totalDiffuse += hemiDiffuse;",
  8619. "totalSpecular += hemiSpecular;",
  8620. "#endif",
  8621. "#if MAX_POINT_LIGHTS > 0",
  8622. "totalDiffuse += pointDiffuse;",
  8623. "totalSpecular += pointSpecular;",
  8624. "#endif",
  8625. "#if MAX_SPOT_LIGHTS > 0",
  8626. "totalDiffuse += spotDiffuse;",
  8627. "totalSpecular += spotSpecular;",
  8628. "#endif",
  8629. "#ifdef METAL",
  8630. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  8631. "#else",
  8632. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  8633. "#endif"
  8634. ].join("\n"),
  8635. // VERTEX COLORS
  8636. color_pars_fragment: [
  8637. "#ifdef USE_COLOR",
  8638. "varying vec3 vColor;",
  8639. "#endif"
  8640. ].join("\n"),
  8641. color_fragment: [
  8642. "#ifdef USE_COLOR",
  8643. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  8644. "#endif"
  8645. ].join("\n"),
  8646. color_pars_vertex: [
  8647. "#ifdef USE_COLOR",
  8648. "varying vec3 vColor;",
  8649. "#endif"
  8650. ].join("\n"),
  8651. color_vertex: [
  8652. "#ifdef USE_COLOR",
  8653. "#ifdef GAMMA_INPUT",
  8654. "vColor = color * color;",
  8655. "#else",
  8656. "vColor = color;",
  8657. "#endif",
  8658. "#endif"
  8659. ].join("\n"),
  8660. // SKINNING
  8661. skinning_pars_vertex: [
  8662. "#ifdef USE_SKINNING",
  8663. "#ifdef BONE_TEXTURE",
  8664. "uniform sampler2D boneTexture;",
  8665. "mat4 getBoneMatrix( const in float i ) {",
  8666. "float j = i * 4.0;",
  8667. "float x = mod( j, N_BONE_PIXEL_X );",
  8668. "float y = floor( j / N_BONE_PIXEL_X );",
  8669. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  8670. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  8671. "y = dy * ( y + 0.5 );",
  8672. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  8673. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  8674. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  8675. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  8676. "mat4 bone = mat4( v1, v2, v3, v4 );",
  8677. "return bone;",
  8678. "}",
  8679. "#else",
  8680. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  8681. "mat4 getBoneMatrix( const in float i ) {",
  8682. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  8683. "return bone;",
  8684. "}",
  8685. "#endif",
  8686. "#endif"
  8687. ].join("\n"),
  8688. skinbase_vertex: [
  8689. "#ifdef USE_SKINNING",
  8690. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  8691. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  8692. "#endif"
  8693. ].join("\n"),
  8694. skinning_vertex: [
  8695. "#ifdef USE_SKINNING",
  8696. "#ifdef USE_MORPHTARGETS",
  8697. "vec4 skinVertex = vec4( morphed, 1.0 );",
  8698. "#else",
  8699. "vec4 skinVertex = vec4( position, 1.0 );",
  8700. "#endif",
  8701. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  8702. "skinned += boneMatY * skinVertex * skinWeight.y;",
  8703. "#endif"
  8704. ].join("\n"),
  8705. // MORPHING
  8706. morphtarget_pars_vertex: [
  8707. "#ifdef USE_MORPHTARGETS",
  8708. "#ifndef USE_MORPHNORMALS",
  8709. "uniform float morphTargetInfluences[ 8 ];",
  8710. "#else",
  8711. "uniform float morphTargetInfluences[ 4 ];",
  8712. "#endif",
  8713. "#endif"
  8714. ].join("\n"),
  8715. morphtarget_vertex: [
  8716. "#ifdef USE_MORPHTARGETS",
  8717. "vec3 morphed = vec3( 0.0 );",
  8718. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  8719. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  8720. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  8721. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  8722. "#ifndef USE_MORPHNORMALS",
  8723. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  8724. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  8725. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  8726. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  8727. "#endif",
  8728. "morphed += position;",
  8729. "#endif"
  8730. ].join("\n"),
  8731. default_vertex : [
  8732. "vec4 mvPosition;",
  8733. "#ifdef USE_SKINNING",
  8734. "mvPosition = modelViewMatrix * skinned;",
  8735. "#endif",
  8736. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  8737. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  8738. "#endif",
  8739. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  8740. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8741. "#endif",
  8742. "gl_Position = projectionMatrix * mvPosition;",
  8743. ].join("\n"),
  8744. morphnormal_vertex: [
  8745. "#ifdef USE_MORPHNORMALS",
  8746. "vec3 morphedNormal = vec3( 0.0 );",
  8747. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  8748. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  8749. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  8750. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  8751. "morphedNormal += normal;",
  8752. "#endif"
  8753. ].join("\n"),
  8754. skinnormal_vertex: [
  8755. "#ifdef USE_SKINNING",
  8756. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  8757. "skinMatrix += skinWeight.y * boneMatY;",
  8758. "#ifdef USE_MORPHNORMALS",
  8759. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  8760. "#else",
  8761. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  8762. "#endif",
  8763. "#endif"
  8764. ].join("\n"),
  8765. defaultnormal_vertex: [
  8766. "vec3 objectNormal;",
  8767. "#ifdef USE_SKINNING",
  8768. "objectNormal = skinnedNormal.xyz;",
  8769. "#endif",
  8770. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  8771. "objectNormal = morphedNormal;",
  8772. "#endif",
  8773. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  8774. "objectNormal = normal;",
  8775. "#endif",
  8776. "#ifdef FLIP_SIDED",
  8777. "objectNormal = -objectNormal;",
  8778. "#endif",
  8779. "vec3 transformedNormal = normalMatrix * objectNormal;",
  8780. ].join("\n"),
  8781. // SHADOW MAP
  8782. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  8783. // http://spidergl.org/example.php?id=6
  8784. // http://fabiensanglard.net/shadowmapping
  8785. shadowmap_pars_fragment: [
  8786. "#ifdef USE_SHADOWMAP",
  8787. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  8788. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  8789. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  8790. "uniform float shadowBias[ MAX_SHADOWS ];",
  8791. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8792. "float unpackDepth( const in vec4 rgba_depth ) {",
  8793. "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 );",
  8794. "float depth = dot( rgba_depth, bit_shift );",
  8795. "return depth;",
  8796. "}",
  8797. "#endif"
  8798. ].join("\n"),
  8799. shadowmap_fragment: [
  8800. "#ifdef USE_SHADOWMAP",
  8801. "#ifdef SHADOWMAP_DEBUG",
  8802. "vec3 frustumColors[3];",
  8803. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  8804. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  8805. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  8806. "#endif",
  8807. "#ifdef SHADOWMAP_CASCADE",
  8808. "int inFrustumCount = 0;",
  8809. "#endif",
  8810. "float fDepth;",
  8811. "vec3 shadowColor = vec3( 1.0 );",
  8812. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8813. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  8814. // "if ( something && something )" breaks ATI OpenGL shader compiler
  8815. // "if ( all( something, something ) )" using this instead
  8816. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  8817. "bool inFrustum = all( inFrustumVec );",
  8818. // don't shadow pixels outside of light frustum
  8819. // use just first frustum (for cascades)
  8820. // don't shadow pixels behind far plane of light frustum
  8821. "#ifdef SHADOWMAP_CASCADE",
  8822. "inFrustumCount += int( inFrustum );",
  8823. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  8824. "#else",
  8825. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  8826. "#endif",
  8827. "bool frustumTest = all( frustumTestVec );",
  8828. "if ( frustumTest ) {",
  8829. "shadowCoord.z += shadowBias[ i ];",
  8830. "#ifdef SHADOWMAP_SOFT",
  8831. // Percentage-close filtering
  8832. // (9 pixel kernel)
  8833. // http://fabiensanglard.net/shadowmappingPCF/
  8834. "float shadow = 0.0;",
  8835. /*
  8836. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  8837. // must enroll loop manually
  8838. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  8839. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  8840. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  8841. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  8842. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  8843. "float fDepth = unpackDepth( rgbaDepth );",
  8844. "if ( fDepth < shadowCoord.z )",
  8845. "shadow += 1.0;",
  8846. "}",
  8847. "shadow /= 9.0;",
  8848. */
  8849. "const float shadowDelta = 1.0 / 9.0;",
  8850. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  8851. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  8852. "float dx0 = -1.25 * xPixelOffset;",
  8853. "float dy0 = -1.25 * yPixelOffset;",
  8854. "float dx1 = 1.25 * xPixelOffset;",
  8855. "float dy1 = 1.25 * yPixelOffset;",
  8856. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  8857. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8858. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  8859. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8860. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  8861. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8862. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  8863. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8864. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  8865. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8866. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  8867. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8868. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  8869. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8870. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  8871. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8872. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  8873. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8874. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  8875. "#else",
  8876. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  8877. "float fDepth = unpackDepth( rgbaDepth );",
  8878. "if ( fDepth < shadowCoord.z )",
  8879. // spot with multiple shadows is darker
  8880. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  8881. // spot with multiple shadows has the same color as single shadow spot
  8882. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  8883. "#endif",
  8884. "}",
  8885. "#ifdef SHADOWMAP_DEBUG",
  8886. "#ifdef SHADOWMAP_CASCADE",
  8887. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  8888. "#else",
  8889. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  8890. "#endif",
  8891. "#endif",
  8892. "}",
  8893. "#ifdef GAMMA_OUTPUT",
  8894. "shadowColor *= shadowColor;",
  8895. "#endif",
  8896. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  8897. "#endif"
  8898. ].join("\n"),
  8899. shadowmap_pars_vertex: [
  8900. "#ifdef USE_SHADOWMAP",
  8901. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8902. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  8903. "#endif"
  8904. ].join("\n"),
  8905. shadowmap_vertex: [
  8906. "#ifdef USE_SHADOWMAP",
  8907. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8908. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  8909. "}",
  8910. "#endif"
  8911. ].join("\n"),
  8912. // ALPHATEST
  8913. alphatest_fragment: [
  8914. "#ifdef ALPHATEST",
  8915. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  8916. "#endif"
  8917. ].join("\n"),
  8918. // LINEAR SPACE
  8919. linear_to_gamma_fragment: [
  8920. "#ifdef GAMMA_OUTPUT",
  8921. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  8922. "#endif"
  8923. ].join("\n"),
  8924. };
  8925. THREE.UniformsUtils = {
  8926. merge: function ( uniforms ) {
  8927. var u, p, tmp, merged = {};
  8928. for ( u = 0; u < uniforms.length; u ++ ) {
  8929. tmp = this.clone( uniforms[ u ] );
  8930. for ( p in tmp ) {
  8931. merged[ p ] = tmp[ p ];
  8932. }
  8933. }
  8934. return merged;
  8935. },
  8936. clone: function ( uniforms_src ) {
  8937. var u, p, parameter, parameter_src, uniforms_dst = {};
  8938. for ( u in uniforms_src ) {
  8939. uniforms_dst[ u ] = {};
  8940. for ( p in uniforms_src[ u ] ) {
  8941. parameter_src = uniforms_src[ u ][ p ];
  8942. if ( parameter_src instanceof THREE.Color ||
  8943. parameter_src instanceof THREE.Vector2 ||
  8944. parameter_src instanceof THREE.Vector3 ||
  8945. parameter_src instanceof THREE.Vector4 ||
  8946. parameter_src instanceof THREE.Matrix4 ||
  8947. parameter_src instanceof THREE.Texture ) {
  8948. uniforms_dst[ u ][ p ] = parameter_src.clone();
  8949. } else if ( parameter_src instanceof Array ) {
  8950. uniforms_dst[ u ][ p ] = parameter_src.slice();
  8951. } else {
  8952. uniforms_dst[ u ][ p ] = parameter_src;
  8953. }
  8954. }
  8955. }
  8956. return uniforms_dst;
  8957. }
  8958. };
  8959. THREE.UniformsLib = {
  8960. common: {
  8961. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8962. "opacity" : { type: "f", value: 1.0 },
  8963. "map" : { type: "t", value: null },
  8964. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  8965. "lightMap" : { type: "t", value: null },
  8966. "specularMap" : { type: "t", value: null },
  8967. "envMap" : { type: "t", value: null },
  8968. "flipEnvMap" : { type: "f", value: -1 },
  8969. "useRefract" : { type: "i", value: 0 },
  8970. "reflectivity" : { type: "f", value: 1.0 },
  8971. "refractionRatio" : { type: "f", value: 0.98 },
  8972. "combine" : { type: "i", value: 0 },
  8973. "morphTargetInfluences" : { type: "f", value: 0 }
  8974. },
  8975. bump: {
  8976. "bumpMap" : { type: "t", value: null },
  8977. "bumpScale" : { type: "f", value: 1 }
  8978. },
  8979. normalmap: {
  8980. "normalMap" : { type: "t", value: null },
  8981. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  8982. },
  8983. fog : {
  8984. "fogDensity" : { type: "f", value: 0.00025 },
  8985. "fogNear" : { type: "f", value: 1 },
  8986. "fogFar" : { type: "f", value: 2000 },
  8987. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8988. },
  8989. lights: {
  8990. "ambientLightColor" : { type: "fv", value: [] },
  8991. "directionalLightDirection" : { type: "fv", value: [] },
  8992. "directionalLightColor" : { type: "fv", value: [] },
  8993. "hemisphereLightDirection" : { type: "fv", value: [] },
  8994. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  8995. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  8996. "pointLightColor" : { type: "fv", value: [] },
  8997. "pointLightPosition" : { type: "fv", value: [] },
  8998. "pointLightDistance" : { type: "fv1", value: [] },
  8999. "spotLightColor" : { type: "fv", value: [] },
  9000. "spotLightPosition" : { type: "fv", value: [] },
  9001. "spotLightDirection" : { type: "fv", value: [] },
  9002. "spotLightDistance" : { type: "fv1", value: [] },
  9003. "spotLightAngleCos" : { type: "fv1", value: [] },
  9004. "spotLightExponent" : { type: "fv1", value: [] }
  9005. },
  9006. particle: {
  9007. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9008. "opacity" : { type: "f", value: 1.0 },
  9009. "size" : { type: "f", value: 1.0 },
  9010. "scale" : { type: "f", value: 1.0 },
  9011. "map" : { type: "t", value: null },
  9012. "fogDensity" : { type: "f", value: 0.00025 },
  9013. "fogNear" : { type: "f", value: 1 },
  9014. "fogFar" : { type: "f", value: 2000 },
  9015. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9016. },
  9017. shadowmap: {
  9018. "shadowMap": { type: "tv", value: [] },
  9019. "shadowMapSize": { type: "v2v", value: [] },
  9020. "shadowBias" : { type: "fv1", value: [] },
  9021. "shadowDarkness": { type: "fv1", value: [] },
  9022. "shadowMatrix" : { type: "m4v", value: [] },
  9023. }
  9024. };
  9025. THREE.ShaderLib = {
  9026. 'depth': {
  9027. uniforms: {
  9028. "mNear": { type: "f", value: 1.0 },
  9029. "mFar" : { type: "f", value: 2000.0 },
  9030. "opacity" : { type: "f", value: 1.0 }
  9031. },
  9032. vertexShader: [
  9033. "void main() {",
  9034. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9035. "}"
  9036. ].join("\n"),
  9037. fragmentShader: [
  9038. "uniform float mNear;",
  9039. "uniform float mFar;",
  9040. "uniform float opacity;",
  9041. "void main() {",
  9042. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9043. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9044. "gl_FragColor = vec4( vec3( color ), opacity );",
  9045. "}"
  9046. ].join("\n")
  9047. },
  9048. 'normal': {
  9049. uniforms: {
  9050. "opacity" : { type: "f", value: 1.0 }
  9051. },
  9052. vertexShader: [
  9053. "varying vec3 vNormal;",
  9054. "void main() {",
  9055. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9056. "vNormal = normalize( normalMatrix * normal );",
  9057. "gl_Position = projectionMatrix * mvPosition;",
  9058. "}"
  9059. ].join("\n"),
  9060. fragmentShader: [
  9061. "uniform float opacity;",
  9062. "varying vec3 vNormal;",
  9063. "void main() {",
  9064. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9065. "}"
  9066. ].join("\n")
  9067. },
  9068. 'basic': {
  9069. uniforms: THREE.UniformsUtils.merge( [
  9070. THREE.UniformsLib[ "common" ],
  9071. THREE.UniformsLib[ "fog" ],
  9072. THREE.UniformsLib[ "shadowmap" ]
  9073. ] ),
  9074. vertexShader: [
  9075. THREE.ShaderChunk[ "map_pars_vertex" ],
  9076. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9077. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9078. THREE.ShaderChunk[ "color_pars_vertex" ],
  9079. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9080. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9081. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9082. "void main() {",
  9083. THREE.ShaderChunk[ "map_vertex" ],
  9084. THREE.ShaderChunk[ "lightmap_vertex" ],
  9085. THREE.ShaderChunk[ "color_vertex" ],
  9086. "#ifdef USE_ENVMAP",
  9087. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9088. THREE.ShaderChunk[ "skinbase_vertex" ],
  9089. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9090. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9091. "#endif",
  9092. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9093. THREE.ShaderChunk[ "skinning_vertex" ],
  9094. THREE.ShaderChunk[ "default_vertex" ],
  9095. THREE.ShaderChunk[ "worldpos_vertex" ],
  9096. THREE.ShaderChunk[ "envmap_vertex" ],
  9097. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9098. "}"
  9099. ].join("\n"),
  9100. fragmentShader: [
  9101. "uniform vec3 diffuse;",
  9102. "uniform float opacity;",
  9103. THREE.ShaderChunk[ "color_pars_fragment" ],
  9104. THREE.ShaderChunk[ "map_pars_fragment" ],
  9105. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9106. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9107. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9108. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9109. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9110. "void main() {",
  9111. "gl_FragColor = vec4( diffuse, opacity );",
  9112. THREE.ShaderChunk[ "map_fragment" ],
  9113. THREE.ShaderChunk[ "alphatest_fragment" ],
  9114. THREE.ShaderChunk[ "specularmap_fragment" ],
  9115. THREE.ShaderChunk[ "lightmap_fragment" ],
  9116. THREE.ShaderChunk[ "color_fragment" ],
  9117. THREE.ShaderChunk[ "envmap_fragment" ],
  9118. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9119. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9120. THREE.ShaderChunk[ "fog_fragment" ],
  9121. "}"
  9122. ].join("\n")
  9123. },
  9124. 'lambert': {
  9125. uniforms: THREE.UniformsUtils.merge( [
  9126. THREE.UniformsLib[ "common" ],
  9127. THREE.UniformsLib[ "fog" ],
  9128. THREE.UniformsLib[ "lights" ],
  9129. THREE.UniformsLib[ "shadowmap" ],
  9130. {
  9131. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9132. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9133. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9134. }
  9135. ] ),
  9136. vertexShader: [
  9137. "#define LAMBERT",
  9138. "varying vec3 vLightFront;",
  9139. "#ifdef DOUBLE_SIDED",
  9140. "varying vec3 vLightBack;",
  9141. "#endif",
  9142. THREE.ShaderChunk[ "map_pars_vertex" ],
  9143. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9144. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9145. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9146. THREE.ShaderChunk[ "color_pars_vertex" ],
  9147. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9148. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9149. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9150. "void main() {",
  9151. THREE.ShaderChunk[ "map_vertex" ],
  9152. THREE.ShaderChunk[ "lightmap_vertex" ],
  9153. THREE.ShaderChunk[ "color_vertex" ],
  9154. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9155. THREE.ShaderChunk[ "skinbase_vertex" ],
  9156. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9157. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9158. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9159. THREE.ShaderChunk[ "skinning_vertex" ],
  9160. THREE.ShaderChunk[ "default_vertex" ],
  9161. THREE.ShaderChunk[ "worldpos_vertex" ],
  9162. THREE.ShaderChunk[ "envmap_vertex" ],
  9163. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9164. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9165. "}"
  9166. ].join("\n"),
  9167. fragmentShader: [
  9168. "uniform float opacity;",
  9169. "varying vec3 vLightFront;",
  9170. "#ifdef DOUBLE_SIDED",
  9171. "varying vec3 vLightBack;",
  9172. "#endif",
  9173. THREE.ShaderChunk[ "color_pars_fragment" ],
  9174. THREE.ShaderChunk[ "map_pars_fragment" ],
  9175. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9176. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9177. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9178. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9179. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9180. "void main() {",
  9181. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9182. THREE.ShaderChunk[ "map_fragment" ],
  9183. THREE.ShaderChunk[ "alphatest_fragment" ],
  9184. THREE.ShaderChunk[ "specularmap_fragment" ],
  9185. "#ifdef DOUBLE_SIDED",
  9186. //"float isFront = float( gl_FrontFacing );",
  9187. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9188. "if ( gl_FrontFacing )",
  9189. "gl_FragColor.xyz *= vLightFront;",
  9190. "else",
  9191. "gl_FragColor.xyz *= vLightBack;",
  9192. "#else",
  9193. "gl_FragColor.xyz *= vLightFront;",
  9194. "#endif",
  9195. THREE.ShaderChunk[ "lightmap_fragment" ],
  9196. THREE.ShaderChunk[ "color_fragment" ],
  9197. THREE.ShaderChunk[ "envmap_fragment" ],
  9198. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9199. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9200. THREE.ShaderChunk[ "fog_fragment" ],
  9201. "}"
  9202. ].join("\n")
  9203. },
  9204. 'phong': {
  9205. uniforms: THREE.UniformsUtils.merge( [
  9206. THREE.UniformsLib[ "common" ],
  9207. THREE.UniformsLib[ "bump" ],
  9208. THREE.UniformsLib[ "normalmap" ],
  9209. THREE.UniformsLib[ "fog" ],
  9210. THREE.UniformsLib[ "lights" ],
  9211. THREE.UniformsLib[ "shadowmap" ],
  9212. {
  9213. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9214. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9215. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9216. "shininess": { type: "f", value: 30 },
  9217. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9218. }
  9219. ] ),
  9220. vertexShader: [
  9221. "#define PHONG",
  9222. "varying vec3 vViewPosition;",
  9223. "varying vec3 vNormal;",
  9224. THREE.ShaderChunk[ "map_pars_vertex" ],
  9225. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9226. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9227. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9228. THREE.ShaderChunk[ "color_pars_vertex" ],
  9229. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9230. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9231. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9232. "void main() {",
  9233. THREE.ShaderChunk[ "map_vertex" ],
  9234. THREE.ShaderChunk[ "lightmap_vertex" ],
  9235. THREE.ShaderChunk[ "color_vertex" ],
  9236. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9237. THREE.ShaderChunk[ "skinbase_vertex" ],
  9238. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9239. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9240. "vNormal = normalize( transformedNormal );",
  9241. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9242. THREE.ShaderChunk[ "skinning_vertex" ],
  9243. THREE.ShaderChunk[ "default_vertex" ],
  9244. "vViewPosition = -mvPosition.xyz;",
  9245. THREE.ShaderChunk[ "worldpos_vertex" ],
  9246. THREE.ShaderChunk[ "envmap_vertex" ],
  9247. THREE.ShaderChunk[ "lights_phong_vertex" ],
  9248. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9249. "}"
  9250. ].join("\n"),
  9251. fragmentShader: [
  9252. "uniform vec3 diffuse;",
  9253. "uniform float opacity;",
  9254. "uniform vec3 ambient;",
  9255. "uniform vec3 emissive;",
  9256. "uniform vec3 specular;",
  9257. "uniform float shininess;",
  9258. THREE.ShaderChunk[ "color_pars_fragment" ],
  9259. THREE.ShaderChunk[ "map_pars_fragment" ],
  9260. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9261. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9262. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9263. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  9264. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9265. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  9266. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  9267. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9268. "void main() {",
  9269. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9270. THREE.ShaderChunk[ "map_fragment" ],
  9271. THREE.ShaderChunk[ "alphatest_fragment" ],
  9272. THREE.ShaderChunk[ "specularmap_fragment" ],
  9273. THREE.ShaderChunk[ "lights_phong_fragment" ],
  9274. THREE.ShaderChunk[ "lightmap_fragment" ],
  9275. THREE.ShaderChunk[ "color_fragment" ],
  9276. THREE.ShaderChunk[ "envmap_fragment" ],
  9277. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9278. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9279. THREE.ShaderChunk[ "fog_fragment" ],
  9280. "}"
  9281. ].join("\n")
  9282. },
  9283. 'particle_basic': {
  9284. uniforms: THREE.UniformsUtils.merge( [
  9285. THREE.UniformsLib[ "particle" ],
  9286. THREE.UniformsLib[ "shadowmap" ]
  9287. ] ),
  9288. vertexShader: [
  9289. "uniform float size;",
  9290. "uniform float scale;",
  9291. THREE.ShaderChunk[ "color_pars_vertex" ],
  9292. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9293. "void main() {",
  9294. THREE.ShaderChunk[ "color_vertex" ],
  9295. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9296. "#ifdef USE_SIZEATTENUATION",
  9297. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  9298. "#else",
  9299. "gl_PointSize = size;",
  9300. "#endif",
  9301. "gl_Position = projectionMatrix * mvPosition;",
  9302. THREE.ShaderChunk[ "worldpos_vertex" ],
  9303. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9304. "}"
  9305. ].join("\n"),
  9306. fragmentShader: [
  9307. "uniform vec3 psColor;",
  9308. "uniform float opacity;",
  9309. THREE.ShaderChunk[ "color_pars_fragment" ],
  9310. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  9311. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9312. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9313. "void main() {",
  9314. "gl_FragColor = vec4( psColor, opacity );",
  9315. THREE.ShaderChunk[ "map_particle_fragment" ],
  9316. THREE.ShaderChunk[ "alphatest_fragment" ],
  9317. THREE.ShaderChunk[ "color_fragment" ],
  9318. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9319. THREE.ShaderChunk[ "fog_fragment" ],
  9320. "}"
  9321. ].join("\n")
  9322. },
  9323. 'dashed': {
  9324. uniforms: THREE.UniformsUtils.merge( [
  9325. THREE.UniformsLib[ "common" ],
  9326. THREE.UniformsLib[ "fog" ],
  9327. {
  9328. "scale": { type: "f", value: 1 },
  9329. "dashSize": { type: "f", value: 1 },
  9330. "totalSize": { type: "f", value: 2 }
  9331. }
  9332. ] ),
  9333. vertexShader: [
  9334. "uniform float scale;",
  9335. "attribute float lineDistance;",
  9336. "varying float vLineDistance;",
  9337. THREE.ShaderChunk[ "color_pars_vertex" ],
  9338. "void main() {",
  9339. THREE.ShaderChunk[ "color_vertex" ],
  9340. "vLineDistance = scale * lineDistance;",
  9341. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9342. "gl_Position = projectionMatrix * mvPosition;",
  9343. "}"
  9344. ].join("\n"),
  9345. fragmentShader: [
  9346. "uniform vec3 diffuse;",
  9347. "uniform float opacity;",
  9348. "uniform float dashSize;",
  9349. "uniform float totalSize;",
  9350. "varying float vLineDistance;",
  9351. THREE.ShaderChunk[ "color_pars_fragment" ],
  9352. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9353. "void main() {",
  9354. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  9355. "discard;",
  9356. "}",
  9357. "gl_FragColor = vec4( diffuse, opacity );",
  9358. THREE.ShaderChunk[ "color_fragment" ],
  9359. THREE.ShaderChunk[ "fog_fragment" ],
  9360. "}"
  9361. ].join("\n")
  9362. },
  9363. // Depth encoding into RGBA texture
  9364. // based on SpiderGL shadow map example
  9365. // http://spidergl.org/example.php?id=6
  9366. // originally from
  9367. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  9368. // see also here:
  9369. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  9370. 'depthRGBA': {
  9371. uniforms: {},
  9372. vertexShader: [
  9373. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9374. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9375. "void main() {",
  9376. THREE.ShaderChunk[ "skinbase_vertex" ],
  9377. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9378. THREE.ShaderChunk[ "skinning_vertex" ],
  9379. THREE.ShaderChunk[ "default_vertex" ],
  9380. "}"
  9381. ].join("\n"),
  9382. fragmentShader: [
  9383. "vec4 pack_depth( const in float depth ) {",
  9384. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  9385. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  9386. "vec4 res = fract( depth * bit_shift );",
  9387. "res -= res.xxyz * bit_mask;",
  9388. "return res;",
  9389. "}",
  9390. "void main() {",
  9391. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  9392. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  9393. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  9394. //"gl_FragData[ 0 ] = pack_depth( z );",
  9395. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  9396. "}"
  9397. ].join("\n")
  9398. }
  9399. };
  9400. /**
  9401. * @author supereggbert / http://www.paulbrunt.co.uk/
  9402. * @author mrdoob / http://mrdoob.com/
  9403. * @author alteredq / http://alteredqualia.com/
  9404. * @author szimek / https://github.com/szimek/
  9405. */
  9406. THREE.WebGLRenderer = function ( parameters ) {
  9407. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9408. parameters = parameters || {};
  9409. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  9410. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  9411. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  9412. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  9413. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  9414. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  9415. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  9416. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  9417. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  9418. // public properties
  9419. this.domElement = _canvas;
  9420. this.context = null;
  9421. // clearing
  9422. this.autoClear = true;
  9423. this.autoClearColor = true;
  9424. this.autoClearDepth = true;
  9425. this.autoClearStencil = true;
  9426. // scene graph
  9427. this.sortObjects = true;
  9428. this.autoUpdateObjects = true;
  9429. this.autoUpdateScene = true;
  9430. // physically based shading
  9431. this.gammaInput = false;
  9432. this.gammaOutput = false;
  9433. this.physicallyBasedShading = false;
  9434. // shadow map
  9435. this.shadowMapEnabled = false;
  9436. this.shadowMapAutoUpdate = true;
  9437. this.shadowMapSoft = true;
  9438. this.shadowMapCullFrontFaces = true;
  9439. this.shadowMapDebug = false;
  9440. this.shadowMapCascade = false;
  9441. // morphs
  9442. this.maxMorphTargets = 8;
  9443. this.maxMorphNormals = 4;
  9444. // flags
  9445. this.autoScaleCubemaps = true;
  9446. // custom render plugins
  9447. this.renderPluginsPre = [];
  9448. this.renderPluginsPost = [];
  9449. // info
  9450. this.info = {
  9451. memory: {
  9452. programs: 0,
  9453. geometries: 0,
  9454. textures: 0
  9455. },
  9456. render: {
  9457. calls: 0,
  9458. vertices: 0,
  9459. faces: 0,
  9460. points: 0
  9461. }
  9462. };
  9463. // internal properties
  9464. var _this = this,
  9465. _programs = [],
  9466. _programs_counter = 0,
  9467. // internal state cache
  9468. _currentProgram = null,
  9469. _currentFramebuffer = null,
  9470. _currentMaterialId = -1,
  9471. _currentGeometryGroupHash = null,
  9472. _currentCamera = null,
  9473. _geometryGroupCounter = 0,
  9474. _usedTextureUnits = 0,
  9475. // GL state cache
  9476. _oldDoubleSided = -1,
  9477. _oldFlipSided = -1,
  9478. _oldBlending = -1,
  9479. _oldBlendEquation = -1,
  9480. _oldBlendSrc = -1,
  9481. _oldBlendDst = -1,
  9482. _oldDepthTest = -1,
  9483. _oldDepthWrite = -1,
  9484. _oldPolygonOffset = null,
  9485. _oldPolygonOffsetFactor = null,
  9486. _oldPolygonOffsetUnits = null,
  9487. _oldLineWidth = null,
  9488. _viewportX = 0,
  9489. _viewportY = 0,
  9490. _viewportWidth = 0,
  9491. _viewportHeight = 0,
  9492. _currentWidth = 0,
  9493. _currentHeight = 0,
  9494. _enabledAttributes = {},
  9495. // frustum
  9496. _frustum = new THREE.Frustum(),
  9497. // camera matrices cache
  9498. _projScreenMatrix = new THREE.Matrix4(),
  9499. _projScreenMatrixPS = new THREE.Matrix4(),
  9500. _vector3 = new THREE.Vector4(),
  9501. // light arrays cache
  9502. _direction = new THREE.Vector3(),
  9503. _lightsNeedUpdate = true,
  9504. _lights = {
  9505. ambient: [ 0, 0, 0 ],
  9506. directional: { length: 0, colors: new Array(), positions: new Array() },
  9507. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  9508. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  9509. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  9510. };
  9511. // initialize
  9512. var _gl;
  9513. var _glExtensionTextureFloat;
  9514. var _glExtensionStandardDerivatives;
  9515. var _glExtensionTextureFilterAnisotropic;
  9516. var _glExtensionCompressedTextureS3TC;
  9517. initGL();
  9518. setDefaultGLState();
  9519. this.context = _gl;
  9520. // GPU capabilities
  9521. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  9522. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9523. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  9524. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9525. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  9526. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  9527. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  9528. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  9529. // API
  9530. this.getContext = function () {
  9531. return _gl;
  9532. };
  9533. this.supportsVertexTextures = function () {
  9534. return _supportsVertexTextures;
  9535. };
  9536. this.getMaxAnisotropy = function () {
  9537. return _maxAnisotropy;
  9538. };
  9539. this.setSize = function ( width, height ) {
  9540. _canvas.width = width;
  9541. _canvas.height = height;
  9542. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  9543. };
  9544. this.setViewport = function ( x, y, width, height ) {
  9545. _viewportX = x !== undefined ? x : 0;
  9546. _viewportY = y !== undefined ? y : 0;
  9547. _viewportWidth = width !== undefined ? width : _canvas.width;
  9548. _viewportHeight = height !== undefined ? height : _canvas.height;
  9549. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  9550. };
  9551. this.setScissor = function ( x, y, width, height ) {
  9552. _gl.scissor( x, y, width, height );
  9553. };
  9554. this.enableScissorTest = function ( enable ) {
  9555. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  9556. };
  9557. // Clearing
  9558. this.setClearColorHex = function ( hex, alpha ) {
  9559. _clearColor.setHex( hex );
  9560. _clearAlpha = alpha;
  9561. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9562. };
  9563. this.setClearColor = function ( color, alpha ) {
  9564. _clearColor.copy( color );
  9565. _clearAlpha = alpha;
  9566. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9567. };
  9568. this.getClearColor = function () {
  9569. return _clearColor;
  9570. };
  9571. this.getClearAlpha = function () {
  9572. return _clearAlpha;
  9573. };
  9574. this.clear = function ( color, depth, stencil ) {
  9575. var bits = 0;
  9576. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  9577. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  9578. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  9579. _gl.clear( bits );
  9580. };
  9581. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  9582. this.setRenderTarget( renderTarget );
  9583. this.clear( color, depth, stencil );
  9584. };
  9585. // Plugins
  9586. this.addPostPlugin = function ( plugin ) {
  9587. plugin.init( this );
  9588. this.renderPluginsPost.push( plugin );
  9589. };
  9590. this.addPrePlugin = function ( plugin ) {
  9591. plugin.init( this );
  9592. this.renderPluginsPre.push( plugin );
  9593. };
  9594. // Deallocation
  9595. this.deallocateObject = function ( object ) {
  9596. if ( ! object.__webglInit ) return;
  9597. object.__webglInit = false;
  9598. delete object._modelViewMatrix;
  9599. delete object._normalMatrix;
  9600. delete object._normalMatrixArray;
  9601. delete object._modelViewMatrixArray;
  9602. delete object._modelMatrixArray;
  9603. if ( object instanceof THREE.Mesh ) {
  9604. for ( var g in object.geometry.geometryGroups ) {
  9605. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  9606. }
  9607. } else if ( object instanceof THREE.Ribbon ) {
  9608. deleteRibbonBuffers( object.geometry );
  9609. } else if ( object instanceof THREE.Line ) {
  9610. deleteLineBuffers( object.geometry );
  9611. } else if ( object instanceof THREE.ParticleSystem ) {
  9612. deleteParticleBuffers( object.geometry );
  9613. }
  9614. };
  9615. this.deallocateTexture = function ( texture ) {
  9616. if ( ! texture.__webglInit ) return;
  9617. texture.__webglInit = false;
  9618. _gl.deleteTexture( texture.__webglTexture );
  9619. _this.info.memory.textures --;
  9620. };
  9621. this.deallocateRenderTarget = function ( renderTarget ) {
  9622. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  9623. _gl.deleteTexture( renderTarget.__webglTexture );
  9624. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9625. for ( var i = 0; i < 6; i ++ ) {
  9626. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  9627. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  9628. }
  9629. } else {
  9630. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  9631. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  9632. }
  9633. };
  9634. this.deallocateMaterial = function ( material ) {
  9635. var program = material.program;
  9636. if ( ! program ) return;
  9637. material.program = undefined;
  9638. // only deallocate GL program if this was the last use of shared program
  9639. // assumed there is only single copy of any program in the _programs list
  9640. // (that's how it's constructed)
  9641. var i, il, programInfo;
  9642. var deleteProgram = false;
  9643. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9644. programInfo = _programs[ i ];
  9645. if ( programInfo.program === program ) {
  9646. programInfo.usedTimes --;
  9647. if ( programInfo.usedTimes === 0 ) {
  9648. deleteProgram = true;
  9649. }
  9650. break;
  9651. }
  9652. }
  9653. if ( deleteProgram ) {
  9654. // avoid using array.splice, this is costlier than creating new array from scratch
  9655. var newPrograms = [];
  9656. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9657. programInfo = _programs[ i ];
  9658. if ( programInfo.program !== program ) {
  9659. newPrograms.push( programInfo );
  9660. }
  9661. }
  9662. _programs = newPrograms;
  9663. _gl.deleteProgram( program );
  9664. _this.info.memory.programs --;
  9665. }
  9666. };
  9667. // Rendering
  9668. this.updateShadowMap = function ( scene, camera ) {
  9669. _currentProgram = null;
  9670. _oldBlending = -1;
  9671. _oldDepthTest = -1;
  9672. _oldDepthWrite = -1;
  9673. _currentGeometryGroupHash = -1;
  9674. _currentMaterialId = -1;
  9675. _lightsNeedUpdate = true;
  9676. _oldDoubleSided = -1;
  9677. _oldFlipSided = -1;
  9678. this.shadowMapPlugin.update( scene, camera );
  9679. };
  9680. // Internal functions
  9681. // Buffer allocation
  9682. function createParticleBuffers ( geometry ) {
  9683. geometry.__webglVertexBuffer = _gl.createBuffer();
  9684. geometry.__webglColorBuffer = _gl.createBuffer();
  9685. _this.info.memory.geometries ++;
  9686. };
  9687. function createLineBuffers ( geometry ) {
  9688. geometry.__webglVertexBuffer = _gl.createBuffer();
  9689. geometry.__webglColorBuffer = _gl.createBuffer();
  9690. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  9691. _this.info.memory.geometries ++;
  9692. };
  9693. function createRibbonBuffers ( geometry ) {
  9694. geometry.__webglVertexBuffer = _gl.createBuffer();
  9695. geometry.__webglColorBuffer = _gl.createBuffer();
  9696. geometry.__webglNormalBuffer = _gl.createBuffer();
  9697. _this.info.memory.geometries ++;
  9698. };
  9699. function createMeshBuffers ( geometryGroup ) {
  9700. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  9701. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  9702. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  9703. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  9704. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  9705. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  9706. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  9707. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  9708. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  9709. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  9710. var m, ml;
  9711. if ( geometryGroup.numMorphTargets ) {
  9712. geometryGroup.__webglMorphTargetsBuffers = [];
  9713. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9714. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  9715. }
  9716. }
  9717. if ( geometryGroup.numMorphNormals ) {
  9718. geometryGroup.__webglMorphNormalsBuffers = [];
  9719. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9720. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  9721. }
  9722. }
  9723. _this.info.memory.geometries ++;
  9724. };
  9725. // Buffer deallocation
  9726. function deleteParticleBuffers ( geometry ) {
  9727. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9728. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9729. deleteCustomAttributesBuffers( geometry );
  9730. _this.info.memory.geometries --;
  9731. };
  9732. function deleteLineBuffers ( geometry ) {
  9733. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9734. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9735. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  9736. deleteCustomAttributesBuffers( geometry );
  9737. _this.info.memory.geometries --;
  9738. };
  9739. function deleteRibbonBuffers ( geometry ) {
  9740. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9741. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9742. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  9743. deleteCustomAttributesBuffers( geometry );
  9744. _this.info.memory.geometries --;
  9745. };
  9746. function deleteMeshBuffers ( geometryGroup ) {
  9747. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  9748. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  9749. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  9750. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  9751. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  9752. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  9753. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  9754. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  9755. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  9756. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  9757. var m, ml;
  9758. if ( geometryGroup.numMorphTargets ) {
  9759. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9760. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  9761. }
  9762. }
  9763. if ( geometryGroup.numMorphNormals ) {
  9764. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9765. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  9766. }
  9767. }
  9768. deleteCustomAttributesBuffers( geometryGroup );
  9769. _this.info.memory.geometries --;
  9770. };
  9771. function deleteCustomAttributesBuffers( geometry ) {
  9772. if ( geometry.__webglCustomAttributesList ) {
  9773. for ( var id in geometry.__webglCustomAttributesList ) {
  9774. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  9775. }
  9776. }
  9777. };
  9778. // Buffer initialization
  9779. function initCustomAttributes ( geometry, object ) {
  9780. var nvertices = geometry.vertices.length;
  9781. var material = object.material;
  9782. if ( material.attributes ) {
  9783. if ( geometry.__webglCustomAttributesList === undefined ) {
  9784. geometry.__webglCustomAttributesList = [];
  9785. }
  9786. for ( var a in material.attributes ) {
  9787. var attribute = material.attributes[ a ];
  9788. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9789. attribute.__webglInitialized = true;
  9790. var size = 1; // "f" and "i"
  9791. if ( attribute.type === "v2" ) size = 2;
  9792. else if ( attribute.type === "v3" ) size = 3;
  9793. else if ( attribute.type === "v4" ) size = 4;
  9794. else if ( attribute.type === "c" ) size = 3;
  9795. attribute.size = size;
  9796. attribute.array = new Float32Array( nvertices * size );
  9797. attribute.buffer = _gl.createBuffer();
  9798. attribute.buffer.belongsToAttribute = a;
  9799. attribute.needsUpdate = true;
  9800. }
  9801. geometry.__webglCustomAttributesList.push( attribute );
  9802. }
  9803. }
  9804. };
  9805. function initParticleBuffers ( geometry, object ) {
  9806. var nvertices = geometry.vertices.length;
  9807. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9808. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9809. geometry.__sortArray = [];
  9810. geometry.__webglParticleCount = nvertices;
  9811. initCustomAttributes ( geometry, object );
  9812. };
  9813. function initLineBuffers ( geometry, object ) {
  9814. var nvertices = geometry.vertices.length;
  9815. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9816. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9817. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  9818. geometry.__webglLineCount = nvertices;
  9819. initCustomAttributes ( geometry, object );
  9820. };
  9821. function initRibbonBuffers ( geometry, object ) {
  9822. var nvertices = geometry.vertices.length;
  9823. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9824. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9825. geometry.__normalArray = new Float32Array( nvertices * 3 );
  9826. geometry.__webglVertexCount = nvertices;
  9827. initCustomAttributes ( geometry, object );
  9828. };
  9829. function initMeshBuffers ( geometryGroup, object ) {
  9830. var geometry = object.geometry,
  9831. faces3 = geometryGroup.faces3,
  9832. faces4 = geometryGroup.faces4,
  9833. nvertices = faces3.length * 3 + faces4.length * 4,
  9834. ntris = faces3.length * 1 + faces4.length * 2,
  9835. nlines = faces3.length * 3 + faces4.length * 4,
  9836. material = getBufferMaterial( object, geometryGroup ),
  9837. uvType = bufferGuessUVType( material ),
  9838. normalType = bufferGuessNormalType( material ),
  9839. vertexColorType = bufferGuessVertexColorType( material );
  9840. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  9841. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  9842. if ( normalType ) {
  9843. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  9844. }
  9845. if ( geometry.hasTangents ) {
  9846. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  9847. }
  9848. if ( vertexColorType ) {
  9849. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  9850. }
  9851. if ( uvType ) {
  9852. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  9853. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  9854. }
  9855. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  9856. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  9857. }
  9858. }
  9859. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  9860. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  9861. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  9862. }
  9863. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  9864. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  9865. var m, ml;
  9866. if ( geometryGroup.numMorphTargets ) {
  9867. geometryGroup.__morphTargetsArrays = [];
  9868. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9869. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  9870. }
  9871. }
  9872. if ( geometryGroup.numMorphNormals ) {
  9873. geometryGroup.__morphNormalsArrays = [];
  9874. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9875. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  9876. }
  9877. }
  9878. geometryGroup.__webglFaceCount = ntris * 3;
  9879. geometryGroup.__webglLineCount = nlines * 2;
  9880. // custom attributes
  9881. if ( material.attributes ) {
  9882. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  9883. geometryGroup.__webglCustomAttributesList = [];
  9884. }
  9885. for ( var a in material.attributes ) {
  9886. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  9887. // attribute buffers which are correctly indexed in the setMeshBuffers function
  9888. var originalAttribute = material.attributes[ a ];
  9889. var attribute = {};
  9890. for ( var property in originalAttribute ) {
  9891. attribute[ property ] = originalAttribute[ property ];
  9892. }
  9893. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9894. attribute.__webglInitialized = true;
  9895. var size = 1; // "f" and "i"
  9896. if( attribute.type === "v2" ) size = 2;
  9897. else if( attribute.type === "v3" ) size = 3;
  9898. else if( attribute.type === "v4" ) size = 4;
  9899. else if( attribute.type === "c" ) size = 3;
  9900. attribute.size = size;
  9901. attribute.array = new Float32Array( nvertices * size );
  9902. attribute.buffer = _gl.createBuffer();
  9903. attribute.buffer.belongsToAttribute = a;
  9904. originalAttribute.needsUpdate = true;
  9905. attribute.__original = originalAttribute;
  9906. }
  9907. geometryGroup.__webglCustomAttributesList.push( attribute );
  9908. }
  9909. }
  9910. geometryGroup.__inittedArrays = true;
  9911. };
  9912. function getBufferMaterial( object, geometryGroup ) {
  9913. return object.material instanceof THREE.MeshFaceMaterial
  9914. ? object.material.materials[ geometryGroup.materialIndex ]
  9915. : object.material;
  9916. };
  9917. function materialNeedsSmoothNormals ( material ) {
  9918. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  9919. };
  9920. function bufferGuessNormalType ( material ) {
  9921. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  9922. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  9923. return false;
  9924. }
  9925. if ( materialNeedsSmoothNormals( material ) ) {
  9926. return THREE.SmoothShading;
  9927. } else {
  9928. return THREE.FlatShading;
  9929. }
  9930. };
  9931. function bufferGuessVertexColorType ( material ) {
  9932. if ( material.vertexColors ) {
  9933. return material.vertexColors;
  9934. }
  9935. return false;
  9936. };
  9937. function bufferGuessUVType ( material ) {
  9938. // material must use some texture to require uvs
  9939. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  9940. return true;
  9941. }
  9942. return false;
  9943. };
  9944. //
  9945. function initDirectBuffers( geometry ) {
  9946. var a, attribute, type;
  9947. for ( a in geometry.attributes ) {
  9948. if ( a === "index" ) {
  9949. type = _gl.ELEMENT_ARRAY_BUFFER;
  9950. } else {
  9951. type = _gl.ARRAY_BUFFER;
  9952. }
  9953. attribute = geometry.attributes[ a ];
  9954. attribute.buffer = _gl.createBuffer();
  9955. _gl.bindBuffer( type, attribute.buffer );
  9956. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  9957. }
  9958. };
  9959. // Buffer setting
  9960. function setParticleBuffers ( geometry, hint, object ) {
  9961. var v, c, vertex, offset, index, color,
  9962. vertices = geometry.vertices,
  9963. vl = vertices.length,
  9964. colors = geometry.colors,
  9965. cl = colors.length,
  9966. vertexArray = geometry.__vertexArray,
  9967. colorArray = geometry.__colorArray,
  9968. sortArray = geometry.__sortArray,
  9969. dirtyVertices = geometry.verticesNeedUpdate,
  9970. dirtyElements = geometry.elementsNeedUpdate,
  9971. dirtyColors = geometry.colorsNeedUpdate,
  9972. customAttributes = geometry.__webglCustomAttributesList,
  9973. i, il,
  9974. a, ca, cal, value,
  9975. customAttribute;
  9976. if ( object.sortParticles ) {
  9977. _projScreenMatrixPS.copy( _projScreenMatrix );
  9978. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  9979. for ( v = 0; v < vl; v ++ ) {
  9980. vertex = vertices[ v ];
  9981. _vector3.copy( vertex );
  9982. _projScreenMatrixPS.multiplyVector3( _vector3 );
  9983. sortArray[ v ] = [ _vector3.z, v ];
  9984. }
  9985. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  9986. for ( v = 0; v < vl; v ++ ) {
  9987. vertex = vertices[ sortArray[v][1] ];
  9988. offset = v * 3;
  9989. vertexArray[ offset ] = vertex.x;
  9990. vertexArray[ offset + 1 ] = vertex.y;
  9991. vertexArray[ offset + 2 ] = vertex.z;
  9992. }
  9993. for ( c = 0; c < cl; c ++ ) {
  9994. offset = c * 3;
  9995. color = colors[ sortArray[c][1] ];
  9996. colorArray[ offset ] = color.r;
  9997. colorArray[ offset + 1 ] = color.g;
  9998. colorArray[ offset + 2 ] = color.b;
  9999. }
  10000. if ( customAttributes ) {
  10001. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10002. customAttribute = customAttributes[ i ];
  10003. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  10004. offset = 0;
  10005. cal = customAttribute.value.length;
  10006. if ( customAttribute.size === 1 ) {
  10007. for ( ca = 0; ca < cal; ca ++ ) {
  10008. index = sortArray[ ca ][ 1 ];
  10009. customAttribute.array[ ca ] = customAttribute.value[ index ];
  10010. }
  10011. } else if ( customAttribute.size === 2 ) {
  10012. for ( ca = 0; ca < cal; ca ++ ) {
  10013. index = sortArray[ ca ][ 1 ];
  10014. value = customAttribute.value[ index ];
  10015. customAttribute.array[ offset ] = value.x;
  10016. customAttribute.array[ offset + 1 ] = value.y;
  10017. offset += 2;
  10018. }
  10019. } else if ( customAttribute.size === 3 ) {
  10020. if ( customAttribute.type === "c" ) {
  10021. for ( ca = 0; ca < cal; ca ++ ) {
  10022. index = sortArray[ ca ][ 1 ];
  10023. value = customAttribute.value[ index ];
  10024. customAttribute.array[ offset ] = value.r;
  10025. customAttribute.array[ offset + 1 ] = value.g;
  10026. customAttribute.array[ offset + 2 ] = value.b;
  10027. offset += 3;
  10028. }
  10029. } else {
  10030. for ( ca = 0; ca < cal; ca ++ ) {
  10031. index = sortArray[ ca ][ 1 ];
  10032. value = customAttribute.value[ index ];
  10033. customAttribute.array[ offset ] = value.x;
  10034. customAttribute.array[ offset + 1 ] = value.y;
  10035. customAttribute.array[ offset + 2 ] = value.z;
  10036. offset += 3;
  10037. }
  10038. }
  10039. } else if ( customAttribute.size === 4 ) {
  10040. for ( ca = 0; ca < cal; ca ++ ) {
  10041. index = sortArray[ ca ][ 1 ];
  10042. value = customAttribute.value[ index ];
  10043. customAttribute.array[ offset ] = value.x;
  10044. customAttribute.array[ offset + 1 ] = value.y;
  10045. customAttribute.array[ offset + 2 ] = value.z;
  10046. customAttribute.array[ offset + 3 ] = value.w;
  10047. offset += 4;
  10048. }
  10049. }
  10050. }
  10051. }
  10052. } else {
  10053. if ( dirtyVertices ) {
  10054. for ( v = 0; v < vl; v ++ ) {
  10055. vertex = vertices[ v ];
  10056. offset = v * 3;
  10057. vertexArray[ offset ] = vertex.x;
  10058. vertexArray[ offset + 1 ] = vertex.y;
  10059. vertexArray[ offset + 2 ] = vertex.z;
  10060. }
  10061. }
  10062. if ( dirtyColors ) {
  10063. for ( c = 0; c < cl; c ++ ) {
  10064. color = colors[ c ];
  10065. offset = c * 3;
  10066. colorArray[ offset ] = color.r;
  10067. colorArray[ offset + 1 ] = color.g;
  10068. colorArray[ offset + 2 ] = color.b;
  10069. }
  10070. }
  10071. if ( customAttributes ) {
  10072. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10073. customAttribute = customAttributes[ i ];
  10074. if ( customAttribute.needsUpdate &&
  10075. ( customAttribute.boundTo === undefined ||
  10076. customAttribute.boundTo === "vertices") ) {
  10077. cal = customAttribute.value.length;
  10078. offset = 0;
  10079. if ( customAttribute.size === 1 ) {
  10080. for ( ca = 0; ca < cal; ca ++ ) {
  10081. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10082. }
  10083. } else if ( customAttribute.size === 2 ) {
  10084. for ( ca = 0; ca < cal; ca ++ ) {
  10085. value = customAttribute.value[ ca ];
  10086. customAttribute.array[ offset ] = value.x;
  10087. customAttribute.array[ offset + 1 ] = value.y;
  10088. offset += 2;
  10089. }
  10090. } else if ( customAttribute.size === 3 ) {
  10091. if ( customAttribute.type === "c" ) {
  10092. for ( ca = 0; ca < cal; ca ++ ) {
  10093. value = customAttribute.value[ ca ];
  10094. customAttribute.array[ offset ] = value.r;
  10095. customAttribute.array[ offset + 1 ] = value.g;
  10096. customAttribute.array[ offset + 2 ] = value.b;
  10097. offset += 3;
  10098. }
  10099. } else {
  10100. for ( ca = 0; ca < cal; ca ++ ) {
  10101. value = customAttribute.value[ ca ];
  10102. customAttribute.array[ offset ] = value.x;
  10103. customAttribute.array[ offset + 1 ] = value.y;
  10104. customAttribute.array[ offset + 2 ] = value.z;
  10105. offset += 3;
  10106. }
  10107. }
  10108. } else if ( customAttribute.size === 4 ) {
  10109. for ( ca = 0; ca < cal; ca ++ ) {
  10110. value = customAttribute.value[ ca ];
  10111. customAttribute.array[ offset ] = value.x;
  10112. customAttribute.array[ offset + 1 ] = value.y;
  10113. customAttribute.array[ offset + 2 ] = value.z;
  10114. customAttribute.array[ offset + 3 ] = value.w;
  10115. offset += 4;
  10116. }
  10117. }
  10118. }
  10119. }
  10120. }
  10121. }
  10122. if ( dirtyVertices || object.sortParticles ) {
  10123. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10124. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10125. }
  10126. if ( dirtyColors || object.sortParticles ) {
  10127. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10128. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10129. }
  10130. if ( customAttributes ) {
  10131. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10132. customAttribute = customAttributes[ i ];
  10133. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10134. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10135. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10136. }
  10137. }
  10138. }
  10139. };
  10140. function setLineBuffers ( geometry, hint ) {
  10141. var v, c, d, vertex, offset, color,
  10142. vertices = geometry.vertices,
  10143. colors = geometry.colors,
  10144. lineDistances = geometry.lineDistances,
  10145. vl = vertices.length,
  10146. cl = colors.length,
  10147. dl = lineDistances.length,
  10148. vertexArray = geometry.__vertexArray,
  10149. colorArray = geometry.__colorArray,
  10150. lineDistanceArray = geometry.__lineDistanceArray,
  10151. dirtyVertices = geometry.verticesNeedUpdate,
  10152. dirtyColors = geometry.colorsNeedUpdate,
  10153. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  10154. customAttributes = geometry.__webglCustomAttributesList,
  10155. i, il,
  10156. a, ca, cal, value,
  10157. customAttribute;
  10158. if ( dirtyVertices ) {
  10159. for ( v = 0; v < vl; v ++ ) {
  10160. vertex = vertices[ v ];
  10161. offset = v * 3;
  10162. vertexArray[ offset ] = vertex.x;
  10163. vertexArray[ offset + 1 ] = vertex.y;
  10164. vertexArray[ offset + 2 ] = vertex.z;
  10165. }
  10166. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10167. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10168. }
  10169. if ( dirtyColors ) {
  10170. for ( c = 0; c < cl; c ++ ) {
  10171. color = colors[ c ];
  10172. offset = c * 3;
  10173. colorArray[ offset ] = color.r;
  10174. colorArray[ offset + 1 ] = color.g;
  10175. colorArray[ offset + 2 ] = color.b;
  10176. }
  10177. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10178. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10179. }
  10180. if ( dirtyLineDistances ) {
  10181. for ( d = 0; d < dl; d ++ ) {
  10182. lineDistanceArray[ d ] = lineDistances[ d ];
  10183. }
  10184. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  10185. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  10186. }
  10187. if ( customAttributes ) {
  10188. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10189. customAttribute = customAttributes[ i ];
  10190. if ( customAttribute.needsUpdate &&
  10191. ( customAttribute.boundTo === undefined ||
  10192. customAttribute.boundTo === "vertices" ) ) {
  10193. offset = 0;
  10194. cal = customAttribute.value.length;
  10195. if ( customAttribute.size === 1 ) {
  10196. for ( ca = 0; ca < cal; ca ++ ) {
  10197. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10198. }
  10199. } else if ( customAttribute.size === 2 ) {
  10200. for ( ca = 0; ca < cal; ca ++ ) {
  10201. value = customAttribute.value[ ca ];
  10202. customAttribute.array[ offset ] = value.x;
  10203. customAttribute.array[ offset + 1 ] = value.y;
  10204. offset += 2;
  10205. }
  10206. } else if ( customAttribute.size === 3 ) {
  10207. if ( customAttribute.type === "c" ) {
  10208. for ( ca = 0; ca < cal; ca ++ ) {
  10209. value = customAttribute.value[ ca ];
  10210. customAttribute.array[ offset ] = value.r;
  10211. customAttribute.array[ offset + 1 ] = value.g;
  10212. customAttribute.array[ offset + 2 ] = value.b;
  10213. offset += 3;
  10214. }
  10215. } else {
  10216. for ( ca = 0; ca < cal; ca ++ ) {
  10217. value = customAttribute.value[ ca ];
  10218. customAttribute.array[ offset ] = value.x;
  10219. customAttribute.array[ offset + 1 ] = value.y;
  10220. customAttribute.array[ offset + 2 ] = value.z;
  10221. offset += 3;
  10222. }
  10223. }
  10224. } else if ( customAttribute.size === 4 ) {
  10225. for ( ca = 0; ca < cal; ca ++ ) {
  10226. value = customAttribute.value[ ca ];
  10227. customAttribute.array[ offset ] = value.x;
  10228. customAttribute.array[ offset + 1 ] = value.y;
  10229. customAttribute.array[ offset + 2 ] = value.z;
  10230. customAttribute.array[ offset + 3 ] = value.w;
  10231. offset += 4;
  10232. }
  10233. }
  10234. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10235. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10236. }
  10237. }
  10238. }
  10239. };
  10240. function setRibbonBuffers ( geometry, hint ) {
  10241. var v, c, n, vertex, offset, color, normal,
  10242. i, il, ca, cal, customAttribute, value,
  10243. vertices = geometry.vertices,
  10244. colors = geometry.colors,
  10245. normals = geometry.normals,
  10246. vl = vertices.length,
  10247. cl = colors.length,
  10248. nl = normals.length,
  10249. vertexArray = geometry.__vertexArray,
  10250. colorArray = geometry.__colorArray,
  10251. normalArray = geometry.__normalArray,
  10252. dirtyVertices = geometry.verticesNeedUpdate,
  10253. dirtyColors = geometry.colorsNeedUpdate,
  10254. dirtyNormals = geometry.normalsNeedUpdate,
  10255. customAttributes = geometry.__webglCustomAttributesList;
  10256. if ( dirtyVertices ) {
  10257. for ( v = 0; v < vl; v ++ ) {
  10258. vertex = vertices[ v ];
  10259. offset = v * 3;
  10260. vertexArray[ offset ] = vertex.x;
  10261. vertexArray[ offset + 1 ] = vertex.y;
  10262. vertexArray[ offset + 2 ] = vertex.z;
  10263. }
  10264. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10265. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10266. }
  10267. if ( dirtyColors ) {
  10268. for ( c = 0; c < cl; c ++ ) {
  10269. color = colors[ c ];
  10270. offset = c * 3;
  10271. colorArray[ offset ] = color.r;
  10272. colorArray[ offset + 1 ] = color.g;
  10273. colorArray[ offset + 2 ] = color.b;
  10274. }
  10275. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10276. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10277. }
  10278. if ( dirtyNormals ) {
  10279. for ( n = 0; n < nl; n ++ ) {
  10280. normal = normals[ n ];
  10281. offset = n * 3;
  10282. normalArray[ offset ] = normal.x;
  10283. normalArray[ offset + 1 ] = normal.y;
  10284. normalArray[ offset + 2 ] = normal.z;
  10285. }
  10286. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  10287. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10288. }
  10289. if ( customAttributes ) {
  10290. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10291. customAttribute = customAttributes[ i ];
  10292. if ( customAttribute.needsUpdate &&
  10293. ( customAttribute.boundTo === undefined ||
  10294. customAttribute.boundTo === "vertices" ) ) {
  10295. offset = 0;
  10296. cal = customAttribute.value.length;
  10297. if ( customAttribute.size === 1 ) {
  10298. for ( ca = 0; ca < cal; ca ++ ) {
  10299. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10300. }
  10301. } else if ( customAttribute.size === 2 ) {
  10302. for ( ca = 0; ca < cal; ca ++ ) {
  10303. value = customAttribute.value[ ca ];
  10304. customAttribute.array[ offset ] = value.x;
  10305. customAttribute.array[ offset + 1 ] = value.y;
  10306. offset += 2;
  10307. }
  10308. } else if ( customAttribute.size === 3 ) {
  10309. if ( customAttribute.type === "c" ) {
  10310. for ( ca = 0; ca < cal; ca ++ ) {
  10311. value = customAttribute.value[ ca ];
  10312. customAttribute.array[ offset ] = value.r;
  10313. customAttribute.array[ offset + 1 ] = value.g;
  10314. customAttribute.array[ offset + 2 ] = value.b;
  10315. offset += 3;
  10316. }
  10317. } else {
  10318. for ( ca = 0; ca < cal; ca ++ ) {
  10319. value = customAttribute.value[ ca ];
  10320. customAttribute.array[ offset ] = value.x;
  10321. customAttribute.array[ offset + 1 ] = value.y;
  10322. customAttribute.array[ offset + 2 ] = value.z;
  10323. offset += 3;
  10324. }
  10325. }
  10326. } else if ( customAttribute.size === 4 ) {
  10327. for ( ca = 0; ca < cal; ca ++ ) {
  10328. value = customAttribute.value[ ca ];
  10329. customAttribute.array[ offset ] = value.x;
  10330. customAttribute.array[ offset + 1 ] = value.y;
  10331. customAttribute.array[ offset + 2 ] = value.z;
  10332. customAttribute.array[ offset + 3 ] = value.w;
  10333. offset += 4;
  10334. }
  10335. }
  10336. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10337. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10338. }
  10339. }
  10340. }
  10341. };
  10342. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  10343. if ( ! geometryGroup.__inittedArrays ) {
  10344. return;
  10345. }
  10346. var normalType = bufferGuessNormalType( material ),
  10347. vertexColorType = bufferGuessVertexColorType( material ),
  10348. uvType = bufferGuessUVType( material ),
  10349. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  10350. var f, fl, fi, face,
  10351. vertexNormals, faceNormal, normal,
  10352. vertexColors, faceColor,
  10353. vertexTangents,
  10354. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  10355. c1, c2, c3, c4,
  10356. sw1, sw2, sw3, sw4,
  10357. si1, si2, si3, si4,
  10358. sa1, sa2, sa3, sa4,
  10359. sb1, sb2, sb3, sb4,
  10360. m, ml, i, il,
  10361. vn, uvi, uv2i,
  10362. vk, vkl, vka,
  10363. nka, chf, faceVertexNormals,
  10364. a,
  10365. vertexIndex = 0,
  10366. offset = 0,
  10367. offset_uv = 0,
  10368. offset_uv2 = 0,
  10369. offset_face = 0,
  10370. offset_normal = 0,
  10371. offset_tangent = 0,
  10372. offset_line = 0,
  10373. offset_color = 0,
  10374. offset_skin = 0,
  10375. offset_morphTarget = 0,
  10376. offset_custom = 0,
  10377. offset_customSrc = 0,
  10378. value,
  10379. vertexArray = geometryGroup.__vertexArray,
  10380. uvArray = geometryGroup.__uvArray,
  10381. uv2Array = geometryGroup.__uv2Array,
  10382. normalArray = geometryGroup.__normalArray,
  10383. tangentArray = geometryGroup.__tangentArray,
  10384. colorArray = geometryGroup.__colorArray,
  10385. skinIndexArray = geometryGroup.__skinIndexArray,
  10386. skinWeightArray = geometryGroup.__skinWeightArray,
  10387. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  10388. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  10389. customAttributes = geometryGroup.__webglCustomAttributesList,
  10390. customAttribute,
  10391. faceArray = geometryGroup.__faceArray,
  10392. lineArray = geometryGroup.__lineArray,
  10393. geometry = object.geometry, // this is shared for all chunks
  10394. dirtyVertices = geometry.verticesNeedUpdate,
  10395. dirtyElements = geometry.elementsNeedUpdate,
  10396. dirtyUvs = geometry.uvsNeedUpdate,
  10397. dirtyNormals = geometry.normalsNeedUpdate,
  10398. dirtyTangents = geometry.tangentsNeedUpdate,
  10399. dirtyColors = geometry.colorsNeedUpdate,
  10400. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  10401. vertices = geometry.vertices,
  10402. chunk_faces3 = geometryGroup.faces3,
  10403. chunk_faces4 = geometryGroup.faces4,
  10404. obj_faces = geometry.faces,
  10405. obj_uvs = geometry.faceVertexUvs[ 0 ],
  10406. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  10407. obj_colors = geometry.colors,
  10408. obj_skinIndices = geometry.skinIndices,
  10409. obj_skinWeights = geometry.skinWeights,
  10410. morphTargets = geometry.morphTargets,
  10411. morphNormals = geometry.morphNormals;
  10412. if ( dirtyVertices ) {
  10413. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10414. face = obj_faces[ chunk_faces3[ f ] ];
  10415. v1 = vertices[ face.a ];
  10416. v2 = vertices[ face.b ];
  10417. v3 = vertices[ face.c ];
  10418. vertexArray[ offset ] = v1.x;
  10419. vertexArray[ offset + 1 ] = v1.y;
  10420. vertexArray[ offset + 2 ] = v1.z;
  10421. vertexArray[ offset + 3 ] = v2.x;
  10422. vertexArray[ offset + 4 ] = v2.y;
  10423. vertexArray[ offset + 5 ] = v2.z;
  10424. vertexArray[ offset + 6 ] = v3.x;
  10425. vertexArray[ offset + 7 ] = v3.y;
  10426. vertexArray[ offset + 8 ] = v3.z;
  10427. offset += 9;
  10428. }
  10429. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10430. face = obj_faces[ chunk_faces4[ f ] ];
  10431. v1 = vertices[ face.a ];
  10432. v2 = vertices[ face.b ];
  10433. v3 = vertices[ face.c ];
  10434. v4 = vertices[ face.d ];
  10435. vertexArray[ offset ] = v1.x;
  10436. vertexArray[ offset + 1 ] = v1.y;
  10437. vertexArray[ offset + 2 ] = v1.z;
  10438. vertexArray[ offset + 3 ] = v2.x;
  10439. vertexArray[ offset + 4 ] = v2.y;
  10440. vertexArray[ offset + 5 ] = v2.z;
  10441. vertexArray[ offset + 6 ] = v3.x;
  10442. vertexArray[ offset + 7 ] = v3.y;
  10443. vertexArray[ offset + 8 ] = v3.z;
  10444. vertexArray[ offset + 9 ] = v4.x;
  10445. vertexArray[ offset + 10 ] = v4.y;
  10446. vertexArray[ offset + 11 ] = v4.z;
  10447. offset += 12;
  10448. }
  10449. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10450. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10451. }
  10452. if ( dirtyMorphTargets ) {
  10453. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  10454. offset_morphTarget = 0;
  10455. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10456. chf = chunk_faces3[ f ];
  10457. face = obj_faces[ chf ];
  10458. // morph positions
  10459. v1 = morphTargets[ vk ].vertices[ face.a ];
  10460. v2 = morphTargets[ vk ].vertices[ face.b ];
  10461. v3 = morphTargets[ vk ].vertices[ face.c ];
  10462. vka = morphTargetsArrays[ vk ];
  10463. vka[ offset_morphTarget ] = v1.x;
  10464. vka[ offset_morphTarget + 1 ] = v1.y;
  10465. vka[ offset_morphTarget + 2 ] = v1.z;
  10466. vka[ offset_morphTarget + 3 ] = v2.x;
  10467. vka[ offset_morphTarget + 4 ] = v2.y;
  10468. vka[ offset_morphTarget + 5 ] = v2.z;
  10469. vka[ offset_morphTarget + 6 ] = v3.x;
  10470. vka[ offset_morphTarget + 7 ] = v3.y;
  10471. vka[ offset_morphTarget + 8 ] = v3.z;
  10472. // morph normals
  10473. if ( material.morphNormals ) {
  10474. if ( needsSmoothNormals ) {
  10475. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10476. n1 = faceVertexNormals.a;
  10477. n2 = faceVertexNormals.b;
  10478. n3 = faceVertexNormals.c;
  10479. } else {
  10480. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10481. n2 = n1;
  10482. n3 = n1;
  10483. }
  10484. nka = morphNormalsArrays[ vk ];
  10485. nka[ offset_morphTarget ] = n1.x;
  10486. nka[ offset_morphTarget + 1 ] = n1.y;
  10487. nka[ offset_morphTarget + 2 ] = n1.z;
  10488. nka[ offset_morphTarget + 3 ] = n2.x;
  10489. nka[ offset_morphTarget + 4 ] = n2.y;
  10490. nka[ offset_morphTarget + 5 ] = n2.z;
  10491. nka[ offset_morphTarget + 6 ] = n3.x;
  10492. nka[ offset_morphTarget + 7 ] = n3.y;
  10493. nka[ offset_morphTarget + 8 ] = n3.z;
  10494. }
  10495. //
  10496. offset_morphTarget += 9;
  10497. }
  10498. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10499. chf = chunk_faces4[ f ];
  10500. face = obj_faces[ chf ];
  10501. // morph positions
  10502. v1 = morphTargets[ vk ].vertices[ face.a ];
  10503. v2 = morphTargets[ vk ].vertices[ face.b ];
  10504. v3 = morphTargets[ vk ].vertices[ face.c ];
  10505. v4 = morphTargets[ vk ].vertices[ face.d ];
  10506. vka = morphTargetsArrays[ vk ];
  10507. vka[ offset_morphTarget ] = v1.x;
  10508. vka[ offset_morphTarget + 1 ] = v1.y;
  10509. vka[ offset_morphTarget + 2 ] = v1.z;
  10510. vka[ offset_morphTarget + 3 ] = v2.x;
  10511. vka[ offset_morphTarget + 4 ] = v2.y;
  10512. vka[ offset_morphTarget + 5 ] = v2.z;
  10513. vka[ offset_morphTarget + 6 ] = v3.x;
  10514. vka[ offset_morphTarget + 7 ] = v3.y;
  10515. vka[ offset_morphTarget + 8 ] = v3.z;
  10516. vka[ offset_morphTarget + 9 ] = v4.x;
  10517. vka[ offset_morphTarget + 10 ] = v4.y;
  10518. vka[ offset_morphTarget + 11 ] = v4.z;
  10519. // morph normals
  10520. if ( material.morphNormals ) {
  10521. if ( needsSmoothNormals ) {
  10522. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10523. n1 = faceVertexNormals.a;
  10524. n2 = faceVertexNormals.b;
  10525. n3 = faceVertexNormals.c;
  10526. n4 = faceVertexNormals.d;
  10527. } else {
  10528. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10529. n2 = n1;
  10530. n3 = n1;
  10531. n4 = n1;
  10532. }
  10533. nka = morphNormalsArrays[ vk ];
  10534. nka[ offset_morphTarget ] = n1.x;
  10535. nka[ offset_morphTarget + 1 ] = n1.y;
  10536. nka[ offset_morphTarget + 2 ] = n1.z;
  10537. nka[ offset_morphTarget + 3 ] = n2.x;
  10538. nka[ offset_morphTarget + 4 ] = n2.y;
  10539. nka[ offset_morphTarget + 5 ] = n2.z;
  10540. nka[ offset_morphTarget + 6 ] = n3.x;
  10541. nka[ offset_morphTarget + 7 ] = n3.y;
  10542. nka[ offset_morphTarget + 8 ] = n3.z;
  10543. nka[ offset_morphTarget + 9 ] = n4.x;
  10544. nka[ offset_morphTarget + 10 ] = n4.y;
  10545. nka[ offset_morphTarget + 11 ] = n4.z;
  10546. }
  10547. //
  10548. offset_morphTarget += 12;
  10549. }
  10550. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  10551. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  10552. if ( material.morphNormals ) {
  10553. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  10554. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  10555. }
  10556. }
  10557. }
  10558. if ( obj_skinWeights.length ) {
  10559. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10560. face = obj_faces[ chunk_faces3[ f ] ];
  10561. // weights
  10562. sw1 = obj_skinWeights[ face.a ];
  10563. sw2 = obj_skinWeights[ face.b ];
  10564. sw3 = obj_skinWeights[ face.c ];
  10565. skinWeightArray[ offset_skin ] = sw1.x;
  10566. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10567. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10568. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10569. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10570. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10571. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10572. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10573. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10574. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10575. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10576. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10577. // indices
  10578. si1 = obj_skinIndices[ face.a ];
  10579. si2 = obj_skinIndices[ face.b ];
  10580. si3 = obj_skinIndices[ face.c ];
  10581. skinIndexArray[ offset_skin ] = si1.x;
  10582. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10583. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10584. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10585. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10586. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10587. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10588. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10589. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10590. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10591. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10592. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10593. offset_skin += 12;
  10594. }
  10595. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10596. face = obj_faces[ chunk_faces4[ f ] ];
  10597. // weights
  10598. sw1 = obj_skinWeights[ face.a ];
  10599. sw2 = obj_skinWeights[ face.b ];
  10600. sw3 = obj_skinWeights[ face.c ];
  10601. sw4 = obj_skinWeights[ face.d ];
  10602. skinWeightArray[ offset_skin ] = sw1.x;
  10603. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10604. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10605. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10606. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10607. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10608. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10609. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10610. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10611. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10612. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10613. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10614. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  10615. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  10616. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  10617. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  10618. // indices
  10619. si1 = obj_skinIndices[ face.a ];
  10620. si2 = obj_skinIndices[ face.b ];
  10621. si3 = obj_skinIndices[ face.c ];
  10622. si4 = obj_skinIndices[ face.d ];
  10623. skinIndexArray[ offset_skin ] = si1.x;
  10624. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10625. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10626. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10627. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10628. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10629. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10630. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10631. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10632. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10633. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10634. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10635. skinIndexArray[ offset_skin + 12 ] = si4.x;
  10636. skinIndexArray[ offset_skin + 13 ] = si4.y;
  10637. skinIndexArray[ offset_skin + 14 ] = si4.z;
  10638. skinIndexArray[ offset_skin + 15 ] = si4.w;
  10639. offset_skin += 16;
  10640. }
  10641. if ( offset_skin > 0 ) {
  10642. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10643. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  10644. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10645. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  10646. }
  10647. }
  10648. if ( dirtyColors && vertexColorType ) {
  10649. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10650. face = obj_faces[ chunk_faces3[ f ] ];
  10651. vertexColors = face.vertexColors;
  10652. faceColor = face.color;
  10653. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  10654. c1 = vertexColors[ 0 ];
  10655. c2 = vertexColors[ 1 ];
  10656. c3 = vertexColors[ 2 ];
  10657. } else {
  10658. c1 = faceColor;
  10659. c2 = faceColor;
  10660. c3 = faceColor;
  10661. }
  10662. colorArray[ offset_color ] = c1.r;
  10663. colorArray[ offset_color + 1 ] = c1.g;
  10664. colorArray[ offset_color + 2 ] = c1.b;
  10665. colorArray[ offset_color + 3 ] = c2.r;
  10666. colorArray[ offset_color + 4 ] = c2.g;
  10667. colorArray[ offset_color + 5 ] = c2.b;
  10668. colorArray[ offset_color + 6 ] = c3.r;
  10669. colorArray[ offset_color + 7 ] = c3.g;
  10670. colorArray[ offset_color + 8 ] = c3.b;
  10671. offset_color += 9;
  10672. }
  10673. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10674. face = obj_faces[ chunk_faces4[ f ] ];
  10675. vertexColors = face.vertexColors;
  10676. faceColor = face.color;
  10677. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  10678. c1 = vertexColors[ 0 ];
  10679. c2 = vertexColors[ 1 ];
  10680. c3 = vertexColors[ 2 ];
  10681. c4 = vertexColors[ 3 ];
  10682. } else {
  10683. c1 = faceColor;
  10684. c2 = faceColor;
  10685. c3 = faceColor;
  10686. c4 = faceColor;
  10687. }
  10688. colorArray[ offset_color ] = c1.r;
  10689. colorArray[ offset_color + 1 ] = c1.g;
  10690. colorArray[ offset_color + 2 ] = c1.b;
  10691. colorArray[ offset_color + 3 ] = c2.r;
  10692. colorArray[ offset_color + 4 ] = c2.g;
  10693. colorArray[ offset_color + 5 ] = c2.b;
  10694. colorArray[ offset_color + 6 ] = c3.r;
  10695. colorArray[ offset_color + 7 ] = c3.g;
  10696. colorArray[ offset_color + 8 ] = c3.b;
  10697. colorArray[ offset_color + 9 ] = c4.r;
  10698. colorArray[ offset_color + 10 ] = c4.g;
  10699. colorArray[ offset_color + 11 ] = c4.b;
  10700. offset_color += 12;
  10701. }
  10702. if ( offset_color > 0 ) {
  10703. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10704. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10705. }
  10706. }
  10707. if ( dirtyTangents && geometry.hasTangents ) {
  10708. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10709. face = obj_faces[ chunk_faces3[ f ] ];
  10710. vertexTangents = face.vertexTangents;
  10711. t1 = vertexTangents[ 0 ];
  10712. t2 = vertexTangents[ 1 ];
  10713. t3 = vertexTangents[ 2 ];
  10714. tangentArray[ offset_tangent ] = t1.x;
  10715. tangentArray[ offset_tangent + 1 ] = t1.y;
  10716. tangentArray[ offset_tangent + 2 ] = t1.z;
  10717. tangentArray[ offset_tangent + 3 ] = t1.w;
  10718. tangentArray[ offset_tangent + 4 ] = t2.x;
  10719. tangentArray[ offset_tangent + 5 ] = t2.y;
  10720. tangentArray[ offset_tangent + 6 ] = t2.z;
  10721. tangentArray[ offset_tangent + 7 ] = t2.w;
  10722. tangentArray[ offset_tangent + 8 ] = t3.x;
  10723. tangentArray[ offset_tangent + 9 ] = t3.y;
  10724. tangentArray[ offset_tangent + 10 ] = t3.z;
  10725. tangentArray[ offset_tangent + 11 ] = t3.w;
  10726. offset_tangent += 12;
  10727. }
  10728. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10729. face = obj_faces[ chunk_faces4[ f ] ];
  10730. vertexTangents = face.vertexTangents;
  10731. t1 = vertexTangents[ 0 ];
  10732. t2 = vertexTangents[ 1 ];
  10733. t3 = vertexTangents[ 2 ];
  10734. t4 = vertexTangents[ 3 ];
  10735. tangentArray[ offset_tangent ] = t1.x;
  10736. tangentArray[ offset_tangent + 1 ] = t1.y;
  10737. tangentArray[ offset_tangent + 2 ] = t1.z;
  10738. tangentArray[ offset_tangent + 3 ] = t1.w;
  10739. tangentArray[ offset_tangent + 4 ] = t2.x;
  10740. tangentArray[ offset_tangent + 5 ] = t2.y;
  10741. tangentArray[ offset_tangent + 6 ] = t2.z;
  10742. tangentArray[ offset_tangent + 7 ] = t2.w;
  10743. tangentArray[ offset_tangent + 8 ] = t3.x;
  10744. tangentArray[ offset_tangent + 9 ] = t3.y;
  10745. tangentArray[ offset_tangent + 10 ] = t3.z;
  10746. tangentArray[ offset_tangent + 11 ] = t3.w;
  10747. tangentArray[ offset_tangent + 12 ] = t4.x;
  10748. tangentArray[ offset_tangent + 13 ] = t4.y;
  10749. tangentArray[ offset_tangent + 14 ] = t4.z;
  10750. tangentArray[ offset_tangent + 15 ] = t4.w;
  10751. offset_tangent += 16;
  10752. }
  10753. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10754. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  10755. }
  10756. if ( dirtyNormals && normalType ) {
  10757. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10758. face = obj_faces[ chunk_faces3[ f ] ];
  10759. vertexNormals = face.vertexNormals;
  10760. faceNormal = face.normal;
  10761. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  10762. for ( i = 0; i < 3; i ++ ) {
  10763. vn = vertexNormals[ i ];
  10764. normalArray[ offset_normal ] = vn.x;
  10765. normalArray[ offset_normal + 1 ] = vn.y;
  10766. normalArray[ offset_normal + 2 ] = vn.z;
  10767. offset_normal += 3;
  10768. }
  10769. } else {
  10770. for ( i = 0; i < 3; i ++ ) {
  10771. normalArray[ offset_normal ] = faceNormal.x;
  10772. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10773. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10774. offset_normal += 3;
  10775. }
  10776. }
  10777. }
  10778. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10779. face = obj_faces[ chunk_faces4[ f ] ];
  10780. vertexNormals = face.vertexNormals;
  10781. faceNormal = face.normal;
  10782. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  10783. for ( i = 0; i < 4; i ++ ) {
  10784. vn = vertexNormals[ i ];
  10785. normalArray[ offset_normal ] = vn.x;
  10786. normalArray[ offset_normal + 1 ] = vn.y;
  10787. normalArray[ offset_normal + 2 ] = vn.z;
  10788. offset_normal += 3;
  10789. }
  10790. } else {
  10791. for ( i = 0; i < 4; i ++ ) {
  10792. normalArray[ offset_normal ] = faceNormal.x;
  10793. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10794. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10795. offset_normal += 3;
  10796. }
  10797. }
  10798. }
  10799. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10800. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10801. }
  10802. if ( dirtyUvs && obj_uvs && uvType ) {
  10803. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10804. fi = chunk_faces3[ f ];
  10805. uv = obj_uvs[ fi ];
  10806. if ( uv === undefined ) continue;
  10807. for ( i = 0; i < 3; i ++ ) {
  10808. uvi = uv[ i ];
  10809. uvArray[ offset_uv ] = uvi.u;
  10810. uvArray[ offset_uv + 1 ] = uvi.v;
  10811. offset_uv += 2;
  10812. }
  10813. }
  10814. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10815. fi = chunk_faces4[ f ];
  10816. uv = obj_uvs[ fi ];
  10817. if ( uv === undefined ) continue;
  10818. for ( i = 0; i < 4; i ++ ) {
  10819. uvi = uv[ i ];
  10820. uvArray[ offset_uv ] = uvi.u;
  10821. uvArray[ offset_uv + 1 ] = uvi.v;
  10822. offset_uv += 2;
  10823. }
  10824. }
  10825. if ( offset_uv > 0 ) {
  10826. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10827. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  10828. }
  10829. }
  10830. if ( dirtyUvs && obj_uvs2 && uvType ) {
  10831. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10832. fi = chunk_faces3[ f ];
  10833. uv2 = obj_uvs2[ fi ];
  10834. if ( uv2 === undefined ) continue;
  10835. for ( i = 0; i < 3; i ++ ) {
  10836. uv2i = uv2[ i ];
  10837. uv2Array[ offset_uv2 ] = uv2i.u;
  10838. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10839. offset_uv2 += 2;
  10840. }
  10841. }
  10842. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10843. fi = chunk_faces4[ f ];
  10844. uv2 = obj_uvs2[ fi ];
  10845. if ( uv2 === undefined ) continue;
  10846. for ( i = 0; i < 4; i ++ ) {
  10847. uv2i = uv2[ i ];
  10848. uv2Array[ offset_uv2 ] = uv2i.u;
  10849. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10850. offset_uv2 += 2;
  10851. }
  10852. }
  10853. if ( offset_uv2 > 0 ) {
  10854. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10855. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  10856. }
  10857. }
  10858. if ( dirtyElements ) {
  10859. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10860. faceArray[ offset_face ] = vertexIndex;
  10861. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10862. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  10863. offset_face += 3;
  10864. lineArray[ offset_line ] = vertexIndex;
  10865. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10866. lineArray[ offset_line + 2 ] = vertexIndex;
  10867. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  10868. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10869. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10870. offset_line += 6;
  10871. vertexIndex += 3;
  10872. }
  10873. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10874. faceArray[ offset_face ] = vertexIndex;
  10875. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10876. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  10877. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  10878. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  10879. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  10880. offset_face += 6;
  10881. lineArray[ offset_line ] = vertexIndex;
  10882. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10883. lineArray[ offset_line + 2 ] = vertexIndex;
  10884. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  10885. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10886. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10887. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  10888. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  10889. offset_line += 8;
  10890. vertexIndex += 4;
  10891. }
  10892. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10893. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  10894. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10895. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  10896. }
  10897. if ( customAttributes ) {
  10898. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10899. customAttribute = customAttributes[ i ];
  10900. if ( ! customAttribute.__original.needsUpdate ) continue;
  10901. offset_custom = 0;
  10902. offset_customSrc = 0;
  10903. if ( customAttribute.size === 1 ) {
  10904. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10905. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10906. face = obj_faces[ chunk_faces3[ f ] ];
  10907. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10908. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10909. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10910. offset_custom += 3;
  10911. }
  10912. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10913. face = obj_faces[ chunk_faces4[ f ] ];
  10914. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10915. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10916. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10917. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  10918. offset_custom += 4;
  10919. }
  10920. } else if ( customAttribute.boundTo === "faces" ) {
  10921. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10922. value = customAttribute.value[ chunk_faces3[ f ] ];
  10923. customAttribute.array[ offset_custom ] = value;
  10924. customAttribute.array[ offset_custom + 1 ] = value;
  10925. customAttribute.array[ offset_custom + 2 ] = value;
  10926. offset_custom += 3;
  10927. }
  10928. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10929. value = customAttribute.value[ chunk_faces4[ f ] ];
  10930. customAttribute.array[ offset_custom ] = value;
  10931. customAttribute.array[ offset_custom + 1 ] = value;
  10932. customAttribute.array[ offset_custom + 2 ] = value;
  10933. customAttribute.array[ offset_custom + 3 ] = value;
  10934. offset_custom += 4;
  10935. }
  10936. }
  10937. } else if ( customAttribute.size === 2 ) {
  10938. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10939. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10940. face = obj_faces[ chunk_faces3[ f ] ];
  10941. v1 = customAttribute.value[ face.a ];
  10942. v2 = customAttribute.value[ face.b ];
  10943. v3 = customAttribute.value[ face.c ];
  10944. customAttribute.array[ offset_custom ] = v1.x;
  10945. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10946. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10947. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10948. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10949. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10950. offset_custom += 6;
  10951. }
  10952. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10953. face = obj_faces[ chunk_faces4[ f ] ];
  10954. v1 = customAttribute.value[ face.a ];
  10955. v2 = customAttribute.value[ face.b ];
  10956. v3 = customAttribute.value[ face.c ];
  10957. v4 = customAttribute.value[ face.d ];
  10958. customAttribute.array[ offset_custom ] = v1.x;
  10959. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10960. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10961. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10962. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10963. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10964. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10965. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10966. offset_custom += 8;
  10967. }
  10968. } else if ( customAttribute.boundTo === "faces" ) {
  10969. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10970. value = customAttribute.value[ chunk_faces3[ f ] ];
  10971. v1 = value;
  10972. v2 = value;
  10973. v3 = value;
  10974. customAttribute.array[ offset_custom ] = v1.x;
  10975. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10976. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10977. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10978. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10979. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10980. offset_custom += 6;
  10981. }
  10982. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10983. value = customAttribute.value[ chunk_faces4[ f ] ];
  10984. v1 = value;
  10985. v2 = value;
  10986. v3 = value;
  10987. v4 = value;
  10988. customAttribute.array[ offset_custom ] = v1.x;
  10989. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10990. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10991. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10992. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10993. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10994. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10995. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10996. offset_custom += 8;
  10997. }
  10998. }
  10999. } else if ( customAttribute.size === 3 ) {
  11000. var pp;
  11001. if ( customAttribute.type === "c" ) {
  11002. pp = [ "r", "g", "b" ];
  11003. } else {
  11004. pp = [ "x", "y", "z" ];
  11005. }
  11006. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11007. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11008. face = obj_faces[ chunk_faces3[ f ] ];
  11009. v1 = customAttribute.value[ face.a ];
  11010. v2 = customAttribute.value[ face.b ];
  11011. v3 = customAttribute.value[ face.c ];
  11012. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11013. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11014. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11015. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11016. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11017. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11018. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11019. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11020. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11021. offset_custom += 9;
  11022. }
  11023. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11024. face = obj_faces[ chunk_faces4[ f ] ];
  11025. v1 = customAttribute.value[ face.a ];
  11026. v2 = customAttribute.value[ face.b ];
  11027. v3 = customAttribute.value[ face.c ];
  11028. v4 = customAttribute.value[ face.d ];
  11029. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11030. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11031. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11032. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11033. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11034. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11035. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11036. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11037. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11038. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11039. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11040. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11041. offset_custom += 12;
  11042. }
  11043. } else if ( customAttribute.boundTo === "faces" ) {
  11044. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11045. value = customAttribute.value[ chunk_faces3[ f ] ];
  11046. v1 = value;
  11047. v2 = value;
  11048. v3 = value;
  11049. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11050. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11051. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11052. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11053. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11054. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11055. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11056. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11057. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11058. offset_custom += 9;
  11059. }
  11060. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11061. value = customAttribute.value[ chunk_faces4[ f ] ];
  11062. v1 = value;
  11063. v2 = value;
  11064. v3 = value;
  11065. v4 = value;
  11066. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11067. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11068. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11069. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11070. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11071. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11072. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11073. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11074. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11075. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11076. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11077. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11078. offset_custom += 12;
  11079. }
  11080. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11081. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11082. value = customAttribute.value[ chunk_faces3[ f ] ];
  11083. v1 = value[ 0 ];
  11084. v2 = value[ 1 ];
  11085. v3 = value[ 2 ];
  11086. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11087. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11088. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11089. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11090. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11091. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11092. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11093. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11094. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11095. offset_custom += 9;
  11096. }
  11097. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11098. value = customAttribute.value[ chunk_faces4[ f ] ];
  11099. v1 = value[ 0 ];
  11100. v2 = value[ 1 ];
  11101. v3 = value[ 2 ];
  11102. v4 = value[ 3 ];
  11103. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11104. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11105. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11106. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11107. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11108. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11109. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11110. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11111. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11112. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11113. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11114. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11115. offset_custom += 12;
  11116. }
  11117. }
  11118. } else if ( customAttribute.size === 4 ) {
  11119. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11120. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11121. face = obj_faces[ chunk_faces3[ f ] ];
  11122. v1 = customAttribute.value[ face.a ];
  11123. v2 = customAttribute.value[ face.b ];
  11124. v3 = customAttribute.value[ face.c ];
  11125. customAttribute.array[ offset_custom ] = v1.x;
  11126. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11127. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11128. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11129. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11130. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11131. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11132. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11133. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11134. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11135. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11136. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11137. offset_custom += 12;
  11138. }
  11139. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11140. face = obj_faces[ chunk_faces4[ f ] ];
  11141. v1 = customAttribute.value[ face.a ];
  11142. v2 = customAttribute.value[ face.b ];
  11143. v3 = customAttribute.value[ face.c ];
  11144. v4 = customAttribute.value[ face.d ];
  11145. customAttribute.array[ offset_custom ] = v1.x;
  11146. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11147. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11148. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11149. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11150. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11151. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11152. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11153. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11154. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11155. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11156. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11157. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11158. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11159. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11160. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11161. offset_custom += 16;
  11162. }
  11163. } else if ( customAttribute.boundTo === "faces" ) {
  11164. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11165. value = customAttribute.value[ chunk_faces3[ f ] ];
  11166. v1 = value;
  11167. v2 = value;
  11168. v3 = value;
  11169. customAttribute.array[ offset_custom ] = v1.x;
  11170. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11171. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11172. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11173. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11174. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11175. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11176. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11177. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11178. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11179. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11180. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11181. offset_custom += 12;
  11182. }
  11183. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11184. value = customAttribute.value[ chunk_faces4[ f ] ];
  11185. v1 = value;
  11186. v2 = value;
  11187. v3 = value;
  11188. v4 = value;
  11189. customAttribute.array[ offset_custom ] = v1.x;
  11190. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11191. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11192. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11193. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11194. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11195. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11196. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11197. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11198. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11199. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11200. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11201. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11202. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11203. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11204. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11205. offset_custom += 16;
  11206. }
  11207. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11208. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11209. value = customAttribute.value[ chunk_faces3[ f ] ];
  11210. v1 = value[ 0 ];
  11211. v2 = value[ 1 ];
  11212. v3 = value[ 2 ];
  11213. customAttribute.array[ offset_custom ] = v1.x;
  11214. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11215. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11216. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11217. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11218. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11219. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11220. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11221. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11222. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11223. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11224. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11225. offset_custom += 12;
  11226. }
  11227. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11228. value = customAttribute.value[ chunk_faces4[ f ] ];
  11229. v1 = value[ 0 ];
  11230. v2 = value[ 1 ];
  11231. v3 = value[ 2 ];
  11232. v4 = value[ 3 ];
  11233. customAttribute.array[ offset_custom ] = v1.x;
  11234. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11235. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11236. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11237. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11238. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11239. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11240. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11241. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11242. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11243. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11244. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11245. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11246. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11247. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11248. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11249. offset_custom += 16;
  11250. }
  11251. }
  11252. }
  11253. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11254. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11255. }
  11256. }
  11257. if ( dispose ) {
  11258. delete geometryGroup.__inittedArrays;
  11259. delete geometryGroup.__colorArray;
  11260. delete geometryGroup.__normalArray;
  11261. delete geometryGroup.__tangentArray;
  11262. delete geometryGroup.__uvArray;
  11263. delete geometryGroup.__uv2Array;
  11264. delete geometryGroup.__faceArray;
  11265. delete geometryGroup.__vertexArray;
  11266. delete geometryGroup.__lineArray;
  11267. delete geometryGroup.__skinIndexArray;
  11268. delete geometryGroup.__skinWeightArray;
  11269. }
  11270. };
  11271. function setDirectBuffers ( geometry, hint, dispose ) {
  11272. var attributes = geometry.attributes;
  11273. var index = attributes[ "index" ];
  11274. var position = attributes[ "position" ];
  11275. var normal = attributes[ "normal" ];
  11276. var uv = attributes[ "uv" ];
  11277. var color = attributes[ "color" ];
  11278. var tangent = attributes[ "tangent" ];
  11279. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  11280. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11281. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  11282. }
  11283. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  11284. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11285. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  11286. }
  11287. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  11288. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11289. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  11290. }
  11291. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  11292. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11293. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  11294. }
  11295. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  11296. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11297. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  11298. }
  11299. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  11300. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11301. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  11302. }
  11303. if ( dispose ) {
  11304. for ( var i in geometry.attributes ) {
  11305. delete geometry.attributes[ i ].array;
  11306. }
  11307. }
  11308. };
  11309. // Buffer rendering
  11310. this.renderBufferImmediate = function ( object, program, material ) {
  11311. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11312. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11313. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11314. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11315. if ( object.hasPositions ) {
  11316. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11317. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11318. _gl.enableVertexAttribArray( program.attributes.position );
  11319. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11320. }
  11321. if ( object.hasNormals ) {
  11322. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11323. if ( material.shading === THREE.FlatShading ) {
  11324. var nx, ny, nz,
  11325. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11326. normalArray,
  11327. i, il = object.count * 3;
  11328. for( i = 0; i < il; i += 9 ) {
  11329. normalArray = object.normalArray;
  11330. nax = normalArray[ i ];
  11331. nay = normalArray[ i + 1 ];
  11332. naz = normalArray[ i + 2 ];
  11333. nbx = normalArray[ i + 3 ];
  11334. nby = normalArray[ i + 4 ];
  11335. nbz = normalArray[ i + 5 ];
  11336. ncx = normalArray[ i + 6 ];
  11337. ncy = normalArray[ i + 7 ];
  11338. ncz = normalArray[ i + 8 ];
  11339. nx = ( nax + nbx + ncx ) / 3;
  11340. ny = ( nay + nby + ncy ) / 3;
  11341. nz = ( naz + nbz + ncz ) / 3;
  11342. normalArray[ i ] = nx;
  11343. normalArray[ i + 1 ] = ny;
  11344. normalArray[ i + 2 ] = nz;
  11345. normalArray[ i + 3 ] = nx;
  11346. normalArray[ i + 4 ] = ny;
  11347. normalArray[ i + 5 ] = nz;
  11348. normalArray[ i + 6 ] = nx;
  11349. normalArray[ i + 7 ] = ny;
  11350. normalArray[ i + 8 ] = nz;
  11351. }
  11352. }
  11353. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11354. _gl.enableVertexAttribArray( program.attributes.normal );
  11355. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11356. }
  11357. if ( object.hasUvs && material.map ) {
  11358. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11359. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11360. _gl.enableVertexAttribArray( program.attributes.uv );
  11361. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11362. }
  11363. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11364. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11365. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11366. _gl.enableVertexAttribArray( program.attributes.color );
  11367. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11368. }
  11369. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11370. object.count = 0;
  11371. };
  11372. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  11373. if ( material.visible === false ) return;
  11374. var program, attributes, linewidth, primitives, a, attribute;
  11375. program = setProgram( camera, lights, fog, material, object );
  11376. attributes = program.attributes;
  11377. var updateBuffers = false,
  11378. wireframeBit = material.wireframe ? 1 : 0,
  11379. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11380. if ( geometryHash !== _currentGeometryGroupHash ) {
  11381. _currentGeometryGroupHash = geometryHash;
  11382. updateBuffers = true;
  11383. }
  11384. if ( updateBuffers ) {
  11385. disableAttributes();
  11386. }
  11387. // render mesh
  11388. if ( object instanceof THREE.Mesh ) {
  11389. var index = geometry.attributes[ "index" ];
  11390. // indexed triangles
  11391. if ( index ) {
  11392. var offsets = geometry.offsets;
  11393. // if there is more than 1 chunk
  11394. // must set attribute pointers to use new offsets for each chunk
  11395. // even if geometry and materials didn't change
  11396. if ( offsets.length > 1 ) updateBuffers = true;
  11397. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11398. var startIndex = offsets[ i ].index;
  11399. if ( updateBuffers ) {
  11400. // vertices
  11401. var position = geometry.attributes[ "position" ];
  11402. var positionSize = position.itemSize;
  11403. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11404. enableAttribute( attributes.position );
  11405. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  11406. // normals
  11407. var normal = geometry.attributes[ "normal" ];
  11408. if ( attributes.normal >= 0 && normal ) {
  11409. var normalSize = normal.itemSize;
  11410. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11411. enableAttribute( attributes.normal );
  11412. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  11413. }
  11414. // uvs
  11415. var uv = geometry.attributes[ "uv" ];
  11416. if ( attributes.uv >= 0 && uv ) {
  11417. var uvSize = uv.itemSize;
  11418. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11419. enableAttribute( attributes.uv );
  11420. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  11421. }
  11422. // colors
  11423. var color = geometry.attributes[ "color" ];
  11424. if ( attributes.color >= 0 && color ) {
  11425. var colorSize = color.itemSize;
  11426. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11427. enableAttribute( attributes.color );
  11428. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  11429. }
  11430. // tangents
  11431. var tangent = geometry.attributes[ "tangent" ];
  11432. if ( attributes.tangent >= 0 && tangent ) {
  11433. var tangentSize = tangent.itemSize;
  11434. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11435. enableAttribute( attributes.tangent );
  11436. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  11437. }
  11438. // indices
  11439. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11440. }
  11441. // render indexed triangles
  11442. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  11443. _this.info.render.calls ++;
  11444. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11445. _this.info.render.faces += offsets[ i ].count / 3;
  11446. }
  11447. // non-indexed triangles
  11448. } else {
  11449. if ( updateBuffers ) {
  11450. // vertices
  11451. var position = geometry.attributes[ "position" ];
  11452. var positionSize = position.itemSize;
  11453. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11454. enableAttribute( attributes.position );
  11455. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  11456. // normals
  11457. var normal = geometry.attributes[ "normal" ];
  11458. if ( attributes.normal >= 0 && normal ) {
  11459. var normalSize = normal.itemSize;
  11460. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11461. enableAttribute( attributes.normal );
  11462. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  11463. }
  11464. // uvs
  11465. var uv = geometry.attributes[ "uv" ];
  11466. if ( attributes.uv >= 0 && uv ) {
  11467. var uvSize = uv.itemSize;
  11468. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11469. enableAttribute( attributes.uv );
  11470. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  11471. }
  11472. // colors
  11473. var color = geometry.attributes[ "color" ];
  11474. if ( attributes.color >= 0 && color ) {
  11475. var colorSize = color.itemSize;
  11476. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11477. enableAttribute( attributes.color );
  11478. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  11479. }
  11480. // tangents
  11481. var tangent = geometry.attributes[ "tangent" ];
  11482. if ( attributes.tangent >= 0 && tangent ) {
  11483. var tangentSize = tangent.itemSize;
  11484. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11485. enableAttribute( attributes.tangent );
  11486. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  11487. }
  11488. }
  11489. // render non-indexed triangles
  11490. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  11491. _this.info.render.calls ++;
  11492. _this.info.render.vertices += position.numItems / 3;
  11493. _this.info.render.faces += position.numItems / 3 / 3;
  11494. }
  11495. // render particles
  11496. } else if ( object instanceof THREE.ParticleSystem ) {
  11497. if ( updateBuffers ) {
  11498. // vertices
  11499. var position = geometry.attributes[ "position" ];
  11500. var positionSize = position.itemSize;
  11501. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11502. enableAttribute( attributes.position );
  11503. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  11504. // colors
  11505. var color = geometry.attributes[ "color" ];
  11506. if ( attributes.color >= 0 && color ) {
  11507. var colorSize = color.itemSize;
  11508. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11509. enableAttribute( attributes.color );
  11510. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  11511. }
  11512. // render particles
  11513. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  11514. _this.info.render.calls ++;
  11515. _this.info.render.points += position.numItems / 3;
  11516. }
  11517. }
  11518. };
  11519. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  11520. if ( material.visible === false ) return;
  11521. var program, attributes, linewidth, primitives, a, attribute, i, il;
  11522. program = setProgram( camera, lights, fog, material, object );
  11523. attributes = program.attributes;
  11524. var updateBuffers = false,
  11525. wireframeBit = material.wireframe ? 1 : 0,
  11526. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11527. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  11528. _currentGeometryGroupHash = geometryGroupHash;
  11529. updateBuffers = true;
  11530. }
  11531. if ( updateBuffers ) {
  11532. disableAttributes();
  11533. }
  11534. // vertices
  11535. if ( !material.morphTargets && attributes.position >= 0 ) {
  11536. if ( updateBuffers ) {
  11537. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11538. enableAttribute( attributes.position );
  11539. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11540. }
  11541. } else {
  11542. if ( object.morphTargetBase ) {
  11543. setupMorphTargets( material, geometryGroup, object );
  11544. }
  11545. }
  11546. if ( updateBuffers ) {
  11547. // custom attributes
  11548. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  11549. if ( geometryGroup.__webglCustomAttributesList ) {
  11550. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  11551. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  11552. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  11553. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  11554. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  11555. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  11556. }
  11557. }
  11558. }
  11559. // colors
  11560. if ( attributes.color >= 0 ) {
  11561. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11562. enableAttribute( attributes.color );
  11563. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11564. }
  11565. // normals
  11566. if ( attributes.normal >= 0 ) {
  11567. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11568. enableAttribute( attributes.normal );
  11569. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11570. }
  11571. // tangents
  11572. if ( attributes.tangent >= 0 ) {
  11573. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11574. enableAttribute( attributes.tangent );
  11575. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  11576. }
  11577. // uvs
  11578. if ( attributes.uv >= 0 ) {
  11579. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11580. enableAttribute( attributes.uv );
  11581. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11582. }
  11583. if ( attributes.uv2 >= 0 ) {
  11584. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11585. enableAttribute( attributes.uv2 );
  11586. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  11587. }
  11588. if ( material.skinning &&
  11589. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11590. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11591. enableAttribute( attributes.skinIndex );
  11592. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  11593. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11594. enableAttribute( attributes.skinWeight );
  11595. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  11596. }
  11597. // line distances
  11598. if ( attributes.lineDistance >= 0 ) {
  11599. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  11600. enableAttribute( attributes.lineDistance );
  11601. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  11602. }
  11603. }
  11604. // render mesh
  11605. if ( object instanceof THREE.Mesh ) {
  11606. // wireframe
  11607. if ( material.wireframe ) {
  11608. setLineWidth( material.wireframeLinewidth );
  11609. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11610. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  11611. // triangles
  11612. } else {
  11613. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11614. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  11615. }
  11616. _this.info.render.calls ++;
  11617. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  11618. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11619. // render lines
  11620. } else if ( object instanceof THREE.Line ) {
  11621. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  11622. setLineWidth( material.linewidth );
  11623. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  11624. _this.info.render.calls ++;
  11625. // render particles
  11626. } else if ( object instanceof THREE.ParticleSystem ) {
  11627. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  11628. _this.info.render.calls ++;
  11629. _this.info.render.points += geometryGroup.__webglParticleCount;
  11630. // render ribbon
  11631. } else if ( object instanceof THREE.Ribbon ) {
  11632. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  11633. _this.info.render.calls ++;
  11634. }
  11635. };
  11636. function enableAttribute( attribute ) {
  11637. if ( ! _enabledAttributes[ attribute ] ) {
  11638. _gl.enableVertexAttribArray( attribute );
  11639. _enabledAttributes[ attribute ] = true;
  11640. }
  11641. };
  11642. function disableAttributes() {
  11643. for ( var attribute in _enabledAttributes ) {
  11644. if ( _enabledAttributes[ attribute ] ) {
  11645. _gl.disableVertexAttribArray( attribute );
  11646. _enabledAttributes[ attribute ] = false;
  11647. }
  11648. }
  11649. };
  11650. function setupMorphTargets ( material, geometryGroup, object ) {
  11651. // set base
  11652. var attributes = material.program.attributes;
  11653. if ( object.morphTargetBase !== -1 ) {
  11654. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  11655. enableAttribute( attributes.position );
  11656. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11657. } else if ( attributes.position >= 0 ) {
  11658. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11659. enableAttribute( attributes.position );
  11660. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11661. }
  11662. if ( object.morphTargetForcedOrder.length ) {
  11663. // set forced order
  11664. var m = 0;
  11665. var order = object.morphTargetForcedOrder;
  11666. var influences = object.morphTargetInfluences;
  11667. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11668. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  11669. enableAttribute( attributes[ "morphTarget" + m ] );
  11670. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11671. if ( material.morphNormals ) {
  11672. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  11673. enableAttribute( attributes[ "morphNormal" + m ] );
  11674. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11675. }
  11676. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11677. m ++;
  11678. }
  11679. } else {
  11680. // find the most influencing
  11681. var influence, activeInfluenceIndices = [];
  11682. var influences = object.morphTargetInfluences;
  11683. var i, il = influences.length;
  11684. for ( i = 0; i < il; i ++ ) {
  11685. influence = influences[ i ];
  11686. if ( influence > 0 ) {
  11687. activeInfluenceIndices.push( [ i, influence ] );
  11688. }
  11689. }
  11690. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11691. activeInfluenceIndices.sort( numericalSort );
  11692. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11693. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11694. activeInfluenceIndices.sort( numericalSort );
  11695. } else if ( activeInfluenceIndices.length === 0 ) {
  11696. activeInfluenceIndices.push( [ 0, 0 ] );
  11697. };
  11698. var influenceIndex, m = 0;
  11699. while ( m < material.numSupportedMorphTargets ) {
  11700. if ( activeInfluenceIndices[ m ] ) {
  11701. influenceIndex = activeInfluenceIndices[ m ][ 0 ];
  11702. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  11703. enableAttribute( attributes[ "morphTarget" + m ] );
  11704. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11705. if ( material.morphNormals ) {
  11706. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  11707. enableAttribute( attributes[ "morphNormal" + m ] );
  11708. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11709. }
  11710. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11711. } else {
  11712. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11713. if ( material.morphNormals ) {
  11714. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11715. }
  11716. object.__webglMorphTargetInfluences[ m ] = 0;
  11717. }
  11718. m ++;
  11719. }
  11720. }
  11721. // load updated influences uniform
  11722. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11723. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11724. }
  11725. };
  11726. // Sorting
  11727. function painterSortStable ( a, b ) {
  11728. if ( a.z !== b.z ) {
  11729. return b.z - a.z;
  11730. } else {
  11731. return b.id - a.id;
  11732. }
  11733. };
  11734. function numericalSort ( a, b ) {
  11735. return b[ 1 ] - a[ 1 ];
  11736. };
  11737. // Rendering
  11738. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11739. if ( camera instanceof THREE.Camera === false ) {
  11740. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11741. return;
  11742. }
  11743. var i, il,
  11744. webglObject, object,
  11745. renderList,
  11746. lights = scene.__lights,
  11747. fog = scene.fog;
  11748. // reset caching for this frame
  11749. _currentMaterialId = -1;
  11750. _lightsNeedUpdate = true;
  11751. // update scene graph
  11752. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11753. // update camera matrices and frustum
  11754. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11755. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  11756. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  11757. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11758. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  11759. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  11760. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11761. _frustum.setFromMatrix( _projScreenMatrix );
  11762. // update WebGL objects
  11763. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11764. // custom render plugins (pre pass)
  11765. renderPlugins( this.renderPluginsPre, scene, camera );
  11766. //
  11767. _this.info.render.calls = 0;
  11768. _this.info.render.vertices = 0;
  11769. _this.info.render.faces = 0;
  11770. _this.info.render.points = 0;
  11771. this.setRenderTarget( renderTarget );
  11772. if ( this.autoClear || forceClear ) {
  11773. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11774. }
  11775. // set matrices for regular objects (frustum culled)
  11776. renderList = scene.__webglObjects;
  11777. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11778. webglObject = renderList[ i ];
  11779. object = webglObject.object;
  11780. webglObject.render = false;
  11781. if ( object.visible ) {
  11782. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11783. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11784. setupMatrices( object, camera );
  11785. unrollBufferMaterial( webglObject );
  11786. webglObject.render = true;
  11787. if ( this.sortObjects === true ) {
  11788. if ( object.renderDepth !== null ) {
  11789. webglObject.z = object.renderDepth;
  11790. } else {
  11791. _vector3.copy( object.matrixWorld.getPosition() );
  11792. _projScreenMatrix.multiplyVector3( _vector3 );
  11793. webglObject.z = _vector3.z;
  11794. }
  11795. webglObject.id = object.id;
  11796. }
  11797. }
  11798. }
  11799. }
  11800. if ( this.sortObjects ) {
  11801. renderList.sort( painterSortStable );
  11802. }
  11803. // set matrices for immediate objects
  11804. renderList = scene.__webglObjectsImmediate;
  11805. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11806. webglObject = renderList[ i ];
  11807. object = webglObject.object;
  11808. if ( object.visible ) {
  11809. /*
  11810. if ( object.matrixAutoUpdate ) {
  11811. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11812. }
  11813. */
  11814. setupMatrices( object, camera );
  11815. unrollImmediateBufferMaterial( webglObject );
  11816. }
  11817. }
  11818. if ( scene.overrideMaterial ) {
  11819. var material = scene.overrideMaterial;
  11820. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11821. this.setDepthTest( material.depthTest );
  11822. this.setDepthWrite( material.depthWrite );
  11823. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11824. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11825. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11826. } else {
  11827. // opaque pass (front-to-back order)
  11828. this.setBlending( THREE.NormalBlending );
  11829. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  11830. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  11831. // transparent pass (back-to-front order)
  11832. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  11833. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  11834. }
  11835. // custom render plugins (post pass)
  11836. renderPlugins( this.renderPluginsPost, scene, camera );
  11837. // Generate mipmap if we're using any kind of mipmap filtering
  11838. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11839. updateRenderTargetMipmap( renderTarget );
  11840. }
  11841. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11842. this.setDepthTest( true );
  11843. this.setDepthWrite( true );
  11844. // _gl.finish();
  11845. };
  11846. function renderPlugins( plugins, scene, camera ) {
  11847. if ( ! plugins.length ) return;
  11848. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11849. // reset state for plugin (to start from clean slate)
  11850. _currentProgram = null;
  11851. _currentCamera = null;
  11852. _oldBlending = -1;
  11853. _oldDepthTest = -1;
  11854. _oldDepthWrite = -1;
  11855. _oldDoubleSided = -1;
  11856. _oldFlipSided = -1;
  11857. _currentGeometryGroupHash = -1;
  11858. _currentMaterialId = -1;
  11859. _lightsNeedUpdate = true;
  11860. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  11861. // reset state after plugin (anything could have changed)
  11862. _currentProgram = null;
  11863. _currentCamera = null;
  11864. _oldBlending = -1;
  11865. _oldDepthTest = -1;
  11866. _oldDepthWrite = -1;
  11867. _oldDoubleSided = -1;
  11868. _oldFlipSided = -1;
  11869. _currentGeometryGroupHash = -1;
  11870. _currentMaterialId = -1;
  11871. _lightsNeedUpdate = true;
  11872. }
  11873. };
  11874. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11875. var webglObject, object, buffer, material, start, end, delta;
  11876. if ( reverse ) {
  11877. start = renderList.length - 1;
  11878. end = -1;
  11879. delta = -1;
  11880. } else {
  11881. start = 0;
  11882. end = renderList.length;
  11883. delta = 1;
  11884. }
  11885. for ( var i = start; i !== end; i += delta ) {
  11886. webglObject = renderList[ i ];
  11887. if ( webglObject.render ) {
  11888. object = webglObject.object;
  11889. buffer = webglObject.buffer;
  11890. if ( overrideMaterial ) {
  11891. material = overrideMaterial;
  11892. } else {
  11893. material = webglObject[ materialType ];
  11894. if ( ! material ) continue;
  11895. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11896. _this.setDepthTest( material.depthTest );
  11897. _this.setDepthWrite( material.depthWrite );
  11898. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11899. }
  11900. _this.setMaterialFaces( material );
  11901. if ( buffer instanceof THREE.BufferGeometry ) {
  11902. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11903. } else {
  11904. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11905. }
  11906. }
  11907. }
  11908. };
  11909. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11910. var webglObject, object, material, program;
  11911. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11912. webglObject = renderList[ i ];
  11913. object = webglObject.object;
  11914. if ( object.visible ) {
  11915. if ( overrideMaterial ) {
  11916. material = overrideMaterial;
  11917. } else {
  11918. material = webglObject[ materialType ];
  11919. if ( ! material ) continue;
  11920. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11921. _this.setDepthTest( material.depthTest );
  11922. _this.setDepthWrite( material.depthWrite );
  11923. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11924. }
  11925. _this.renderImmediateObject( camera, lights, fog, material, object );
  11926. }
  11927. }
  11928. };
  11929. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  11930. var program = setProgram( camera, lights, fog, material, object );
  11931. _currentGeometryGroupHash = -1;
  11932. _this.setMaterialFaces( material );
  11933. if ( object.immediateRenderCallback ) {
  11934. object.immediateRenderCallback( program, _gl, _frustum );
  11935. } else {
  11936. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  11937. }
  11938. };
  11939. function unrollImmediateBufferMaterial ( globject ) {
  11940. var object = globject.object,
  11941. material = object.material;
  11942. if ( material.transparent ) {
  11943. globject.transparent = material;
  11944. globject.opaque = null;
  11945. } else {
  11946. globject.opaque = material;
  11947. globject.transparent = null;
  11948. }
  11949. };
  11950. function unrollBufferMaterial ( globject ) {
  11951. var object = globject.object,
  11952. buffer = globject.buffer,
  11953. material, materialIndex, meshMaterial;
  11954. meshMaterial = object.material;
  11955. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  11956. materialIndex = buffer.materialIndex;
  11957. if ( materialIndex >= 0 ) {
  11958. material = meshMaterial.materials[ materialIndex ];
  11959. if ( material.transparent ) {
  11960. globject.transparent = material;
  11961. globject.opaque = null;
  11962. } else {
  11963. globject.opaque = material;
  11964. globject.transparent = null;
  11965. }
  11966. }
  11967. } else {
  11968. material = meshMaterial;
  11969. if ( material ) {
  11970. if ( material.transparent ) {
  11971. globject.transparent = material;
  11972. globject.opaque = null;
  11973. } else {
  11974. globject.opaque = material;
  11975. globject.transparent = null;
  11976. }
  11977. }
  11978. }
  11979. };
  11980. // Geometry splitting
  11981. function sortFacesByMaterial ( geometry, material ) {
  11982. var f, fl, face, materialIndex, vertices,
  11983. materialHash, groupHash,
  11984. hash_map = {};
  11985. var numMorphTargets = geometry.morphTargets.length;
  11986. var numMorphNormals = geometry.morphNormals.length;
  11987. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  11988. geometry.geometryGroups = {};
  11989. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  11990. face = geometry.faces[ f ];
  11991. materialIndex = usesFaceMaterial ? face.materialIndex : undefined;
  11992. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  11993. if ( hash_map[ materialHash ] === undefined ) {
  11994. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  11995. }
  11996. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11997. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11998. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11999. }
  12000. vertices = face instanceof THREE.Face3 ? 3 : 4;
  12001. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  12002. hash_map[ materialHash ].counter += 1;
  12003. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  12004. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12005. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12006. }
  12007. }
  12008. if ( face instanceof THREE.Face3 ) {
  12009. geometry.geometryGroups[ groupHash ].faces3.push( f );
  12010. } else {
  12011. geometry.geometryGroups[ groupHash ].faces4.push( f );
  12012. }
  12013. geometry.geometryGroups[ groupHash ].vertices += vertices;
  12014. }
  12015. geometry.geometryGroupsList = [];
  12016. for ( var g in geometry.geometryGroups ) {
  12017. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  12018. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  12019. }
  12020. };
  12021. // Objects refresh
  12022. this.initWebGLObjects = function ( scene ) {
  12023. if ( !scene.__webglObjects ) {
  12024. scene.__webglObjects = [];
  12025. scene.__webglObjectsImmediate = [];
  12026. scene.__webglSprites = [];
  12027. scene.__webglFlares = [];
  12028. }
  12029. while ( scene.__objectsAdded.length ) {
  12030. addObject( scene.__objectsAdded[ 0 ], scene );
  12031. scene.__objectsAdded.splice( 0, 1 );
  12032. }
  12033. while ( scene.__objectsRemoved.length ) {
  12034. removeObject( scene.__objectsRemoved[ 0 ], scene );
  12035. scene.__objectsRemoved.splice( 0, 1 );
  12036. }
  12037. // update must be called after objects adding / removal
  12038. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  12039. updateObject( scene.__webglObjects[ o ].object );
  12040. }
  12041. };
  12042. // Objects adding
  12043. function addObject ( object, scene ) {
  12044. var g, geometry, material, geometryGroup;
  12045. if ( ! object.__webglInit ) {
  12046. object.__webglInit = true;
  12047. object._modelViewMatrix = new THREE.Matrix4();
  12048. object._normalMatrix = new THREE.Matrix3();
  12049. if ( object instanceof THREE.Mesh ) {
  12050. geometry = object.geometry;
  12051. material = object.material;
  12052. if ( geometry instanceof THREE.Geometry ) {
  12053. if ( geometry.geometryGroups === undefined ) {
  12054. sortFacesByMaterial( geometry, material );
  12055. }
  12056. // create separate VBOs per geometry chunk
  12057. for ( g in geometry.geometryGroups ) {
  12058. geometryGroup = geometry.geometryGroups[ g ];
  12059. // initialise VBO on the first access
  12060. if ( ! geometryGroup.__webglVertexBuffer ) {
  12061. createMeshBuffers( geometryGroup );
  12062. initMeshBuffers( geometryGroup, object );
  12063. geometry.verticesNeedUpdate = true;
  12064. geometry.morphTargetsNeedUpdate = true;
  12065. geometry.elementsNeedUpdate = true;
  12066. geometry.uvsNeedUpdate = true;
  12067. geometry.normalsNeedUpdate = true;
  12068. geometry.tangentsNeedUpdate = true;
  12069. geometry.colorsNeedUpdate = true;
  12070. }
  12071. }
  12072. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12073. initDirectBuffers( geometry );
  12074. }
  12075. } else if ( object instanceof THREE.Ribbon ) {
  12076. geometry = object.geometry;
  12077. if ( ! geometry.__webglVertexBuffer ) {
  12078. createRibbonBuffers( geometry );
  12079. initRibbonBuffers( geometry, object );
  12080. geometry.verticesNeedUpdate = true;
  12081. geometry.colorsNeedUpdate = true;
  12082. geometry.normalsNeedUpdate = true;
  12083. }
  12084. } else if ( object instanceof THREE.Line ) {
  12085. geometry = object.geometry;
  12086. if ( ! geometry.__webglVertexBuffer ) {
  12087. createLineBuffers( geometry );
  12088. initLineBuffers( geometry, object );
  12089. geometry.verticesNeedUpdate = true;
  12090. geometry.colorsNeedUpdate = true;
  12091. geometry.lineDistancesNeedUpdate = true;
  12092. }
  12093. } else if ( object instanceof THREE.ParticleSystem ) {
  12094. geometry = object.geometry;
  12095. if ( ! geometry.__webglVertexBuffer ) {
  12096. if ( geometry instanceof THREE.Geometry ) {
  12097. createParticleBuffers( geometry );
  12098. initParticleBuffers( geometry, object );
  12099. geometry.verticesNeedUpdate = true;
  12100. geometry.colorsNeedUpdate = true;
  12101. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12102. initDirectBuffers( geometry );
  12103. }
  12104. }
  12105. }
  12106. }
  12107. if ( ! object.__webglActive ) {
  12108. if ( object instanceof THREE.Mesh ) {
  12109. geometry = object.geometry;
  12110. if ( geometry instanceof THREE.BufferGeometry ) {
  12111. addBuffer( scene.__webglObjects, geometry, object );
  12112. } else {
  12113. for ( g in geometry.geometryGroups ) {
  12114. geometryGroup = geometry.geometryGroups[ g ];
  12115. addBuffer( scene.__webglObjects, geometryGroup, object );
  12116. }
  12117. }
  12118. } else if ( object instanceof THREE.Ribbon ||
  12119. object instanceof THREE.Line ||
  12120. object instanceof THREE.ParticleSystem ) {
  12121. geometry = object.geometry;
  12122. addBuffer( scene.__webglObjects, geometry, object );
  12123. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12124. addBufferImmediate( scene.__webglObjectsImmediate, object );
  12125. } else if ( object instanceof THREE.Sprite ) {
  12126. scene.__webglSprites.push( object );
  12127. } else if ( object instanceof THREE.LensFlare ) {
  12128. scene.__webglFlares.push( object );
  12129. }
  12130. object.__webglActive = true;
  12131. }
  12132. };
  12133. function addBuffer ( objlist, buffer, object ) {
  12134. objlist.push(
  12135. {
  12136. buffer: buffer,
  12137. object: object,
  12138. opaque: null,
  12139. transparent: null
  12140. }
  12141. );
  12142. };
  12143. function addBufferImmediate ( objlist, object ) {
  12144. objlist.push(
  12145. {
  12146. object: object,
  12147. opaque: null,
  12148. transparent: null
  12149. }
  12150. );
  12151. };
  12152. // Objects updates
  12153. function updateObject ( object ) {
  12154. var geometry = object.geometry,
  12155. geometryGroup, customAttributesDirty, material;
  12156. if ( object instanceof THREE.Mesh ) {
  12157. if ( geometry instanceof THREE.BufferGeometry ) {
  12158. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  12159. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12160. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  12161. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12162. }
  12163. geometry.verticesNeedUpdate = false;
  12164. geometry.elementsNeedUpdate = false;
  12165. geometry.uvsNeedUpdate = false;
  12166. geometry.normalsNeedUpdate = false;
  12167. geometry.colorsNeedUpdate = false;
  12168. geometry.tangentsNeedUpdate = false;
  12169. } else {
  12170. // check all geometry groups
  12171. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  12172. geometryGroup = geometry.geometryGroupsList[ i ];
  12173. material = getBufferMaterial( object, geometryGroup );
  12174. if ( geometry.buffersNeedUpdate ) {
  12175. initMeshBuffers( geometryGroup, object );
  12176. }
  12177. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12178. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12179. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12180. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12181. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  12182. }
  12183. }
  12184. geometry.verticesNeedUpdate = false;
  12185. geometry.morphTargetsNeedUpdate = false;
  12186. geometry.elementsNeedUpdate = false;
  12187. geometry.uvsNeedUpdate = false;
  12188. geometry.normalsNeedUpdate = false;
  12189. geometry.colorsNeedUpdate = false;
  12190. geometry.tangentsNeedUpdate = false;
  12191. geometry.buffersNeedUpdate = false;
  12192. material.attributes && clearCustomAttributes( material );
  12193. }
  12194. } else if ( object instanceof THREE.Ribbon ) {
  12195. material = getBufferMaterial( object, geometry );
  12196. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12197. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  12198. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  12199. }
  12200. geometry.verticesNeedUpdate = false;
  12201. geometry.colorsNeedUpdate = false;
  12202. geometry.normalsNeedUpdate = false;
  12203. material.attributes && clearCustomAttributes( material );
  12204. } else if ( object instanceof THREE.Line ) {
  12205. material = getBufferMaterial( object, geometry );
  12206. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12207. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12208. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12209. }
  12210. geometry.verticesNeedUpdate = false;
  12211. geometry.colorsNeedUpdate = false;
  12212. geometry.lineDistancesNeedUpdate = false;
  12213. material.attributes && clearCustomAttributes( material );
  12214. } else if ( object instanceof THREE.ParticleSystem ) {
  12215. if ( geometry instanceof THREE.BufferGeometry ) {
  12216. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12217. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12218. }
  12219. geometry.verticesNeedUpdate = false;
  12220. geometry.colorsNeedUpdate = false;
  12221. } else {
  12222. material = getBufferMaterial( object, geometry );
  12223. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12224. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  12225. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12226. }
  12227. geometry.verticesNeedUpdate = false;
  12228. geometry.colorsNeedUpdate = false;
  12229. material.attributes && clearCustomAttributes( material );
  12230. }
  12231. }
  12232. };
  12233. // Objects updates - custom attributes check
  12234. function areCustomAttributesDirty ( material ) {
  12235. for ( var a in material.attributes ) {
  12236. if ( material.attributes[ a ].needsUpdate ) return true;
  12237. }
  12238. return false;
  12239. };
  12240. function clearCustomAttributes ( material ) {
  12241. for ( var a in material.attributes ) {
  12242. material.attributes[ a ].needsUpdate = false;
  12243. }
  12244. };
  12245. // Objects removal
  12246. function removeObject ( object, scene ) {
  12247. if ( object instanceof THREE.Mesh ||
  12248. object instanceof THREE.ParticleSystem ||
  12249. object instanceof THREE.Ribbon ||
  12250. object instanceof THREE.Line ) {
  12251. removeInstances( scene.__webglObjects, object );
  12252. } else if ( object instanceof THREE.Sprite ) {
  12253. removeInstancesDirect( scene.__webglSprites, object );
  12254. } else if ( object instanceof THREE.LensFlare ) {
  12255. removeInstancesDirect( scene.__webglFlares, object );
  12256. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12257. removeInstances( scene.__webglObjectsImmediate, object );
  12258. }
  12259. object.__webglActive = false;
  12260. };
  12261. function removeInstances ( objlist, object ) {
  12262. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12263. if ( objlist[ o ].object === object ) {
  12264. objlist.splice( o, 1 );
  12265. }
  12266. }
  12267. };
  12268. function removeInstancesDirect ( objlist, object ) {
  12269. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12270. if ( objlist[ o ] === object ) {
  12271. objlist.splice( o, 1 );
  12272. }
  12273. }
  12274. };
  12275. // Materials
  12276. this.initMaterial = function ( material, lights, fog, object ) {
  12277. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  12278. if ( material instanceof THREE.MeshDepthMaterial ) {
  12279. shaderID = 'depth';
  12280. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12281. shaderID = 'normal';
  12282. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  12283. shaderID = 'basic';
  12284. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12285. shaderID = 'lambert';
  12286. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12287. shaderID = 'phong';
  12288. } else if ( material instanceof THREE.LineBasicMaterial ) {
  12289. shaderID = 'basic';
  12290. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12291. shaderID = 'dashed';
  12292. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12293. shaderID = 'particle_basic';
  12294. }
  12295. if ( shaderID ) {
  12296. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  12297. }
  12298. // heuristics to create shader parameters according to lights in the scene
  12299. // (not to blow over maxLights budget)
  12300. maxLightCount = allocateLights( lights );
  12301. maxShadows = allocateShadows( lights );
  12302. maxBones = allocateBones( object );
  12303. parameters = {
  12304. map: !!material.map,
  12305. envMap: !!material.envMap,
  12306. lightMap: !!material.lightMap,
  12307. bumpMap: !!material.bumpMap,
  12308. normalMap: !!material.normalMap,
  12309. specularMap: !!material.specularMap,
  12310. vertexColors: material.vertexColors,
  12311. fog: fog,
  12312. useFog: material.fog,
  12313. fogExp: fog instanceof THREE.FogExp2,
  12314. sizeAttenuation: material.sizeAttenuation,
  12315. skinning: material.skinning,
  12316. maxBones: maxBones,
  12317. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  12318. boneTextureWidth: object && object.boneTextureWidth,
  12319. boneTextureHeight: object && object.boneTextureHeight,
  12320. morphTargets: material.morphTargets,
  12321. morphNormals: material.morphNormals,
  12322. maxMorphTargets: this.maxMorphTargets,
  12323. maxMorphNormals: this.maxMorphNormals,
  12324. maxDirLights: maxLightCount.directional,
  12325. maxPointLights: maxLightCount.point,
  12326. maxSpotLights: maxLightCount.spot,
  12327. maxHemiLights: maxLightCount.hemi,
  12328. maxShadows: maxShadows,
  12329. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  12330. shadowMapSoft: this.shadowMapSoft,
  12331. shadowMapDebug: this.shadowMapDebug,
  12332. shadowMapCascade: this.shadowMapCascade,
  12333. alphaTest: material.alphaTest,
  12334. metal: material.metal,
  12335. perPixel: material.perPixel,
  12336. wrapAround: material.wrapAround,
  12337. doubleSided: material.side === THREE.DoubleSide,
  12338. flipSided: material.side === THREE.BackSide
  12339. };
  12340. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  12341. var attributes = material.program.attributes;
  12342. if ( material.morphTargets ) {
  12343. material.numSupportedMorphTargets = 0;
  12344. var id, base = "morphTarget";
  12345. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  12346. id = base + i;
  12347. if ( attributes[ id ] >= 0 ) {
  12348. material.numSupportedMorphTargets ++;
  12349. }
  12350. }
  12351. }
  12352. if ( material.morphNormals ) {
  12353. material.numSupportedMorphNormals = 0;
  12354. var id, base = "morphNormal";
  12355. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  12356. id = base + i;
  12357. if ( attributes[ id ] >= 0 ) {
  12358. material.numSupportedMorphNormals ++;
  12359. }
  12360. }
  12361. }
  12362. material.uniformsList = [];
  12363. for ( u in material.uniforms ) {
  12364. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  12365. }
  12366. };
  12367. function setMaterialShaders( material, shaders ) {
  12368. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  12369. material.vertexShader = shaders.vertexShader;
  12370. material.fragmentShader = shaders.fragmentShader;
  12371. };
  12372. function setProgram( camera, lights, fog, material, object ) {
  12373. _usedTextureUnits = 0;
  12374. if ( material.needsUpdate ) {
  12375. if ( material.program ) _this.deallocateMaterial( material );
  12376. _this.initMaterial( material, lights, fog, object );
  12377. material.needsUpdate = false;
  12378. }
  12379. if ( material.morphTargets ) {
  12380. if ( ! object.__webglMorphTargetInfluences ) {
  12381. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  12382. }
  12383. }
  12384. var refreshMaterial = false;
  12385. var program = material.program,
  12386. p_uniforms = program.uniforms,
  12387. m_uniforms = material.uniforms;
  12388. if ( program !== _currentProgram ) {
  12389. _gl.useProgram( program );
  12390. _currentProgram = program;
  12391. refreshMaterial = true;
  12392. }
  12393. if ( material.id !== _currentMaterialId ) {
  12394. _currentMaterialId = material.id;
  12395. refreshMaterial = true;
  12396. }
  12397. if ( refreshMaterial || camera !== _currentCamera ) {
  12398. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  12399. if ( camera !== _currentCamera ) _currentCamera = camera;
  12400. }
  12401. // skinning uniforms must be set even if material didn't change
  12402. // auto-setting of texture unit for bone texture must go before other textures
  12403. // not sure why, but otherwise weird things happen
  12404. if ( material.skinning ) {
  12405. if ( _supportsBoneTextures && object.useVertexTexture ) {
  12406. if ( p_uniforms.boneTexture !== null ) {
  12407. var textureUnit = getTextureUnit();
  12408. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  12409. _this.setTexture( object.boneTexture, textureUnit );
  12410. }
  12411. } else {
  12412. if ( p_uniforms.boneGlobalMatrices !== null ) {
  12413. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  12414. }
  12415. }
  12416. }
  12417. if ( refreshMaterial ) {
  12418. // refresh uniforms common to several materials
  12419. if ( fog && material.fog ) {
  12420. refreshUniformsFog( m_uniforms, fog );
  12421. }
  12422. if ( material instanceof THREE.MeshPhongMaterial ||
  12423. material instanceof THREE.MeshLambertMaterial ||
  12424. material.lights ) {
  12425. if ( _lightsNeedUpdate ) {
  12426. setupLights( program, lights );
  12427. _lightsNeedUpdate = false;
  12428. }
  12429. refreshUniformsLights( m_uniforms, _lights );
  12430. }
  12431. if ( material instanceof THREE.MeshBasicMaterial ||
  12432. material instanceof THREE.MeshLambertMaterial ||
  12433. material instanceof THREE.MeshPhongMaterial ) {
  12434. refreshUniformsCommon( m_uniforms, material );
  12435. }
  12436. // refresh single material specific uniforms
  12437. if ( material instanceof THREE.LineBasicMaterial ) {
  12438. refreshUniformsLine( m_uniforms, material );
  12439. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12440. refreshUniformsLine( m_uniforms, material );
  12441. refreshUniformsDash( m_uniforms, material );
  12442. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12443. refreshUniformsParticle( m_uniforms, material );
  12444. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12445. refreshUniformsPhong( m_uniforms, material );
  12446. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12447. refreshUniformsLambert( m_uniforms, material );
  12448. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  12449. m_uniforms.mNear.value = camera.near;
  12450. m_uniforms.mFar.value = camera.far;
  12451. m_uniforms.opacity.value = material.opacity;
  12452. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12453. m_uniforms.opacity.value = material.opacity;
  12454. }
  12455. if ( object.receiveShadow && ! material._shadowPass ) {
  12456. refreshUniformsShadow( m_uniforms, lights );
  12457. }
  12458. // load common uniforms
  12459. loadUniformsGeneric( program, material.uniformsList );
  12460. // load material specific uniforms
  12461. // (shader material also gets them for the sake of genericity)
  12462. if ( material instanceof THREE.ShaderMaterial ||
  12463. material instanceof THREE.MeshPhongMaterial ||
  12464. material.envMap ) {
  12465. if ( p_uniforms.cameraPosition !== null ) {
  12466. var position = camera.matrixWorld.getPosition();
  12467. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  12468. }
  12469. }
  12470. if ( material instanceof THREE.MeshPhongMaterial ||
  12471. material instanceof THREE.MeshLambertMaterial ||
  12472. material instanceof THREE.ShaderMaterial ||
  12473. material.skinning ) {
  12474. if ( p_uniforms.viewMatrix !== null ) {
  12475. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  12476. }
  12477. }
  12478. }
  12479. loadUniformsMatrices( p_uniforms, object );
  12480. if ( p_uniforms.modelMatrix !== null ) {
  12481. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  12482. }
  12483. return program;
  12484. };
  12485. // Uniforms (refresh uniforms objects)
  12486. function refreshUniformsCommon ( uniforms, material ) {
  12487. uniforms.opacity.value = material.opacity;
  12488. if ( _this.gammaInput ) {
  12489. uniforms.diffuse.value.copyGammaToLinear( material.color );
  12490. } else {
  12491. uniforms.diffuse.value = material.color;
  12492. }
  12493. uniforms.map.value = material.map;
  12494. uniforms.lightMap.value = material.lightMap;
  12495. uniforms.specularMap.value = material.specularMap;
  12496. if ( material.bumpMap ) {
  12497. uniforms.bumpMap.value = material.bumpMap;
  12498. uniforms.bumpScale.value = material.bumpScale;
  12499. }
  12500. if ( material.normalMap ) {
  12501. uniforms.normalMap.value = material.normalMap;
  12502. uniforms.normalScale.value.copy( material.normalScale );
  12503. }
  12504. // uv repeat and offset setting priorities
  12505. // 1. color map
  12506. // 2. specular map
  12507. // 3. normal map
  12508. // 4. bump map
  12509. var uvScaleMap;
  12510. if ( material.map ) {
  12511. uvScaleMap = material.map;
  12512. } else if ( material.specularMap ) {
  12513. uvScaleMap = material.specularMap;
  12514. } else if ( material.normalMap ) {
  12515. uvScaleMap = material.normalMap;
  12516. } else if ( material.bumpMap ) {
  12517. uvScaleMap = material.bumpMap;
  12518. }
  12519. if ( uvScaleMap !== undefined ) {
  12520. var offset = uvScaleMap.offset;
  12521. var repeat = uvScaleMap.repeat;
  12522. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12523. }
  12524. uniforms.envMap.value = material.envMap;
  12525. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  12526. if ( _this.gammaInput ) {
  12527. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  12528. uniforms.reflectivity.value = material.reflectivity;
  12529. } else {
  12530. uniforms.reflectivity.value = material.reflectivity;
  12531. }
  12532. uniforms.refractionRatio.value = material.refractionRatio;
  12533. uniforms.combine.value = material.combine;
  12534. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  12535. };
  12536. function refreshUniformsLine ( uniforms, material ) {
  12537. uniforms.diffuse.value = material.color;
  12538. uniforms.opacity.value = material.opacity;
  12539. };
  12540. function refreshUniformsDash ( uniforms, material ) {
  12541. uniforms.dashSize.value = material.dashSize;
  12542. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12543. uniforms.scale.value = material.scale;
  12544. };
  12545. function refreshUniformsParticle ( uniforms, material ) {
  12546. uniforms.psColor.value = material.color;
  12547. uniforms.opacity.value = material.opacity;
  12548. uniforms.size.value = material.size;
  12549. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  12550. uniforms.map.value = material.map;
  12551. };
  12552. function refreshUniformsFog ( uniforms, fog ) {
  12553. uniforms.fogColor.value = fog.color;
  12554. if ( fog instanceof THREE.Fog ) {
  12555. uniforms.fogNear.value = fog.near;
  12556. uniforms.fogFar.value = fog.far;
  12557. } else if ( fog instanceof THREE.FogExp2 ) {
  12558. uniforms.fogDensity.value = fog.density;
  12559. }
  12560. };
  12561. function refreshUniformsPhong ( uniforms, material ) {
  12562. uniforms.shininess.value = material.shininess;
  12563. if ( _this.gammaInput ) {
  12564. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12565. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12566. uniforms.specular.value.copyGammaToLinear( material.specular );
  12567. } else {
  12568. uniforms.ambient.value = material.ambient;
  12569. uniforms.emissive.value = material.emissive;
  12570. uniforms.specular.value = material.specular;
  12571. }
  12572. if ( material.wrapAround ) {
  12573. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12574. }
  12575. };
  12576. function refreshUniformsLambert ( uniforms, material ) {
  12577. if ( _this.gammaInput ) {
  12578. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12579. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12580. } else {
  12581. uniforms.ambient.value = material.ambient;
  12582. uniforms.emissive.value = material.emissive;
  12583. }
  12584. if ( material.wrapAround ) {
  12585. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12586. }
  12587. };
  12588. function refreshUniformsLights ( uniforms, lights ) {
  12589. uniforms.ambientLightColor.value = lights.ambient;
  12590. uniforms.directionalLightColor.value = lights.directional.colors;
  12591. uniforms.directionalLightDirection.value = lights.directional.positions;
  12592. uniforms.pointLightColor.value = lights.point.colors;
  12593. uniforms.pointLightPosition.value = lights.point.positions;
  12594. uniforms.pointLightDistance.value = lights.point.distances;
  12595. uniforms.spotLightColor.value = lights.spot.colors;
  12596. uniforms.spotLightPosition.value = lights.spot.positions;
  12597. uniforms.spotLightDistance.value = lights.spot.distances;
  12598. uniforms.spotLightDirection.value = lights.spot.directions;
  12599. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  12600. uniforms.spotLightExponent.value = lights.spot.exponents;
  12601. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12602. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12603. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  12604. };
  12605. function refreshUniformsShadow ( uniforms, lights ) {
  12606. if ( uniforms.shadowMatrix ) {
  12607. var j = 0;
  12608. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12609. var light = lights[ i ];
  12610. if ( ! light.castShadow ) continue;
  12611. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12612. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12613. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12614. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12615. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12616. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12617. j ++;
  12618. }
  12619. }
  12620. }
  12621. };
  12622. // Uniforms (load to GPU)
  12623. function loadUniformsMatrices ( uniforms, object ) {
  12624. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  12625. if ( uniforms.normalMatrix ) {
  12626. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  12627. }
  12628. };
  12629. function getTextureUnit() {
  12630. var textureUnit = _usedTextureUnits;
  12631. if ( textureUnit >= _maxTextures ) {
  12632. console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  12633. }
  12634. _usedTextureUnits += 1;
  12635. return textureUnit;
  12636. };
  12637. function loadUniformsGeneric ( program, uniforms ) {
  12638. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  12639. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12640. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  12641. if ( !location ) continue;
  12642. uniform = uniforms[ j ][ 0 ];
  12643. type = uniform.type;
  12644. value = uniform.value;
  12645. if ( type === "i" ) { // single integer
  12646. _gl.uniform1i( location, value );
  12647. } else if ( type === "f" ) { // single float
  12648. _gl.uniform1f( location, value );
  12649. } else if ( type === "v2" ) { // single THREE.Vector2
  12650. _gl.uniform2f( location, value.x, value.y );
  12651. } else if ( type === "v3" ) { // single THREE.Vector3
  12652. _gl.uniform3f( location, value.x, value.y, value.z );
  12653. } else if ( type === "v4" ) { // single THREE.Vector4
  12654. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  12655. } else if ( type === "c" ) { // single THREE.Color
  12656. _gl.uniform3f( location, value.r, value.g, value.b );
  12657. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  12658. _gl.uniform1iv( location, value );
  12659. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  12660. _gl.uniform3iv( location, value );
  12661. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  12662. _gl.uniform1fv( location, value );
  12663. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  12664. _gl.uniform3fv( location, value );
  12665. } else if ( type === "v2v" ) { // array of THREE.Vector2
  12666. if ( uniform._array === undefined ) {
  12667. uniform._array = new Float32Array( 2 * value.length );
  12668. }
  12669. for ( i = 0, il = value.length; i < il; i ++ ) {
  12670. offset = i * 2;
  12671. uniform._array[ offset ] = value[ i ].x;
  12672. uniform._array[ offset + 1 ] = value[ i ].y;
  12673. }
  12674. _gl.uniform2fv( location, uniform._array );
  12675. } else if ( type === "v3v" ) { // array of THREE.Vector3
  12676. if ( uniform._array === undefined ) {
  12677. uniform._array = new Float32Array( 3 * value.length );
  12678. }
  12679. for ( i = 0, il = value.length; i < il; i ++ ) {
  12680. offset = i * 3;
  12681. uniform._array[ offset ] = value[ i ].x;
  12682. uniform._array[ offset + 1 ] = value[ i ].y;
  12683. uniform._array[ offset + 2 ] = value[ i ].z;
  12684. }
  12685. _gl.uniform3fv( location, uniform._array );
  12686. } else if ( type === "v4v" ) { // array of THREE.Vector4
  12687. if ( uniform._array === undefined ) {
  12688. uniform._array = new Float32Array( 4 * value.length );
  12689. }
  12690. for ( i = 0, il = value.length; i < il; i ++ ) {
  12691. offset = i * 4;
  12692. uniform._array[ offset ] = value[ i ].x;
  12693. uniform._array[ offset + 1 ] = value[ i ].y;
  12694. uniform._array[ offset + 2 ] = value[ i ].z;
  12695. uniform._array[ offset + 3 ] = value[ i ].w;
  12696. }
  12697. _gl.uniform4fv( location, uniform._array );
  12698. } else if ( type === "m4") { // single THREE.Matrix4
  12699. if ( uniform._array === undefined ) {
  12700. uniform._array = new Float32Array( 16 );
  12701. }
  12702. value.flattenToArray( uniform._array );
  12703. _gl.uniformMatrix4fv( location, false, uniform._array );
  12704. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  12705. if ( uniform._array === undefined ) {
  12706. uniform._array = new Float32Array( 16 * value.length );
  12707. }
  12708. for ( i = 0, il = value.length; i < il; i ++ ) {
  12709. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12710. }
  12711. _gl.uniformMatrix4fv( location, false, uniform._array );
  12712. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  12713. texture = value;
  12714. textureUnit = getTextureUnit();
  12715. _gl.uniform1i( location, textureUnit );
  12716. if ( !texture ) continue;
  12717. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  12718. setCubeTexture( texture, textureUnit );
  12719. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12720. setCubeTextureDynamic( texture, textureUnit );
  12721. } else {
  12722. _this.setTexture( texture, textureUnit );
  12723. }
  12724. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  12725. if ( uniform._array === undefined ) {
  12726. uniform._array = [];
  12727. }
  12728. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12729. uniform._array[ i ] = getTextureUnit();
  12730. }
  12731. _gl.uniform1iv( location, uniform._array );
  12732. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12733. texture = uniform.value[ i ];
  12734. textureUnit = uniform._array[ i ];
  12735. if ( !texture ) continue;
  12736. _this.setTexture( texture, textureUnit );
  12737. }
  12738. }
  12739. }
  12740. };
  12741. function setupMatrices ( object, camera ) {
  12742. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  12743. object._normalMatrix.getInverse( object._modelViewMatrix );
  12744. object._normalMatrix.transpose();
  12745. };
  12746. //
  12747. function setColorGamma( array, offset, color, intensitySq ) {
  12748. array[ offset ] = color.r * color.r * intensitySq;
  12749. array[ offset + 1 ] = color.g * color.g * intensitySq;
  12750. array[ offset + 2 ] = color.b * color.b * intensitySq;
  12751. };
  12752. function setColorLinear( array, offset, color, intensity ) {
  12753. array[ offset ] = color.r * intensity;
  12754. array[ offset + 1 ] = color.g * intensity;
  12755. array[ offset + 2 ] = color.b * intensity;
  12756. };
  12757. function setupLights ( program, lights ) {
  12758. var l, ll, light, n,
  12759. r = 0, g = 0, b = 0,
  12760. color, skyColor, groundColor,
  12761. intensity, intensitySq,
  12762. position,
  12763. distance,
  12764. zlights = _lights,
  12765. dirColors = zlights.directional.colors,
  12766. dirPositions = zlights.directional.positions,
  12767. pointColors = zlights.point.colors,
  12768. pointPositions = zlights.point.positions,
  12769. pointDistances = zlights.point.distances,
  12770. spotColors = zlights.spot.colors,
  12771. spotPositions = zlights.spot.positions,
  12772. spotDistances = zlights.spot.distances,
  12773. spotDirections = zlights.spot.directions,
  12774. spotAnglesCos = zlights.spot.anglesCos,
  12775. spotExponents = zlights.spot.exponents,
  12776. hemiSkyColors = zlights.hemi.skyColors,
  12777. hemiGroundColors = zlights.hemi.groundColors,
  12778. hemiPositions = zlights.hemi.positions,
  12779. dirLength = 0,
  12780. pointLength = 0,
  12781. spotLength = 0,
  12782. hemiLength = 0,
  12783. dirCount = 0,
  12784. pointCount = 0,
  12785. spotCount = 0,
  12786. hemiCount = 0,
  12787. dirOffset = 0,
  12788. pointOffset = 0,
  12789. spotOffset = 0,
  12790. hemiOffset = 0;
  12791. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12792. light = lights[ l ];
  12793. if ( light.onlyShadow ) continue;
  12794. color = light.color;
  12795. intensity = light.intensity;
  12796. distance = light.distance;
  12797. if ( light instanceof THREE.AmbientLight ) {
  12798. if ( ! light.visible ) continue;
  12799. if ( _this.gammaInput ) {
  12800. r += color.r * color.r;
  12801. g += color.g * color.g;
  12802. b += color.b * color.b;
  12803. } else {
  12804. r += color.r;
  12805. g += color.g;
  12806. b += color.b;
  12807. }
  12808. } else if ( light instanceof THREE.DirectionalLight ) {
  12809. dirCount += 1;
  12810. if ( ! light.visible ) continue;
  12811. dirOffset = dirLength * 3;
  12812. if ( _this.gammaInput ) {
  12813. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  12814. } else {
  12815. setColorLinear( dirColors, dirOffset, color, intensity );
  12816. }
  12817. _direction.copy( light.matrixWorld.getPosition() );
  12818. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12819. _direction.normalize();
  12820. dirPositions[ dirOffset ] = _direction.x;
  12821. dirPositions[ dirOffset + 1 ] = _direction.y;
  12822. dirPositions[ dirOffset + 2 ] = _direction.z;
  12823. dirLength += 1;
  12824. } else if ( light instanceof THREE.PointLight ) {
  12825. pointCount += 1;
  12826. if ( ! light.visible ) continue;
  12827. pointOffset = pointLength * 3;
  12828. if ( _this.gammaInput ) {
  12829. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  12830. } else {
  12831. setColorLinear( pointColors, pointOffset, color, intensity );
  12832. }
  12833. position = light.matrixWorld.getPosition();
  12834. pointPositions[ pointOffset ] = position.x;
  12835. pointPositions[ pointOffset + 1 ] = position.y;
  12836. pointPositions[ pointOffset + 2 ] = position.z;
  12837. pointDistances[ pointLength ] = distance;
  12838. pointLength += 1;
  12839. } else if ( light instanceof THREE.SpotLight ) {
  12840. spotCount += 1;
  12841. if ( ! light.visible ) continue;
  12842. spotOffset = spotLength * 3;
  12843. if ( _this.gammaInput ) {
  12844. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  12845. } else {
  12846. setColorLinear( spotColors, spotOffset, color, intensity );
  12847. }
  12848. position = light.matrixWorld.getPosition();
  12849. spotPositions[ spotOffset ] = position.x;
  12850. spotPositions[ spotOffset + 1 ] = position.y;
  12851. spotPositions[ spotOffset + 2 ] = position.z;
  12852. spotDistances[ spotLength ] = distance;
  12853. _direction.copy( position );
  12854. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12855. _direction.normalize();
  12856. spotDirections[ spotOffset ] = _direction.x;
  12857. spotDirections[ spotOffset + 1 ] = _direction.y;
  12858. spotDirections[ spotOffset + 2 ] = _direction.z;
  12859. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  12860. spotExponents[ spotLength ] = light.exponent;
  12861. spotLength += 1;
  12862. } else if ( light instanceof THREE.HemisphereLight ) {
  12863. hemiCount += 1;
  12864. if ( ! light.visible ) continue;
  12865. skyColor = light.color;
  12866. groundColor = light.groundColor;
  12867. hemiOffset = hemiLength * 3;
  12868. if ( _this.gammaInput ) {
  12869. intensitySq = intensity * intensity;
  12870. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  12871. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  12872. } else {
  12873. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  12874. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  12875. }
  12876. _direction.copy( light.matrixWorld.getPosition() );
  12877. _direction.normalize();
  12878. hemiPositions[ hemiOffset ] = _direction.x;
  12879. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  12880. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  12881. hemiLength += 1;
  12882. }
  12883. }
  12884. // null eventual remains from removed lights
  12885. // (this is to avoid if in shader)
  12886. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  12887. for ( l = dirLength * 3, ll = Math.max( dirPositions.length, dirCount * 3 ); l < ll; l ++ ) dirPositions[ l ] = 0.0;
  12888. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  12889. for ( l = pointLength * 3, ll = Math.max( pointPositions.length, pointCount * 3 ); l < ll; l ++ ) pointPositions[ l ] = 0.0;
  12890. for ( l = pointLength, ll = Math.max( pointDistances.length, pointCount ); l < ll; l ++ ) pointDistances[ l ] = 0.0;
  12891. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  12892. for ( l = spotLength * 3, ll = Math.max( spotPositions.length, spotCount * 3 ); l < ll; l ++ ) spotPositions[ l ] = 0.0;
  12893. for ( l = spotLength * 3, ll = Math.max( spotDirections.length, spotCount * 3 ); l < ll; l ++ ) spotDirections[ l ] = 0.0;
  12894. for ( l = spotLength, ll = Math.max( spotAnglesCos.length, spotCount ); l < ll; l ++ ) spotAnglesCos[ l ] = 0.0;
  12895. for ( l = spotLength, ll = Math.max( spotExponents.length, spotCount ); l < ll; l ++ ) spotExponents[ l ] = 0.0;
  12896. for ( l = spotLength, ll = Math.max( spotDistances.length, spotCount ); l < ll; l ++ ) spotDistances[ l ] = 0.0;
  12897. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  12898. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  12899. for ( l = hemiLength * 3, ll = Math.max( hemiPositions.length, hemiCount * 3 ); l < ll; l ++ ) hemiPositions[ l ] = 0.0;
  12900. zlights.directional.length = dirLength;
  12901. zlights.point.length = pointLength;
  12902. zlights.spot.length = spotLength;
  12903. zlights.hemi.length = hemiLength;
  12904. zlights.ambient[ 0 ] = r;
  12905. zlights.ambient[ 1 ] = g;
  12906. zlights.ambient[ 2 ] = b;
  12907. };
  12908. // GL state setting
  12909. this.setFaceCulling = function ( cullFace, frontFace ) {
  12910. if ( cullFace ) {
  12911. if ( !frontFace || frontFace === "ccw" ) {
  12912. _gl.frontFace( _gl.CCW );
  12913. } else {
  12914. _gl.frontFace( _gl.CW );
  12915. }
  12916. if( cullFace === "back" ) {
  12917. _gl.cullFace( _gl.BACK );
  12918. } else if( cullFace === "front" ) {
  12919. _gl.cullFace( _gl.FRONT );
  12920. } else {
  12921. _gl.cullFace( _gl.FRONT_AND_BACK );
  12922. }
  12923. _gl.enable( _gl.CULL_FACE );
  12924. } else {
  12925. _gl.disable( _gl.CULL_FACE );
  12926. }
  12927. };
  12928. this.setMaterialFaces = function ( material ) {
  12929. var doubleSided = material.side === THREE.DoubleSide;
  12930. var flipSided = material.side === THREE.BackSide;
  12931. if ( _oldDoubleSided !== doubleSided ) {
  12932. if ( doubleSided ) {
  12933. _gl.disable( _gl.CULL_FACE );
  12934. } else {
  12935. _gl.enable( _gl.CULL_FACE );
  12936. }
  12937. _oldDoubleSided = doubleSided;
  12938. }
  12939. if ( _oldFlipSided !== flipSided ) {
  12940. if ( flipSided ) {
  12941. _gl.frontFace( _gl.CW );
  12942. } else {
  12943. _gl.frontFace( _gl.CCW );
  12944. }
  12945. _oldFlipSided = flipSided;
  12946. }
  12947. };
  12948. this.setDepthTest = function ( depthTest ) {
  12949. if ( _oldDepthTest !== depthTest ) {
  12950. if ( depthTest ) {
  12951. _gl.enable( _gl.DEPTH_TEST );
  12952. } else {
  12953. _gl.disable( _gl.DEPTH_TEST );
  12954. }
  12955. _oldDepthTest = depthTest;
  12956. }
  12957. };
  12958. this.setDepthWrite = function ( depthWrite ) {
  12959. if ( _oldDepthWrite !== depthWrite ) {
  12960. _gl.depthMask( depthWrite );
  12961. _oldDepthWrite = depthWrite;
  12962. }
  12963. };
  12964. function setLineWidth ( width ) {
  12965. if ( width !== _oldLineWidth ) {
  12966. _gl.lineWidth( width );
  12967. _oldLineWidth = width;
  12968. }
  12969. };
  12970. function setPolygonOffset ( polygonoffset, factor, units ) {
  12971. if ( _oldPolygonOffset !== polygonoffset ) {
  12972. if ( polygonoffset ) {
  12973. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  12974. } else {
  12975. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  12976. }
  12977. _oldPolygonOffset = polygonoffset;
  12978. }
  12979. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  12980. _gl.polygonOffset( factor, units );
  12981. _oldPolygonOffsetFactor = factor;
  12982. _oldPolygonOffsetUnits = units;
  12983. }
  12984. };
  12985. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  12986. if ( blending !== _oldBlending ) {
  12987. if ( blending === THREE.NoBlending ) {
  12988. _gl.disable( _gl.BLEND );
  12989. } else if ( blending === THREE.AdditiveBlending ) {
  12990. _gl.enable( _gl.BLEND );
  12991. _gl.blendEquation( _gl.FUNC_ADD );
  12992. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  12993. } else if ( blending === THREE.SubtractiveBlending ) {
  12994. // TODO: Find blendFuncSeparate() combination
  12995. _gl.enable( _gl.BLEND );
  12996. _gl.blendEquation( _gl.FUNC_ADD );
  12997. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  12998. } else if ( blending === THREE.MultiplyBlending ) {
  12999. // TODO: Find blendFuncSeparate() combination
  13000. _gl.enable( _gl.BLEND );
  13001. _gl.blendEquation( _gl.FUNC_ADD );
  13002. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  13003. } else if ( blending === THREE.CustomBlending ) {
  13004. _gl.enable( _gl.BLEND );
  13005. } else {
  13006. _gl.enable( _gl.BLEND );
  13007. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  13008. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  13009. }
  13010. _oldBlending = blending;
  13011. }
  13012. if ( blending === THREE.CustomBlending ) {
  13013. if ( blendEquation !== _oldBlendEquation ) {
  13014. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  13015. _oldBlendEquation = blendEquation;
  13016. }
  13017. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  13018. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  13019. _oldBlendSrc = blendSrc;
  13020. _oldBlendDst = blendDst;
  13021. }
  13022. } else {
  13023. _oldBlendEquation = null;
  13024. _oldBlendSrc = null;
  13025. _oldBlendDst = null;
  13026. }
  13027. };
  13028. // Defines
  13029. function generateDefines ( defines ) {
  13030. var value, chunk, chunks = [];
  13031. for ( var d in defines ) {
  13032. value = defines[ d ];
  13033. if ( value === false ) continue;
  13034. chunk = "#define " + d + " " + value;
  13035. chunks.push( chunk );
  13036. }
  13037. return chunks.join( "\n" );
  13038. };
  13039. // Shaders
  13040. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13041. var p, pl, d, program, code;
  13042. var chunks = [];
  13043. // Generate code
  13044. if ( shaderID ) {
  13045. chunks.push( shaderID );
  13046. } else {
  13047. chunks.push( fragmentShader );
  13048. chunks.push( vertexShader );
  13049. }
  13050. for ( d in defines ) {
  13051. chunks.push( d );
  13052. chunks.push( defines[ d ] );
  13053. }
  13054. for ( p in parameters ) {
  13055. chunks.push( p );
  13056. chunks.push( parameters[ p ] );
  13057. }
  13058. code = chunks.join();
  13059. // Check if code has been already compiled
  13060. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  13061. var programInfo = _programs[ p ];
  13062. if ( programInfo.code === code ) {
  13063. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13064. programInfo.usedTimes ++;
  13065. return programInfo.program;
  13066. }
  13067. }
  13068. //console.log( "building new program " );
  13069. //
  13070. var customDefines = generateDefines( defines );
  13071. //
  13072. program = _gl.createProgram();
  13073. var prefix_vertex = [
  13074. "precision " + _precision + " float;",
  13075. customDefines,
  13076. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13077. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13078. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13079. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13080. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13081. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13082. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13083. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13084. "#define MAX_SHADOWS " + parameters.maxShadows,
  13085. "#define MAX_BONES " + parameters.maxBones,
  13086. parameters.map ? "#define USE_MAP" : "",
  13087. parameters.envMap ? "#define USE_ENVMAP" : "",
  13088. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13089. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13090. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13091. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13092. parameters.vertexColors ? "#define USE_COLOR" : "",
  13093. parameters.skinning ? "#define USE_SKINNING" : "",
  13094. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13095. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13096. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13097. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13098. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13099. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13100. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13101. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13102. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13103. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13104. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13105. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13106. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13107. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13108. "uniform mat4 modelMatrix;",
  13109. "uniform mat4 modelViewMatrix;",
  13110. "uniform mat4 projectionMatrix;",
  13111. "uniform mat4 viewMatrix;",
  13112. "uniform mat3 normalMatrix;",
  13113. "uniform vec3 cameraPosition;",
  13114. "attribute vec3 position;",
  13115. "attribute vec3 normal;",
  13116. "attribute vec2 uv;",
  13117. "attribute vec2 uv2;",
  13118. "#ifdef USE_COLOR",
  13119. "attribute vec3 color;",
  13120. "#endif",
  13121. "#ifdef USE_MORPHTARGETS",
  13122. "attribute vec3 morphTarget0;",
  13123. "attribute vec3 morphTarget1;",
  13124. "attribute vec3 morphTarget2;",
  13125. "attribute vec3 morphTarget3;",
  13126. "#ifdef USE_MORPHNORMALS",
  13127. "attribute vec3 morphNormal0;",
  13128. "attribute vec3 morphNormal1;",
  13129. "attribute vec3 morphNormal2;",
  13130. "attribute vec3 morphNormal3;",
  13131. "#else",
  13132. "attribute vec3 morphTarget4;",
  13133. "attribute vec3 morphTarget5;",
  13134. "attribute vec3 morphTarget6;",
  13135. "attribute vec3 morphTarget7;",
  13136. "#endif",
  13137. "#endif",
  13138. "#ifdef USE_SKINNING",
  13139. "attribute vec4 skinIndex;",
  13140. "attribute vec4 skinWeight;",
  13141. "#endif",
  13142. ""
  13143. ].join("\n");
  13144. var prefix_fragment = [
  13145. "precision " + _precision + " float;",
  13146. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13147. customDefines,
  13148. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13149. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13150. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13151. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13152. "#define MAX_SHADOWS " + parameters.maxShadows,
  13153. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13154. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13155. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13156. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13157. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13158. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13159. parameters.map ? "#define USE_MAP" : "",
  13160. parameters.envMap ? "#define USE_ENVMAP" : "",
  13161. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13162. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13163. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13164. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13165. parameters.vertexColors ? "#define USE_COLOR" : "",
  13166. parameters.metal ? "#define METAL" : "",
  13167. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13168. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13169. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13170. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13171. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13172. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13173. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13174. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13175. "uniform mat4 viewMatrix;",
  13176. "uniform vec3 cameraPosition;",
  13177. ""
  13178. ].join("\n");
  13179. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  13180. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  13181. _gl.attachShader( program, glVertexShader );
  13182. _gl.attachShader( program, glFragmentShader );
  13183. _gl.linkProgram( program );
  13184. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13185. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13186. }
  13187. // clean up
  13188. _gl.deleteShader( glFragmentShader );
  13189. _gl.deleteShader( glVertexShader );
  13190. //console.log( prefix_fragment + fragmentShader );
  13191. //console.log( prefix_vertex + vertexShader );
  13192. program.uniforms = {};
  13193. program.attributes = {};
  13194. var identifiers, u, a, i;
  13195. // cache uniform locations
  13196. identifiers = [
  13197. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13198. 'morphTargetInfluences'
  13199. ];
  13200. if ( parameters.useVertexTexture ) {
  13201. identifiers.push( 'boneTexture' );
  13202. } else {
  13203. identifiers.push( 'boneGlobalMatrices' );
  13204. }
  13205. for ( u in uniforms ) {
  13206. identifiers.push( u );
  13207. }
  13208. cacheUniformLocations( program, identifiers );
  13209. // cache attributes locations
  13210. identifiers = [
  13211. "position", "normal", "uv", "uv2", "tangent", "color",
  13212. "skinIndex", "skinWeight", "lineDistance"
  13213. ];
  13214. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13215. identifiers.push( "morphTarget" + i );
  13216. }
  13217. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  13218. identifiers.push( "morphNormal" + i );
  13219. }
  13220. for ( a in attributes ) {
  13221. identifiers.push( a );
  13222. }
  13223. cacheAttributeLocations( program, identifiers );
  13224. program.id = _programs_counter ++;
  13225. _programs.push( { program: program, code: code, usedTimes: 1 } );
  13226. _this.info.memory.programs = _programs.length;
  13227. return program;
  13228. };
  13229. // Shader parameters cache
  13230. function cacheUniformLocations ( program, identifiers ) {
  13231. var i, l, id;
  13232. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13233. id = identifiers[ i ];
  13234. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  13235. }
  13236. };
  13237. function cacheAttributeLocations ( program, identifiers ) {
  13238. var i, l, id;
  13239. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13240. id = identifiers[ i ];
  13241. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  13242. }
  13243. };
  13244. function addLineNumbers ( string ) {
  13245. var chunks = string.split( "\n" );
  13246. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  13247. // Chrome reports shader errors on lines
  13248. // starting counting from 1
  13249. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  13250. }
  13251. return chunks.join( "\n" );
  13252. };
  13253. function getShader ( type, string ) {
  13254. var shader;
  13255. if ( type === "fragment" ) {
  13256. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  13257. } else if ( type === "vertex" ) {
  13258. shader = _gl.createShader( _gl.VERTEX_SHADER );
  13259. }
  13260. _gl.shaderSource( shader, string );
  13261. _gl.compileShader( shader );
  13262. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  13263. console.error( _gl.getShaderInfoLog( shader ) );
  13264. console.error( addLineNumbers( string ) );
  13265. return null;
  13266. }
  13267. return shader;
  13268. };
  13269. // Textures
  13270. function isPowerOfTwo ( value ) {
  13271. return ( value & ( value - 1 ) ) === 0;
  13272. };
  13273. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13274. if ( isImagePowerOfTwo ) {
  13275. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13276. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13277. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13278. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13279. } else {
  13280. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13281. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13282. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13283. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13284. }
  13285. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  13286. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  13287. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  13288. texture.__oldAnisotropy = texture.anisotropy;
  13289. }
  13290. }
  13291. };
  13292. this.setTexture = function ( texture, slot ) {
  13293. if ( texture.needsUpdate ) {
  13294. if ( ! texture.__webglInit ) {
  13295. texture.__webglInit = true;
  13296. texture.__webglTexture = _gl.createTexture();
  13297. _this.info.memory.textures ++;
  13298. }
  13299. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13300. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13301. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13302. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13303. var image = texture.image,
  13304. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13305. glFormat = paramThreeToGL( texture.format ),
  13306. glType = paramThreeToGL( texture.type );
  13307. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13308. if ( texture instanceof THREE.CompressedTexture ) {
  13309. var mipmap, mipmaps = texture.mipmaps;
  13310. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13311. mipmap = mipmaps[ i ];
  13312. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13313. }
  13314. } else if ( texture instanceof THREE.DataTexture ) {
  13315. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13316. } else {
  13317. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13318. }
  13319. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13320. texture.needsUpdate = false;
  13321. if ( texture.onUpdate ) texture.onUpdate();
  13322. } else {
  13323. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13324. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13325. }
  13326. };
  13327. function clampToMaxSize ( image, maxSize ) {
  13328. if ( image.width <= maxSize && image.height <= maxSize ) {
  13329. return image;
  13330. }
  13331. // Warning: Scaling through the canvas will only work with images that use
  13332. // premultiplied alpha.
  13333. var maxDimension = Math.max( image.width, image.height );
  13334. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  13335. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  13336. var canvas = document.createElement( 'canvas' );
  13337. canvas.width = newWidth;
  13338. canvas.height = newHeight;
  13339. var ctx = canvas.getContext( "2d" );
  13340. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  13341. return canvas;
  13342. }
  13343. function setCubeTexture ( texture, slot ) {
  13344. if ( texture.image.length === 6 ) {
  13345. if ( texture.needsUpdate ) {
  13346. if ( ! texture.image.__webglTextureCube ) {
  13347. texture.image.__webglTextureCube = _gl.createTexture();
  13348. }
  13349. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13350. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13351. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13352. var isCompressed = texture instanceof THREE.CompressedTexture;
  13353. var cubeImage = [];
  13354. for ( var i = 0; i < 6; i ++ ) {
  13355. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  13356. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13357. } else {
  13358. cubeImage[ i ] = texture.image[ i ];
  13359. }
  13360. }
  13361. var image = cubeImage[ 0 ],
  13362. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13363. glFormat = paramThreeToGL( texture.format ),
  13364. glType = paramThreeToGL( texture.type );
  13365. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13366. for ( var i = 0; i < 6; i ++ ) {
  13367. if ( isCompressed ) {
  13368. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13369. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13370. mipmap = mipmaps[ j ];
  13371. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13372. }
  13373. } else {
  13374. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13375. }
  13376. }
  13377. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13378. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13379. }
  13380. texture.needsUpdate = false;
  13381. if ( texture.onUpdate ) texture.onUpdate();
  13382. } else {
  13383. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13384. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13385. }
  13386. }
  13387. };
  13388. function setCubeTextureDynamic ( texture, slot ) {
  13389. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13390. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13391. };
  13392. // Render targets
  13393. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13394. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13395. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13396. };
  13397. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13398. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13399. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13400. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13401. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13402. /* For some reason this is not working. Defaulting to RGBA4.
  13403. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13404. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13405. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13406. */
  13407. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13408. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13409. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13410. } else {
  13411. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13412. }
  13413. };
  13414. this.setRenderTarget = function ( renderTarget ) {
  13415. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13416. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  13417. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13418. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13419. renderTarget.__webglTexture = _gl.createTexture();
  13420. // Setup texture, create render and frame buffers
  13421. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  13422. glFormat = paramThreeToGL( renderTarget.format ),
  13423. glType = paramThreeToGL( renderTarget.type );
  13424. if ( isCube ) {
  13425. renderTarget.__webglFramebuffer = [];
  13426. renderTarget.__webglRenderbuffer = [];
  13427. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13428. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13429. for ( var i = 0; i < 6; i ++ ) {
  13430. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13431. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13432. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13433. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13434. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13435. }
  13436. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13437. } else {
  13438. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13439. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13440. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13441. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13442. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13443. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13444. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13445. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13446. }
  13447. // Release everything
  13448. if ( isCube ) {
  13449. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13450. } else {
  13451. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13452. }
  13453. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13454. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  13455. }
  13456. var framebuffer, width, height, vx, vy;
  13457. if ( renderTarget ) {
  13458. if ( isCube ) {
  13459. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13460. } else {
  13461. framebuffer = renderTarget.__webglFramebuffer;
  13462. }
  13463. width = renderTarget.width;
  13464. height = renderTarget.height;
  13465. vx = 0;
  13466. vy = 0;
  13467. } else {
  13468. framebuffer = null;
  13469. width = _viewportWidth;
  13470. height = _viewportHeight;
  13471. vx = _viewportX;
  13472. vy = _viewportY;
  13473. }
  13474. if ( framebuffer !== _currentFramebuffer ) {
  13475. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13476. _gl.viewport( vx, vy, width, height );
  13477. _currentFramebuffer = framebuffer;
  13478. }
  13479. _currentWidth = width;
  13480. _currentHeight = height;
  13481. };
  13482. function updateRenderTargetMipmap ( renderTarget ) {
  13483. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13484. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13485. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13486. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13487. } else {
  13488. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13489. _gl.generateMipmap( _gl.TEXTURE_2D );
  13490. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13491. }
  13492. };
  13493. // Fallback filters for non-power-of-2 textures
  13494. function filterFallback ( f ) {
  13495. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  13496. return _gl.NEAREST;
  13497. }
  13498. return _gl.LINEAR;
  13499. };
  13500. // Map three.js constants to WebGL constants
  13501. function paramThreeToGL ( p ) {
  13502. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13503. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13504. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13505. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13506. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13507. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13508. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13509. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13510. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13511. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13512. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13513. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13514. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13515. if ( p === THREE.ByteType ) return _gl.BYTE;
  13516. if ( p === THREE.ShortType ) return _gl.SHORT;
  13517. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13518. if ( p === THREE.IntType ) return _gl.INT;
  13519. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13520. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13521. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13522. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13523. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13524. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13525. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13526. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13527. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13528. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13529. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13530. if ( p === THREE.OneFactor ) return _gl.ONE;
  13531. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13532. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13533. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13534. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13535. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13536. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13537. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13538. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13539. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13540. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  13541. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13542. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13543. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13544. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13545. }
  13546. return 0;
  13547. };
  13548. // Allocations
  13549. function allocateBones ( object ) {
  13550. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  13551. return 1024;
  13552. } else {
  13553. // default for when object is not specified
  13554. // ( for example when prebuilding shader
  13555. // to be used with multiple objects )
  13556. //
  13557. // - leave some extra space for other uniforms
  13558. // - limit here is ANGLE's 254 max uniform vectors
  13559. // (up to 54 should be safe)
  13560. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  13561. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  13562. var maxBones = nVertexMatrices;
  13563. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  13564. maxBones = Math.min( object.bones.length, maxBones );
  13565. if ( maxBones < object.bones.length ) {
  13566. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  13567. }
  13568. }
  13569. return maxBones;
  13570. }
  13571. };
  13572. function allocateLights ( lights ) {
  13573. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  13574. dirLights = pointLights = spotLights = hemiLights = 0;
  13575. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13576. light = lights[ l ];
  13577. if ( light.onlyShadow ) continue;
  13578. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  13579. if ( light instanceof THREE.PointLight ) pointLights ++;
  13580. if ( light instanceof THREE.SpotLight ) spotLights ++;
  13581. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  13582. }
  13583. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  13584. };
  13585. function allocateShadows ( lights ) {
  13586. var l, ll, light, maxShadows = 0;
  13587. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  13588. light = lights[ l ];
  13589. if ( ! light.castShadow ) continue;
  13590. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  13591. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  13592. }
  13593. return maxShadows;
  13594. };
  13595. // Initialization
  13596. function initGL () {
  13597. try {
  13598. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  13599. throw 'Error creating WebGL context.';
  13600. }
  13601. } catch ( error ) {
  13602. console.error( error );
  13603. }
  13604. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  13605. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  13606. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  13607. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  13608. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13609. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  13610. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  13611. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13612. if ( ! _glExtensionTextureFloat ) {
  13613. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  13614. }
  13615. if ( ! _glExtensionStandardDerivatives ) {
  13616. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  13617. }
  13618. if ( ! _glExtensionTextureFilterAnisotropic ) {
  13619. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  13620. }
  13621. if ( ! _glExtensionCompressedTextureS3TC ) {
  13622. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  13623. }
  13624. };
  13625. function setDefaultGLState () {
  13626. _gl.clearColor( 0, 0, 0, 1 );
  13627. _gl.clearDepth( 1 );
  13628. _gl.clearStencil( 0 );
  13629. _gl.enable( _gl.DEPTH_TEST );
  13630. _gl.depthFunc( _gl.LEQUAL );
  13631. _gl.frontFace( _gl.CCW );
  13632. _gl.cullFace( _gl.BACK );
  13633. _gl.enable( _gl.CULL_FACE );
  13634. _gl.enable( _gl.BLEND );
  13635. _gl.blendEquation( _gl.FUNC_ADD );
  13636. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  13637. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  13638. };
  13639. // default plugins (order is important)
  13640. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  13641. this.addPrePlugin( this.shadowMapPlugin );
  13642. this.addPostPlugin( new THREE.SpritePlugin() );
  13643. this.addPostPlugin( new THREE.LensFlarePlugin() );
  13644. };
  13645. /**
  13646. * @author szimek / https://github.com/szimek/
  13647. * @author alteredq / http://alteredqualia.com/
  13648. */
  13649. THREE.WebGLRenderTarget = function ( width, height, options ) {
  13650. this.width = width;
  13651. this.height = height;
  13652. options = options || {};
  13653. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  13654. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  13655. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  13656. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  13657. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  13658. this.offset = new THREE.Vector2( 0, 0 );
  13659. this.repeat = new THREE.Vector2( 1, 1 );
  13660. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  13661. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  13662. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  13663. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  13664. this.generateMipmaps = true;
  13665. };
  13666. THREE.WebGLRenderTarget.prototype.clone = function() {
  13667. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  13668. tmp.wrapS = this.wrapS;
  13669. tmp.wrapT = this.wrapT;
  13670. tmp.magFilter = this.magFilter;
  13671. tmp.anisotropy = this.anisotropy;
  13672. tmp.minFilter = this.minFilter;
  13673. tmp.offset.copy( this.offset );
  13674. tmp.repeat.copy( this.repeat );
  13675. tmp.format = this.format;
  13676. tmp.type = this.type;
  13677. tmp.depthBuffer = this.depthBuffer;
  13678. tmp.stencilBuffer = this.stencilBuffer;
  13679. tmp.generateMipmaps = this.generateMipmaps;
  13680. return tmp;
  13681. };
  13682. /**
  13683. * @author alteredq / http://alteredqualia.com
  13684. */
  13685. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  13686. THREE.WebGLRenderTarget.call( this, width, height, options );
  13687. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  13688. };
  13689. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  13690. /**
  13691. * @author mrdoob / http://mrdoob.com/
  13692. */
  13693. THREE.RenderableVertex = function () {
  13694. this.positionWorld = new THREE.Vector3();
  13695. this.positionScreen = new THREE.Vector4();
  13696. this.visible = true;
  13697. };
  13698. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  13699. this.positionWorld.copy( vertex.positionWorld );
  13700. this.positionScreen.copy( vertex.positionScreen );
  13701. }
  13702. /**
  13703. * @author mrdoob / http://mrdoob.com/
  13704. */
  13705. THREE.RenderableFace3 = function () {
  13706. this.v1 = new THREE.RenderableVertex();
  13707. this.v2 = new THREE.RenderableVertex();
  13708. this.v3 = new THREE.RenderableVertex();
  13709. this.centroidWorld = new THREE.Vector3();
  13710. this.centroidScreen = new THREE.Vector3();
  13711. this.normalWorld = new THREE.Vector3();
  13712. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13713. this.vertexNormalsLength = 0;
  13714. this.color = null;
  13715. this.material = null;
  13716. this.uvs = [[]];
  13717. this.z = null;
  13718. };
  13719. /**
  13720. * @author mrdoob / http://mrdoob.com/
  13721. */
  13722. THREE.RenderableFace4 = function () {
  13723. this.v1 = new THREE.RenderableVertex();
  13724. this.v2 = new THREE.RenderableVertex();
  13725. this.v3 = new THREE.RenderableVertex();
  13726. this.v4 = new THREE.RenderableVertex();
  13727. this.centroidWorld = new THREE.Vector3();
  13728. this.centroidScreen = new THREE.Vector3();
  13729. this.normalWorld = new THREE.Vector3();
  13730. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13731. this.vertexNormalsLength = 0;
  13732. this.color = null;
  13733. this.material = null;
  13734. this.uvs = [[]];
  13735. this.z = null;
  13736. };
  13737. /**
  13738. * @author mrdoob / http://mrdoob.com/
  13739. */
  13740. THREE.RenderableObject = function () {
  13741. this.object = null;
  13742. this.z = null;
  13743. };
  13744. /**
  13745. * @author mrdoob / http://mrdoob.com/
  13746. */
  13747. THREE.RenderableParticle = function () {
  13748. this.object = null;
  13749. this.x = null;
  13750. this.y = null;
  13751. this.z = null;
  13752. this.rotation = null;
  13753. this.scale = new THREE.Vector2();
  13754. this.material = null;
  13755. };
  13756. /**
  13757. * @author mrdoob / http://mrdoob.com/
  13758. */
  13759. THREE.RenderableLine = function () {
  13760. this.z = null;
  13761. this.v1 = new THREE.RenderableVertex();
  13762. this.v2 = new THREE.RenderableVertex();
  13763. this.material = null;
  13764. };
  13765. /**
  13766. * @author alteredq / http://alteredqualia.com/
  13767. */
  13768. THREE.ColorUtils = {
  13769. adjustHSV : function ( color, h, s, v ) {
  13770. var hsv = THREE.ColorUtils.__hsv;
  13771. color.getHSV( hsv );
  13772. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  13773. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  13774. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  13775. color.setHSV( hsv.h, hsv.s, hsv.v );
  13776. }
  13777. };
  13778. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  13779. * @author mrdoob / http://mrdoob.com/
  13780. * @author alteredq / http://alteredqualia.com/
  13781. */
  13782. THREE.GeometryUtils = {
  13783. // Merge two geometries or geometry and geometry from object (using object's transform)
  13784. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  13785. var matrix, matrixRotation,
  13786. vertexOffset = geometry1.vertices.length,
  13787. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  13788. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  13789. vertices1 = geometry1.vertices,
  13790. vertices2 = geometry2.vertices,
  13791. faces1 = geometry1.faces,
  13792. faces2 = geometry2.faces,
  13793. uvs1 = geometry1.faceVertexUvs[ 0 ],
  13794. uvs2 = geometry2.faceVertexUvs[ 0 ];
  13795. if ( object2 instanceof THREE.Mesh ) {
  13796. object2.matrixAutoUpdate && object2.updateMatrix();
  13797. matrix = object2.matrix;
  13798. matrixRotation = new THREE.Matrix4();
  13799. matrixRotation.extractRotation( matrix, object2.scale );
  13800. }
  13801. // vertices
  13802. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  13803. var vertex = vertices2[ i ];
  13804. var vertexCopy = vertex.clone();
  13805. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  13806. vertices1.push( vertexCopy );
  13807. }
  13808. // faces
  13809. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  13810. var face = faces2[ i ], faceCopy, normal, color,
  13811. faceVertexNormals = face.vertexNormals,
  13812. faceVertexColors = face.vertexColors;
  13813. if ( face instanceof THREE.Face3 ) {
  13814. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  13815. } else if ( face instanceof THREE.Face4 ) {
  13816. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  13817. }
  13818. faceCopy.normal.copy( face.normal );
  13819. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  13820. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  13821. normal = faceVertexNormals[ j ].clone();
  13822. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  13823. faceCopy.vertexNormals.push( normal );
  13824. }
  13825. faceCopy.color.copy( face.color );
  13826. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  13827. color = faceVertexColors[ j ];
  13828. faceCopy.vertexColors.push( color.clone() );
  13829. }
  13830. faceCopy.materialIndex = face.materialIndex;
  13831. faceCopy.centroid.copy( face.centroid );
  13832. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  13833. faces1.push( faceCopy );
  13834. }
  13835. // uvs
  13836. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  13837. var uv = uvs2[ i ], uvCopy = [];
  13838. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13839. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13840. }
  13841. uvs1.push( uvCopy );
  13842. }
  13843. },
  13844. removeMaterials: function ( geometry, materialIndexArray ) {
  13845. var materialIndexMap = {};
  13846. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  13847. materialIndexMap[ materialIndexArray[i] ] = true;
  13848. }
  13849. var face, newFaces = [];
  13850. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13851. face = geometry.faces[ i ];
  13852. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  13853. }
  13854. geometry.faces = newFaces;
  13855. },
  13856. // Get random point in triangle (via barycentric coordinates)
  13857. // (uniform distribution)
  13858. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  13859. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  13860. var a, b, c,
  13861. point = new THREE.Vector3(),
  13862. tmp = THREE.GeometryUtils.__v1;
  13863. a = THREE.GeometryUtils.random();
  13864. b = THREE.GeometryUtils.random();
  13865. if ( ( a + b ) > 1 ) {
  13866. a = 1 - a;
  13867. b = 1 - b;
  13868. }
  13869. c = 1 - a - b;
  13870. point.copy( vectorA );
  13871. point.multiplyScalar( a );
  13872. tmp.copy( vectorB );
  13873. tmp.multiplyScalar( b );
  13874. point.addSelf( tmp );
  13875. tmp.copy( vectorC );
  13876. tmp.multiplyScalar( c );
  13877. point.addSelf( tmp );
  13878. return point;
  13879. },
  13880. // Get random point in face (triangle / quad)
  13881. // (uniform distribution)
  13882. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  13883. var vA, vB, vC, vD;
  13884. if ( face instanceof THREE.Face3 ) {
  13885. vA = geometry.vertices[ face.a ];
  13886. vB = geometry.vertices[ face.b ];
  13887. vC = geometry.vertices[ face.c ];
  13888. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  13889. } else if ( face instanceof THREE.Face4 ) {
  13890. vA = geometry.vertices[ face.a ];
  13891. vB = geometry.vertices[ face.b ];
  13892. vC = geometry.vertices[ face.c ];
  13893. vD = geometry.vertices[ face.d ];
  13894. var area1, area2;
  13895. if ( useCachedAreas ) {
  13896. if ( face._area1 && face._area2 ) {
  13897. area1 = face._area1;
  13898. area2 = face._area2;
  13899. } else {
  13900. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13901. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13902. face._area1 = area1;
  13903. face._area2 = area2;
  13904. }
  13905. } else {
  13906. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  13907. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13908. }
  13909. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  13910. if ( r < area1 ) {
  13911. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  13912. } else {
  13913. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  13914. }
  13915. }
  13916. },
  13917. // Get uniformly distributed random points in mesh
  13918. // - create array with cumulative sums of face areas
  13919. // - pick random number from 0 to total area
  13920. // - find corresponding place in area array by binary search
  13921. // - get random point in face
  13922. randomPointsInGeometry: function ( geometry, n ) {
  13923. var face, i,
  13924. faces = geometry.faces,
  13925. vertices = geometry.vertices,
  13926. il = faces.length,
  13927. totalArea = 0,
  13928. cumulativeAreas = [],
  13929. vA, vB, vC, vD;
  13930. // precompute face areas
  13931. for ( i = 0; i < il; i ++ ) {
  13932. face = faces[ i ];
  13933. if ( face instanceof THREE.Face3 ) {
  13934. vA = vertices[ face.a ];
  13935. vB = vertices[ face.b ];
  13936. vC = vertices[ face.c ];
  13937. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  13938. } else if ( face instanceof THREE.Face4 ) {
  13939. vA = vertices[ face.a ];
  13940. vB = vertices[ face.b ];
  13941. vC = vertices[ face.c ];
  13942. vD = vertices[ face.d ];
  13943. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13944. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13945. face._area = face._area1 + face._area2;
  13946. }
  13947. totalArea += face._area;
  13948. cumulativeAreas[ i ] = totalArea;
  13949. }
  13950. // binary search cumulative areas array
  13951. function binarySearchIndices( value ) {
  13952. function binarySearch( start, end ) {
  13953. // return closest larger index
  13954. // if exact number is not found
  13955. if ( end < start )
  13956. return start;
  13957. var mid = start + Math.floor( ( end - start ) / 2 );
  13958. if ( cumulativeAreas[ mid ] > value ) {
  13959. return binarySearch( start, mid - 1 );
  13960. } else if ( cumulativeAreas[ mid ] < value ) {
  13961. return binarySearch( mid + 1, end );
  13962. } else {
  13963. return mid;
  13964. }
  13965. }
  13966. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  13967. return result;
  13968. }
  13969. // pick random face weighted by face area
  13970. var r, index,
  13971. result = [];
  13972. var stats = {};
  13973. for ( i = 0; i < n; i ++ ) {
  13974. r = THREE.GeometryUtils.random() * totalArea;
  13975. index = binarySearchIndices( r );
  13976. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  13977. if ( ! stats[ index ] ) {
  13978. stats[ index ] = 1;
  13979. } else {
  13980. stats[ index ] += 1;
  13981. }
  13982. }
  13983. return result;
  13984. },
  13985. // Get triangle area (by Heron's formula)
  13986. // http://en.wikipedia.org/wiki/Heron%27s_formula
  13987. triangleArea: function ( vectorA, vectorB, vectorC ) {
  13988. var s, a, b, c,
  13989. tmp = THREE.GeometryUtils.__v1;
  13990. tmp.sub( vectorA, vectorB );
  13991. a = tmp.length();
  13992. tmp.sub( vectorA, vectorC );
  13993. b = tmp.length();
  13994. tmp.sub( vectorB, vectorC );
  13995. c = tmp.length();
  13996. s = 0.5 * ( a + b + c );
  13997. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  13998. },
  13999. // Center geometry so that 0,0,0 is in center of bounding box
  14000. center: function ( geometry ) {
  14001. geometry.computeBoundingBox();
  14002. var bb = geometry.boundingBox;
  14003. var offset = new THREE.Vector3();
  14004. offset.add( bb.min, bb.max );
  14005. offset.multiplyScalar( -0.5 );
  14006. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  14007. geometry.computeBoundingBox();
  14008. return offset;
  14009. },
  14010. // Normalize UVs to be from <0,1>
  14011. // (for now just the first set of UVs)
  14012. normalizeUVs: function ( geometry ) {
  14013. var uvSet = geometry.faceVertexUvs[ 0 ];
  14014. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  14015. var uvs = uvSet[ i ];
  14016. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  14017. // texture repeat
  14018. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  14019. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  14020. }
  14021. }
  14022. },
  14023. triangulateQuads: function ( geometry ) {
  14024. var i, il, j, jl;
  14025. var faces = [];
  14026. var faceUvs = [];
  14027. var faceVertexUvs = [];
  14028. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  14029. faceUvs[ i ] = [];
  14030. }
  14031. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14032. faceVertexUvs[ i ] = [];
  14033. }
  14034. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14035. var face = geometry.faces[ i ];
  14036. if ( face instanceof THREE.Face4 ) {
  14037. var a = face.a;
  14038. var b = face.b;
  14039. var c = face.c;
  14040. var d = face.d;
  14041. var triA = new THREE.Face3();
  14042. var triB = new THREE.Face3();
  14043. triA.color.copy( face.color );
  14044. triB.color.copy( face.color );
  14045. triA.materialIndex = face.materialIndex;
  14046. triB.materialIndex = face.materialIndex;
  14047. triA.a = a;
  14048. triA.b = b;
  14049. triA.c = d;
  14050. triB.a = b;
  14051. triB.b = c;
  14052. triB.c = d;
  14053. if ( face.vertexColors.length === 4 ) {
  14054. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  14055. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  14056. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14057. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  14058. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  14059. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14060. }
  14061. faces.push( triA, triB );
  14062. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14063. if ( geometry.faceVertexUvs[ j ].length ) {
  14064. var uvs = geometry.faceVertexUvs[ j ][ i ];
  14065. var uvA = uvs[ 0 ];
  14066. var uvB = uvs[ 1 ];
  14067. var uvC = uvs[ 2 ];
  14068. var uvD = uvs[ 3 ];
  14069. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  14070. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  14071. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14072. }
  14073. }
  14074. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14075. if ( geometry.faceUvs[ j ].length ) {
  14076. var faceUv = geometry.faceUvs[ j ][ i ];
  14077. faceUvs[ j ].push( faceUv, faceUv );
  14078. }
  14079. }
  14080. } else {
  14081. faces.push( face );
  14082. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14083. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  14084. }
  14085. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14086. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14087. }
  14088. }
  14089. }
  14090. geometry.faces = faces;
  14091. geometry.faceUvs = faceUvs;
  14092. geometry.faceVertexUvs = faceVertexUvs;
  14093. geometry.computeCentroids();
  14094. geometry.computeFaceNormals();
  14095. geometry.computeVertexNormals();
  14096. if ( geometry.hasTangents ) geometry.computeTangents();
  14097. },
  14098. // Make all faces use unique vertices
  14099. // so that each face can be separated from others
  14100. explode: function( geometry ) {
  14101. var vertices = [];
  14102. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14103. var n = vertices.length;
  14104. var face = geometry.faces[ i ];
  14105. if ( face instanceof THREE.Face4 ) {
  14106. var a = face.a;
  14107. var b = face.b;
  14108. var c = face.c;
  14109. var d = face.d;
  14110. var va = geometry.vertices[ a ];
  14111. var vb = geometry.vertices[ b ];
  14112. var vc = geometry.vertices[ c ];
  14113. var vd = geometry.vertices[ d ];
  14114. vertices.push( va.clone() );
  14115. vertices.push( vb.clone() );
  14116. vertices.push( vc.clone() );
  14117. vertices.push( vd.clone() );
  14118. face.a = n;
  14119. face.b = n + 1;
  14120. face.c = n + 2;
  14121. face.d = n + 3;
  14122. } else {
  14123. var a = face.a;
  14124. var b = face.b;
  14125. var c = face.c;
  14126. var va = geometry.vertices[ a ];
  14127. var vb = geometry.vertices[ b ];
  14128. var vc = geometry.vertices[ c ];
  14129. vertices.push( va.clone() );
  14130. vertices.push( vb.clone() );
  14131. vertices.push( vc.clone() );
  14132. face.a = n;
  14133. face.b = n + 1;
  14134. face.c = n + 2;
  14135. }
  14136. }
  14137. geometry.vertices = vertices;
  14138. delete geometry.__tmpVertices;
  14139. },
  14140. // Break faces with edges longer than maxEdgeLength
  14141. // - not recursive
  14142. tessellate: function ( geometry, maxEdgeLength ) {
  14143. var i, il, face,
  14144. a, b, c, d,
  14145. va, vb, vc, vd,
  14146. dab, dbc, dac, dcd, dad,
  14147. m, m1, m2,
  14148. vm, vm1, vm2,
  14149. vnm, vnm1, vnm2,
  14150. vcm, vcm1, vcm2,
  14151. triA, triB,
  14152. quadA, quadB,
  14153. edge;
  14154. var faces = [];
  14155. var faceVertexUvs = [];
  14156. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14157. faceVertexUvs[ i ] = [];
  14158. }
  14159. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14160. face = geometry.faces[ i ];
  14161. if ( face instanceof THREE.Face3 ) {
  14162. a = face.a;
  14163. b = face.b;
  14164. c = face.c;
  14165. va = geometry.vertices[ a ];
  14166. vb = geometry.vertices[ b ];
  14167. vc = geometry.vertices[ c ];
  14168. dab = va.distanceTo( vb );
  14169. dbc = vb.distanceTo( vc );
  14170. dac = va.distanceTo( vc );
  14171. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  14172. m = geometry.vertices.length;
  14173. triA = face.clone();
  14174. triB = face.clone();
  14175. if ( dab >= dbc && dab >= dac ) {
  14176. vm = va.clone();
  14177. vm.lerpSelf( vb, 0.5 );
  14178. triA.a = a;
  14179. triA.b = m;
  14180. triA.c = c;
  14181. triB.a = m;
  14182. triB.b = b;
  14183. triB.c = c;
  14184. if ( face.vertexNormals.length === 3 ) {
  14185. vnm = face.vertexNormals[ 0 ].clone();
  14186. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14187. triA.vertexNormals[ 1 ].copy( vnm );
  14188. triB.vertexNormals[ 0 ].copy( vnm );
  14189. }
  14190. if ( face.vertexColors.length === 3 ) {
  14191. vcm = face.vertexColors[ 0 ].clone();
  14192. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14193. triA.vertexColors[ 1 ].copy( vcm );
  14194. triB.vertexColors[ 0 ].copy( vcm );
  14195. }
  14196. edge = 0;
  14197. } else if ( dbc >= dab && dbc >= dac ) {
  14198. vm = vb.clone();
  14199. vm.lerpSelf( vc, 0.5 );
  14200. triA.a = a;
  14201. triA.b = b;
  14202. triA.c = m;
  14203. triB.a = m;
  14204. triB.b = c;
  14205. triB.c = a;
  14206. if ( face.vertexNormals.length === 3 ) {
  14207. vnm = face.vertexNormals[ 1 ].clone();
  14208. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14209. triA.vertexNormals[ 2 ].copy( vnm );
  14210. triB.vertexNormals[ 0 ].copy( vnm );
  14211. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  14212. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  14213. }
  14214. if ( face.vertexColors.length === 3 ) {
  14215. vcm = face.vertexColors[ 1 ].clone();
  14216. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14217. triA.vertexColors[ 2 ].copy( vcm );
  14218. triB.vertexColors[ 0 ].copy( vcm );
  14219. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  14220. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  14221. }
  14222. edge = 1;
  14223. } else {
  14224. vm = va.clone();
  14225. vm.lerpSelf( vc, 0.5 );
  14226. triA.a = a;
  14227. triA.b = b;
  14228. triA.c = m;
  14229. triB.a = m;
  14230. triB.b = b;
  14231. triB.c = c;
  14232. if ( face.vertexNormals.length === 3 ) {
  14233. vnm = face.vertexNormals[ 0 ].clone();
  14234. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14235. triA.vertexNormals[ 2 ].copy( vnm );
  14236. triB.vertexNormals[ 0 ].copy( vnm );
  14237. }
  14238. if ( face.vertexColors.length === 3 ) {
  14239. vcm = face.vertexColors[ 0 ].clone();
  14240. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14241. triA.vertexColors[ 2 ].copy( vcm );
  14242. triB.vertexColors[ 0 ].copy( vcm );
  14243. }
  14244. edge = 2;
  14245. }
  14246. faces.push( triA, triB );
  14247. geometry.vertices.push( vm );
  14248. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  14249. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14250. if ( geometry.faceVertexUvs[ j ].length ) {
  14251. uvs = geometry.faceVertexUvs[ j ][ i ];
  14252. uvA = uvs[ 0 ];
  14253. uvB = uvs[ 1 ];
  14254. uvC = uvs[ 2 ];
  14255. // AB
  14256. if ( edge === 0 ) {
  14257. uvM = uvA.clone();
  14258. uvM.lerpSelf( uvB, 0.5 );
  14259. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  14260. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14261. // BC
  14262. } else if ( edge === 1 ) {
  14263. uvM = uvB.clone();
  14264. uvM.lerpSelf( uvC, 0.5 );
  14265. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14266. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  14267. // AC
  14268. } else {
  14269. uvM = uvA.clone();
  14270. uvM.lerpSelf( uvC, 0.5 );
  14271. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14272. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14273. }
  14274. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14275. }
  14276. }
  14277. } else {
  14278. faces.push( face );
  14279. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14280. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14281. }
  14282. }
  14283. } else {
  14284. a = face.a;
  14285. b = face.b;
  14286. c = face.c;
  14287. d = face.d;
  14288. va = geometry.vertices[ a ];
  14289. vb = geometry.vertices[ b ];
  14290. vc = geometry.vertices[ c ];
  14291. vd = geometry.vertices[ d ];
  14292. dab = va.distanceTo( vb );
  14293. dbc = vb.distanceTo( vc );
  14294. dcd = vc.distanceTo( vd );
  14295. dad = va.distanceTo( vd );
  14296. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  14297. m1 = geometry.vertices.length;
  14298. m2 = geometry.vertices.length + 1;
  14299. quadA = face.clone();
  14300. quadB = face.clone();
  14301. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  14302. vm1 = va.clone();
  14303. vm1.lerpSelf( vb, 0.5 );
  14304. vm2 = vc.clone();
  14305. vm2.lerpSelf( vd, 0.5 );
  14306. quadA.a = a;
  14307. quadA.b = m1;
  14308. quadA.c = m2;
  14309. quadA.d = d;
  14310. quadB.a = m1;
  14311. quadB.b = b;
  14312. quadB.c = c;
  14313. quadB.d = m2;
  14314. if ( face.vertexNormals.length === 4 ) {
  14315. vnm1 = face.vertexNormals[ 0 ].clone();
  14316. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14317. vnm2 = face.vertexNormals[ 2 ].clone();
  14318. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  14319. quadA.vertexNormals[ 1 ].copy( vnm1 );
  14320. quadA.vertexNormals[ 2 ].copy( vnm2 );
  14321. quadB.vertexNormals[ 0 ].copy( vnm1 );
  14322. quadB.vertexNormals[ 3 ].copy( vnm2 );
  14323. }
  14324. if ( face.vertexColors.length === 4 ) {
  14325. vcm1 = face.vertexColors[ 0 ].clone();
  14326. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14327. vcm2 = face.vertexColors[ 2 ].clone();
  14328. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  14329. quadA.vertexColors[ 1 ].copy( vcm1 );
  14330. quadA.vertexColors[ 2 ].copy( vcm2 );
  14331. quadB.vertexColors[ 0 ].copy( vcm1 );
  14332. quadB.vertexColors[ 3 ].copy( vcm2 );
  14333. }
  14334. edge = 0;
  14335. } else {
  14336. vm1 = vb.clone();
  14337. vm1.lerpSelf( vc, 0.5 );
  14338. vm2 = vd.clone();
  14339. vm2.lerpSelf( va, 0.5 );
  14340. quadA.a = a;
  14341. quadA.b = b;
  14342. quadA.c = m1;
  14343. quadA.d = m2;
  14344. quadB.a = m2;
  14345. quadB.b = m1;
  14346. quadB.c = c;
  14347. quadB.d = d;
  14348. if ( face.vertexNormals.length === 4 ) {
  14349. vnm1 = face.vertexNormals[ 1 ].clone();
  14350. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14351. vnm2 = face.vertexNormals[ 3 ].clone();
  14352. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  14353. quadA.vertexNormals[ 2 ].copy( vnm1 );
  14354. quadA.vertexNormals[ 3 ].copy( vnm2 );
  14355. quadB.vertexNormals[ 0 ].copy( vnm2 );
  14356. quadB.vertexNormals[ 1 ].copy( vnm1 );
  14357. }
  14358. if ( face.vertexColors.length === 4 ) {
  14359. vcm1 = face.vertexColors[ 1 ].clone();
  14360. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14361. vcm2 = face.vertexColors[ 3 ].clone();
  14362. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  14363. quadA.vertexColors[ 2 ].copy( vcm1 );
  14364. quadA.vertexColors[ 3 ].copy( vcm2 );
  14365. quadB.vertexColors[ 0 ].copy( vcm2 );
  14366. quadB.vertexColors[ 1 ].copy( vcm1 );
  14367. }
  14368. edge = 1;
  14369. }
  14370. faces.push( quadA, quadB );
  14371. geometry.vertices.push( vm1, vm2 );
  14372. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  14373. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14374. if ( geometry.faceVertexUvs[ j ].length ) {
  14375. uvs = geometry.faceVertexUvs[ j ][ i ];
  14376. uvA = uvs[ 0 ];
  14377. uvB = uvs[ 1 ];
  14378. uvC = uvs[ 2 ];
  14379. uvD = uvs[ 3 ];
  14380. // AB + CD
  14381. if ( edge === 0 ) {
  14382. uvM1 = uvA.clone();
  14383. uvM1.lerpSelf( uvB, 0.5 );
  14384. uvM2 = uvC.clone();
  14385. uvM2.lerpSelf( uvD, 0.5 );
  14386. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  14387. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  14388. // BC + AD
  14389. } else {
  14390. uvM1 = uvB.clone();
  14391. uvM1.lerpSelf( uvC, 0.5 );
  14392. uvM2 = uvD.clone();
  14393. uvM2.lerpSelf( uvA, 0.5 );
  14394. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  14395. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  14396. }
  14397. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  14398. }
  14399. }
  14400. } else {
  14401. faces.push( face );
  14402. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14403. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14404. }
  14405. }
  14406. }
  14407. }
  14408. geometry.faces = faces;
  14409. geometry.faceVertexUvs = faceVertexUvs;
  14410. }
  14411. };
  14412. THREE.GeometryUtils.random = THREE.Math.random16;
  14413. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  14414. /**
  14415. * @author alteredq / http://alteredqualia.com/
  14416. * @author mrdoob / http://mrdoob.com/
  14417. */
  14418. THREE.ImageUtils = {
  14419. crossOrigin: 'anonymous',
  14420. loadTexture: function ( url, mapping, onLoad, onError ) {
  14421. var image = new Image();
  14422. var texture = new THREE.Texture( image, mapping );
  14423. var loader = new THREE.ImageLoader();
  14424. loader.addEventListener( 'load', function ( event ) {
  14425. texture.image = event.content;
  14426. texture.needsUpdate = true;
  14427. if ( onLoad ) onLoad( texture );
  14428. } );
  14429. loader.addEventListener( 'error', function ( event ) {
  14430. if ( onError ) onError( event.message );
  14431. } );
  14432. loader.crossOrigin = this.crossOrigin;
  14433. loader.load( url, image );
  14434. texture.sourceFile = url;
  14435. return texture;
  14436. },
  14437. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  14438. var texture = new THREE.CompressedTexture();
  14439. texture.mapping = mapping;
  14440. var request = new XMLHttpRequest();
  14441. request.onload = function () {
  14442. var buffer = request.response;
  14443. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14444. texture.format = dds.format;
  14445. texture.mipmaps = dds.mipmaps;
  14446. texture.image.width = dds.width;
  14447. texture.image.height = dds.height;
  14448. // gl.generateMipmap fails for compressed textures
  14449. // mipmaps must be embedded in the DDS file
  14450. // or texture filters must not use mipmapping
  14451. texture.generateMipmaps = false;
  14452. texture.needsUpdate = true;
  14453. if ( onLoad ) onLoad( texture );
  14454. }
  14455. request.onerror = onError;
  14456. request.open( 'GET', url, true );
  14457. request.responseType = "arraybuffer";
  14458. request.send( null );
  14459. return texture;
  14460. },
  14461. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  14462. var images = [];
  14463. images.loadCount = 0;
  14464. var texture = new THREE.Texture();
  14465. texture.image = images;
  14466. if ( mapping !== undefined ) texture.mapping = mapping;
  14467. // no flipping needed for cube textures
  14468. texture.flipY = false;
  14469. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14470. var cubeImage = new Image();
  14471. images[ i ] = cubeImage;
  14472. cubeImage.onload = function () {
  14473. images.loadCount += 1;
  14474. if ( images.loadCount === 6 ) {
  14475. texture.needsUpdate = true;
  14476. if ( onLoad ) onLoad();
  14477. }
  14478. };
  14479. cubeImage.onerror = onError;
  14480. cubeImage.crossOrigin = this.crossOrigin;
  14481. cubeImage.src = array[ i ];
  14482. }
  14483. return texture;
  14484. },
  14485. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  14486. var images = [];
  14487. images.loadCount = 0;
  14488. var texture = new THREE.CompressedTexture();
  14489. texture.image = images;
  14490. if ( mapping !== undefined ) texture.mapping = mapping;
  14491. // no flipping for cube textures
  14492. // (also flipping doesn't work for compressed textures )
  14493. texture.flipY = false;
  14494. // can't generate mipmaps for compressed textures
  14495. // mips must be embedded in DDS files
  14496. texture.generateMipmaps = false;
  14497. var generateCubeFaceCallback = function ( rq, img ) {
  14498. return function () {
  14499. var buffer = rq.response;
  14500. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14501. img.format = dds.format;
  14502. img.mipmaps = dds.mipmaps;
  14503. img.width = dds.width;
  14504. img.height = dds.height;
  14505. images.loadCount += 1;
  14506. if ( images.loadCount === 6 ) {
  14507. texture.format = dds.format;
  14508. texture.needsUpdate = true;
  14509. if ( onLoad ) onLoad();
  14510. }
  14511. }
  14512. }
  14513. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14514. var cubeImage = {};
  14515. images[ i ] = cubeImage;
  14516. var request = new XMLHttpRequest();
  14517. request.onload = generateCubeFaceCallback( request, cubeImage );
  14518. request.onerror = onError;
  14519. var url = array[ i ];
  14520. request.open( 'GET', url, true );
  14521. request.responseType = "arraybuffer";
  14522. request.send( null );
  14523. }
  14524. return texture;
  14525. },
  14526. parseDDS: function ( buffer, loadMipmaps ) {
  14527. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  14528. // Adapted from @toji's DDS utils
  14529. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  14530. // All values and structures referenced from:
  14531. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  14532. var DDS_MAGIC = 0x20534444;
  14533. var DDSD_CAPS = 0x1,
  14534. DDSD_HEIGHT = 0x2,
  14535. DDSD_WIDTH = 0x4,
  14536. DDSD_PITCH = 0x8,
  14537. DDSD_PIXELFORMAT = 0x1000,
  14538. DDSD_MIPMAPCOUNT = 0x20000,
  14539. DDSD_LINEARSIZE = 0x80000,
  14540. DDSD_DEPTH = 0x800000;
  14541. var DDSCAPS_COMPLEX = 0x8,
  14542. DDSCAPS_MIPMAP = 0x400000,
  14543. DDSCAPS_TEXTURE = 0x1000;
  14544. var DDSCAPS2_CUBEMAP = 0x200,
  14545. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  14546. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  14547. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  14548. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  14549. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  14550. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  14551. DDSCAPS2_VOLUME = 0x200000;
  14552. var DDPF_ALPHAPIXELS = 0x1,
  14553. DDPF_ALPHA = 0x2,
  14554. DDPF_FOURCC = 0x4,
  14555. DDPF_RGB = 0x40,
  14556. DDPF_YUV = 0x200,
  14557. DDPF_LUMINANCE = 0x20000;
  14558. function fourCCToInt32( value ) {
  14559. return value.charCodeAt(0) +
  14560. (value.charCodeAt(1) << 8) +
  14561. (value.charCodeAt(2) << 16) +
  14562. (value.charCodeAt(3) << 24);
  14563. }
  14564. function int32ToFourCC( value ) {
  14565. return String.fromCharCode(
  14566. value & 0xff,
  14567. (value >> 8) & 0xff,
  14568. (value >> 16) & 0xff,
  14569. (value >> 24) & 0xff
  14570. );
  14571. }
  14572. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  14573. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  14574. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  14575. var headerLengthInt = 31; // The header length in 32 bit ints
  14576. // Offsets into the header array
  14577. var off_magic = 0;
  14578. var off_size = 1;
  14579. var off_flags = 2;
  14580. var off_height = 3;
  14581. var off_width = 4;
  14582. var off_mipmapCount = 7;
  14583. var off_pfFlags = 20;
  14584. var off_pfFourCC = 21;
  14585. // Parse header
  14586. var header = new Int32Array( buffer, 0, headerLengthInt );
  14587. if ( header[ off_magic ] !== DDS_MAGIC ) {
  14588. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  14589. return dds;
  14590. }
  14591. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  14592. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  14593. return dds;
  14594. }
  14595. var blockBytes;
  14596. var fourCC = header[ off_pfFourCC ];
  14597. switch ( fourCC ) {
  14598. case FOURCC_DXT1:
  14599. blockBytes = 8;
  14600. dds.format = THREE.RGB_S3TC_DXT1_Format;
  14601. break;
  14602. case FOURCC_DXT3:
  14603. blockBytes = 16;
  14604. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  14605. break;
  14606. case FOURCC_DXT5:
  14607. blockBytes = 16;
  14608. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  14609. break;
  14610. default:
  14611. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  14612. return dds;
  14613. }
  14614. dds.mipmapCount = 1;
  14615. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  14616. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  14617. }
  14618. dds.width = header[ off_width ];
  14619. dds.height = header[ off_height ];
  14620. var dataOffset = header[ off_size ] + 4;
  14621. // Extract mipmaps buffers
  14622. var width = dds.width;
  14623. var height = dds.height;
  14624. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  14625. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  14626. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  14627. var mipmap = { "data": byteArray, "width": width, "height": height };
  14628. dds.mipmaps.push( mipmap );
  14629. dataOffset += dataLength;
  14630. width = Math.max( width * 0.5, 1 );
  14631. height = Math.max( height * 0.5, 1 );
  14632. }
  14633. return dds;
  14634. },
  14635. getNormalMap: function ( image, depth ) {
  14636. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  14637. var cross = function ( a, b ) {
  14638. 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 ] ];
  14639. }
  14640. var subtract = function ( a, b ) {
  14641. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  14642. }
  14643. var normalize = function ( a ) {
  14644. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  14645. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  14646. }
  14647. depth = depth | 1;
  14648. var width = image.width;
  14649. var height = image.height;
  14650. var canvas = document.createElement( 'canvas' );
  14651. canvas.width = width;
  14652. canvas.height = height;
  14653. var context = canvas.getContext( '2d' );
  14654. context.drawImage( image, 0, 0 );
  14655. var data = context.getImageData( 0, 0, width, height ).data;
  14656. var imageData = context.createImageData( width, height );
  14657. var output = imageData.data;
  14658. for ( var x = 0; x < width; x ++ ) {
  14659. for ( var y = 0; y < height; y ++ ) {
  14660. var ly = y - 1 < 0 ? 0 : y - 1;
  14661. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  14662. var lx = x - 1 < 0 ? 0 : x - 1;
  14663. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  14664. var points = [];
  14665. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  14666. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  14667. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  14668. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  14669. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  14670. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  14671. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  14672. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  14673. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  14674. var normals = [];
  14675. var num_points = points.length;
  14676. for ( var i = 0; i < num_points; i ++ ) {
  14677. var v1 = points[ i ];
  14678. var v2 = points[ ( i + 1 ) % num_points ];
  14679. v1 = subtract( v1, origin );
  14680. v2 = subtract( v2, origin );
  14681. normals.push( normalize( cross( v1, v2 ) ) );
  14682. }
  14683. var normal = [ 0, 0, 0 ];
  14684. for ( var i = 0; i < normals.length; i ++ ) {
  14685. normal[ 0 ] += normals[ i ][ 0 ];
  14686. normal[ 1 ] += normals[ i ][ 1 ];
  14687. normal[ 2 ] += normals[ i ][ 2 ];
  14688. }
  14689. normal[ 0 ] /= normals.length;
  14690. normal[ 1 ] /= normals.length;
  14691. normal[ 2 ] /= normals.length;
  14692. var idx = ( y * width + x ) * 4;
  14693. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14694. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14695. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  14696. output[ idx + 3 ] = 255;
  14697. }
  14698. }
  14699. context.putImageData( imageData, 0, 0 );
  14700. return canvas;
  14701. },
  14702. generateDataTexture: function ( width, height, color ) {
  14703. var size = width * height;
  14704. var data = new Uint8Array( 3 * size );
  14705. var r = Math.floor( color.r * 255 );
  14706. var g = Math.floor( color.g * 255 );
  14707. var b = Math.floor( color.b * 255 );
  14708. for ( var i = 0; i < size; i ++ ) {
  14709. data[ i * 3 ] = r;
  14710. data[ i * 3 + 1 ] = g;
  14711. data[ i * 3 + 2 ] = b;
  14712. }
  14713. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  14714. texture.needsUpdate = true;
  14715. return texture;
  14716. }
  14717. };
  14718. /**
  14719. * @author alteredq / http://alteredqualia.com/
  14720. */
  14721. THREE.SceneUtils = {
  14722. createMultiMaterialObject: function ( geometry, materials ) {
  14723. var group = new THREE.Object3D();
  14724. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  14725. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  14726. }
  14727. return group;
  14728. },
  14729. detach : function ( child, parent, scene ) {
  14730. child.applyMatrix( parent.matrixWorld );
  14731. parent.remove( child );
  14732. scene.add( child );
  14733. },
  14734. attach: function ( child, scene, parent ) {
  14735. var matrixWorldInverse = new THREE.Matrix4();
  14736. matrixWorldInverse.getInverse( parent.matrixWorld );
  14737. child.applyMatrix( matrixWorldInverse );
  14738. scene.remove( child );
  14739. parent.add( child );
  14740. }
  14741. };
  14742. /**
  14743. * @author alteredq / http://alteredqualia.com/
  14744. * @author mrdoob / http://mrdoob.com/
  14745. *
  14746. * ShaderUtils currently contains:
  14747. *
  14748. * fresnel
  14749. * normal
  14750. * cube
  14751. *
  14752. */
  14753. THREE.ShaderUtils = {
  14754. lib: {
  14755. /* -------------------------------------------------------------------------
  14756. // Fresnel shader
  14757. // - based on Nvidia Cg tutorial
  14758. ------------------------------------------------------------------------- */
  14759. 'fresnel': {
  14760. uniforms: {
  14761. "mRefractionRatio": { type: "f", value: 1.02 },
  14762. "mFresnelBias": { type: "f", value: 0.1 },
  14763. "mFresnelPower": { type: "f", value: 2.0 },
  14764. "mFresnelScale": { type: "f", value: 1.0 },
  14765. "tCube": { type: "t", value: null }
  14766. },
  14767. fragmentShader: [
  14768. "uniform samplerCube tCube;",
  14769. "varying vec3 vReflect;",
  14770. "varying vec3 vRefract[3];",
  14771. "varying float vReflectionFactor;",
  14772. "void main() {",
  14773. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14774. "vec4 refractedColor = vec4( 1.0 );",
  14775. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  14776. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  14777. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  14778. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  14779. "}"
  14780. ].join("\n"),
  14781. vertexShader: [
  14782. "uniform float mRefractionRatio;",
  14783. "uniform float mFresnelBias;",
  14784. "uniform float mFresnelScale;",
  14785. "uniform float mFresnelPower;",
  14786. "varying vec3 vReflect;",
  14787. "varying vec3 vRefract[3];",
  14788. "varying float vReflectionFactor;",
  14789. "void main() {",
  14790. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14791. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  14792. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  14793. "vec3 I = worldPosition.xyz - cameraPosition;",
  14794. "vReflect = reflect( I, worldNormal );",
  14795. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  14796. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  14797. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  14798. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  14799. "gl_Position = projectionMatrix * mvPosition;",
  14800. "}"
  14801. ].join("\n")
  14802. },
  14803. /* -------------------------------------------------------------------------
  14804. // Normal map shader
  14805. // - Blinn-Phong
  14806. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  14807. // - point and directional lights (use with "lights: true" material option)
  14808. ------------------------------------------------------------------------- */
  14809. 'normal' : {
  14810. uniforms: THREE.UniformsUtils.merge( [
  14811. THREE.UniformsLib[ "fog" ],
  14812. THREE.UniformsLib[ "lights" ],
  14813. THREE.UniformsLib[ "shadowmap" ],
  14814. {
  14815. "enableAO" : { type: "i", value: 0 },
  14816. "enableDiffuse" : { type: "i", value: 0 },
  14817. "enableSpecular" : { type: "i", value: 0 },
  14818. "enableReflection": { type: "i", value: 0 },
  14819. "enableDisplacement": { type: "i", value: 0 },
  14820. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  14821. "tDiffuse" : { type: "t", value: null },
  14822. "tCube" : { type: "t", value: null },
  14823. "tNormal" : { type: "t", value: null },
  14824. "tSpecular" : { type: "t", value: null },
  14825. "tAO" : { type: "t", value: null },
  14826. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14827. "uDisplacementBias": { type: "f", value: 0.0 },
  14828. "uDisplacementScale": { type: "f", value: 1.0 },
  14829. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14830. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  14831. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14832. "uShininess": { type: "f", value: 30 },
  14833. "uOpacity": { type: "f", value: 1 },
  14834. "useRefract": { type: "i", value: 0 },
  14835. "uRefractionRatio": { type: "f", value: 0.98 },
  14836. "uReflectivity": { type: "f", value: 0.5 },
  14837. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  14838. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14839. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  14840. }
  14841. ] ),
  14842. fragmentShader: [
  14843. "uniform vec3 uAmbientColor;",
  14844. "uniform vec3 uDiffuseColor;",
  14845. "uniform vec3 uSpecularColor;",
  14846. "uniform float uShininess;",
  14847. "uniform float uOpacity;",
  14848. "uniform bool enableDiffuse;",
  14849. "uniform bool enableSpecular;",
  14850. "uniform bool enableAO;",
  14851. "uniform bool enableReflection;",
  14852. "uniform sampler2D tDiffuse;",
  14853. "uniform sampler2D tNormal;",
  14854. "uniform sampler2D tSpecular;",
  14855. "uniform sampler2D tAO;",
  14856. "uniform samplerCube tCube;",
  14857. "uniform vec2 uNormalScale;",
  14858. "uniform bool useRefract;",
  14859. "uniform float uRefractionRatio;",
  14860. "uniform float uReflectivity;",
  14861. "varying vec3 vTangent;",
  14862. "varying vec3 vBinormal;",
  14863. "varying vec3 vNormal;",
  14864. "varying vec2 vUv;",
  14865. "uniform vec3 ambientLightColor;",
  14866. "#if MAX_DIR_LIGHTS > 0",
  14867. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  14868. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  14869. "#endif",
  14870. "#if MAX_HEMI_LIGHTS > 0",
  14871. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  14872. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  14873. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  14874. "#endif",
  14875. "#if MAX_POINT_LIGHTS > 0",
  14876. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  14877. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  14878. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  14879. "#endif",
  14880. "#if MAX_SPOT_LIGHTS > 0",
  14881. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  14882. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  14883. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  14884. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  14885. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  14886. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  14887. "#endif",
  14888. "#ifdef WRAP_AROUND",
  14889. "uniform vec3 wrapRGB;",
  14890. "#endif",
  14891. "varying vec3 vWorldPosition;",
  14892. "varying vec3 vViewPosition;",
  14893. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14894. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14895. "void main() {",
  14896. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  14897. "vec3 specularTex = vec3( 1.0 );",
  14898. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  14899. "normalTex.xy *= uNormalScale;",
  14900. "normalTex = normalize( normalTex );",
  14901. "if( enableDiffuse ) {",
  14902. "#ifdef GAMMA_INPUT",
  14903. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  14904. "texelColor.xyz *= texelColor.xyz;",
  14905. "gl_FragColor = gl_FragColor * texelColor;",
  14906. "#else",
  14907. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  14908. "#endif",
  14909. "}",
  14910. "if( enableAO ) {",
  14911. "#ifdef GAMMA_INPUT",
  14912. "vec4 aoColor = texture2D( tAO, vUv );",
  14913. "aoColor.xyz *= aoColor.xyz;",
  14914. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  14915. "#else",
  14916. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  14917. "#endif",
  14918. "}",
  14919. "if( enableSpecular )",
  14920. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  14921. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  14922. "vec3 finalNormal = tsb * normalTex;",
  14923. "#ifdef FLIP_SIDED",
  14924. "finalNormal = -finalNormal;",
  14925. "#endif",
  14926. "vec3 normal = normalize( finalNormal );",
  14927. "vec3 viewPosition = normalize( vViewPosition );",
  14928. // point lights
  14929. "#if MAX_POINT_LIGHTS > 0",
  14930. "vec3 pointDiffuse = vec3( 0.0 );",
  14931. "vec3 pointSpecular = vec3( 0.0 );",
  14932. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  14933. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  14934. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  14935. "float pointDistance = 1.0;",
  14936. "if ( pointLightDistance[ i ] > 0.0 )",
  14937. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  14938. "pointVector = normalize( pointVector );",
  14939. // diffuse
  14940. "#ifdef WRAP_AROUND",
  14941. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  14942. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  14943. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  14944. "#else",
  14945. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  14946. "#endif",
  14947. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  14948. // specular
  14949. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  14950. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  14951. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  14952. "#ifdef PHYSICALLY_BASED_SHADING",
  14953. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14954. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14955. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  14956. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  14957. "#else",
  14958. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  14959. "#endif",
  14960. "}",
  14961. "#endif",
  14962. // spot lights
  14963. "#if MAX_SPOT_LIGHTS > 0",
  14964. "vec3 spotDiffuse = vec3( 0.0 );",
  14965. "vec3 spotSpecular = vec3( 0.0 );",
  14966. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  14967. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  14968. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  14969. "float spotDistance = 1.0;",
  14970. "if ( spotLightDistance[ i ] > 0.0 )",
  14971. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  14972. "spotVector = normalize( spotVector );",
  14973. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  14974. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  14975. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  14976. // diffuse
  14977. "#ifdef WRAP_AROUND",
  14978. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  14979. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  14980. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  14981. "#else",
  14982. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  14983. "#endif",
  14984. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  14985. // specular
  14986. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  14987. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  14988. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  14989. "#ifdef PHYSICALLY_BASED_SHADING",
  14990. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14991. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14992. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  14993. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  14994. "#else",
  14995. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  14996. "#endif",
  14997. "}",
  14998. "}",
  14999. "#endif",
  15000. // directional lights
  15001. "#if MAX_DIR_LIGHTS > 0",
  15002. "vec3 dirDiffuse = vec3( 0.0 );",
  15003. "vec3 dirSpecular = vec3( 0.0 );",
  15004. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  15005. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  15006. "vec3 dirVector = normalize( lDirection.xyz );",
  15007. // diffuse
  15008. "#ifdef WRAP_AROUND",
  15009. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  15010. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  15011. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  15012. "#else",
  15013. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  15014. "#endif",
  15015. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  15016. // specular
  15017. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  15018. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  15019. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  15020. "#ifdef PHYSICALLY_BASED_SHADING",
  15021. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15022. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15023. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  15024. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  15025. "#else",
  15026. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  15027. "#endif",
  15028. "}",
  15029. "#endif",
  15030. // hemisphere lights
  15031. "#if MAX_HEMI_LIGHTS > 0",
  15032. "vec3 hemiDiffuse = vec3( 0.0 );",
  15033. "vec3 hemiSpecular = vec3( 0.0 );" ,
  15034. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  15035. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  15036. "vec3 lVector = normalize( lDirection.xyz );",
  15037. // diffuse
  15038. "float dotProduct = dot( normal, lVector );",
  15039. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  15040. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  15041. "hemiDiffuse += uDiffuseColor * hemiColor;",
  15042. // specular (sky light)
  15043. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  15044. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  15045. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  15046. // specular (ground light)
  15047. "vec3 lVectorGround = -lVector;",
  15048. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  15049. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  15050. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  15051. "#ifdef PHYSICALLY_BASED_SHADING",
  15052. "float dotProductGround = dot( normal, lVectorGround );",
  15053. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15054. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15055. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  15056. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  15057. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  15058. "#else",
  15059. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  15060. "#endif",
  15061. "}",
  15062. "#endif",
  15063. // all lights contribution summation
  15064. "vec3 totalDiffuse = vec3( 0.0 );",
  15065. "vec3 totalSpecular = vec3( 0.0 );",
  15066. "#if MAX_DIR_LIGHTS > 0",
  15067. "totalDiffuse += dirDiffuse;",
  15068. "totalSpecular += dirSpecular;",
  15069. "#endif",
  15070. "#if MAX_HEMI_LIGHTS > 0",
  15071. "totalDiffuse += hemiDiffuse;",
  15072. "totalSpecular += hemiSpecular;",
  15073. "#endif",
  15074. "#if MAX_POINT_LIGHTS > 0",
  15075. "totalDiffuse += pointDiffuse;",
  15076. "totalSpecular += pointSpecular;",
  15077. "#endif",
  15078. "#if MAX_SPOT_LIGHTS > 0",
  15079. "totalDiffuse += spotDiffuse;",
  15080. "totalSpecular += spotSpecular;",
  15081. "#endif",
  15082. "#ifdef METAL",
  15083. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  15084. "#else",
  15085. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  15086. "#endif",
  15087. "if ( enableReflection ) {",
  15088. "vec3 vReflect;",
  15089. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  15090. "if ( useRefract ) {",
  15091. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  15092. "} else {",
  15093. "vReflect = reflect( cameraToVertex, normal );",
  15094. "}",
  15095. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15096. "#ifdef GAMMA_INPUT",
  15097. "cubeColor.xyz *= cubeColor.xyz;",
  15098. "#endif",
  15099. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  15100. "}",
  15101. THREE.ShaderChunk[ "shadowmap_fragment" ],
  15102. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  15103. THREE.ShaderChunk[ "fog_fragment" ],
  15104. "}"
  15105. ].join("\n"),
  15106. vertexShader: [
  15107. "attribute vec4 tangent;",
  15108. "uniform vec2 uOffset;",
  15109. "uniform vec2 uRepeat;",
  15110. "uniform bool enableDisplacement;",
  15111. "#ifdef VERTEX_TEXTURES",
  15112. "uniform sampler2D tDisplacement;",
  15113. "uniform float uDisplacementScale;",
  15114. "uniform float uDisplacementBias;",
  15115. "#endif",
  15116. "varying vec3 vTangent;",
  15117. "varying vec3 vBinormal;",
  15118. "varying vec3 vNormal;",
  15119. "varying vec2 vUv;",
  15120. "varying vec3 vWorldPosition;",
  15121. "varying vec3 vViewPosition;",
  15122. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  15123. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  15124. "void main() {",
  15125. THREE.ShaderChunk[ "skinbase_vertex" ],
  15126. THREE.ShaderChunk[ "skinnormal_vertex" ],
  15127. // normal, tangent and binormal vectors
  15128. "#ifdef USE_SKINNING",
  15129. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  15130. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  15131. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  15132. "#else",
  15133. "vNormal = normalize( normalMatrix * normal );",
  15134. "vTangent = normalize( normalMatrix * tangent.xyz );",
  15135. "#endif",
  15136. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  15137. "vUv = uv * uRepeat + uOffset;",
  15138. // displacement mapping
  15139. "vec3 displacedPosition;",
  15140. "#ifdef VERTEX_TEXTURES",
  15141. "if ( enableDisplacement ) {",
  15142. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  15143. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  15144. "displacedPosition = position + normalize( normal ) * df;",
  15145. "} else {",
  15146. "#ifdef USE_SKINNING",
  15147. "vec4 skinVertex = vec4( position, 1.0 );",
  15148. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15149. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15150. "displacedPosition = skinned.xyz;",
  15151. "#else",
  15152. "displacedPosition = position;",
  15153. "#endif",
  15154. "}",
  15155. "#else",
  15156. "#ifdef USE_SKINNING",
  15157. "vec4 skinVertex = vec4( position, 1.0 );",
  15158. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15159. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15160. "displacedPosition = skinned.xyz;",
  15161. "#else",
  15162. "displacedPosition = position;",
  15163. "#endif",
  15164. "#endif",
  15165. //
  15166. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  15167. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  15168. "gl_Position = projectionMatrix * mvPosition;",
  15169. //
  15170. "vWorldPosition = worldPosition.xyz;",
  15171. "vViewPosition = -mvPosition.xyz;",
  15172. // shadows
  15173. "#ifdef USE_SHADOWMAP",
  15174. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  15175. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  15176. "}",
  15177. "#endif",
  15178. "}"
  15179. ].join("\n")
  15180. },
  15181. /* -------------------------------------------------------------------------
  15182. // Cube map shader
  15183. ------------------------------------------------------------------------- */
  15184. 'cube': {
  15185. uniforms: { "tCube": { type: "t", value: null },
  15186. "tFlip": { type: "f", value: -1 } },
  15187. vertexShader: [
  15188. "varying vec3 vWorldPosition;",
  15189. "void main() {",
  15190. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15191. "vWorldPosition = worldPosition.xyz;",
  15192. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  15193. "}"
  15194. ].join("\n"),
  15195. fragmentShader: [
  15196. "uniform samplerCube tCube;",
  15197. "uniform float tFlip;",
  15198. "varying vec3 vWorldPosition;",
  15199. "void main() {",
  15200. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  15201. "}"
  15202. ].join("\n")
  15203. }
  15204. }
  15205. };
  15206. /**
  15207. * @author zz85 / http://www.lab4games.net/zz85/blog
  15208. * @author alteredq / http://alteredqualia.com/
  15209. *
  15210. * For Text operations in three.js (See TextGeometry)
  15211. *
  15212. * It uses techniques used in:
  15213. *
  15214. * typeface.js and canvastext
  15215. * For converting fonts and rendering with javascript
  15216. * http://typeface.neocracy.org
  15217. *
  15218. * Triangulation ported from AS3
  15219. * Simple Polygon Triangulation
  15220. * http://actionsnippet.com/?p=1462
  15221. *
  15222. * A Method to triangulate shapes with holes
  15223. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15224. *
  15225. */
  15226. THREE.FontUtils = {
  15227. faces : {},
  15228. // Just for now. face[weight][style]
  15229. face : "helvetiker",
  15230. weight: "normal",
  15231. style : "normal",
  15232. size : 150,
  15233. divisions : 10,
  15234. getFace : function() {
  15235. return this.faces[ this.face ][ this.weight ][ this.style ];
  15236. },
  15237. loadFace : function( data ) {
  15238. var family = data.familyName.toLowerCase();
  15239. var ThreeFont = this;
  15240. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15241. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15242. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15243. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15244. return data;
  15245. },
  15246. drawText : function( text ) {
  15247. var characterPts = [], allPts = [];
  15248. // RenderText
  15249. var i, p,
  15250. face = this.getFace(),
  15251. scale = this.size / face.resolution,
  15252. offset = 0,
  15253. chars = String( text ).split( '' ),
  15254. length = chars.length;
  15255. var fontPaths = [];
  15256. for ( i = 0; i < length; i ++ ) {
  15257. var path = new THREE.Path();
  15258. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15259. offset += ret.offset;
  15260. fontPaths.push( ret.path );
  15261. }
  15262. // get the width
  15263. var width = offset / 2;
  15264. //
  15265. // for ( p = 0; p < allPts.length; p++ ) {
  15266. //
  15267. // allPts[ p ].x -= width;
  15268. //
  15269. // }
  15270. //var extract = this.extractPoints( allPts, characterPts );
  15271. //extract.contour = allPts;
  15272. //extract.paths = fontPaths;
  15273. //extract.offset = width;
  15274. return { paths : fontPaths, offset : width };
  15275. },
  15276. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15277. var pts = [];
  15278. var i, i2, divisions,
  15279. outline, action, length,
  15280. scaleX, scaleY,
  15281. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15282. laste,
  15283. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15284. if ( !glyph ) return;
  15285. if ( glyph.o ) {
  15286. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15287. length = outline.length;
  15288. scaleX = scale;
  15289. scaleY = scale;
  15290. for ( i = 0; i < length; ) {
  15291. action = outline[ i ++ ];
  15292. //console.log( action );
  15293. switch( action ) {
  15294. case 'm':
  15295. // Move To
  15296. x = outline[ i++ ] * scaleX + offset;
  15297. y = outline[ i++ ] * scaleY;
  15298. path.moveTo( x, y );
  15299. break;
  15300. case 'l':
  15301. // Line To
  15302. x = outline[ i++ ] * scaleX + offset;
  15303. y = outline[ i++ ] * scaleY;
  15304. path.lineTo(x,y);
  15305. break;
  15306. case 'q':
  15307. // QuadraticCurveTo
  15308. cpx = outline[ i++ ] * scaleX + offset;
  15309. cpy = outline[ i++ ] * scaleY;
  15310. cpx1 = outline[ i++ ] * scaleX + offset;
  15311. cpy1 = outline[ i++ ] * scaleY;
  15312. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15313. laste = pts[ pts.length - 1 ];
  15314. if ( laste ) {
  15315. cpx0 = laste.x;
  15316. cpy0 = laste.y;
  15317. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15318. var t = i2 / divisions;
  15319. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15320. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15321. }
  15322. }
  15323. break;
  15324. case 'b':
  15325. // Cubic Bezier Curve
  15326. cpx = outline[ i++ ] * scaleX + offset;
  15327. cpy = outline[ i++ ] * scaleY;
  15328. cpx1 = outline[ i++ ] * scaleX + offset;
  15329. cpy1 = outline[ i++ ] * -scaleY;
  15330. cpx2 = outline[ i++ ] * scaleX + offset;
  15331. cpy2 = outline[ i++ ] * -scaleY;
  15332. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15333. laste = pts[ pts.length - 1 ];
  15334. if ( laste ) {
  15335. cpx0 = laste.x;
  15336. cpy0 = laste.y;
  15337. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15338. var t = i2 / divisions;
  15339. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15340. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15341. }
  15342. }
  15343. break;
  15344. }
  15345. }
  15346. }
  15347. return { offset: glyph.ha*scale, path:path};
  15348. }
  15349. };
  15350. THREE.FontUtils.generateShapes = function( text, parameters ) {
  15351. // Parameters
  15352. parameters = parameters || {};
  15353. var size = parameters.size !== undefined ? parameters.size : 100;
  15354. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  15355. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  15356. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  15357. var style = parameters.style !== undefined ? parameters.style : "normal";
  15358. THREE.FontUtils.size = size;
  15359. THREE.FontUtils.divisions = curveSegments;
  15360. THREE.FontUtils.face = font;
  15361. THREE.FontUtils.weight = weight;
  15362. THREE.FontUtils.style = style;
  15363. // Get a Font data json object
  15364. var data = THREE.FontUtils.drawText( text );
  15365. var paths = data.paths;
  15366. var shapes = [];
  15367. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15368. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15369. }
  15370. return shapes;
  15371. };
  15372. /**
  15373. * This code is a quick port of code written in C++ which was submitted to
  15374. * flipcode.com by John W. Ratcliff // July 22, 2000
  15375. * See original code and more information here:
  15376. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15377. *
  15378. * ported to actionscript by Zevan Rosser
  15379. * www.actionsnippet.com
  15380. *
  15381. * ported to javascript by Joshua Koo
  15382. * http://www.lab4games.net/zz85/blog
  15383. *
  15384. */
  15385. ( function( namespace ) {
  15386. var EPSILON = 0.0000000001;
  15387. // takes in an contour array and returns
  15388. var process = function( contour, indices ) {
  15389. var n = contour.length;
  15390. if ( n < 3 ) return null;
  15391. var result = [],
  15392. verts = [],
  15393. vertIndices = [];
  15394. /* we want a counter-clockwise polygon in verts */
  15395. var u, v, w;
  15396. if ( area( contour ) > 0.0 ) {
  15397. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15398. } else {
  15399. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15400. }
  15401. var nv = n;
  15402. /* remove nv - 2 vertices, creating 1 triangle every time */
  15403. var count = 2 * nv; /* error detection */
  15404. for( v = nv - 1; nv > 2; ) {
  15405. /* if we loop, it is probably a non-simple polygon */
  15406. if ( ( count-- ) <= 0 ) {
  15407. //** Triangulate: ERROR - probable bad polygon!
  15408. //throw ( "Warning, unable to triangulate polygon!" );
  15409. //return null;
  15410. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15411. console.log( "Warning, unable to triangulate polygon!" );
  15412. if ( indices ) return vertIndices;
  15413. return result;
  15414. }
  15415. /* three consecutive vertices in current polygon, <u,v,w> */
  15416. u = v; if ( nv <= u ) u = 0; /* previous */
  15417. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15418. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15419. if ( snip( contour, u, v, w, nv, verts ) ) {
  15420. var a, b, c, s, t;
  15421. /* true names of the vertices */
  15422. a = verts[ u ];
  15423. b = verts[ v ];
  15424. c = verts[ w ];
  15425. /* output Triangle */
  15426. /*
  15427. result.push( contour[ a ] );
  15428. result.push( contour[ b ] );
  15429. result.push( contour[ c ] );
  15430. */
  15431. result.push( [ contour[ a ],
  15432. contour[ b ],
  15433. contour[ c ] ] );
  15434. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15435. /* remove v from the remaining polygon */
  15436. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15437. verts[ s ] = verts[ t ];
  15438. }
  15439. nv--;
  15440. /* reset error detection counter */
  15441. count = 2 * nv;
  15442. }
  15443. }
  15444. if ( indices ) return vertIndices;
  15445. return result;
  15446. };
  15447. // calculate area of the contour polygon
  15448. var area = function ( contour ) {
  15449. var n = contour.length;
  15450. var a = 0.0;
  15451. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15452. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15453. }
  15454. return a * 0.5;
  15455. };
  15456. // see if p is inside triangle abc
  15457. var insideTriangle = function( ax, ay,
  15458. bx, by,
  15459. cx, cy,
  15460. px, py ) {
  15461. var aX, aY, bX, bY;
  15462. var cX, cY, apx, apy;
  15463. var bpx, bpy, cpx, cpy;
  15464. var cCROSSap, bCROSScp, aCROSSbp;
  15465. aX = cx - bx; aY = cy - by;
  15466. bX = ax - cx; bY = ay - cy;
  15467. cX = bx - ax; cY = by - ay;
  15468. apx= px -ax; apy= py - ay;
  15469. bpx= px - bx; bpy= py - by;
  15470. cpx= px - cx; cpy= py - cy;
  15471. aCROSSbp = aX*bpy - aY*bpx;
  15472. cCROSSap = cX*apy - cY*apx;
  15473. bCROSScp = bX*cpy - bY*cpx;
  15474. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  15475. };
  15476. var snip = function ( contour, u, v, w, n, verts ) {
  15477. var p;
  15478. var ax, ay, bx, by;
  15479. var cx, cy, px, py;
  15480. ax = contour[ verts[ u ] ].x;
  15481. ay = contour[ verts[ u ] ].y;
  15482. bx = contour[ verts[ v ] ].x;
  15483. by = contour[ verts[ v ] ].y;
  15484. cx = contour[ verts[ w ] ].x;
  15485. cy = contour[ verts[ w ] ].y;
  15486. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  15487. for ( p = 0; p < n; p++ ) {
  15488. if( (p == u) || (p == v) || (p == w) ) continue;
  15489. px = contour[ verts[ p ] ].x
  15490. py = contour[ verts[ p ] ].y
  15491. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  15492. }
  15493. return true;
  15494. };
  15495. namespace.Triangulate = process;
  15496. namespace.Triangulate.area = area;
  15497. return namespace;
  15498. })(THREE.FontUtils);
  15499. // To use the typeface.js face files, hook up the API
  15500. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  15501. * @author zz85 / http://www.lab4games.net/zz85/blog
  15502. * Extensible curve object
  15503. *
  15504. * Some common of Curve methods
  15505. * .getPoint(t), getTangent(t)
  15506. * .getPointAt(u), getTagentAt(u)
  15507. * .getPoints(), .getSpacedPoints()
  15508. * .getLength()
  15509. * .updateArcLengths()
  15510. *
  15511. * This file contains following classes:
  15512. *
  15513. * -- 2d classes --
  15514. * THREE.Curve
  15515. * THREE.LineCurve
  15516. * THREE.QuadraticBezierCurve
  15517. * THREE.CubicBezierCurve
  15518. * THREE.SplineCurve
  15519. * THREE.ArcCurve
  15520. * THREE.EllipseCurve
  15521. *
  15522. * -- 3d classes --
  15523. * THREE.LineCurve3
  15524. * THREE.QuadraticBezierCurve3
  15525. * THREE.CubicBezierCurve3
  15526. * THREE.SplineCurve3
  15527. * THREE.ClosedSplineCurve3
  15528. *
  15529. * A series of curves can be represented as a THREE.CurvePath
  15530. *
  15531. **/
  15532. /**************************************************************
  15533. * Abstract Curve base class
  15534. **************************************************************/
  15535. THREE.Curve = function () {
  15536. };
  15537. // Virtual base class method to overwrite and implement in subclasses
  15538. // - t [0 .. 1]
  15539. THREE.Curve.prototype.getPoint = function ( t ) {
  15540. console.log( "Warning, getPoint() not implemented!" );
  15541. return null;
  15542. };
  15543. // Get point at relative position in curve according to arc length
  15544. // - u [0 .. 1]
  15545. THREE.Curve.prototype.getPointAt = function ( u ) {
  15546. var t = this.getUtoTmapping( u );
  15547. return this.getPoint( t );
  15548. };
  15549. // Get sequence of points using getPoint( t )
  15550. THREE.Curve.prototype.getPoints = function ( divisions ) {
  15551. if ( !divisions ) divisions = 5;
  15552. var d, pts = [];
  15553. for ( d = 0; d <= divisions; d ++ ) {
  15554. pts.push( this.getPoint( d / divisions ) );
  15555. }
  15556. return pts;
  15557. };
  15558. // Get sequence of points using getPointAt( u )
  15559. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  15560. if ( !divisions ) divisions = 5;
  15561. var d, pts = [];
  15562. for ( d = 0; d <= divisions; d ++ ) {
  15563. pts.push( this.getPointAt( d / divisions ) );
  15564. }
  15565. return pts;
  15566. };
  15567. // Get total curve arc length
  15568. THREE.Curve.prototype.getLength = function () {
  15569. var lengths = this.getLengths();
  15570. return lengths[ lengths.length - 1 ];
  15571. };
  15572. // Get list of cumulative segment lengths
  15573. THREE.Curve.prototype.getLengths = function ( divisions ) {
  15574. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  15575. if ( this.cacheArcLengths
  15576. && ( this.cacheArcLengths.length == divisions + 1 )
  15577. && !this.needsUpdate) {
  15578. //console.log( "cached", this.cacheArcLengths );
  15579. return this.cacheArcLengths;
  15580. }
  15581. this.needsUpdate = false;
  15582. var cache = [];
  15583. var current, last = this.getPoint( 0 );
  15584. var p, sum = 0;
  15585. cache.push( 0 );
  15586. for ( p = 1; p <= divisions; p ++ ) {
  15587. current = this.getPoint ( p / divisions );
  15588. sum += current.distanceTo( last );
  15589. cache.push( sum );
  15590. last = current;
  15591. }
  15592. this.cacheArcLengths = cache;
  15593. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  15594. };
  15595. THREE.Curve.prototype.updateArcLengths = function() {
  15596. this.needsUpdate = true;
  15597. this.getLengths();
  15598. };
  15599. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  15600. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  15601. var arcLengths = this.getLengths();
  15602. var i = 0, il = arcLengths.length;
  15603. var targetArcLength; // The targeted u distance value to get
  15604. if ( distance ) {
  15605. targetArcLength = distance;
  15606. } else {
  15607. targetArcLength = u * arcLengths[ il - 1 ];
  15608. }
  15609. //var time = Date.now();
  15610. // binary search for the index with largest value smaller than target u distance
  15611. var low = 0, high = il - 1, comparison;
  15612. while ( low <= high ) {
  15613. 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
  15614. comparison = arcLengths[ i ] - targetArcLength;
  15615. if ( comparison < 0 ) {
  15616. low = i + 1;
  15617. continue;
  15618. } else if ( comparison > 0 ) {
  15619. high = i - 1;
  15620. continue;
  15621. } else {
  15622. high = i;
  15623. break;
  15624. // DONE
  15625. }
  15626. }
  15627. i = high;
  15628. //console.log('b' , i, low, high, Date.now()- time);
  15629. if ( arcLengths[ i ] == targetArcLength ) {
  15630. var t = i / ( il - 1 );
  15631. return t;
  15632. }
  15633. // we could get finer grain at lengths, or use simple interpolatation between two points
  15634. var lengthBefore = arcLengths[ i ];
  15635. var lengthAfter = arcLengths[ i + 1 ];
  15636. var segmentLength = lengthAfter - lengthBefore;
  15637. // determine where we are between the 'before' and 'after' points
  15638. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  15639. // add that fractional amount to t
  15640. var t = ( i + segmentFraction ) / ( il -1 );
  15641. return t;
  15642. };
  15643. // In 2D space, there are actually 2 normal vectors,
  15644. // and in 3D space, infinte
  15645. // TODO this should be depreciated.
  15646. THREE.Curve.prototype.getNormalVector = function( t ) {
  15647. var vec = this.getTangent( t );
  15648. return new THREE.Vector2( -vec.y , vec.x );
  15649. };
  15650. // Returns a unit vector tangent at t
  15651. // In case any sub curve does not implement its tangent / normal finding,
  15652. // we get 2 points with a small delta and find a gradient of the 2 points
  15653. // which seems to make a reasonable approximation
  15654. THREE.Curve.prototype.getTangent = function( t ) {
  15655. var delta = 0.0001;
  15656. var t1 = t - delta;
  15657. var t2 = t + delta;
  15658. // Capping in case of danger
  15659. if ( t1 < 0 ) t1 = 0;
  15660. if ( t2 > 1 ) t2 = 1;
  15661. var pt1 = this.getPoint( t1 );
  15662. var pt2 = this.getPoint( t2 );
  15663. var vec = pt2.clone().subSelf(pt1);
  15664. return vec.normalize();
  15665. };
  15666. THREE.Curve.prototype.getTangentAt = function ( u ) {
  15667. var t = this.getUtoTmapping( u );
  15668. return this.getTangent( t );
  15669. };
  15670. /**************************************************************
  15671. * Line
  15672. **************************************************************/
  15673. THREE.LineCurve = function ( v1, v2 ) {
  15674. this.v1 = v1;
  15675. this.v2 = v2;
  15676. };
  15677. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  15678. THREE.LineCurve.prototype.getPoint = function ( t ) {
  15679. var point = this.v2.clone().subSelf(this.v1);
  15680. point.multiplyScalar( t ).addSelf( this.v1 );
  15681. return point;
  15682. };
  15683. // Line curve is linear, so we can overwrite default getPointAt
  15684. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  15685. return this.getPoint( u );
  15686. };
  15687. THREE.LineCurve.prototype.getTangent = function( t ) {
  15688. var tangent = this.v2.clone().subSelf(this.v1);
  15689. return tangent.normalize();
  15690. };
  15691. /**************************************************************
  15692. * Quadratic Bezier curve
  15693. **************************************************************/
  15694. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  15695. this.v0 = v0;
  15696. this.v1 = v1;
  15697. this.v2 = v2;
  15698. };
  15699. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15700. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  15701. var tx, ty;
  15702. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15703. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15704. return new THREE.Vector2( tx, ty );
  15705. };
  15706. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  15707. var tx, ty;
  15708. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  15709. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  15710. // returns unit vector
  15711. var tangent = new THREE.Vector2( tx, ty );
  15712. tangent.normalize();
  15713. return tangent;
  15714. };
  15715. /**************************************************************
  15716. * Cubic Bezier curve
  15717. **************************************************************/
  15718. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  15719. this.v0 = v0;
  15720. this.v1 = v1;
  15721. this.v2 = v2;
  15722. this.v3 = v3;
  15723. };
  15724. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15725. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  15726. var tx, ty;
  15727. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15728. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15729. return new THREE.Vector2( tx, ty );
  15730. };
  15731. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  15732. var tx, ty;
  15733. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15734. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15735. var tangent = new THREE.Vector2( tx, ty );
  15736. tangent.normalize();
  15737. return tangent;
  15738. };
  15739. /**************************************************************
  15740. * Spline curve
  15741. **************************************************************/
  15742. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  15743. this.points = (points == undefined) ? [] : points;
  15744. };
  15745. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  15746. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  15747. var v = new THREE.Vector2();
  15748. var c = [];
  15749. var points = this.points, point, intPoint, weight;
  15750. point = ( points.length - 1 ) * t;
  15751. intPoint = Math.floor( point );
  15752. weight = point - intPoint;
  15753. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15754. c[ 1 ] = intPoint;
  15755. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  15756. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  15757. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15758. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15759. return v;
  15760. };
  15761. /**************************************************************
  15762. * Ellipse curve
  15763. **************************************************************/
  15764. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  15765. aStartAngle, aEndAngle,
  15766. aClockwise ) {
  15767. this.aX = aX;
  15768. this.aY = aY;
  15769. this.xRadius = xRadius;
  15770. this.yRadius = yRadius;
  15771. this.aStartAngle = aStartAngle;
  15772. this.aEndAngle = aEndAngle;
  15773. this.aClockwise = aClockwise;
  15774. };
  15775. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  15776. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  15777. var deltaAngle = this.aEndAngle - this.aStartAngle;
  15778. if ( !this.aClockwise ) {
  15779. t = 1 - t;
  15780. }
  15781. var angle = this.aStartAngle + t * deltaAngle;
  15782. var tx = this.aX + this.xRadius * Math.cos( angle );
  15783. var ty = this.aY + this.yRadius * Math.sin( angle );
  15784. return new THREE.Vector2( tx, ty );
  15785. };
  15786. /**************************************************************
  15787. * Arc curve
  15788. **************************************************************/
  15789. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  15790. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  15791. };
  15792. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  15793. /**************************************************************
  15794. * Utils
  15795. **************************************************************/
  15796. THREE.Curve.Utils = {
  15797. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  15798. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  15799. },
  15800. // Puay Bing, thanks for helping with this derivative!
  15801. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  15802. return -3 * p0 * (1 - t) * (1 - t) +
  15803. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  15804. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  15805. 3 * t * t * p3;
  15806. },
  15807. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  15808. // To check if my formulas are correct
  15809. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  15810. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  15811. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  15812. var h11 = 3 * t * t - 2 * t; // t3 − t2
  15813. return h00 + h10 + h01 + h11;
  15814. },
  15815. // Catmull-Rom
  15816. interpolate: function( p0, p1, p2, p3, t ) {
  15817. var v0 = ( p2 - p0 ) * 0.5;
  15818. var v1 = ( p3 - p1 ) * 0.5;
  15819. var t2 = t * t;
  15820. var t3 = t * t2;
  15821. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  15822. }
  15823. };
  15824. // TODO: Transformation for Curves?
  15825. /**************************************************************
  15826. * 3D Curves
  15827. **************************************************************/
  15828. // A Factory method for creating new curve subclasses
  15829. THREE.Curve.create = function ( constructor, getPointFunc ) {
  15830. constructor.prototype = Object.create( THREE.Curve.prototype );
  15831. constructor.prototype.getPoint = getPointFunc;
  15832. return constructor;
  15833. };
  15834. /**************************************************************
  15835. * Line3D
  15836. **************************************************************/
  15837. THREE.LineCurve3 = THREE.Curve.create(
  15838. function ( v1, v2 ) {
  15839. this.v1 = v1;
  15840. this.v2 = v2;
  15841. },
  15842. function ( t ) {
  15843. var r = new THREE.Vector3();
  15844. r.sub( this.v2, this.v1 ); // diff
  15845. r.multiplyScalar( t );
  15846. r.addSelf( this.v1 );
  15847. return r;
  15848. }
  15849. );
  15850. /**************************************************************
  15851. * Quadratic Bezier 3D curve
  15852. **************************************************************/
  15853. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  15854. function ( v0, v1, v2 ) {
  15855. this.v0 = v0;
  15856. this.v1 = v1;
  15857. this.v2 = v2;
  15858. },
  15859. function ( t ) {
  15860. var tx, ty, tz;
  15861. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15862. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15863. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  15864. return new THREE.Vector3( tx, ty, tz );
  15865. }
  15866. );
  15867. /**************************************************************
  15868. * Cubic Bezier 3D curve
  15869. **************************************************************/
  15870. THREE.CubicBezierCurve3 = THREE.Curve.create(
  15871. function ( v0, v1, v2, v3 ) {
  15872. this.v0 = v0;
  15873. this.v1 = v1;
  15874. this.v2 = v2;
  15875. this.v3 = v3;
  15876. },
  15877. function ( t ) {
  15878. var tx, ty, tz;
  15879. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15880. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15881. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  15882. return new THREE.Vector3( tx, ty, tz );
  15883. }
  15884. );
  15885. /**************************************************************
  15886. * Spline 3D curve
  15887. **************************************************************/
  15888. THREE.SplineCurve3 = THREE.Curve.create(
  15889. function ( points /* array of Vector3 */) {
  15890. this.points = (points == undefined) ? [] : points;
  15891. },
  15892. function ( t ) {
  15893. var v = new THREE.Vector3();
  15894. var c = [];
  15895. var points = this.points, point, intPoint, weight;
  15896. point = ( points.length - 1 ) * t;
  15897. intPoint = Math.floor( point );
  15898. weight = point - intPoint;
  15899. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15900. c[ 1 ] = intPoint;
  15901. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15902. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15903. var pt0 = points[ c[0] ],
  15904. pt1 = points[ c[1] ],
  15905. pt2 = points[ c[2] ],
  15906. pt3 = points[ c[3] ];
  15907. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  15908. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  15909. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  15910. return v;
  15911. }
  15912. );
  15913. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  15914. // var v = new THREE.Vector3();
  15915. // var c = [];
  15916. // var points = this.points, point, intPoint, weight;
  15917. // point = ( points.length - 1 ) * t;
  15918. // intPoint = Math.floor( point );
  15919. // weight = point - intPoint;
  15920. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15921. // c[ 1 ] = intPoint;
  15922. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15923. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15924. // var pt0 = points[ c[0] ],
  15925. // pt1 = points[ c[1] ],
  15926. // pt2 = points[ c[2] ],
  15927. // pt3 = points[ c[3] ];
  15928. // // t = weight;
  15929. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  15930. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  15931. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  15932. // return v;
  15933. // }
  15934. /**************************************************************
  15935. * Closed Spline 3D curve
  15936. **************************************************************/
  15937. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  15938. function ( points /* array of Vector3 */) {
  15939. this.points = (points == undefined) ? [] : points;
  15940. },
  15941. function ( t ) {
  15942. var v = new THREE.Vector3();
  15943. var c = [];
  15944. var points = this.points, point, intPoint, weight;
  15945. point = ( points.length - 0 ) * t;
  15946. // This needs to be from 0-length +1
  15947. intPoint = Math.floor( point );
  15948. weight = point - intPoint;
  15949. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  15950. c[ 0 ] = ( intPoint - 1 ) % points.length;
  15951. c[ 1 ] = ( intPoint ) % points.length;
  15952. c[ 2 ] = ( intPoint + 1 ) % points.length;
  15953. c[ 3 ] = ( intPoint + 2 ) % points.length;
  15954. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15955. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15956. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  15957. return v;
  15958. }
  15959. );
  15960. /**
  15961. * @author zz85 / http://www.lab4games.net/zz85/blog
  15962. *
  15963. **/
  15964. /**************************************************************
  15965. * Curved Path - a curve path is simply a array of connected
  15966. * curves, but retains the api of a curve
  15967. **************************************************************/
  15968. THREE.CurvePath = function () {
  15969. this.curves = [];
  15970. this.bends = [];
  15971. this.autoClose = false; // Automatically closes the path
  15972. };
  15973. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  15974. THREE.CurvePath.prototype.add = function ( curve ) {
  15975. this.curves.push( curve );
  15976. };
  15977. THREE.CurvePath.prototype.checkConnection = function() {
  15978. // TODO
  15979. // If the ending of curve is not connected to the starting
  15980. // or the next curve, then, this is not a real path
  15981. };
  15982. THREE.CurvePath.prototype.closePath = function() {
  15983. // TODO Test
  15984. // and verify for vector3 (needs to implement equals)
  15985. // Add a line curve if start and end of lines are not connected
  15986. var startPoint = this.curves[0].getPoint(0);
  15987. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  15988. if (!startPoint.equals(endPoint)) {
  15989. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  15990. }
  15991. };
  15992. // To get accurate point with reference to
  15993. // entire path distance at time t,
  15994. // following has to be done:
  15995. // 1. Length of each sub path have to be known
  15996. // 2. Locate and identify type of curve
  15997. // 3. Get t for the curve
  15998. // 4. Return curve.getPointAt(t')
  15999. THREE.CurvePath.prototype.getPoint = function( t ) {
  16000. var d = t * this.getLength();
  16001. var curveLengths = this.getCurveLengths();
  16002. var i = 0, diff, curve;
  16003. // To think about boundaries points.
  16004. while ( i < curveLengths.length ) {
  16005. if ( curveLengths[ i ] >= d ) {
  16006. diff = curveLengths[ i ] - d;
  16007. curve = this.curves[ i ];
  16008. var u = 1 - diff / curve.getLength();
  16009. return curve.getPointAt( u );
  16010. break;
  16011. }
  16012. i ++;
  16013. }
  16014. return null;
  16015. // loop where sum != 0, sum > d , sum+1 <d
  16016. };
  16017. /*
  16018. THREE.CurvePath.prototype.getTangent = function( t ) {
  16019. };*/
  16020. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16021. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16022. // getPoint() depends on getLength
  16023. THREE.CurvePath.prototype.getLength = function() {
  16024. var lens = this.getCurveLengths();
  16025. return lens[ lens.length - 1 ];
  16026. };
  16027. // Compute lengths and cache them
  16028. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16029. THREE.CurvePath.prototype.getCurveLengths = function() {
  16030. // We use cache values if curves and cache array are same length
  16031. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16032. return this.cacheLengths;
  16033. };
  16034. // Get length of subsurve
  16035. // Push sums into cached array
  16036. var lengths = [], sums = 0;
  16037. var i, il = this.curves.length;
  16038. for ( i = 0; i < il; i ++ ) {
  16039. sums += this.curves[ i ].getLength();
  16040. lengths.push( sums );
  16041. }
  16042. this.cacheLengths = lengths;
  16043. return lengths;
  16044. };
  16045. // Returns min and max coordinates, as well as centroid
  16046. THREE.CurvePath.prototype.getBoundingBox = function () {
  16047. var points = this.getPoints();
  16048. var maxX, maxY, maxZ;
  16049. var minX, minY, minZ;
  16050. maxX = maxY = Number.NEGATIVE_INFINITY;
  16051. minX = minY = Number.POSITIVE_INFINITY;
  16052. var p, i, il, sum;
  16053. var v3 = points[0] instanceof THREE.Vector3;
  16054. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16055. for ( i = 0, il = points.length; i < il; i ++ ) {
  16056. p = points[ i ];
  16057. if ( p.x > maxX ) maxX = p.x;
  16058. else if ( p.x < minX ) minX = p.x;
  16059. if ( p.y > maxY ) maxY = p.y;
  16060. else if ( p.y < minY ) minY = p.y;
  16061. if (v3) {
  16062. if ( p.z > maxZ ) maxZ = p.z;
  16063. else if ( p.z < minZ ) minZ = p.z;
  16064. }
  16065. sum.addSelf( p );
  16066. }
  16067. var ret = {
  16068. minX: minX,
  16069. minY: minY,
  16070. maxX: maxX,
  16071. maxY: maxY,
  16072. centroid: sum.divideScalar( il )
  16073. };
  16074. if (v3) {
  16075. ret.maxZ = maxZ;
  16076. ret.minZ = minZ;
  16077. }
  16078. return ret;
  16079. };
  16080. /**************************************************************
  16081. * Create Geometries Helpers
  16082. **************************************************************/
  16083. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16084. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16085. var pts = this.getPoints( divisions, true );
  16086. return this.createGeometry( pts );
  16087. };
  16088. // Generate geometry from equidistance sampling along the path
  16089. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16090. var pts = this.getSpacedPoints( divisions, true );
  16091. return this.createGeometry( pts );
  16092. };
  16093. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16094. var geometry = new THREE.Geometry();
  16095. for ( var i = 0; i < points.length; i ++ ) {
  16096. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16097. }
  16098. return geometry;
  16099. };
  16100. /**************************************************************
  16101. * Bend / Wrap Helper Methods
  16102. **************************************************************/
  16103. // Wrap path / Bend modifiers?
  16104. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16105. this.bends.push( bendpath );
  16106. };
  16107. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16108. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16109. var i, il;
  16110. if ( !bends ) {
  16111. bends = this.bends;
  16112. }
  16113. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16114. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16115. }
  16116. return oldPts;
  16117. };
  16118. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16119. var oldPts = this.getSpacedPoints( segments );
  16120. var i, il;
  16121. if ( !bends ) {
  16122. bends = this.bends;
  16123. }
  16124. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16125. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16126. }
  16127. return oldPts;
  16128. };
  16129. // This returns getPoints() bend/wrapped around the contour of a path.
  16130. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16131. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16132. var bounds = this.getBoundingBox();
  16133. var i, il, p, oldX, oldY, xNorm;
  16134. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16135. p = oldPts[ i ];
  16136. oldX = p.x;
  16137. oldY = p.y;
  16138. xNorm = oldX / bounds.maxX;
  16139. // If using actual distance, for length > path, requires line extrusions
  16140. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16141. xNorm = path.getUtoTmapping( xNorm, oldX );
  16142. // check for out of bounds?
  16143. var pathPt = path.getPoint( xNorm );
  16144. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16145. p.x = pathPt.x + normal.x;
  16146. p.y = pathPt.y + normal.y;
  16147. }
  16148. return oldPts;
  16149. };
  16150. /**
  16151. * @author alteredq / http://alteredqualia.com/
  16152. */
  16153. THREE.Gyroscope = function () {
  16154. THREE.Object3D.call( this );
  16155. };
  16156. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16157. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16158. this.matrixAutoUpdate && this.updateMatrix();
  16159. // update matrixWorld
  16160. if ( this.matrixWorldNeedsUpdate || force ) {
  16161. if ( this.parent ) {
  16162. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  16163. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16164. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16165. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16166. } else {
  16167. this.matrixWorld.copy( this.matrix );
  16168. }
  16169. this.matrixWorldNeedsUpdate = false;
  16170. force = true;
  16171. }
  16172. // update children
  16173. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16174. this.children[ i ].updateMatrixWorld( force );
  16175. }
  16176. };
  16177. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16178. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16179. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16180. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16181. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16182. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16183. /**
  16184. * @author zz85 / http://www.lab4games.net/zz85/blog
  16185. * Creates free form 2d path using series of points, lines or curves.
  16186. *
  16187. **/
  16188. THREE.Path = function ( points ) {
  16189. THREE.CurvePath.call(this);
  16190. this.actions = [];
  16191. if ( points ) {
  16192. this.fromPoints( points );
  16193. }
  16194. };
  16195. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16196. THREE.PathActions = {
  16197. MOVE_TO: 'moveTo',
  16198. LINE_TO: 'lineTo',
  16199. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16200. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16201. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16202. ARC: 'arc', // Circle
  16203. ELLIPSE: 'ellipse'
  16204. };
  16205. // TODO Clean up PATH API
  16206. // Create path using straight lines to connect all points
  16207. // - vectors: array of Vector2
  16208. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16209. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16210. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16211. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16212. };
  16213. };
  16214. // startPath() endPath()?
  16215. THREE.Path.prototype.moveTo = function ( x, y ) {
  16216. var args = Array.prototype.slice.call( arguments );
  16217. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16218. };
  16219. THREE.Path.prototype.lineTo = function ( x, y ) {
  16220. var args = Array.prototype.slice.call( arguments );
  16221. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16222. var x0 = lastargs[ lastargs.length - 2 ];
  16223. var y0 = lastargs[ lastargs.length - 1 ];
  16224. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16225. this.curves.push( curve );
  16226. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16227. };
  16228. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16229. var args = Array.prototype.slice.call( arguments );
  16230. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16231. var x0 = lastargs[ lastargs.length - 2 ];
  16232. var y0 = lastargs[ lastargs.length - 1 ];
  16233. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16234. new THREE.Vector2( aCPx, aCPy ),
  16235. new THREE.Vector2( aX, aY ) );
  16236. this.curves.push( curve );
  16237. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16238. };
  16239. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16240. aCP2x, aCP2y,
  16241. aX, aY ) {
  16242. var args = Array.prototype.slice.call( arguments );
  16243. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16244. var x0 = lastargs[ lastargs.length - 2 ];
  16245. var y0 = lastargs[ lastargs.length - 1 ];
  16246. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16247. new THREE.Vector2( aCP1x, aCP1y ),
  16248. new THREE.Vector2( aCP2x, aCP2y ),
  16249. new THREE.Vector2( aX, aY ) );
  16250. this.curves.push( curve );
  16251. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16252. };
  16253. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16254. var args = Array.prototype.slice.call( arguments );
  16255. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16256. var x0 = lastargs[ lastargs.length - 2 ];
  16257. var y0 = lastargs[ lastargs.length - 1 ];
  16258. //---
  16259. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16260. Array.prototype.push.apply( npts, pts );
  16261. var curve = new THREE.SplineCurve( npts );
  16262. this.curves.push( curve );
  16263. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16264. };
  16265. // FUTURE: Change the API or follow canvas API?
  16266. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16267. aStartAngle, aEndAngle, aClockwise ) {
  16268. var lastargs = this.actions[ this.actions.length - 1].args;
  16269. var x0 = lastargs[ lastargs.length - 2 ];
  16270. var y0 = lastargs[ lastargs.length - 1 ];
  16271. this.absarc(aX + x0, aY + y0, aRadius,
  16272. aStartAngle, aEndAngle, aClockwise );
  16273. };
  16274. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16275. aStartAngle, aEndAngle, aClockwise ) {
  16276. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16277. };
  16278. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16279. aStartAngle, aEndAngle, aClockwise ) {
  16280. var lastargs = this.actions[ this.actions.length - 1].args;
  16281. var x0 = lastargs[ lastargs.length - 2 ];
  16282. var y0 = lastargs[ lastargs.length - 1 ];
  16283. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16284. aStartAngle, aEndAngle, aClockwise );
  16285. };
  16286. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16287. aStartAngle, aEndAngle, aClockwise ) {
  16288. var args = Array.prototype.slice.call( arguments );
  16289. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16290. aStartAngle, aEndAngle, aClockwise );
  16291. this.curves.push( curve );
  16292. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16293. args.push(lastPoint.x);
  16294. args.push(lastPoint.y);
  16295. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16296. };
  16297. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16298. if ( ! divisions ) divisions = 40;
  16299. var points = [];
  16300. for ( var i = 0; i < divisions; i ++ ) {
  16301. points.push( this.getPoint( i / divisions ) );
  16302. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16303. }
  16304. // if ( closedPath ) {
  16305. //
  16306. // points.push( points[ 0 ] );
  16307. //
  16308. // }
  16309. return points;
  16310. };
  16311. /* Return an array of vectors based on contour of the path */
  16312. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16313. if (this.useSpacedPoints) {
  16314. console.log('tata');
  16315. return this.getSpacedPoints( divisions, closedPath );
  16316. }
  16317. divisions = divisions || 12;
  16318. var points = [];
  16319. var i, il, item, action, args;
  16320. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16321. laste, j,
  16322. t, tx, ty;
  16323. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16324. item = this.actions[ i ];
  16325. action = item.action;
  16326. args = item.args;
  16327. switch( action ) {
  16328. case THREE.PathActions.MOVE_TO:
  16329. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16330. break;
  16331. case THREE.PathActions.LINE_TO:
  16332. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16333. break;
  16334. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16335. cpx = args[ 2 ];
  16336. cpy = args[ 3 ];
  16337. cpx1 = args[ 0 ];
  16338. cpy1 = args[ 1 ];
  16339. if ( points.length > 0 ) {
  16340. laste = points[ points.length - 1 ];
  16341. cpx0 = laste.x;
  16342. cpy0 = laste.y;
  16343. } else {
  16344. laste = this.actions[ i - 1 ].args;
  16345. cpx0 = laste[ laste.length - 2 ];
  16346. cpy0 = laste[ laste.length - 1 ];
  16347. }
  16348. for ( j = 1; j <= divisions; j ++ ) {
  16349. t = j / divisions;
  16350. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16351. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16352. points.push( new THREE.Vector2( tx, ty ) );
  16353. }
  16354. break;
  16355. case THREE.PathActions.BEZIER_CURVE_TO:
  16356. cpx = args[ 4 ];
  16357. cpy = args[ 5 ];
  16358. cpx1 = args[ 0 ];
  16359. cpy1 = args[ 1 ];
  16360. cpx2 = args[ 2 ];
  16361. cpy2 = args[ 3 ];
  16362. if ( points.length > 0 ) {
  16363. laste = points[ points.length - 1 ];
  16364. cpx0 = laste.x;
  16365. cpy0 = laste.y;
  16366. } else {
  16367. laste = this.actions[ i - 1 ].args;
  16368. cpx0 = laste[ laste.length - 2 ];
  16369. cpy0 = laste[ laste.length - 1 ];
  16370. }
  16371. for ( j = 1; j <= divisions; j ++ ) {
  16372. t = j / divisions;
  16373. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16374. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16375. points.push( new THREE.Vector2( tx, ty ) );
  16376. }
  16377. break;
  16378. case THREE.PathActions.CSPLINE_THRU:
  16379. laste = this.actions[ i - 1 ].args;
  16380. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16381. var spts = [ last ];
  16382. var n = divisions * args[ 0 ].length;
  16383. spts = spts.concat( args[ 0 ] );
  16384. var spline = new THREE.SplineCurve( spts );
  16385. for ( j = 1; j <= n; j ++ ) {
  16386. points.push( spline.getPointAt( j / n ) ) ;
  16387. }
  16388. break;
  16389. case THREE.PathActions.ARC:
  16390. var aX = args[ 0 ], aY = args[ 1 ],
  16391. aRadius = args[ 2 ],
  16392. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16393. aClockwise = !!args[ 5 ];
  16394. var deltaAngle = aEndAngle - aStartAngle;
  16395. var angle;
  16396. var tdivisions = divisions * 2;
  16397. for ( j = 1; j <= tdivisions; j ++ ) {
  16398. t = j / tdivisions;
  16399. if ( ! aClockwise ) {
  16400. t = 1 - t;
  16401. }
  16402. angle = aStartAngle + t * deltaAngle;
  16403. tx = aX + aRadius * Math.cos( angle );
  16404. ty = aY + aRadius * Math.sin( angle );
  16405. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16406. points.push( new THREE.Vector2( tx, ty ) );
  16407. }
  16408. //console.log(points);
  16409. break;
  16410. case THREE.PathActions.ELLIPSE:
  16411. var aX = args[ 0 ], aY = args[ 1 ],
  16412. xRadius = args[ 2 ],
  16413. yRadius = args[ 3 ],
  16414. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16415. aClockwise = !!args[ 6 ];
  16416. var deltaAngle = aEndAngle - aStartAngle;
  16417. var angle;
  16418. var tdivisions = divisions * 2;
  16419. for ( j = 1; j <= tdivisions; j ++ ) {
  16420. t = j / tdivisions;
  16421. if ( ! aClockwise ) {
  16422. t = 1 - t;
  16423. }
  16424. angle = aStartAngle + t * deltaAngle;
  16425. tx = aX + xRadius * Math.cos( angle );
  16426. ty = aY + yRadius * Math.sin( angle );
  16427. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16428. points.push( new THREE.Vector2( tx, ty ) );
  16429. }
  16430. //console.log(points);
  16431. break;
  16432. } // end switch
  16433. }
  16434. // Normalize to remove the closing point by default.
  16435. var lastPoint = points[ points.length - 1];
  16436. var EPSILON = 0.0000000001;
  16437. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16438. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16439. points.splice( points.length - 1, 1);
  16440. if ( closedPath ) {
  16441. points.push( points[ 0 ] );
  16442. }
  16443. return points;
  16444. };
  16445. // Breaks path into shapes
  16446. THREE.Path.prototype.toShapes = function() {
  16447. var i, il, item, action, args;
  16448. var subPaths = [], lastPath = new THREE.Path();
  16449. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16450. item = this.actions[ i ];
  16451. args = item.args;
  16452. action = item.action;
  16453. if ( action == THREE.PathActions.MOVE_TO ) {
  16454. if ( lastPath.actions.length != 0 ) {
  16455. subPaths.push( lastPath );
  16456. lastPath = new THREE.Path();
  16457. }
  16458. }
  16459. lastPath[ action ].apply( lastPath, args );
  16460. }
  16461. if ( lastPath.actions.length != 0 ) {
  16462. subPaths.push( lastPath );
  16463. }
  16464. // console.log(subPaths);
  16465. if ( subPaths.length == 0 ) return [];
  16466. var tmpPath, tmpShape, shapes = [];
  16467. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16468. // console.log("Holes first", holesFirst);
  16469. if ( subPaths.length == 1) {
  16470. tmpPath = subPaths[0];
  16471. tmpShape = new THREE.Shape();
  16472. tmpShape.actions = tmpPath.actions;
  16473. tmpShape.curves = tmpPath.curves;
  16474. shapes.push( tmpShape );
  16475. return shapes;
  16476. };
  16477. if ( holesFirst ) {
  16478. tmpShape = new THREE.Shape();
  16479. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16480. tmpPath = subPaths[ i ];
  16481. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16482. tmpShape.actions = tmpPath.actions;
  16483. tmpShape.curves = tmpPath.curves;
  16484. shapes.push( tmpShape );
  16485. tmpShape = new THREE.Shape();
  16486. //console.log('cw', i);
  16487. } else {
  16488. tmpShape.holes.push( tmpPath );
  16489. //console.log('ccw', i);
  16490. }
  16491. }
  16492. } else {
  16493. // Shapes first
  16494. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16495. tmpPath = subPaths[ i ];
  16496. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16497. if ( tmpShape ) shapes.push( tmpShape );
  16498. tmpShape = new THREE.Shape();
  16499. tmpShape.actions = tmpPath.actions;
  16500. tmpShape.curves = tmpPath.curves;
  16501. } else {
  16502. tmpShape.holes.push( tmpPath );
  16503. }
  16504. }
  16505. shapes.push( tmpShape );
  16506. }
  16507. //console.log("shape", shapes);
  16508. return shapes;
  16509. };
  16510. /**
  16511. * @author zz85 / http://www.lab4games.net/zz85/blog
  16512. * Defines a 2d shape plane using paths.
  16513. **/
  16514. // STEP 1 Create a path.
  16515. // STEP 2 Turn path into shape.
  16516. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16517. // STEP 3a - Extract points from each shape, turn to vertices
  16518. // STEP 3b - Triangulate each shape, add faces.
  16519. THREE.Shape = function ( ) {
  16520. THREE.Path.apply( this, arguments );
  16521. this.holes = [];
  16522. };
  16523. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  16524. // Convenience method to return ExtrudeGeometry
  16525. THREE.Shape.prototype.extrude = function ( options ) {
  16526. var extruded = new THREE.ExtrudeGeometry( this, options );
  16527. return extruded;
  16528. };
  16529. // Convenience method to return ShapeGeometry
  16530. THREE.Shape.prototype.makeGeometry = function ( options ) {
  16531. var geometry = new THREE.ShapeGeometry( this, options );
  16532. return geometry;
  16533. };
  16534. // Get points of holes
  16535. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  16536. var i, il = this.holes.length, holesPts = [];
  16537. for ( i = 0; i < il; i ++ ) {
  16538. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  16539. }
  16540. return holesPts;
  16541. };
  16542. // Get points of holes (spaced by regular distance)
  16543. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  16544. var i, il = this.holes.length, holesPts = [];
  16545. for ( i = 0; i < il; i ++ ) {
  16546. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  16547. }
  16548. return holesPts;
  16549. };
  16550. // Get points of shape and holes (keypoints based on segments parameter)
  16551. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  16552. return {
  16553. shape: this.getTransformedPoints( divisions ),
  16554. holes: this.getPointsHoles( divisions )
  16555. };
  16556. };
  16557. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  16558. if (this.useSpacedPoints) {
  16559. return this.extractAllSpacedPoints(divisions);
  16560. }
  16561. return this.extractAllPoints(divisions);
  16562. };
  16563. //
  16564. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  16565. //
  16566. // return {
  16567. //
  16568. // shape: this.transform( bend, divisions ),
  16569. // holes: this.getPointsHoles( divisions, bend )
  16570. //
  16571. // };
  16572. //
  16573. // };
  16574. // Get points of shape and holes (spaced by regular distance)
  16575. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  16576. return {
  16577. shape: this.getTransformedSpacedPoints( divisions ),
  16578. holes: this.getSpacedPointsHoles( divisions )
  16579. };
  16580. };
  16581. /**************************************************************
  16582. * Utils
  16583. **************************************************************/
  16584. THREE.Shape.Utils = {
  16585. /*
  16586. contour - array of vector2 for contour
  16587. holes - array of array of vector2
  16588. */
  16589. removeHoles: function ( contour, holes ) {
  16590. var shape = contour.concat(); // work on this shape
  16591. var allpoints = shape.concat();
  16592. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  16593. var prevShapeVert, nextShapeVert,
  16594. prevHoleVert, nextHoleVert,
  16595. holeIndex, shapeIndex,
  16596. shapeId, shapeGroup,
  16597. h, h2,
  16598. hole, shortest, d,
  16599. p, pts1, pts2,
  16600. tmpShape1, tmpShape2,
  16601. tmpHole1, tmpHole2,
  16602. verts = [];
  16603. for ( h = 0; h < holes.length; h ++ ) {
  16604. hole = holes[ h ];
  16605. /*
  16606. shapeholes[ h ].concat(); // preserves original
  16607. holes.push( hole );
  16608. */
  16609. Array.prototype.push.apply( allpoints, hole );
  16610. shortest = Number.POSITIVE_INFINITY;
  16611. // Find the shortest pair of pts between shape and hole
  16612. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  16613. // Using distanceToSquared() intead of distanceTo() should speed a little
  16614. // since running square roots operations are reduced.
  16615. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  16616. pts1 = hole[ h2 ];
  16617. var dist = [];
  16618. for ( p = 0; p < shape.length; p++ ) {
  16619. pts2 = shape[ p ];
  16620. d = pts1.distanceToSquared( pts2 );
  16621. dist.push( d );
  16622. if ( d < shortest ) {
  16623. shortest = d;
  16624. holeIndex = h2;
  16625. shapeIndex = p;
  16626. }
  16627. }
  16628. }
  16629. //console.log("shortest", shortest, dist);
  16630. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16631. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16632. var areaapts = [
  16633. hole[ holeIndex ],
  16634. shape[ shapeIndex ],
  16635. shape[ prevShapeVert ]
  16636. ];
  16637. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  16638. var areabpts = [
  16639. hole[ holeIndex ],
  16640. hole[ prevHoleVert ],
  16641. shape[ shapeIndex ]
  16642. ];
  16643. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  16644. var shapeOffset = 1;
  16645. var holeOffset = -1;
  16646. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  16647. shapeIndex += shapeOffset;
  16648. holeIndex += holeOffset;
  16649. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16650. shapeIndex %= shape.length;
  16651. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16652. holeIndex %= hole.length;
  16653. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16654. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16655. areaapts = [
  16656. hole[ holeIndex ],
  16657. shape[ shapeIndex ],
  16658. shape[ prevShapeVert ]
  16659. ];
  16660. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  16661. areabpts = [
  16662. hole[ holeIndex ],
  16663. hole[ prevHoleVert ],
  16664. shape[ shapeIndex ]
  16665. ];
  16666. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  16667. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  16668. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  16669. // In case areas are not correct.
  16670. //console.log("USE THIS");
  16671. shapeIndex = oldShapeIndex;
  16672. holeIndex = oldHoleIndex ;
  16673. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16674. shapeIndex %= shape.length;
  16675. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16676. holeIndex %= hole.length;
  16677. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16678. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16679. } else {
  16680. //console.log("USE THAT ")
  16681. }
  16682. tmpShape1 = shape.slice( 0, shapeIndex );
  16683. tmpShape2 = shape.slice( shapeIndex );
  16684. tmpHole1 = hole.slice( holeIndex );
  16685. tmpHole2 = hole.slice( 0, holeIndex );
  16686. // Should check orders here again?
  16687. var trianglea = [
  16688. hole[ holeIndex ],
  16689. shape[ shapeIndex ],
  16690. shape[ prevShapeVert ]
  16691. ];
  16692. var triangleb = [
  16693. hole[ holeIndex ] ,
  16694. hole[ prevHoleVert ],
  16695. shape[ shapeIndex ]
  16696. ];
  16697. verts.push( trianglea );
  16698. verts.push( triangleb );
  16699. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  16700. }
  16701. return {
  16702. shape:shape, /* shape with no holes */
  16703. isolatedPts: verts, /* isolated faces */
  16704. allpoints: allpoints
  16705. }
  16706. },
  16707. triangulateShape: function ( contour, holes ) {
  16708. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  16709. var shape = shapeWithoutHoles.shape,
  16710. allpoints = shapeWithoutHoles.allpoints,
  16711. isolatedPts = shapeWithoutHoles.isolatedPts;
  16712. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  16713. // 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.
  16714. //console.log( "triangles",triangles, triangles.length );
  16715. //console.log( "allpoints",allpoints, allpoints.length );
  16716. var i, il, f, face,
  16717. key, index,
  16718. allPointsMap = {},
  16719. isolatedPointsMap = {};
  16720. // prepare all points map
  16721. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  16722. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  16723. if ( allPointsMap[ key ] !== undefined ) {
  16724. console.log( "Duplicate point", key );
  16725. }
  16726. allPointsMap[ key ] = i;
  16727. }
  16728. // check all face vertices against all points map
  16729. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  16730. face = triangles[ i ];
  16731. for ( f = 0; f < 3; f ++ ) {
  16732. key = face[ f ].x + ":" + face[ f ].y;
  16733. index = allPointsMap[ key ];
  16734. if ( index !== undefined ) {
  16735. face[ f ] = index;
  16736. }
  16737. }
  16738. }
  16739. // check isolated points vertices against all points map
  16740. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  16741. face = isolatedPts[ i ];
  16742. for ( f = 0; f < 3; f ++ ) {
  16743. key = face[ f ].x + ":" + face[ f ].y;
  16744. index = allPointsMap[ key ];
  16745. if ( index !== undefined ) {
  16746. face[ f ] = index;
  16747. }
  16748. }
  16749. }
  16750. return triangles.concat( isolatedPts );
  16751. }, // end triangulate shapes
  16752. /*
  16753. triangulate2 : function( pts, holes ) {
  16754. // For use with Poly2Tri.js
  16755. var allpts = pts.concat();
  16756. var shape = [];
  16757. for (var p in pts) {
  16758. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  16759. }
  16760. var swctx = new js.poly2tri.SweepContext(shape);
  16761. for (var h in holes) {
  16762. var aHole = holes[h];
  16763. var newHole = []
  16764. for (i in aHole) {
  16765. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  16766. allpts.push(aHole[i]);
  16767. }
  16768. swctx.AddHole(newHole);
  16769. }
  16770. var find;
  16771. var findIndexForPt = function (pt) {
  16772. find = new THREE.Vector2(pt.x, pt.y);
  16773. var p;
  16774. for (p=0, pl = allpts.length; p<pl; p++) {
  16775. if (allpts[p].equals(find)) return p;
  16776. }
  16777. return -1;
  16778. };
  16779. // triangulate
  16780. js.poly2tri.sweep.Triangulate(swctx);
  16781. var triangles = swctx.GetTriangles();
  16782. var tr ;
  16783. var facesPts = [];
  16784. for (var t in triangles) {
  16785. tr = triangles[t];
  16786. facesPts.push([
  16787. findIndexForPt(tr.GetPoint(0)),
  16788. findIndexForPt(tr.GetPoint(1)),
  16789. findIndexForPt(tr.GetPoint(2))
  16790. ]);
  16791. }
  16792. // console.log(facesPts);
  16793. // console.log("triangles", triangles.length, triangles);
  16794. // Returns array of faces with 3 element each
  16795. return facesPts;
  16796. },
  16797. */
  16798. isClockWise: function ( pts ) {
  16799. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  16800. },
  16801. // Bezier Curves formulas obtained from
  16802. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  16803. // Quad Bezier Functions
  16804. b2p0: function ( t, p ) {
  16805. var k = 1 - t;
  16806. return k * k * p;
  16807. },
  16808. b2p1: function ( t, p ) {
  16809. return 2 * ( 1 - t ) * t * p;
  16810. },
  16811. b2p2: function ( t, p ) {
  16812. return t * t * p;
  16813. },
  16814. b2: function ( t, p0, p1, p2 ) {
  16815. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  16816. },
  16817. // Cubic Bezier Functions
  16818. b3p0: function ( t, p ) {
  16819. var k = 1 - t;
  16820. return k * k * k * p;
  16821. },
  16822. b3p1: function ( t, p ) {
  16823. var k = 1 - t;
  16824. return 3 * k * k * t * p;
  16825. },
  16826. b3p2: function ( t, p ) {
  16827. var k = 1 - t;
  16828. return 3 * k * t * t * p;
  16829. },
  16830. b3p3: function ( t, p ) {
  16831. return t * t * t * p;
  16832. },
  16833. b3: function ( t, p0, p1, p2, p3 ) {
  16834. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  16835. }
  16836. };
  16837. /**
  16838. * @author mikael emtinger / http://gomo.se/
  16839. */
  16840. THREE.AnimationHandler = (function() {
  16841. var playing = [];
  16842. var library = {};
  16843. var that = {};
  16844. //--- update ---
  16845. that.update = function( deltaTimeMS ) {
  16846. for( var i = 0; i < playing.length; i ++ )
  16847. playing[ i ].update( deltaTimeMS );
  16848. };
  16849. //--- add ---
  16850. that.addToUpdate = function( animation ) {
  16851. if ( playing.indexOf( animation ) === -1 )
  16852. playing.push( animation );
  16853. };
  16854. //--- remove ---
  16855. that.removeFromUpdate = function( animation ) {
  16856. var index = playing.indexOf( animation );
  16857. if( index !== -1 )
  16858. playing.splice( index, 1 );
  16859. };
  16860. //--- add ---
  16861. that.add = function( data ) {
  16862. if ( library[ data.name ] !== undefined )
  16863. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  16864. library[ data.name ] = data;
  16865. initData( data );
  16866. };
  16867. //--- get ---
  16868. that.get = function( name ) {
  16869. if ( typeof name === "string" ) {
  16870. if ( library[ name ] ) {
  16871. return library[ name ];
  16872. } else {
  16873. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  16874. return null;
  16875. }
  16876. } else {
  16877. // todo: add simple tween library
  16878. }
  16879. };
  16880. //--- parse ---
  16881. that.parse = function( root ) {
  16882. // setup hierarchy
  16883. var hierarchy = [];
  16884. if ( root instanceof THREE.SkinnedMesh ) {
  16885. for( var b = 0; b < root.bones.length; b++ ) {
  16886. hierarchy.push( root.bones[ b ] );
  16887. }
  16888. } else {
  16889. parseRecurseHierarchy( root, hierarchy );
  16890. }
  16891. return hierarchy;
  16892. };
  16893. var parseRecurseHierarchy = function( root, hierarchy ) {
  16894. hierarchy.push( root );
  16895. for( var c = 0; c < root.children.length; c++ )
  16896. parseRecurseHierarchy( root.children[ c ], hierarchy );
  16897. }
  16898. //--- init data ---
  16899. var initData = function( data ) {
  16900. if( data.initialized === true )
  16901. return;
  16902. // loop through all keys
  16903. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  16904. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16905. // remove minus times
  16906. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  16907. data.hierarchy[ h ].keys[ k ].time = 0;
  16908. // create quaternions
  16909. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  16910. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  16911. var quat = data.hierarchy[ h ].keys[ k ].rot;
  16912. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  16913. }
  16914. }
  16915. // prepare morph target keys
  16916. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  16917. // get all used
  16918. var usedMorphTargets = {};
  16919. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16920. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16921. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  16922. usedMorphTargets[ morphTargetName ] = -1;
  16923. }
  16924. }
  16925. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  16926. // set all used on all frames
  16927. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16928. var influences = {};
  16929. for ( var morphTargetName in usedMorphTargets ) {
  16930. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16931. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  16932. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  16933. break;
  16934. }
  16935. }
  16936. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  16937. influences[ morphTargetName ] = 0;
  16938. }
  16939. }
  16940. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  16941. }
  16942. }
  16943. // remove all keys that are on the same time
  16944. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16945. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  16946. data.hierarchy[ h ].keys.splice( k, 1 );
  16947. k --;
  16948. }
  16949. }
  16950. // set index
  16951. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16952. data.hierarchy[ h ].keys[ k ].index = k;
  16953. }
  16954. }
  16955. // JIT
  16956. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  16957. data.JIT = {};
  16958. data.JIT.hierarchy = [];
  16959. for( var h = 0; h < data.hierarchy.length; h ++ )
  16960. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  16961. // done
  16962. data.initialized = true;
  16963. };
  16964. // interpolation types
  16965. that.LINEAR = 0;
  16966. that.CATMULLROM = 1;
  16967. that.CATMULLROM_FORWARD = 2;
  16968. return that;
  16969. }());
  16970. /**
  16971. * @author mikael emtinger / http://gomo.se/
  16972. * @author mrdoob / http://mrdoob.com/
  16973. * @author alteredq / http://alteredqualia.com/
  16974. */
  16975. THREE.Animation = function ( root, name, interpolationType ) {
  16976. this.root = root;
  16977. this.data = THREE.AnimationHandler.get( name );
  16978. this.hierarchy = THREE.AnimationHandler.parse( root );
  16979. this.currentTime = 0;
  16980. this.timeScale = 1;
  16981. this.isPlaying = false;
  16982. this.isPaused = true;
  16983. this.loop = true;
  16984. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  16985. this.points = [];
  16986. this.target = new THREE.Vector3();
  16987. };
  16988. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  16989. if ( this.isPlaying === false ) {
  16990. this.isPlaying = true;
  16991. this.loop = loop !== undefined ? loop : true;
  16992. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  16993. // reset key cache
  16994. var h, hl = this.hierarchy.length,
  16995. object;
  16996. for ( h = 0; h < hl; h ++ ) {
  16997. object = this.hierarchy[ h ];
  16998. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16999. object.useQuaternion = true;
  17000. }
  17001. object.matrixAutoUpdate = true;
  17002. if ( object.animationCache === undefined ) {
  17003. object.animationCache = {};
  17004. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17005. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17006. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17007. }
  17008. var prevKey = object.animationCache.prevKey;
  17009. var nextKey = object.animationCache.nextKey;
  17010. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17011. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17012. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17013. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17014. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17015. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17016. }
  17017. this.update( 0 );
  17018. }
  17019. this.isPaused = false;
  17020. THREE.AnimationHandler.addToUpdate( this );
  17021. };
  17022. THREE.Animation.prototype.pause = function() {
  17023. if ( this.isPaused === true ) {
  17024. THREE.AnimationHandler.addToUpdate( this );
  17025. } else {
  17026. THREE.AnimationHandler.removeFromUpdate( this );
  17027. }
  17028. this.isPaused = !this.isPaused;
  17029. };
  17030. THREE.Animation.prototype.stop = function() {
  17031. this.isPlaying = false;
  17032. this.isPaused = false;
  17033. THREE.AnimationHandler.removeFromUpdate( this );
  17034. };
  17035. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17036. // early out
  17037. if ( this.isPlaying === false ) return;
  17038. // vars
  17039. var types = [ "pos", "rot", "scl" ];
  17040. var type;
  17041. var scale;
  17042. var vector;
  17043. var prevXYZ, nextXYZ;
  17044. var prevKey, nextKey;
  17045. var object;
  17046. var animationCache;
  17047. var frame;
  17048. var JIThierarchy = this.data.JIT.hierarchy;
  17049. var currentTime, unloopedCurrentTime;
  17050. var currentPoint, forwardPoint, angle;
  17051. this.currentTime += deltaTimeMS * this.timeScale;
  17052. unloopedCurrentTime = this.currentTime;
  17053. currentTime = this.currentTime = this.currentTime % this.data.length;
  17054. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17055. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17056. object = this.hierarchy[ h ];
  17057. animationCache = object.animationCache;
  17058. // loop through pos/rot/scl
  17059. for ( var t = 0; t < 3; t ++ ) {
  17060. // get keys
  17061. type = types[ t ];
  17062. prevKey = animationCache.prevKey[ type ];
  17063. nextKey = animationCache.nextKey[ type ];
  17064. // switch keys?
  17065. if ( nextKey.time <= unloopedCurrentTime ) {
  17066. // did we loop?
  17067. if ( currentTime < unloopedCurrentTime ) {
  17068. if ( this.loop ) {
  17069. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17070. nextKey = this.getNextKeyWith( type, h, 1 );
  17071. while( nextKey.time < currentTime ) {
  17072. prevKey = nextKey;
  17073. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17074. }
  17075. } else {
  17076. this.stop();
  17077. return;
  17078. }
  17079. } else {
  17080. do {
  17081. prevKey = nextKey;
  17082. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17083. } while( nextKey.time < currentTime )
  17084. }
  17085. animationCache.prevKey[ type ] = prevKey;
  17086. animationCache.nextKey[ type ] = nextKey;
  17087. }
  17088. object.matrixAutoUpdate = true;
  17089. object.matrixWorldNeedsUpdate = true;
  17090. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17091. prevXYZ = prevKey[ type ];
  17092. nextXYZ = nextKey[ type ];
  17093. // check scale error
  17094. if ( scale < 0 || scale > 1 ) {
  17095. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17096. scale = scale < 0 ? 0 : 1;
  17097. }
  17098. // interpolate
  17099. if ( type === "pos" ) {
  17100. vector = object.position;
  17101. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17102. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17103. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17104. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17105. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17106. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17107. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17108. this.points[ 1 ] = prevXYZ;
  17109. this.points[ 2 ] = nextXYZ;
  17110. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17111. scale = scale * 0.33 + 0.33;
  17112. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17113. vector.x = currentPoint[ 0 ];
  17114. vector.y = currentPoint[ 1 ];
  17115. vector.z = currentPoint[ 2 ];
  17116. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17117. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17118. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17119. this.target.subSelf( vector );
  17120. this.target.y = 0;
  17121. this.target.normalize();
  17122. angle = Math.atan2( this.target.x, this.target.z );
  17123. object.rotation.set( 0, angle, 0 );
  17124. }
  17125. }
  17126. } else if ( type === "rot" ) {
  17127. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17128. } else if ( type === "scl" ) {
  17129. vector = object.scale;
  17130. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17131. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17132. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17133. }
  17134. }
  17135. }
  17136. };
  17137. // Catmull-Rom spline
  17138. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17139. var c = [], v3 = [],
  17140. point, intPoint, weight, w2, w3,
  17141. pa, pb, pc, pd;
  17142. point = ( points.length - 1 ) * scale;
  17143. intPoint = Math.floor( point );
  17144. weight = point - intPoint;
  17145. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17146. c[ 1 ] = intPoint;
  17147. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17148. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17149. pa = points[ c[ 0 ] ];
  17150. pb = points[ c[ 1 ] ];
  17151. pc = points[ c[ 2 ] ];
  17152. pd = points[ c[ 3 ] ];
  17153. w2 = weight * weight;
  17154. w3 = weight * w2;
  17155. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17156. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17157. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17158. return v3;
  17159. };
  17160. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17161. var v0 = ( p2 - p0 ) * 0.5,
  17162. v1 = ( p3 - p1 ) * 0.5;
  17163. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17164. };
  17165. // Get next key with
  17166. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17167. var keys = this.data.hierarchy[ h ].keys;
  17168. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17169. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17170. key = key < keys.length - 1 ? key : keys.length - 1;
  17171. } else {
  17172. key = key % keys.length;
  17173. }
  17174. for ( ; key < keys.length; key++ ) {
  17175. if ( keys[ key ][ type ] !== undefined ) {
  17176. return keys[ key ];
  17177. }
  17178. }
  17179. return this.data.hierarchy[ h ].keys[ 0 ];
  17180. };
  17181. // Get previous key with
  17182. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17183. var keys = this.data.hierarchy[ h ].keys;
  17184. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17185. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17186. key = key > 0 ? key : 0;
  17187. } else {
  17188. key = key >= 0 ? key : key + keys.length;
  17189. }
  17190. for ( ; key >= 0; key -- ) {
  17191. if ( keys[ key ][ type ] !== undefined ) {
  17192. return keys[ key ];
  17193. }
  17194. }
  17195. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17196. };
  17197. /**
  17198. * @author mikael emtinger / http://gomo.se/
  17199. * @author mrdoob / http://mrdoob.com/
  17200. * @author alteredq / http://alteredqualia.com/
  17201. * @author khang duong
  17202. * @author erik kitson
  17203. */
  17204. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17205. this.root = root;
  17206. this.data = THREE.AnimationHandler.get( data );
  17207. this.hierarchy = THREE.AnimationHandler.parse( root );
  17208. this.currentTime = 0;
  17209. this.timeScale = 0.001;
  17210. this.isPlaying = false;
  17211. this.isPaused = true;
  17212. this.loop = true;
  17213. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17214. // initialize to first keyframes
  17215. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17216. var keys = this.data.hierarchy[h].keys,
  17217. sids = this.data.hierarchy[h].sids,
  17218. obj = this.hierarchy[h];
  17219. if ( keys.length && sids ) {
  17220. for ( var s = 0; s < sids.length; s++ ) {
  17221. var sid = sids[ s ],
  17222. next = this.getNextKeyWith( sid, h, 0 );
  17223. if ( next ) {
  17224. next.apply( sid );
  17225. }
  17226. }
  17227. obj.matrixAutoUpdate = false;
  17228. this.data.hierarchy[h].node.updateMatrix();
  17229. obj.matrixWorldNeedsUpdate = true;
  17230. }
  17231. }
  17232. };
  17233. // Play
  17234. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17235. if( !this.isPlaying ) {
  17236. this.isPlaying = true;
  17237. this.loop = loop !== undefined ? loop : true;
  17238. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17239. this.startTimeMs = startTimeMS;
  17240. this.startTime = 10000000;
  17241. this.endTime = -this.startTime;
  17242. // reset key cache
  17243. var h, hl = this.hierarchy.length,
  17244. object,
  17245. node;
  17246. for ( h = 0; h < hl; h++ ) {
  17247. object = this.hierarchy[ h ];
  17248. node = this.data.hierarchy[ h ];
  17249. object.useQuaternion = true;
  17250. if ( node.animationCache === undefined ) {
  17251. node.animationCache = {};
  17252. node.animationCache.prevKey = null;
  17253. node.animationCache.nextKey = null;
  17254. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17255. }
  17256. var keys = this.data.hierarchy[h].keys;
  17257. if (keys.length) {
  17258. node.animationCache.prevKey = keys[ 0 ];
  17259. node.animationCache.nextKey = keys[ 1 ];
  17260. this.startTime = Math.min( keys[0].time, this.startTime );
  17261. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17262. }
  17263. }
  17264. this.update( 0 );
  17265. }
  17266. this.isPaused = false;
  17267. THREE.AnimationHandler.addToUpdate( this );
  17268. };
  17269. // Pause
  17270. THREE.KeyFrameAnimation.prototype.pause = function() {
  17271. if( this.isPaused ) {
  17272. THREE.AnimationHandler.addToUpdate( this );
  17273. } else {
  17274. THREE.AnimationHandler.removeFromUpdate( this );
  17275. }
  17276. this.isPaused = !this.isPaused;
  17277. };
  17278. // Stop
  17279. THREE.KeyFrameAnimation.prototype.stop = function() {
  17280. this.isPlaying = false;
  17281. this.isPaused = false;
  17282. THREE.AnimationHandler.removeFromUpdate( this );
  17283. // reset JIT matrix and remove cache
  17284. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17285. var obj = this.hierarchy[ h ];
  17286. var node = this.data.hierarchy[ h ];
  17287. if ( node.animationCache !== undefined ) {
  17288. var original = node.animationCache.originalMatrix;
  17289. if( obj instanceof THREE.Bone ) {
  17290. original.copy( obj.skinMatrix );
  17291. obj.skinMatrix = original;
  17292. } else {
  17293. original.copy( obj.matrix );
  17294. obj.matrix = original;
  17295. }
  17296. delete node.animationCache;
  17297. }
  17298. }
  17299. };
  17300. // Update
  17301. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17302. // early out
  17303. if( !this.isPlaying ) return;
  17304. // vars
  17305. var prevKey, nextKey;
  17306. var object;
  17307. var node;
  17308. var frame;
  17309. var JIThierarchy = this.data.JIT.hierarchy;
  17310. var currentTime, unloopedCurrentTime;
  17311. var looped;
  17312. // update
  17313. this.currentTime += deltaTimeMS * this.timeScale;
  17314. unloopedCurrentTime = this.currentTime;
  17315. currentTime = this.currentTime = this.currentTime % this.data.length;
  17316. // if looped around, the current time should be based on the startTime
  17317. if ( currentTime < this.startTimeMs ) {
  17318. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17319. }
  17320. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17321. looped = currentTime < unloopedCurrentTime;
  17322. if ( looped && !this.loop ) {
  17323. // Set the animation to the last keyframes and stop
  17324. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17325. var keys = this.data.hierarchy[h].keys,
  17326. sids = this.data.hierarchy[h].sids,
  17327. end = keys.length-1,
  17328. obj = this.hierarchy[h];
  17329. if ( keys.length ) {
  17330. for ( var s = 0; s < sids.length; s++ ) {
  17331. var sid = sids[ s ],
  17332. prev = this.getPrevKeyWith( sid, h, end );
  17333. if ( prev ) {
  17334. prev.apply( sid );
  17335. }
  17336. }
  17337. this.data.hierarchy[h].node.updateMatrix();
  17338. obj.matrixWorldNeedsUpdate = true;
  17339. }
  17340. }
  17341. this.stop();
  17342. return;
  17343. }
  17344. // check pre-infinity
  17345. if ( currentTime < this.startTime ) {
  17346. return;
  17347. }
  17348. // update
  17349. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17350. object = this.hierarchy[ h ];
  17351. node = this.data.hierarchy[ h ];
  17352. var keys = node.keys,
  17353. animationCache = node.animationCache;
  17354. // use JIT?
  17355. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  17356. if( object instanceof THREE.Bone ) {
  17357. object.skinMatrix = JIThierarchy[ h ][ frame ];
  17358. object.matrixWorldNeedsUpdate = false;
  17359. } else {
  17360. object.matrix = JIThierarchy[ h ][ frame ];
  17361. object.matrixWorldNeedsUpdate = true;
  17362. }
  17363. // use interpolation
  17364. } else if ( keys.length ) {
  17365. // make sure so original matrix and not JIT matrix is set
  17366. if ( this.JITCompile && animationCache ) {
  17367. if( object instanceof THREE.Bone ) {
  17368. object.skinMatrix = animationCache.originalMatrix;
  17369. } else {
  17370. object.matrix = animationCache.originalMatrix;
  17371. }
  17372. }
  17373. prevKey = animationCache.prevKey;
  17374. nextKey = animationCache.nextKey;
  17375. if ( prevKey && nextKey ) {
  17376. // switch keys?
  17377. if ( nextKey.time <= unloopedCurrentTime ) {
  17378. // did we loop?
  17379. if ( looped && this.loop ) {
  17380. prevKey = keys[ 0 ];
  17381. nextKey = keys[ 1 ];
  17382. while ( nextKey.time < currentTime ) {
  17383. prevKey = nextKey;
  17384. nextKey = keys[ prevKey.index + 1 ];
  17385. }
  17386. } else if ( !looped ) {
  17387. var lastIndex = keys.length - 1;
  17388. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  17389. prevKey = nextKey;
  17390. nextKey = keys[ prevKey.index + 1 ];
  17391. }
  17392. }
  17393. animationCache.prevKey = prevKey;
  17394. animationCache.nextKey = nextKey;
  17395. }
  17396. if(nextKey.time >= currentTime)
  17397. prevKey.interpolate( nextKey, currentTime );
  17398. else
  17399. prevKey.interpolate( nextKey, nextKey.time);
  17400. }
  17401. this.data.hierarchy[h].node.updateMatrix();
  17402. object.matrixWorldNeedsUpdate = true;
  17403. }
  17404. }
  17405. // update JIT?
  17406. if ( this.JITCompile ) {
  17407. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  17408. this.hierarchy[ 0 ].updateMatrixWorld( true );
  17409. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  17410. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  17411. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  17412. } else {
  17413. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  17414. }
  17415. }
  17416. }
  17417. }
  17418. };
  17419. // Get next key with
  17420. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  17421. var keys = this.data.hierarchy[ h ].keys;
  17422. key = key % keys.length;
  17423. for ( ; key < keys.length; key++ ) {
  17424. if ( keys[ key ].hasTarget( sid ) ) {
  17425. return keys[ key ];
  17426. }
  17427. }
  17428. return keys[ 0 ];
  17429. };
  17430. // Get previous key with
  17431. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  17432. var keys = this.data.hierarchy[ h ].keys;
  17433. key = key >= 0 ? key : key + keys.length;
  17434. for ( ; key >= 0; key-- ) {
  17435. if ( keys[ key ].hasTarget( sid ) ) {
  17436. return keys[ key ];
  17437. }
  17438. }
  17439. return keys[ keys.length - 1 ];
  17440. };
  17441. /**
  17442. * Camera for rendering cube maps
  17443. * - renders scene into axis-aligned cube
  17444. *
  17445. * @author alteredq / http://alteredqualia.com/
  17446. */
  17447. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  17448. THREE.Object3D.call( this );
  17449. var fov = 90, aspect = 1;
  17450. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17451. cameraPX.up.set( 0, -1, 0 );
  17452. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  17453. this.add( cameraPX );
  17454. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17455. cameraNX.up.set( 0, -1, 0 );
  17456. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  17457. this.add( cameraNX );
  17458. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17459. cameraPY.up.set( 0, 0, 1 );
  17460. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  17461. this.add( cameraPY );
  17462. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17463. cameraNY.up.set( 0, 0, -1 );
  17464. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  17465. this.add( cameraNY );
  17466. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17467. cameraPZ.up.set( 0, -1, 0 );
  17468. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  17469. this.add( cameraPZ );
  17470. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17471. cameraNZ.up.set( 0, -1, 0 );
  17472. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  17473. this.add( cameraNZ );
  17474. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  17475. this.updateCubeMap = function ( renderer, scene ) {
  17476. var renderTarget = this.renderTarget;
  17477. var generateMipmaps = renderTarget.generateMipmaps;
  17478. renderTarget.generateMipmaps = false;
  17479. renderTarget.activeCubeFace = 0;
  17480. renderer.render( scene, cameraPX, renderTarget );
  17481. renderTarget.activeCubeFace = 1;
  17482. renderer.render( scene, cameraNX, renderTarget );
  17483. renderTarget.activeCubeFace = 2;
  17484. renderer.render( scene, cameraPY, renderTarget );
  17485. renderTarget.activeCubeFace = 3;
  17486. renderer.render( scene, cameraNY, renderTarget );
  17487. renderTarget.activeCubeFace = 4;
  17488. renderer.render( scene, cameraPZ, renderTarget );
  17489. renderTarget.generateMipmaps = generateMipmaps;
  17490. renderTarget.activeCubeFace = 5;
  17491. renderer.render( scene, cameraNZ, renderTarget );
  17492. };
  17493. };
  17494. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  17495. /*
  17496. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  17497. *
  17498. * A general perpose camera, for setting FOV, Lens Focal Length,
  17499. * and switching between perspective and orthographic views easily.
  17500. * Use this only if you do not wish to manage
  17501. * both a Orthographic and Perspective Camera
  17502. *
  17503. */
  17504. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  17505. THREE.Camera.call( this );
  17506. this.fov = fov;
  17507. this.left = -width / 2;
  17508. this.right = width / 2
  17509. this.top = height / 2;
  17510. this.bottom = -height / 2;
  17511. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  17512. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  17513. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  17514. this.zoom = 1;
  17515. this.toPerspective();
  17516. var aspect = width/height;
  17517. };
  17518. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  17519. THREE.CombinedCamera.prototype.toPerspective = function () {
  17520. // Switches to the Perspective Camera
  17521. this.near = this.cameraP.near;
  17522. this.far = this.cameraP.far;
  17523. this.cameraP.fov = this.fov / this.zoom ;
  17524. this.cameraP.updateProjectionMatrix();
  17525. this.projectionMatrix = this.cameraP.projectionMatrix;
  17526. this.inPerspectiveMode = true;
  17527. this.inOrthographicMode = false;
  17528. };
  17529. THREE.CombinedCamera.prototype.toOrthographic = function () {
  17530. // Switches to the Orthographic camera estimating viewport from Perspective
  17531. var fov = this.fov;
  17532. var aspect = this.cameraP.aspect;
  17533. var near = this.cameraP.near;
  17534. var far = this.cameraP.far;
  17535. // The size that we set is the mid plane of the viewing frustum
  17536. var hyperfocus = ( near + far ) / 2;
  17537. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  17538. var planeHeight = 2 * halfHeight;
  17539. var planeWidth = planeHeight * aspect;
  17540. var halfWidth = planeWidth / 2;
  17541. halfHeight /= this.zoom;
  17542. halfWidth /= this.zoom;
  17543. this.cameraO.left = -halfWidth;
  17544. this.cameraO.right = halfWidth;
  17545. this.cameraO.top = halfHeight;
  17546. this.cameraO.bottom = -halfHeight;
  17547. // this.cameraO.left = -farHalfWidth;
  17548. // this.cameraO.right = farHalfWidth;
  17549. // this.cameraO.top = farHalfHeight;
  17550. // this.cameraO.bottom = -farHalfHeight;
  17551. // this.cameraO.left = this.left / this.zoom;
  17552. // this.cameraO.right = this.right / this.zoom;
  17553. // this.cameraO.top = this.top / this.zoom;
  17554. // this.cameraO.bottom = this.bottom / this.zoom;
  17555. this.cameraO.updateProjectionMatrix();
  17556. this.near = this.cameraO.near;
  17557. this.far = this.cameraO.far;
  17558. this.projectionMatrix = this.cameraO.projectionMatrix;
  17559. this.inPerspectiveMode = false;
  17560. this.inOrthographicMode = true;
  17561. };
  17562. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  17563. this.cameraP.aspect = width / height;
  17564. this.left = -width / 2;
  17565. this.right = width / 2
  17566. this.top = height / 2;
  17567. this.bottom = -height / 2;
  17568. };
  17569. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  17570. this.fov = fov;
  17571. if ( this.inPerspectiveMode ) {
  17572. this.toPerspective();
  17573. } else {
  17574. this.toOrthographic();
  17575. }
  17576. };
  17577. // For mantaining similar API with PerspectiveCamera
  17578. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  17579. if ( this.inPerspectiveMode ) {
  17580. this.toPerspective();
  17581. } else {
  17582. this.toPerspective();
  17583. this.toOrthographic();
  17584. }
  17585. };
  17586. /*
  17587. * Uses Focal Length (in mm) to estimate and set FOV
  17588. * 35mm (fullframe) camera is used if frame size is not specified;
  17589. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  17590. */
  17591. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  17592. if ( frameHeight === undefined ) frameHeight = 24;
  17593. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  17594. this.setFov( fov );
  17595. return fov;
  17596. };
  17597. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  17598. this.zoom = zoom;
  17599. if ( this.inPerspectiveMode ) {
  17600. this.toPerspective();
  17601. } else {
  17602. this.toOrthographic();
  17603. }
  17604. };
  17605. THREE.CombinedCamera.prototype.toFrontView = function() {
  17606. this.rotation.x = 0;
  17607. this.rotation.y = 0;
  17608. this.rotation.z = 0;
  17609. // should we be modifing the matrix instead?
  17610. this.rotationAutoUpdate = false;
  17611. };
  17612. THREE.CombinedCamera.prototype.toBackView = function() {
  17613. this.rotation.x = 0;
  17614. this.rotation.y = Math.PI;
  17615. this.rotation.z = 0;
  17616. this.rotationAutoUpdate = false;
  17617. };
  17618. THREE.CombinedCamera.prototype.toLeftView = function() {
  17619. this.rotation.x = 0;
  17620. this.rotation.y = - Math.PI / 2;
  17621. this.rotation.z = 0;
  17622. this.rotationAutoUpdate = false;
  17623. };
  17624. THREE.CombinedCamera.prototype.toRightView = function() {
  17625. this.rotation.x = 0;
  17626. this.rotation.y = Math.PI / 2;
  17627. this.rotation.z = 0;
  17628. this.rotationAutoUpdate = false;
  17629. };
  17630. THREE.CombinedCamera.prototype.toTopView = function() {
  17631. this.rotation.x = - Math.PI / 2;
  17632. this.rotation.y = 0;
  17633. this.rotation.z = 0;
  17634. this.rotationAutoUpdate = false;
  17635. };
  17636. THREE.CombinedCamera.prototype.toBottomView = function() {
  17637. this.rotation.x = Math.PI / 2;
  17638. this.rotation.y = 0;
  17639. this.rotation.z = 0;
  17640. this.rotationAutoUpdate = false;
  17641. };
  17642. /**
  17643. * @author alteredq / http://alteredqualia.com/
  17644. *
  17645. * - 3d asterisk shape (for line pieces THREE.Line)
  17646. */
  17647. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  17648. THREE.Geometry.call( this );
  17649. var sd = innerRadius;
  17650. var ed = outerRadius;
  17651. var sd2 = 0.707 * sd;
  17652. var ed2 = 0.707 * ed;
  17653. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  17654. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  17655. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  17656. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  17657. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  17658. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  17659. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  17660. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  17661. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  17662. ];
  17663. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  17664. var x = rays[ i ][ 0 ];
  17665. var y = rays[ i ][ 1 ];
  17666. var z = rays[ i ][ 2 ];
  17667. this.vertices.push( new THREE.Vector3( x, y, z ) );
  17668. }
  17669. };
  17670. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  17671. * @author hughes
  17672. */
  17673. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  17674. THREE.Geometry.call( this );
  17675. radius = radius || 50;
  17676. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17677. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17678. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17679. var i, uvs = [],
  17680. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  17681. this.vertices.push(center);
  17682. uvs.push( centerUV );
  17683. for ( i = 0; i <= segments; i ++ ) {
  17684. var vertex = new THREE.Vector3();
  17685. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  17686. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  17687. this.vertices.push( vertex );
  17688. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  17689. }
  17690. var n = new THREE.Vector3( 0, 0, -1 );
  17691. for ( i = 1; i <= segments; i ++ ) {
  17692. var v1 = i;
  17693. var v2 = i + 1 ;
  17694. var v3 = 0;
  17695. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  17696. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  17697. }
  17698. this.computeCentroids();
  17699. this.computeFaceNormals();
  17700. this.boundingSphere = { radius: radius };
  17701. };
  17702. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17703. /**
  17704. * @author mrdoob / http://mrdoob.com/
  17705. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  17706. */
  17707. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  17708. THREE.Geometry.call( this );
  17709. var scope = this;
  17710. this.width = width;
  17711. this.height = height;
  17712. this.depth = depth;
  17713. this.widthSegments = widthSegments || 1;
  17714. this.heightSegments = heightSegments || 1;
  17715. this.depthSegments = depthSegments || 1;
  17716. var width_half = this.width / 2;
  17717. var height_half = this.height / 2;
  17718. var depth_half = this.depth / 2;
  17719. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  17720. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  17721. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  17722. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  17723. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  17724. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  17725. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  17726. var w, ix, iy,
  17727. gridX = scope.widthSegments,
  17728. gridY = scope.heightSegments,
  17729. width_half = width / 2,
  17730. height_half = height / 2,
  17731. offset = scope.vertices.length;
  17732. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  17733. w = 'z';
  17734. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  17735. w = 'y';
  17736. gridY = scope.depthSegments;
  17737. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  17738. w = 'x';
  17739. gridX = scope.depthSegments;
  17740. }
  17741. var gridX1 = gridX + 1,
  17742. gridY1 = gridY + 1,
  17743. segment_width = width / gridX,
  17744. segment_height = height / gridY,
  17745. normal = new THREE.Vector3();
  17746. normal[ w ] = depth > 0 ? 1 : - 1;
  17747. for ( iy = 0; iy < gridY1; iy ++ ) {
  17748. for ( ix = 0; ix < gridX1; ix ++ ) {
  17749. var vector = new THREE.Vector3();
  17750. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  17751. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  17752. vector[ w ] = depth;
  17753. scope.vertices.push( vector );
  17754. }
  17755. }
  17756. for ( iy = 0; iy < gridY; iy++ ) {
  17757. for ( ix = 0; ix < gridX; ix++ ) {
  17758. var a = ix + gridX1 * iy;
  17759. var b = ix + gridX1 * ( iy + 1 );
  17760. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  17761. var d = ( ix + 1 ) + gridX1 * iy;
  17762. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  17763. face.normal.copy( normal );
  17764. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  17765. face.materialIndex = materialIndex;
  17766. scope.faces.push( face );
  17767. scope.faceVertexUvs[ 0 ].push( [
  17768. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  17769. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  17770. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  17771. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  17772. ] );
  17773. }
  17774. }
  17775. }
  17776. this.computeCentroids();
  17777. this.mergeVertices();
  17778. };
  17779. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17780. /**
  17781. * @author mrdoob / http://mrdoob.com/
  17782. */
  17783. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  17784. THREE.Geometry.call( this );
  17785. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  17786. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  17787. height = height !== undefined ? height : 100;
  17788. var heightHalf = height / 2;
  17789. var segmentsX = radiusSegments || 8;
  17790. var segmentsY = heightSegments || 1;
  17791. var x, y, vertices = [], uvs = [];
  17792. for ( y = 0; y <= segmentsY; y ++ ) {
  17793. var verticesRow = [];
  17794. var uvsRow = [];
  17795. var v = y / segmentsY;
  17796. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17797. for ( x = 0; x <= segmentsX; x ++ ) {
  17798. var u = x / segmentsX;
  17799. var vertex = new THREE.Vector3();
  17800. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  17801. vertex.y = - v * height + heightHalf;
  17802. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  17803. this.vertices.push( vertex );
  17804. verticesRow.push( this.vertices.length - 1 );
  17805. uvsRow.push( new THREE.UV( u, 1 - v ) );
  17806. }
  17807. vertices.push( verticesRow );
  17808. uvs.push( uvsRow );
  17809. }
  17810. var tanTheta = ( radiusBottom - radiusTop ) / height;
  17811. var na, nb;
  17812. for ( x = 0; x < segmentsX; x ++ ) {
  17813. if ( radiusTop !== 0 ) {
  17814. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  17815. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  17816. } else {
  17817. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  17818. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  17819. }
  17820. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  17821. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  17822. for ( y = 0; y < segmentsY; y ++ ) {
  17823. var v1 = vertices[ y ][ x ];
  17824. var v2 = vertices[ y + 1 ][ x ];
  17825. var v3 = vertices[ y + 1 ][ x + 1 ];
  17826. var v4 = vertices[ y ][ x + 1 ];
  17827. var n1 = na.clone();
  17828. var n2 = na.clone();
  17829. var n3 = nb.clone();
  17830. var n4 = nb.clone();
  17831. var uv1 = uvs[ y ][ x ].clone();
  17832. var uv2 = uvs[ y + 1 ][ x ].clone();
  17833. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  17834. var uv4 = uvs[ y ][ x + 1 ].clone();
  17835. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  17836. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  17837. }
  17838. }
  17839. // top cap
  17840. if ( !openEnded && radiusTop > 0 ) {
  17841. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  17842. for ( x = 0; x < segmentsX; x ++ ) {
  17843. var v1 = vertices[ 0 ][ x ];
  17844. var v2 = vertices[ 0 ][ x + 1 ];
  17845. var v3 = this.vertices.length - 1;
  17846. var n1 = new THREE.Vector3( 0, 1, 0 );
  17847. var n2 = new THREE.Vector3( 0, 1, 0 );
  17848. var n3 = new THREE.Vector3( 0, 1, 0 );
  17849. var uv1 = uvs[ 0 ][ x ].clone();
  17850. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  17851. var uv3 = new THREE.UV( uv2.u, 0 );
  17852. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  17853. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  17854. }
  17855. }
  17856. // bottom cap
  17857. if ( !openEnded && radiusBottom > 0 ) {
  17858. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  17859. for ( x = 0; x < segmentsX; x ++ ) {
  17860. var v1 = vertices[ y ][ x + 1 ];
  17861. var v2 = vertices[ y ][ x ];
  17862. var v3 = this.vertices.length - 1;
  17863. var n1 = new THREE.Vector3( 0, - 1, 0 );
  17864. var n2 = new THREE.Vector3( 0, - 1, 0 );
  17865. var n3 = new THREE.Vector3( 0, - 1, 0 );
  17866. var uv1 = uvs[ y ][ x + 1 ].clone();
  17867. var uv2 = uvs[ y ][ x ].clone();
  17868. var uv3 = new THREE.UV( uv2.u, 1 );
  17869. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  17870. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  17871. }
  17872. }
  17873. this.computeCentroids();
  17874. this.computeFaceNormals();
  17875. }
  17876. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17877. /**
  17878. * @author zz85 / http://www.lab4games.net/zz85/blog
  17879. *
  17880. * Creates extruded geometry from a path shape.
  17881. *
  17882. * parameters = {
  17883. *
  17884. * size: <float>, // size of the text
  17885. * height: <float>, // thickness to extrude text
  17886. * curveSegments: <int>, // number of points on the curves
  17887. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  17888. * amount: <int>, // Amount
  17889. *
  17890. * bevelEnabled: <bool>, // turn on bevel
  17891. * bevelThickness: <float>, // how deep into text bevel goes
  17892. * bevelSize: <float>, // how far from text outline is bevel
  17893. * bevelSegments: <int>, // number of bevel layers
  17894. *
  17895. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  17896. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  17897. *
  17898. * material: <int> // material index for front and back faces
  17899. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  17900. * uvGenerator: <Object> // object that provides UV generator functions
  17901. *
  17902. * }
  17903. **/
  17904. THREE.ExtrudeGeometry = function ( shapes, options ) {
  17905. if ( typeof( shapes ) === "undefined" ) {
  17906. shapes = [];
  17907. return;
  17908. }
  17909. THREE.Geometry.call( this );
  17910. shapes = shapes instanceof Array ? shapes : [ shapes ];
  17911. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  17912. this.addShapeList( shapes, options );
  17913. this.computeCentroids();
  17914. this.computeFaceNormals();
  17915. // can't really use automatic vertex normals
  17916. // as then front and back sides get smoothed too
  17917. // should do separate smoothing just for sides
  17918. //this.computeVertexNormals();
  17919. //console.log( "took", ( Date.now() - startTime ) );
  17920. };
  17921. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17922. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  17923. var sl = shapes.length;
  17924. for ( var s = 0; s < sl; s ++ ) {
  17925. var shape = shapes[ s ];
  17926. this.addShape( shape, options );
  17927. }
  17928. };
  17929. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  17930. var amount = options.amount !== undefined ? options.amount : 100;
  17931. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  17932. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  17933. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  17934. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  17935. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  17936. var steps = options.steps !== undefined ? options.steps : 1;
  17937. var extrudePath = options.extrudePath;
  17938. var extrudePts, extrudeByPath = false;
  17939. var material = options.material;
  17940. var extrudeMaterial = options.extrudeMaterial;
  17941. // Use default WorldUVGenerator if no UV generators are specified.
  17942. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  17943. var shapebb = this.shapebb;
  17944. //shapebb = shape.getBoundingBox();
  17945. var splineTube, binormal, normal, position2;
  17946. if ( extrudePath ) {
  17947. extrudePts = extrudePath.getSpacedPoints( steps );
  17948. extrudeByPath = true;
  17949. bevelEnabled = false; // bevels not supported for path extrusion
  17950. // SETUP TNB variables
  17951. // Reuse TNB from TubeGeomtry for now.
  17952. // TODO1 - have a .isClosed in spline?
  17953. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  17954. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  17955. binormal = new THREE.Vector3();
  17956. normal = new THREE.Vector3();
  17957. position2 = new THREE.Vector3();
  17958. }
  17959. // Safeguards if bevels are not enabled
  17960. if ( ! bevelEnabled ) {
  17961. bevelSegments = 0;
  17962. bevelThickness = 0;
  17963. bevelSize = 0;
  17964. }
  17965. // Variables initalization
  17966. var ahole, h, hl; // looping of holes
  17967. var scope = this;
  17968. var bevelPoints = [];
  17969. var shapesOffset = this.vertices.length;
  17970. var shapePoints = shape.extractPoints();
  17971. var vertices = shapePoints.shape;
  17972. var holes = shapePoints.holes;
  17973. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  17974. if ( reverse ) {
  17975. vertices = vertices.reverse();
  17976. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  17977. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  17978. ahole = holes[ h ];
  17979. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  17980. holes[ h ] = ahole.reverse();
  17981. }
  17982. }
  17983. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  17984. }
  17985. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  17986. /* Vertices */
  17987. var contour = vertices; // vertices has all points but contour has only points of circumference
  17988. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  17989. ahole = holes[ h ];
  17990. vertices = vertices.concat( ahole );
  17991. }
  17992. function scalePt2 ( pt, vec, size ) {
  17993. if ( !vec ) console.log( "die" );
  17994. return vec.clone().multiplyScalar( size ).addSelf( pt );
  17995. }
  17996. var b, bs, t, z,
  17997. vert, vlen = vertices.length,
  17998. face, flen = faces.length,
  17999. cont, clen = contour.length;
  18000. // Find directions for point movement
  18001. var RAD_TO_DEGREES = 180 / Math.PI;
  18002. function getBevelVec( pt_i, pt_j, pt_k ) {
  18003. // Algorithm 2
  18004. return getBevelVec2( pt_i, pt_j, pt_k );
  18005. }
  18006. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18007. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18008. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18009. if ( anglea > angleb ) {
  18010. angleb += Math.PI * 2;
  18011. }
  18012. var anglec = ( anglea + angleb ) / 2;
  18013. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18014. var x = - Math.cos( anglec );
  18015. var y = - Math.sin( anglec );
  18016. var vec = new THREE.Vector2( x, y ); //.normalize();
  18017. return vec;
  18018. }
  18019. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18020. var a = THREE.ExtrudeGeometry.__v1,
  18021. b = THREE.ExtrudeGeometry.__v2,
  18022. v_hat = THREE.ExtrudeGeometry.__v3,
  18023. w_hat = THREE.ExtrudeGeometry.__v4,
  18024. p = THREE.ExtrudeGeometry.__v5,
  18025. q = THREE.ExtrudeGeometry.__v6,
  18026. v, w,
  18027. v_dot_w_hat, q_sub_p_dot_w_hat,
  18028. s, intersection;
  18029. // good reading for line-line intersection
  18030. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18031. // define a as vector j->i
  18032. // define b as vectot k->i
  18033. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18034. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18035. // get unit vectors
  18036. v = a.normalize();
  18037. w = b.normalize();
  18038. // normals from pt i
  18039. v_hat.set( -v.y, v.x );
  18040. w_hat.set( w.y, -w.x );
  18041. // pts from i
  18042. p.copy( pt_i ).addSelf( v_hat );
  18043. q.copy( pt_i ).addSelf( w_hat );
  18044. if ( p.equals( q ) ) {
  18045. //console.log("Warning: lines are straight");
  18046. return w_hat.clone();
  18047. }
  18048. // Points from j, k. helps prevents points cross overover most of the time
  18049. p.copy( pt_j ).addSelf( v_hat );
  18050. q.copy( pt_k ).addSelf( w_hat );
  18051. v_dot_w_hat = v.dot( w_hat );
  18052. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18053. // We should not reach these conditions
  18054. if ( v_dot_w_hat === 0 ) {
  18055. console.log( "Either infinite or no solutions!" );
  18056. if ( q_sub_p_dot_w_hat === 0 ) {
  18057. console.log( "Its finite solutions." );
  18058. } else {
  18059. console.log( "Too bad, no solutions." );
  18060. }
  18061. }
  18062. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18063. if ( s < 0 ) {
  18064. // in case of emergecy, revert to algorithm 1.
  18065. return getBevelVec1( pt_i, pt_j, pt_k );
  18066. }
  18067. intersection = v.multiplyScalar( s ).addSelf( p );
  18068. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18069. }
  18070. var contourMovements = [];
  18071. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18072. if ( j === il ) j = 0;
  18073. if ( k === il ) k = 0;
  18074. // (j)---(i)---(k)
  18075. // console.log('i,j,k', i, j , k)
  18076. var pt_i = contour[ i ];
  18077. var pt_j = contour[ j ];
  18078. var pt_k = contour[ k ];
  18079. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18080. }
  18081. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18082. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18083. ahole = holes[ h ];
  18084. oneHoleMovements = [];
  18085. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18086. if ( j === il ) j = 0;
  18087. if ( k === il ) k = 0;
  18088. // (j)---(i)---(k)
  18089. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18090. }
  18091. holesMovements.push( oneHoleMovements );
  18092. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18093. }
  18094. // Loop bevelSegments, 1 for the front, 1 for the back
  18095. for ( b = 0; b < bevelSegments; b ++ ) {
  18096. //for ( b = bevelSegments; b > 0; b -- ) {
  18097. t = b / bevelSegments;
  18098. z = bevelThickness * ( 1 - t );
  18099. //z = bevelThickness * t;
  18100. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18101. //bs = bevelSize * t ; // linear
  18102. // contract shape
  18103. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18104. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18105. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18106. v( vert.x, vert.y, - z );
  18107. }
  18108. // expand holes
  18109. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18110. ahole = holes[ h ];
  18111. oneHoleMovements = holesMovements[ h ];
  18112. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18113. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18114. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18115. v( vert.x, vert.y, -z );
  18116. }
  18117. }
  18118. }
  18119. bs = bevelSize;
  18120. // Back facing vertices
  18121. for ( i = 0; i < vlen; i ++ ) {
  18122. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18123. if ( !extrudeByPath ) {
  18124. v( vert.x, vert.y, 0 );
  18125. } else {
  18126. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18127. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18128. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18129. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  18130. v( position2.x, position2.y, position2.z );
  18131. }
  18132. }
  18133. // Add stepped vertices...
  18134. // Including front facing vertices
  18135. var s;
  18136. for ( s = 1; s <= steps; s ++ ) {
  18137. for ( i = 0; i < vlen; i ++ ) {
  18138. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18139. if ( !extrudeByPath ) {
  18140. v( vert.x, vert.y, amount / steps * s );
  18141. } else {
  18142. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18143. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18144. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18145. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  18146. v( position2.x, position2.y, position2.z );
  18147. }
  18148. }
  18149. }
  18150. // Add bevel segments planes
  18151. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18152. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18153. t = b / bevelSegments;
  18154. z = bevelThickness * ( 1 - t );
  18155. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18156. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18157. // contract shape
  18158. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18159. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18160. v( vert.x, vert.y, amount + z );
  18161. }
  18162. // expand holes
  18163. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18164. ahole = holes[ h ];
  18165. oneHoleMovements = holesMovements[ h ];
  18166. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18167. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18168. if ( !extrudeByPath ) {
  18169. v( vert.x, vert.y, amount + z );
  18170. } else {
  18171. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18172. }
  18173. }
  18174. }
  18175. }
  18176. /* Faces */
  18177. // Top and bottom faces
  18178. buildLidFaces();
  18179. // Sides faces
  18180. buildSideFaces();
  18181. ///// Internal functions
  18182. function buildLidFaces() {
  18183. if ( bevelEnabled ) {
  18184. var layer = 0 ; // steps + 1
  18185. var offset = vlen * layer;
  18186. // Bottom faces
  18187. for ( i = 0; i < flen; i ++ ) {
  18188. face = faces[ i ];
  18189. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18190. }
  18191. layer = steps + bevelSegments * 2;
  18192. offset = vlen * layer;
  18193. // Top faces
  18194. for ( i = 0; i < flen; i ++ ) {
  18195. face = faces[ i ];
  18196. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18197. }
  18198. } else {
  18199. // Bottom faces
  18200. for ( i = 0; i < flen; i++ ) {
  18201. face = faces[ i ];
  18202. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18203. }
  18204. // Top faces
  18205. for ( i = 0; i < flen; i ++ ) {
  18206. face = faces[ i ];
  18207. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18208. }
  18209. }
  18210. }
  18211. // Create faces for the z-sides of the shape
  18212. function buildSideFaces() {
  18213. var layeroffset = 0;
  18214. sidewalls( contour, layeroffset );
  18215. layeroffset += contour.length;
  18216. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18217. ahole = holes[ h ];
  18218. sidewalls( ahole, layeroffset );
  18219. //, true
  18220. layeroffset += ahole.length;
  18221. }
  18222. }
  18223. function sidewalls( contour, layeroffset ) {
  18224. var j, k;
  18225. i = contour.length;
  18226. while ( --i >= 0 ) {
  18227. j = i;
  18228. k = i - 1;
  18229. if ( k < 0 ) k = contour.length - 1;
  18230. //console.log('b', i,j, i-1, k,vertices.length);
  18231. var s = 0, sl = steps + bevelSegments * 2;
  18232. for ( s = 0; s < sl; s ++ ) {
  18233. var slen1 = vlen * s;
  18234. var slen2 = vlen * ( s + 1 );
  18235. var a = layeroffset + j + slen1,
  18236. b = layeroffset + k + slen1,
  18237. c = layeroffset + k + slen2,
  18238. d = layeroffset + j + slen2;
  18239. f4( a, b, c, d, contour, s, sl, j, k );
  18240. }
  18241. }
  18242. }
  18243. function v( x, y, z ) {
  18244. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18245. }
  18246. function f3( a, b, c, isBottom ) {
  18247. a += shapesOffset;
  18248. b += shapesOffset;
  18249. c += shapesOffset;
  18250. // normal, color, material
  18251. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18252. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18253. scope.faceVertexUvs[ 0 ].push( uvs );
  18254. }
  18255. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18256. a += shapesOffset;
  18257. b += shapesOffset;
  18258. c += shapesOffset;
  18259. d += shapesOffset;
  18260. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18261. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18262. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18263. scope.faceVertexUvs[ 0 ].push( uvs );
  18264. }
  18265. };
  18266. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18267. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18268. var ax = geometry.vertices[ indexA ].x,
  18269. ay = geometry.vertices[ indexA ].y,
  18270. bx = geometry.vertices[ indexB ].x,
  18271. by = geometry.vertices[ indexB ].y,
  18272. cx = geometry.vertices[ indexC ].x,
  18273. cy = geometry.vertices[ indexC ].y;
  18274. return [
  18275. new THREE.UV( ax, ay ),
  18276. new THREE.UV( bx, by ),
  18277. new THREE.UV( cx, cy )
  18278. ];
  18279. },
  18280. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18281. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18282. },
  18283. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18284. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18285. contourIndex1, contourIndex2 ) {
  18286. var ax = geometry.vertices[ indexA ].x,
  18287. ay = geometry.vertices[ indexA ].y,
  18288. az = geometry.vertices[ indexA ].z,
  18289. bx = geometry.vertices[ indexB ].x,
  18290. by = geometry.vertices[ indexB ].y,
  18291. bz = geometry.vertices[ indexB ].z,
  18292. cx = geometry.vertices[ indexC ].x,
  18293. cy = geometry.vertices[ indexC ].y,
  18294. cz = geometry.vertices[ indexC ].z,
  18295. dx = geometry.vertices[ indexD ].x,
  18296. dy = geometry.vertices[ indexD ].y,
  18297. dz = geometry.vertices[ indexD ].z;
  18298. if ( Math.abs( ay - by ) < 0.01 ) {
  18299. return [
  18300. new THREE.UV( ax, 1 - az ),
  18301. new THREE.UV( bx, 1 - bz ),
  18302. new THREE.UV( cx, 1 - cz ),
  18303. new THREE.UV( dx, 1 - dz )
  18304. ];
  18305. } else {
  18306. return [
  18307. new THREE.UV( ay, 1 - az ),
  18308. new THREE.UV( by, 1 - bz ),
  18309. new THREE.UV( cy, 1 - cz ),
  18310. new THREE.UV( dy, 1 - dz )
  18311. ];
  18312. }
  18313. }
  18314. };
  18315. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18316. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18317. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18318. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18319. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18320. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18321. /**
  18322. * @author jonobr1 / http://jonobr1.com
  18323. *
  18324. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18325. * ExtrudeGeometry.
  18326. *
  18327. * parameters = {
  18328. *
  18329. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18330. *
  18331. * material: <int> // material index for front and back faces
  18332. * uvGenerator: <Object> // object that provides UV generator functions
  18333. *
  18334. * }
  18335. **/
  18336. THREE.ShapeGeometry = function ( shapes, options ) {
  18337. THREE.Geometry.call( this );
  18338. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18339. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18340. this.addShapeList( shapes, options );
  18341. this.computeCentroids();
  18342. this.computeFaceNormals();
  18343. };
  18344. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18345. /**
  18346. * Add an array of shapes to THREE.ShapeGeometry.
  18347. */
  18348. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18349. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  18350. this.addShape( shapes[ i ], options );
  18351. }
  18352. return this;
  18353. };
  18354. /**
  18355. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18356. */
  18357. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18358. if ( options === undefined ) options = {};
  18359. var material = options.material;
  18360. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18361. var shapebb = this.shapebb;
  18362. //
  18363. var i, l, hole, s;
  18364. var shapesOffset = this.vertices.length;
  18365. var shapePoints = shape.extractPoints();
  18366. var vertices = shapePoints.shape;
  18367. var holes = shapePoints.holes;
  18368. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  18369. if ( reverse ) {
  18370. vertices = vertices.reverse();
  18371. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18372. for ( i = 0, l = holes.length; i < l; i++ ) {
  18373. hole = holes[ i ];
  18374. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18375. holes[ i ] = hole.reverse();
  18376. }
  18377. }
  18378. reverse = false;
  18379. }
  18380. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18381. // Vertices
  18382. var contour = vertices;
  18383. for ( i = 0, l = holes.length; i < l; i++ ) {
  18384. hole = holes[ i ];
  18385. vertices = vertices.concat( hole );
  18386. }
  18387. //
  18388. var vert, vlen = vertices.length;
  18389. var face, flen = faces.length;
  18390. var cont, clen = contour.length;
  18391. for ( i = 0; i < vlen; i++ ) {
  18392. vert = vertices[ i ];
  18393. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18394. }
  18395. for ( i = 0; i < flen; i++ ) {
  18396. face = faces[ i ];
  18397. var a = face[ 0 ] + shapesOffset;
  18398. var b = face[ 1 ] + shapesOffset;
  18399. var c = face[ 2 ] + shapesOffset;
  18400. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18401. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  18402. }
  18403. };
  18404. /**
  18405. * @author astrodud / http://astrodud.isgreat.org/
  18406. * @author zz85 / https://github.com/zz85
  18407. */
  18408. THREE.LatheGeometry = function ( points, steps, angle ) {
  18409. THREE.Geometry.call( this );
  18410. var _steps = steps || 12;
  18411. var _angle = angle || 2 * Math.PI;
  18412. var _newV = [];
  18413. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  18414. for ( var j = 0; j < points.length; j ++ ) {
  18415. _newV[ j ] = points[ j ].clone();
  18416. this.vertices.push( _newV[ j ] );
  18417. }
  18418. var i, il = _steps + 1;
  18419. for ( i = 0; i < il; i ++ ) {
  18420. for ( var j = 0; j < _newV.length; j ++ ) {
  18421. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  18422. this.vertices.push( _newV[ j ] );
  18423. }
  18424. }
  18425. for ( i = 0; i < _steps; i ++ ) {
  18426. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  18427. var a = i * kl + k;
  18428. var b = ( ( i + 1 ) % il ) * kl + k;
  18429. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  18430. var d = i * kl + ( k + 1 ) % kl;
  18431. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18432. this.faceVertexUvs[ 0 ].push( [
  18433. new THREE.UV( 1 - i / _steps, k / kl ),
  18434. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  18435. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  18436. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  18437. ] );
  18438. }
  18439. }
  18440. this.computeCentroids();
  18441. this.computeFaceNormals();
  18442. this.computeVertexNormals();
  18443. };
  18444. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18445. /**
  18446. * @author mrdoob / http://mrdoob.com/
  18447. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18448. */
  18449. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  18450. THREE.Geometry.call( this );
  18451. this.width = width;
  18452. this.height = height;
  18453. this.widthSegments = widthSegments || 1;
  18454. this.heightSegments = heightSegments || 1;
  18455. var ix, iz;
  18456. var width_half = width / 2;
  18457. var height_half = height / 2;
  18458. var gridX = this.widthSegments;
  18459. var gridZ = this.heightSegments;
  18460. var gridX1 = gridX + 1;
  18461. var gridZ1 = gridZ + 1;
  18462. var segment_width = this.width / gridX;
  18463. var segment_height = this.height / gridZ;
  18464. var normal = new THREE.Vector3( 0, 0, 1 );
  18465. for ( iz = 0; iz < gridZ1; iz ++ ) {
  18466. for ( ix = 0; ix < gridX1; ix ++ ) {
  18467. var x = ix * segment_width - width_half;
  18468. var y = iz * segment_height - height_half;
  18469. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  18470. }
  18471. }
  18472. for ( iz = 0; iz < gridZ; iz ++ ) {
  18473. for ( ix = 0; ix < gridX; ix ++ ) {
  18474. var a = ix + gridX1 * iz;
  18475. var b = ix + gridX1 * ( iz + 1 );
  18476. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  18477. var d = ( ix + 1 ) + gridX1 * iz;
  18478. var face = new THREE.Face4( a, b, c, d );
  18479. face.normal.copy( normal );
  18480. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18481. this.faces.push( face );
  18482. this.faceVertexUvs[ 0 ].push( [
  18483. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  18484. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  18485. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  18486. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  18487. ] );
  18488. }
  18489. }
  18490. this.computeCentroids();
  18491. };
  18492. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18493. /**
  18494. * @author mrdoob / http://mrdoob.com/
  18495. */
  18496. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  18497. THREE.Geometry.call( this );
  18498. this.radius = radius || 50;
  18499. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  18500. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  18501. phiStart = phiStart !== undefined ? phiStart : 0;
  18502. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18503. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18504. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18505. var x, y, vertices = [], uvs = [];
  18506. for ( y = 0; y <= this.heightSegments; y ++ ) {
  18507. var verticesRow = [];
  18508. var uvsRow = [];
  18509. for ( x = 0; x <= this.widthSegments; x ++ ) {
  18510. var u = x / this.widthSegments;
  18511. var v = y / this.heightSegments;
  18512. var vertex = new THREE.Vector3();
  18513. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18514. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  18515. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18516. this.vertices.push( vertex );
  18517. verticesRow.push( this.vertices.length - 1 );
  18518. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18519. }
  18520. vertices.push( verticesRow );
  18521. uvs.push( uvsRow );
  18522. }
  18523. for ( y = 0; y < this.heightSegments; y ++ ) {
  18524. for ( x = 0; x < this.widthSegments; x ++ ) {
  18525. var v1 = vertices[ y ][ x + 1 ];
  18526. var v2 = vertices[ y ][ x ];
  18527. var v3 = vertices[ y + 1 ][ x ];
  18528. var v4 = vertices[ y + 1 ][ x + 1 ];
  18529. var n1 = this.vertices[ v1 ].clone().normalize();
  18530. var n2 = this.vertices[ v2 ].clone().normalize();
  18531. var n3 = this.vertices[ v3 ].clone().normalize();
  18532. var n4 = this.vertices[ v4 ].clone().normalize();
  18533. var uv1 = uvs[ y ][ x + 1 ].clone();
  18534. var uv2 = uvs[ y ][ x ].clone();
  18535. var uv3 = uvs[ y + 1 ][ x ].clone();
  18536. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  18537. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  18538. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  18539. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  18540. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  18541. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18542. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18543. } else {
  18544. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18545. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18546. }
  18547. }
  18548. }
  18549. this.computeCentroids();
  18550. this.computeFaceNormals();
  18551. this.boundingSphere = { radius: this.radius };
  18552. };
  18553. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18554. /**
  18555. * @author zz85 / http://www.lab4games.net/zz85/blog
  18556. * @author alteredq / http://alteredqualia.com/
  18557. *
  18558. * For creating 3D text geometry in three.js
  18559. *
  18560. * Text = 3D Text
  18561. *
  18562. * parameters = {
  18563. * size: <float>, // size of the text
  18564. * height: <float>, // thickness to extrude text
  18565. * curveSegments: <int>, // number of points on the curves
  18566. *
  18567. * font: <string>, // font name
  18568. * weight: <string>, // font weight (normal, bold)
  18569. * style: <string>, // font style (normal, italics)
  18570. *
  18571. * bevelEnabled: <bool>, // turn on bevel
  18572. * bevelThickness: <float>, // how deep into text bevel goes
  18573. * bevelSize: <float>, // how far from text outline is bevel
  18574. * }
  18575. *
  18576. */
  18577. /* Usage Examples
  18578. // TextGeometry wrapper
  18579. var text3d = new TextGeometry( text, options );
  18580. // Complete manner
  18581. var textShapes = THREE.FontUtils.generateShapes( text, options );
  18582. var text3d = new ExtrudeGeometry( textShapes, options );
  18583. */
  18584. THREE.TextGeometry = function ( text, parameters ) {
  18585. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  18586. // translate parameters to ExtrudeGeometry API
  18587. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  18588. // defaults
  18589. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18590. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18591. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18592. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  18593. };
  18594. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  18595. /**
  18596. * @author oosmoxiecode
  18597. * @author mrdoob / http://mrdoob.com/
  18598. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  18599. */
  18600. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  18601. THREE.Geometry.call( this );
  18602. var scope = this;
  18603. this.radius = radius || 100;
  18604. this.tube = tube || 40;
  18605. this.radialSegments = radialSegments || 8;
  18606. this.tubularSegments = tubularSegments || 6;
  18607. this.arc = arc || Math.PI * 2;
  18608. var center = new THREE.Vector3(), uvs = [], normals = [];
  18609. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  18610. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  18611. var u = i / this.tubularSegments * this.arc;
  18612. var v = j / this.radialSegments * Math.PI * 2;
  18613. center.x = this.radius * Math.cos( u );
  18614. center.y = this.radius * Math.sin( u );
  18615. var vertex = new THREE.Vector3();
  18616. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  18617. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  18618. vertex.z = this.tube * Math.sin( v );
  18619. this.vertices.push( vertex );
  18620. uvs.push( new THREE.UV( i / this.tubularSegments, j / this.radialSegments ) );
  18621. normals.push( vertex.clone().subSelf( center ).normalize() );
  18622. }
  18623. }
  18624. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  18625. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  18626. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  18627. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  18628. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  18629. var d = ( this.tubularSegments + 1 ) * j + i;
  18630. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  18631. face.normal.addSelf( normals[ a ] );
  18632. face.normal.addSelf( normals[ b ] );
  18633. face.normal.addSelf( normals[ c ] );
  18634. face.normal.addSelf( normals[ d ] );
  18635. face.normal.normalize();
  18636. this.faces.push( face );
  18637. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  18638. }
  18639. }
  18640. this.computeCentroids();
  18641. };
  18642. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18643. /**
  18644. * @author oosmoxiecode
  18645. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  18646. */
  18647. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  18648. THREE.Geometry.call( this );
  18649. var scope = this;
  18650. this.radius = radius || 200;
  18651. this.tube = tube || 40;
  18652. this.radialSegments = radialSegments || 64;
  18653. this.tubularSegments = tubularSegments || 8;
  18654. this.p = p || 2;
  18655. this.q = q || 3;
  18656. this.heightScale = heightScale || 1;
  18657. this.grid = new Array(this.radialSegments);
  18658. var tang = new THREE.Vector3();
  18659. var n = new THREE.Vector3();
  18660. var bitan = new THREE.Vector3();
  18661. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18662. this.grid[ i ] = new Array( this.tubularSegments );
  18663. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18664. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  18665. var v = j / this.tubularSegments * 2 * Math.PI;
  18666. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  18667. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  18668. var cx, cy;
  18669. tang.sub( p2, p1 );
  18670. n.add( p2, p1 );
  18671. bitan.cross( tang, n );
  18672. n.cross( bitan, tang );
  18673. bitan.normalize();
  18674. n.normalize();
  18675. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18676. cy = this.tube * Math.sin( v );
  18677. p1.x += cx * n.x + cy * bitan.x;
  18678. p1.y += cx * n.y + cy * bitan.y;
  18679. p1.z += cx * n.z + cy * bitan.z;
  18680. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  18681. }
  18682. }
  18683. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18684. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18685. var ip = ( i + 1 ) % this.radialSegments;
  18686. var jp = ( j + 1 ) % this.tubularSegments;
  18687. var a = this.grid[ i ][ j ];
  18688. var b = this.grid[ ip ][ j ];
  18689. var c = this.grid[ ip ][ jp ];
  18690. var d = this.grid[ i ][ jp ];
  18691. var uva = new THREE.UV( i / this.radialSegments, j / this.tubularSegments );
  18692. var uvb = new THREE.UV( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  18693. var uvc = new THREE.UV( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18694. var uvd = new THREE.UV( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18695. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18696. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  18697. }
  18698. }
  18699. this.computeCentroids();
  18700. this.computeFaceNormals();
  18701. this.computeVertexNormals();
  18702. function vert( x, y, z ) {
  18703. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18704. }
  18705. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  18706. var cu = Math.cos( u );
  18707. var cv = Math.cos( v );
  18708. var su = Math.sin( u );
  18709. var quOverP = in_q / in_p * u;
  18710. var cs = Math.cos( quOverP );
  18711. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  18712. var ty = radius * ( 2 + cs ) * su * 0.5;
  18713. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  18714. return new THREE.Vector3( tx, ty, tz );
  18715. }
  18716. };
  18717. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18718. /**
  18719. * @author WestLangley / https://github.com/WestLangley
  18720. * @author zz85 / https://github.com/zz85
  18721. * @author miningold / https://github.com/miningold
  18722. *
  18723. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18724. *
  18725. * Creates a tube which extrudes along a 3d spline
  18726. *
  18727. * Uses parallel transport frames as described in
  18728. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18729. */
  18730. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  18731. THREE.Geometry.call( this );
  18732. this.path = path;
  18733. this.segments = segments || 64;
  18734. this.radius = radius || 1;
  18735. this.radiusSegments = radiusSegments || 8;
  18736. this.closed = closed || false;
  18737. if ( debug ) this.debug = new THREE.Object3D();
  18738. this.grid = [];
  18739. var scope = this,
  18740. tangent,
  18741. normal,
  18742. binormal,
  18743. numpoints = this.segments + 1,
  18744. x, y, z,
  18745. tx, ty, tz,
  18746. u, v,
  18747. cx, cy,
  18748. pos, pos2 = new THREE.Vector3(),
  18749. i, j,
  18750. ip, jp,
  18751. a, b, c, d,
  18752. uva, uvb, uvc, uvd;
  18753. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  18754. tangents = frames.tangents,
  18755. normals = frames.normals,
  18756. binormals = frames.binormals;
  18757. // proxy internals
  18758. this.tangents = tangents;
  18759. this.normals = normals;
  18760. this.binormals = binormals;
  18761. function vert( x, y, z ) {
  18762. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18763. }
  18764. // consruct the grid
  18765. for ( i = 0; i < numpoints; i++ ) {
  18766. this.grid[ i ] = [];
  18767. u = i / ( numpoints - 1 );
  18768. pos = path.getPointAt( u );
  18769. tangent = tangents[ i ];
  18770. normal = normals[ i ];
  18771. binormal = binormals[ i ];
  18772. if ( this.debug ) {
  18773. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  18774. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  18775. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  18776. }
  18777. for ( j = 0; j < this.radiusSegments; j++ ) {
  18778. v = j / this.radiusSegments * 2 * Math.PI;
  18779. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18780. cy = this.radius * Math.sin( v );
  18781. pos2.copy( pos );
  18782. pos2.x += cx * normal.x + cy * binormal.x;
  18783. pos2.y += cx * normal.y + cy * binormal.y;
  18784. pos2.z += cx * normal.z + cy * binormal.z;
  18785. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18786. }
  18787. }
  18788. // construct the mesh
  18789. for ( i = 0; i < this.segments; i++ ) {
  18790. for ( j = 0; j < this.radiusSegments; j++ ) {
  18791. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  18792. jp = (j + 1) % this.radiusSegments;
  18793. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18794. b = this.grid[ ip ][ j ];
  18795. c = this.grid[ ip ][ jp ];
  18796. d = this.grid[ i ][ jp ];
  18797. uva = new THREE.UV( i / this.segments, j / this.radiusSegments );
  18798. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.radiusSegments );
  18799. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  18800. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.radiusSegments );
  18801. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18802. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  18803. }
  18804. }
  18805. this.computeCentroids();
  18806. this.computeFaceNormals();
  18807. this.computeVertexNormals();
  18808. };
  18809. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18810. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  18811. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  18812. var
  18813. tangent = new THREE.Vector3(),
  18814. normal = new THREE.Vector3(),
  18815. binormal = new THREE.Vector3(),
  18816. tangents = [],
  18817. normals = [],
  18818. binormals = [],
  18819. vec = new THREE.Vector3(),
  18820. mat = new THREE.Matrix4(),
  18821. numpoints = segments + 1,
  18822. theta,
  18823. epsilon = 0.0001,
  18824. smallest,
  18825. tx, ty, tz,
  18826. i, u, v;
  18827. // expose internals
  18828. this.tangents = tangents;
  18829. this.normals = normals;
  18830. this.binormals = binormals;
  18831. // compute the tangent vectors for each segment on the path
  18832. for ( i = 0; i < numpoints; i++ ) {
  18833. u = i / ( numpoints - 1 );
  18834. tangents[ i ] = path.getTangentAt( u );
  18835. tangents[ i ].normalize();
  18836. }
  18837. initialNormal3();
  18838. function initialNormal1(lastBinormal) {
  18839. // fixed start binormal. Has dangers of 0 vectors
  18840. normals[ 0 ] = new THREE.Vector3();
  18841. binormals[ 0 ] = new THREE.Vector3();
  18842. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  18843. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  18844. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18845. }
  18846. function initialNormal2() {
  18847. // This uses the Frenet-Serret formula for deriving binormal
  18848. var t2 = path.getTangentAt( epsilon );
  18849. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  18850. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  18851. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  18852. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18853. }
  18854. function initialNormal3() {
  18855. // select an initial normal vector perpenicular to the first tangent vector,
  18856. // and in the direction of the smallest tangent xyz component
  18857. normals[ 0 ] = new THREE.Vector3();
  18858. binormals[ 0 ] = new THREE.Vector3();
  18859. smallest = Number.MAX_VALUE;
  18860. tx = Math.abs( tangents[ 0 ].x );
  18861. ty = Math.abs( tangents[ 0 ].y );
  18862. tz = Math.abs( tangents[ 0 ].z );
  18863. if ( tx <= smallest ) {
  18864. smallest = tx;
  18865. normal.set( 1, 0, 0 );
  18866. }
  18867. if ( ty <= smallest ) {
  18868. smallest = ty;
  18869. normal.set( 0, 1, 0 );
  18870. }
  18871. if ( tz <= smallest ) {
  18872. normal.set( 0, 0, 1 );
  18873. }
  18874. vec.cross( tangents[ 0 ], normal ).normalize();
  18875. normals[ 0 ].cross( tangents[ 0 ], vec );
  18876. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  18877. }
  18878. // compute the slowly-varying normal and binormal vectors for each segment on the path
  18879. for ( i = 1; i < numpoints; i++ ) {
  18880. normals[ i ] = normals[ i-1 ].clone();
  18881. binormals[ i ] = binormals[ i-1 ].clone();
  18882. vec.cross( tangents[ i-1 ], tangents[ i ] );
  18883. if ( vec.length() > epsilon ) {
  18884. vec.normalize();
  18885. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  18886. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  18887. }
  18888. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  18889. }
  18890. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18891. if ( closed ) {
  18892. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  18893. theta /= ( numpoints - 1 );
  18894. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  18895. theta = -theta;
  18896. }
  18897. for ( i = 1; i < numpoints; i++ ) {
  18898. // twist a little...
  18899. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  18900. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  18901. }
  18902. }
  18903. };
  18904. /**
  18905. * @author clockworkgeek / https://github.com/clockworkgeek
  18906. * @author timothypratley / https://github.com/timothypratley
  18907. */
  18908. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  18909. THREE.Geometry.call( this );
  18910. radius = radius || 1;
  18911. detail = detail || 0;
  18912. var that = this;
  18913. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  18914. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  18915. }
  18916. var midpoints = [], p = this.vertices;
  18917. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  18918. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  18919. }
  18920. this.mergeVertices();
  18921. // Apply radius
  18922. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  18923. this.vertices[ i ].multiplyScalar( radius );
  18924. }
  18925. // Project vector onto sphere's surface
  18926. function prepare( vector ) {
  18927. var vertex = vector.normalize().clone();
  18928. vertex.index = that.vertices.push( vertex ) - 1;
  18929. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  18930. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  18931. var v = inclination( vector ) / Math.PI + 0.5;
  18932. vertex.uv = new THREE.UV( u, 1 - v );
  18933. return vertex;
  18934. }
  18935. // Approximate a curved face with recursively sub-divided triangles.
  18936. function make( v1, v2, v3, detail ) {
  18937. if ( detail < 1 ) {
  18938. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  18939. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  18940. face.normal = face.centroid.clone().normalize();
  18941. that.faces.push( face );
  18942. var azi = azimuth( face.centroid );
  18943. that.faceVertexUvs[ 0 ].push( [
  18944. correctUV( v1.uv, v1, azi ),
  18945. correctUV( v2.uv, v2, azi ),
  18946. correctUV( v3.uv, v3, azi )
  18947. ] );
  18948. } else {
  18949. detail -= 1;
  18950. // split triangle into 4 smaller triangles
  18951. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  18952. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  18953. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  18954. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  18955. }
  18956. }
  18957. function midpoint( v1, v2 ) {
  18958. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  18959. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  18960. var mid = midpoints[ v1.index ][ v2.index ];
  18961. if ( mid === undefined ) {
  18962. // generate mean point and project to surface with prepare()
  18963. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  18964. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  18965. );
  18966. }
  18967. return mid;
  18968. }
  18969. // Angle around the Y axis, counter-clockwise when looking from above.
  18970. function azimuth( vector ) {
  18971. return Math.atan2( vector.z, -vector.x );
  18972. }
  18973. // Angle above the XZ plane.
  18974. function inclination( vector ) {
  18975. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18976. }
  18977. // Texture fixing helper. Spheres have some odd behaviours.
  18978. function correctUV( uv, vector, azimuth ) {
  18979. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  18980. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  18981. return uv;
  18982. }
  18983. this.computeCentroids();
  18984. this.boundingSphere = { radius: radius };
  18985. };
  18986. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18987. /**
  18988. * @author timothypratley / https://github.com/timothypratley
  18989. */
  18990. THREE.IcosahedronGeometry = function ( radius, detail ) {
  18991. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18992. var vertices = [
  18993. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  18994. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  18995. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  18996. ];
  18997. var faces = [
  18998. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  18999. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19000. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19001. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19002. ];
  19003. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19004. };
  19005. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19006. /**
  19007. * @author timothypratley / https://github.com/timothypratley
  19008. */
  19009. THREE.OctahedronGeometry = function ( radius, detail ) {
  19010. var vertices = [
  19011. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19012. ];
  19013. var faces = [
  19014. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19015. ];
  19016. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19017. };
  19018. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19019. /**
  19020. * @author timothypratley / https://github.com/timothypratley
  19021. */
  19022. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19023. var vertices = [
  19024. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19025. ];
  19026. var faces = [
  19027. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19028. ];
  19029. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19030. };
  19031. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19032. /**
  19033. * @author zz85 / https://github.com/zz85
  19034. * Parametric Surfaces Geometry
  19035. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19036. *
  19037. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19038. *
  19039. */
  19040. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19041. THREE.Geometry.call( this );
  19042. var verts = this.vertices;
  19043. var faces = this.faces;
  19044. var uvs = this.faceVertexUvs[ 0 ];
  19045. useTris = (useTris === undefined) ? false : useTris;
  19046. var i, il, j, p;
  19047. var u, v;
  19048. var stackCount = stacks + 1;
  19049. var sliceCount = slices + 1;
  19050. for ( i = 0; i <= stacks; i ++ ) {
  19051. v = i / stacks;
  19052. for ( j = 0; j <= slices; j ++ ) {
  19053. u = j / slices;
  19054. p = func( u, v );
  19055. verts.push( p );
  19056. }
  19057. }
  19058. var a, b, c, d;
  19059. var uva, uvb, uvc, uvd;
  19060. for ( i = 0; i < stacks; i ++ ) {
  19061. for ( j = 0; j < slices; j ++ ) {
  19062. a = i * sliceCount + j;
  19063. b = i * sliceCount + j + 1;
  19064. c = (i + 1) * sliceCount + j;
  19065. d = (i + 1) * sliceCount + j + 1;
  19066. uva = new THREE.UV( j / slices, i / stacks );
  19067. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  19068. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  19069. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19070. if ( useTris ) {
  19071. faces.push( new THREE.Face3( a, b, c ) );
  19072. faces.push( new THREE.Face3( b, d, c ) );
  19073. uvs.push( [ uva, uvb, uvc ] );
  19074. uvs.push( [ uvb, uvd, uvc ] );
  19075. } else {
  19076. faces.push( new THREE.Face4( a, b, d, c ) );
  19077. uvs.push( [ uva, uvb, uvd, uvc ] );
  19078. }
  19079. }
  19080. }
  19081. // console.log(this);
  19082. // magic bullet
  19083. // var diff = this.mergeVertices();
  19084. // console.log('removed ', diff, ' vertices by merging');
  19085. this.computeCentroids();
  19086. this.computeFaceNormals();
  19087. this.computeVertexNormals();
  19088. };
  19089. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19090. /**
  19091. * @author qiao / https://github.com/qiao
  19092. * @fileoverview This is a convex hull generator using the incremental method.
  19093. * The complexity is O(n^2) where n is the number of vertices.
  19094. * O(nlogn) algorithms do exist, but they are much more complicated.
  19095. *
  19096. * Benchmark:
  19097. *
  19098. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19099. *
  19100. * Num Vertices Time(ms)
  19101. *
  19102. * 10 1
  19103. * 20 3
  19104. * 30 19
  19105. * 40 48
  19106. * 50 107
  19107. */
  19108. THREE.ConvexGeometry = function( vertices ) {
  19109. THREE.Geometry.call( this );
  19110. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19111. for ( var i = 3; i < vertices.length; i++ ) {
  19112. addPoint( i );
  19113. }
  19114. function addPoint( vertexId ) {
  19115. var vertex = vertices[ vertexId ].clone();
  19116. var mag = vertex.length();
  19117. vertex.x += mag * randomOffset();
  19118. vertex.y += mag * randomOffset();
  19119. vertex.z += mag * randomOffset();
  19120. var hole = [];
  19121. for ( var f = 0; f < faces.length; ) {
  19122. var face = faces[ f ];
  19123. // for each face, if the vertex can see it,
  19124. // then we try to add the face's edges into the hole.
  19125. if ( visible( face, vertex ) ) {
  19126. for ( var e = 0; e < 3; e++ ) {
  19127. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19128. var boundary = true;
  19129. // remove duplicated edges.
  19130. for ( var h = 0; h < hole.length; h++ ) {
  19131. if ( equalEdge( hole[ h ], edge ) ) {
  19132. hole[ h ] = hole[ hole.length - 1 ];
  19133. hole.pop();
  19134. boundary = false;
  19135. break;
  19136. }
  19137. }
  19138. if ( boundary ) {
  19139. hole.push( edge );
  19140. }
  19141. }
  19142. // remove faces[ f ]
  19143. faces[ f ] = faces[ faces.length - 1 ];
  19144. faces.pop();
  19145. } else { // not visible
  19146. f++;
  19147. }
  19148. }
  19149. // construct the new faces formed by the edges of the hole and the vertex
  19150. for ( var h = 0; h < hole.length; h++ ) {
  19151. faces.push( [
  19152. hole[ h ][ 0 ],
  19153. hole[ h ][ 1 ],
  19154. vertexId
  19155. ] );
  19156. }
  19157. }
  19158. /**
  19159. * Whether the face is visible from the vertex
  19160. */
  19161. function visible( face, vertex ) {
  19162. var va = vertices[ face[ 0 ] ];
  19163. var vb = vertices[ face[ 1 ] ];
  19164. var vc = vertices[ face[ 2 ] ];
  19165. var n = normal( va, vb, vc );
  19166. // distance from face to origin
  19167. var dist = n.dot( va );
  19168. return n.dot( vertex ) >= dist;
  19169. }
  19170. /**
  19171. * Face normal
  19172. */
  19173. function normal( va, vb, vc ) {
  19174. var cb = new THREE.Vector3();
  19175. var ab = new THREE.Vector3();
  19176. cb.sub( vc, vb );
  19177. ab.sub( va, vb );
  19178. cb.crossSelf( ab );
  19179. cb.normalize();
  19180. return cb;
  19181. }
  19182. /**
  19183. * Detect whether two edges are equal.
  19184. * Note that when constructing the convex hull, two same edges can only
  19185. * be of the negative direction.
  19186. */
  19187. function equalEdge( ea, eb ) {
  19188. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19189. }
  19190. /**
  19191. * Create a random offset between -1e-6 and 1e-6.
  19192. */
  19193. function randomOffset() {
  19194. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19195. }
  19196. /**
  19197. * XXX: Not sure if this is the correct approach. Need someone to review.
  19198. */
  19199. function vertexUv( vertex ) {
  19200. var mag = vertex.length();
  19201. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  19202. }
  19203. // Push vertices into `this.vertices`, skipping those inside the hull
  19204. var id = 0;
  19205. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19206. for ( var i = 0; i < faces.length; i++ ) {
  19207. var face = faces[ i ];
  19208. for ( var j = 0; j < 3; j++ ) {
  19209. if ( newId[ face[ j ] ] === undefined ) {
  19210. newId[ face[ j ] ] = id++;
  19211. this.vertices.push( vertices[ face[ j ] ] );
  19212. }
  19213. face[ j ] = newId[ face[ j ] ];
  19214. }
  19215. }
  19216. // Convert faces into instances of THREE.Face3
  19217. for ( var i = 0; i < faces.length; i++ ) {
  19218. this.faces.push( new THREE.Face3(
  19219. faces[ i ][ 0 ],
  19220. faces[ i ][ 1 ],
  19221. faces[ i ][ 2 ]
  19222. ) );
  19223. }
  19224. // Compute UVs
  19225. for ( var i = 0; i < this.faces.length; i++ ) {
  19226. var face = this.faces[ i ];
  19227. this.faceVertexUvs[ 0 ].push( [
  19228. vertexUv( this.vertices[ face.a ] ),
  19229. vertexUv( this.vertices[ face.b ] ),
  19230. vertexUv( this.vertices[ face.c ])
  19231. ] );
  19232. }
  19233. this.computeCentroids();
  19234. this.computeFaceNormals();
  19235. this.computeVertexNormals();
  19236. };
  19237. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19238. /**
  19239. * @author sroucheray / http://sroucheray.org/
  19240. * @author mrdoob / http://mrdoob.com/
  19241. */
  19242. THREE.AxisHelper = function ( size ) {
  19243. var geometry = new THREE.Geometry();
  19244. geometry.vertices.push(
  19245. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19246. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19247. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19248. );
  19249. geometry.colors.push(
  19250. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19251. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19252. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19253. );
  19254. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19255. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19256. };
  19257. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19258. /**
  19259. * @author WestLangley / http://github.com/WestLangley
  19260. * @author zz85 / https://github.com/zz85
  19261. *
  19262. * Creates an arrow for visualizing directions
  19263. *
  19264. * Parameters:
  19265. * dir - Vector3
  19266. * origin - Vector3
  19267. * length - Number
  19268. * hex - color in hex value
  19269. */
  19270. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19271. THREE.Object3D.call( this );
  19272. if ( hex === undefined ) hex = 0xffff00;
  19273. if ( length === undefined ) length = 20;
  19274. var lineGeometry = new THREE.Geometry();
  19275. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19276. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19277. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19278. this.add( this.line );
  19279. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19280. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19281. this.cone.position.set( 0, 1, 0 );
  19282. this.add( this.cone );
  19283. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19284. this.setDirection( dir );
  19285. this.setLength( length );
  19286. };
  19287. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19288. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19289. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  19290. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  19291. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  19292. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  19293. };
  19294. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19295. this.scale.set( length, length, length );
  19296. };
  19297. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19298. this.line.material.color.setHex( hex );
  19299. this.cone.material.color.setHex( hex );
  19300. };
  19301. /**
  19302. * @author alteredq / http://alteredqualia.com/
  19303. *
  19304. * - shows frustum, line of sight and up of the camera
  19305. * - suitable for fast updates
  19306. * - based on frustum visualization in lightgl.js shadowmap example
  19307. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19308. */
  19309. THREE.CameraHelper = function ( camera ) {
  19310. THREE.Line.call( this );
  19311. var scope = this;
  19312. this.geometry = new THREE.Geometry();
  19313. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19314. this.type = THREE.LinePieces;
  19315. this.matrixWorld = camera.matrixWorld;
  19316. this.matrixAutoUpdate = false;
  19317. this.pointMap = {};
  19318. // colors
  19319. var hexFrustum = 0xffaa00;
  19320. var hexCone = 0xff0000;
  19321. var hexUp = 0x00aaff;
  19322. var hexTarget = 0xffffff;
  19323. var hexCross = 0x333333;
  19324. // near
  19325. addLine( "n1", "n2", hexFrustum );
  19326. addLine( "n2", "n4", hexFrustum );
  19327. addLine( "n4", "n3", hexFrustum );
  19328. addLine( "n3", "n1", hexFrustum );
  19329. // far
  19330. addLine( "f1", "f2", hexFrustum );
  19331. addLine( "f2", "f4", hexFrustum );
  19332. addLine( "f4", "f3", hexFrustum );
  19333. addLine( "f3", "f1", hexFrustum );
  19334. // sides
  19335. addLine( "n1", "f1", hexFrustum );
  19336. addLine( "n2", "f2", hexFrustum );
  19337. addLine( "n3", "f3", hexFrustum );
  19338. addLine( "n4", "f4", hexFrustum );
  19339. // cone
  19340. addLine( "p", "n1", hexCone );
  19341. addLine( "p", "n2", hexCone );
  19342. addLine( "p", "n3", hexCone );
  19343. addLine( "p", "n4", hexCone );
  19344. // up
  19345. addLine( "u1", "u2", hexUp );
  19346. addLine( "u2", "u3", hexUp );
  19347. addLine( "u3", "u1", hexUp );
  19348. // target
  19349. addLine( "c", "t", hexTarget );
  19350. addLine( "p", "c", hexCross );
  19351. // cross
  19352. addLine( "cn1", "cn2", hexCross );
  19353. addLine( "cn3", "cn4", hexCross );
  19354. addLine( "cf1", "cf2", hexCross );
  19355. addLine( "cf3", "cf4", hexCross );
  19356. this.camera = camera;
  19357. function addLine( a, b, hex ) {
  19358. addPoint( a, hex );
  19359. addPoint( b, hex );
  19360. }
  19361. function addPoint( id, hex ) {
  19362. scope.geometry.vertices.push( new THREE.Vector3() );
  19363. scope.geometry.colors.push( new THREE.Color( hex ) );
  19364. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  19365. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  19366. }
  19367. this.update( camera );
  19368. };
  19369. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  19370. THREE.CameraHelper.prototype.update = function () {
  19371. var scope = this;
  19372. var w = 1, h = 1;
  19373. // we need just camera projection matrix
  19374. // world matrix must be identity
  19375. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  19376. // center / target
  19377. setPoint( "c", 0, 0, -1 );
  19378. setPoint( "t", 0, 0, 1 );
  19379. // near
  19380. setPoint( "n1", -w, -h, -1 );
  19381. setPoint( "n2", w, -h, -1 );
  19382. setPoint( "n3", -w, h, -1 );
  19383. setPoint( "n4", w, h, -1 );
  19384. // far
  19385. setPoint( "f1", -w, -h, 1 );
  19386. setPoint( "f2", w, -h, 1 );
  19387. setPoint( "f3", -w, h, 1 );
  19388. setPoint( "f4", w, h, 1 );
  19389. // up
  19390. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19391. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19392. setPoint( "u3", 0, h * 2, -1 );
  19393. // cross
  19394. setPoint( "cf1", -w, 0, 1 );
  19395. setPoint( "cf2", w, 0, 1 );
  19396. setPoint( "cf3", 0, -h, 1 );
  19397. setPoint( "cf4", 0, h, 1 );
  19398. setPoint( "cn1", -w, 0, -1 );
  19399. setPoint( "cn2", w, 0, -1 );
  19400. setPoint( "cn3", 0, -h, -1 );
  19401. setPoint( "cn4", 0, h, -1 );
  19402. function setPoint( point, x, y, z ) {
  19403. THREE.CameraHelper.__v.set( x, y, z );
  19404. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19405. var points = scope.pointMap[ point ];
  19406. if ( points !== undefined ) {
  19407. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19408. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  19409. }
  19410. }
  19411. }
  19412. this.geometry.verticesNeedUpdate = true;
  19413. };
  19414. THREE.CameraHelper.__projector = new THREE.Projector();
  19415. THREE.CameraHelper.__v = new THREE.Vector3();
  19416. THREE.CameraHelper.__c = new THREE.Camera();
  19417. /**
  19418. * @author alteredq / http://alteredqualia.com/
  19419. *
  19420. * - shows directional light color, intensity, position, orientation and target
  19421. */
  19422. THREE.DirectionalLightHelper = function ( light, sphereSize, arrowLength ) {
  19423. THREE.Object3D.call( this );
  19424. this.light = light;
  19425. // position
  19426. this.position = light.position;
  19427. // direction
  19428. this.direction = new THREE.Vector3();
  19429. this.direction.sub( light.target.position, light.position );
  19430. // color
  19431. this.color = light.color.clone();
  19432. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19433. this.color.r *= intensity;
  19434. this.color.g *= intensity;
  19435. this.color.b *= intensity;
  19436. var hexColor = this.color.getHex();
  19437. // light helper
  19438. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19439. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19440. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19441. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19442. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19443. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19444. this.lightArrow.cone.material.fog = false;
  19445. this.lightArrow.line.material.fog = false;
  19446. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19447. this.add( this.lightArrow );
  19448. this.add( this.lightSphere );
  19449. this.add( this.lightRays );
  19450. this.lightSphere.properties.isGizmo = true;
  19451. this.lightSphere.properties.gizmoSubject = light;
  19452. this.lightSphere.properties.gizmoRoot = this;
  19453. // light target helper
  19454. this.targetSphere = null;
  19455. if ( light.target.properties.targetInverse ) {
  19456. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19457. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  19458. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  19459. this.targetSphere.position = light.target.position;
  19460. this.targetSphere.properties.isGizmo = true;
  19461. this.targetSphere.properties.gizmoSubject = light.target;
  19462. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  19463. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  19464. var lineGeometry = new THREE.Geometry();
  19465. lineGeometry.vertices.push( this.position.clone() );
  19466. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  19467. lineGeometry.computeLineDistances();
  19468. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  19469. this.targetLine.properties.isGizmo = true;
  19470. }
  19471. //
  19472. this.properties.isGizmo = true;
  19473. }
  19474. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19475. THREE.DirectionalLightHelper.prototype.update = function () {
  19476. // update arrow orientation
  19477. // pointing from light to target
  19478. this.direction.sub( this.light.target.position, this.light.position );
  19479. this.lightArrow.setDirection( this.direction );
  19480. // update arrow, spheres, rays and line colors to light color * light intensity
  19481. this.color.copy( this.light.color );
  19482. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19483. this.color.r *= intensity;
  19484. this.color.g *= intensity;
  19485. this.color.b *= intensity;
  19486. this.lightArrow.setColor( this.color.getHex() );
  19487. this.lightSphere.material.color.copy( this.color );
  19488. this.lightRays.material.color.copy( this.color );
  19489. this.targetSphere.material.color.copy( this.color );
  19490. this.targetLine.material.color.copy( this.color );
  19491. // update target line vertices
  19492. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  19493. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  19494. this.targetLine.geometry.computeLineDistances();
  19495. this.targetLine.geometry.verticesNeedUpdate = true;
  19496. }
  19497. /**
  19498. * @author alteredq / http://alteredqualia.com/
  19499. *
  19500. * - shows hemisphere light intensity, sky and ground colors and directions
  19501. */
  19502. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  19503. THREE.Object3D.call( this );
  19504. this.light = light;
  19505. // position
  19506. this.position = light.position;
  19507. //
  19508. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19509. // sky color
  19510. this.color = light.color.clone();
  19511. this.color.r *= intensity;
  19512. this.color.g *= intensity;
  19513. this.color.b *= intensity;
  19514. var hexColor = this.color.getHex();
  19515. // ground color
  19516. this.groundColor = light.groundColor.clone();
  19517. this.groundColor.r *= intensity;
  19518. this.groundColor.g *= intensity;
  19519. this.groundColor.b *= intensity;
  19520. var hexColorGround = this.groundColor.getHex();
  19521. // double colored light bulb
  19522. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  19523. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  19524. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19525. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  19526. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  19527. bulbGeometry.faces[ i ].materialIndex = 0;
  19528. }
  19529. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  19530. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  19531. }
  19532. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  19533. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  19534. // arrows for sky and ground light directions
  19535. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  19536. this.lightArrow.rotation.x = Math.PI;
  19537. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  19538. var joint = new THREE.Object3D();
  19539. joint.rotation.x = -Math.PI * 0.5;
  19540. joint.add( this.lightSphere );
  19541. joint.add( this.lightArrow );
  19542. joint.add( this.lightArrowGround );
  19543. this.add( joint );
  19544. //
  19545. this.lightSphere.properties.isGizmo = true;
  19546. this.lightSphere.properties.gizmoSubject = light;
  19547. this.lightSphere.properties.gizmoRoot = this;
  19548. //
  19549. this.properties.isGizmo = true;
  19550. //
  19551. this.target = new THREE.Vector3();
  19552. this.lookAt( this.target );
  19553. }
  19554. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19555. THREE.HemisphereLightHelper.prototype.update = function () {
  19556. // update sphere sky and ground colors to light color * light intensity
  19557. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19558. this.color.copy( this.light.color );
  19559. this.groundColor.copy( this.light.groundColor );
  19560. this.color.r *= intensity;
  19561. this.color.g *= intensity;
  19562. this.color.b *= intensity;
  19563. this.groundColor.r *= intensity;
  19564. this.groundColor.g *= intensity;
  19565. this.groundColor.b *= intensity;
  19566. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  19567. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  19568. this.lightArrow.setColor( this.color.getHex() );
  19569. this.lightArrowGround.setColor( this.groundColor.getHex() );
  19570. this.lookAt( this.target );
  19571. }
  19572. /**
  19573. * @author alteredq / http://alteredqualia.com/
  19574. *
  19575. * - shows point light color, intensity, position and distance
  19576. */
  19577. THREE.PointLightHelper = function ( light, sphereSize ) {
  19578. THREE.Object3D.call( this );
  19579. this.light = light;
  19580. // position
  19581. this.position = light.position;
  19582. // color
  19583. this.color = light.color.clone();
  19584. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19585. this.color.r *= intensity;
  19586. this.color.g *= intensity;
  19587. this.color.b *= intensity;
  19588. var hexColor = this.color.getHex();
  19589. // light helper
  19590. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19591. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19592. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  19593. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19594. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19595. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  19596. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19597. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19598. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  19599. var d = light.distance;
  19600. if ( d === 0.0 ) {
  19601. this.lightDistance.visible = false;
  19602. } else {
  19603. this.lightDistance.scale.set( d, d, d );
  19604. }
  19605. this.add( this.lightSphere );
  19606. this.add( this.lightRays );
  19607. this.add( this.lightDistance );
  19608. //
  19609. this.lightSphere.properties.isGizmo = true;
  19610. this.lightSphere.properties.gizmoSubject = light;
  19611. this.lightSphere.properties.gizmoRoot = this;
  19612. //
  19613. this.properties.isGizmo = true;
  19614. }
  19615. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19616. THREE.PointLightHelper.prototype.update = function () {
  19617. // update sphere and rays colors to light color * light intensity
  19618. this.color.copy( this.light.color );
  19619. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19620. this.color.r *= intensity;
  19621. this.color.g *= intensity;
  19622. this.color.b *= intensity;
  19623. this.lightSphere.material.color.copy( this.color );
  19624. this.lightRays.material.color.copy( this.color );
  19625. this.lightDistance.material.color.copy( this.color );
  19626. //
  19627. var d = this.light.distance;
  19628. if ( d === 0.0 ) {
  19629. this.lightDistance.visible = false;
  19630. } else {
  19631. this.lightDistance.visible = true;
  19632. this.lightDistance.scale.set( d, d, d );
  19633. }
  19634. }
  19635. /**
  19636. * @author alteredq / http://alteredqualia.com/
  19637. *
  19638. * - shows spot light color, intensity, position, orientation, light cone and target
  19639. */
  19640. THREE.SpotLightHelper = function ( light, sphereSize, arrowLength ) {
  19641. THREE.Object3D.call( this );
  19642. this.light = light;
  19643. // position
  19644. this.position = light.position;
  19645. // direction
  19646. this.direction = new THREE.Vector3();
  19647. this.direction.sub( light.target.position, light.position );
  19648. // color
  19649. this.color = light.color.clone();
  19650. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19651. this.color.r *= intensity;
  19652. this.color.g *= intensity;
  19653. this.color.b *= intensity;
  19654. var hexColor = this.color.getHex();
  19655. // light helper
  19656. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19657. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19658. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  19659. var coneMatrix = new THREE.Matrix4();
  19660. coneMatrix.rotateX( -Math.PI/2 );
  19661. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  19662. coneGeometry.applyMatrix( coneMatrix );
  19663. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19664. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19665. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  19666. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19667. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19668. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  19669. var coneLength = light.distance ? light.distance : 10000;
  19670. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  19671. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  19672. this.lightArrow.cone.material.fog = false;
  19673. this.lightArrow.line.material.fog = false;
  19674. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19675. this.gyroscope = new THREE.Gyroscope();
  19676. this.gyroscope.add( this.lightArrow );
  19677. this.gyroscope.add( this.lightSphere );
  19678. this.gyroscope.add( this.lightRays );
  19679. this.add( this.gyroscope );
  19680. this.add( this.lightCone );
  19681. this.lookAt( light.target.position );
  19682. this.lightSphere.properties.isGizmo = true;
  19683. this.lightSphere.properties.gizmoSubject = light;
  19684. this.lightSphere.properties.gizmoRoot = this;
  19685. // light target helper
  19686. this.targetSphere = null;
  19687. if ( light.target.properties.targetInverse ) {
  19688. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19689. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  19690. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  19691. this.targetSphere.position = light.target.position;
  19692. this.targetSphere.properties.isGizmo = true;
  19693. this.targetSphere.properties.gizmoSubject = light.target;
  19694. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  19695. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  19696. var lineGeometry = new THREE.Geometry();
  19697. lineGeometry.vertices.push( this.position.clone() );
  19698. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  19699. lineGeometry.computeLineDistances();
  19700. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  19701. this.targetLine.properties.isGizmo = true;
  19702. }
  19703. //
  19704. this.properties.isGizmo = true;
  19705. }
  19706. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19707. THREE.SpotLightHelper.prototype.update = function () {
  19708. // update arrow orientation
  19709. // pointing from light to target
  19710. this.direction.sub( this.light.target.position, this.light.position );
  19711. this.lightArrow.setDirection( this.direction );
  19712. // update light cone orientation and size
  19713. this.lookAt( this.light.target.position );
  19714. var coneLength = this.light.distance ? this.light.distance : 10000;
  19715. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  19716. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  19717. // update arrow, spheres, rays and line colors to light color * light intensity
  19718. this.color.copy( this.light.color );
  19719. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19720. this.color.r *= intensity;
  19721. this.color.g *= intensity;
  19722. this.color.b *= intensity;
  19723. this.lightArrow.setColor( this.color.getHex() );
  19724. this.lightSphere.material.color.copy( this.color );
  19725. this.lightRays.material.color.copy( this.color );
  19726. this.lightCone.material.color.copy( this.color );
  19727. this.targetSphere.material.color.copy( this.color );
  19728. this.targetLine.material.color.copy( this.color );
  19729. // update target line vertices
  19730. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  19731. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  19732. this.targetLine.geometry.computeLineDistances();
  19733. this.targetLine.geometry.verticesNeedUpdate = true;
  19734. }
  19735. /*
  19736. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19737. *
  19738. * Subdivision Geometry Modifier
  19739. * using Catmull-Clark Subdivision Surfaces
  19740. * for creating smooth geometry meshes
  19741. *
  19742. * Note: a modifier modifies vertices and faces of geometry,
  19743. * so use geometry.clone() if original geometry needs to be retained
  19744. *
  19745. * Readings:
  19746. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19747. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  19748. * http://xrt.wikidot.com/blog:31
  19749. * "Subdivision Surfaces in Character Animation"
  19750. *
  19751. * (on boundary edges)
  19752. * http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19753. * https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description
  19754. *
  19755. * Supports:
  19756. * Closed and Open geometries.
  19757. *
  19758. * TODO:
  19759. * crease vertex and "semi-sharp" features
  19760. * selective subdivision
  19761. */
  19762. THREE.SubdivisionModifier = function( subdivisions ) {
  19763. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  19764. // Settings
  19765. this.useOldVertexColors = false;
  19766. this.supportUVs = true;
  19767. this.debug = false;
  19768. };
  19769. // Applies the "modify" pattern
  19770. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  19771. var repeats = this.subdivisions;
  19772. while ( repeats-- > 0 ) {
  19773. this.smooth( geometry );
  19774. }
  19775. };
  19776. /// REFACTORING THIS OUT
  19777. THREE.GeometryUtils.orderedKey = function ( a, b ) {
  19778. return Math.min( a, b ) + "_" + Math.max( a, b );
  19779. };
  19780. // Returns a hashmap - of { edge_key: face_index }
  19781. THREE.GeometryUtils.computeEdgeFaces = function ( geometry ) {
  19782. var i, il, v1, v2, j, k,
  19783. face, faceIndices, faceIndex,
  19784. edge,
  19785. hash,
  19786. edgeFaceMap = {};
  19787. var orderedKey = THREE.GeometryUtils.orderedKey;
  19788. function mapEdgeHash( hash, i ) {
  19789. if ( edgeFaceMap[ hash ] === undefined ) {
  19790. edgeFaceMap[ hash ] = [];
  19791. }
  19792. edgeFaceMap[ hash ].push( i );
  19793. }
  19794. // construct vertex -> face map
  19795. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  19796. face = geometry.faces[ i ];
  19797. if ( face instanceof THREE.Face3 ) {
  19798. hash = orderedKey( face.a, face.b );
  19799. mapEdgeHash( hash, i );
  19800. hash = orderedKey( face.b, face.c );
  19801. mapEdgeHash( hash, i );
  19802. hash = orderedKey( face.c, face.a );
  19803. mapEdgeHash( hash, i );
  19804. } else if ( face instanceof THREE.Face4 ) {
  19805. hash = orderedKey( face.a, face.b );
  19806. mapEdgeHash( hash, i );
  19807. hash = orderedKey( face.b, face.c );
  19808. mapEdgeHash( hash, i );
  19809. hash = orderedKey( face.c, face.d );
  19810. mapEdgeHash( hash, i );
  19811. hash = orderedKey( face.d, face.a );
  19812. mapEdgeHash( hash, i );
  19813. }
  19814. }
  19815. // extract faces
  19816. // var edges = [];
  19817. //
  19818. // var numOfEdges = 0;
  19819. // for (i in edgeFaceMap) {
  19820. // numOfEdges++;
  19821. //
  19822. // edge = edgeFaceMap[i];
  19823. // edges.push(edge);
  19824. //
  19825. // }
  19826. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  19827. return edgeFaceMap;
  19828. }
  19829. /////////////////////////////
  19830. // Performs an iteration of Catmull-Clark Subdivision
  19831. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  19832. //debug( 'running smooth' );
  19833. // New set of vertices, faces and uvs
  19834. var newVertices = [], newFaces = [], newUVs = [];
  19835. function v( x, y, z ) {
  19836. newVertices.push( new THREE.Vector3( x, y, z ) );
  19837. }
  19838. var scope = this;
  19839. var orderedKey = THREE.GeometryUtils.orderedKey;
  19840. var computeEdgeFaces = THREE.GeometryUtils.computeEdgeFaces;
  19841. function assert() {
  19842. if (scope.debug && console && console.assert) console.assert.apply(console, arguments);
  19843. }
  19844. function debug() {
  19845. if (scope.debug) console.log.apply(console, arguments);
  19846. }
  19847. function warn() {
  19848. if (console)
  19849. console.log.apply(console, arguments);
  19850. }
  19851. function f4( a, b, c, d, oldFace, orders, facei ) {
  19852. // TODO move vertex selection over here!
  19853. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  19854. if (scope.useOldVertexColors) {
  19855. newFace.vertexColors = [];
  19856. var color, tmpColor, order;
  19857. for (var i=0;i<4;i++) {
  19858. order = orders[i];
  19859. color = new THREE.Color(),
  19860. color.setRGB(0,0,0);
  19861. for (var j=0, jl=0; j<order.length;j++) {
  19862. tmpColor = oldFace.vertexColors[order[j]-1];
  19863. color.r += tmpColor.r;
  19864. color.g += tmpColor.g;
  19865. color.b += tmpColor.b;
  19866. }
  19867. color.r /= order.length;
  19868. color.g /= order.length;
  19869. color.b /= order.length;
  19870. newFace.vertexColors[i] = color;
  19871. }
  19872. }
  19873. newFaces.push( newFace );
  19874. if (scope.supportUVs) {
  19875. var aUv = [
  19876. getUV(a, ''),
  19877. getUV(b, facei),
  19878. getUV(c, facei),
  19879. getUV(d, facei)
  19880. ];
  19881. if (!aUv[0]) debug('a :( ', a+':'+facei);
  19882. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  19883. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  19884. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  19885. else
  19886. newUVs.push( aUv );
  19887. }
  19888. }
  19889. var originalPoints = oldGeometry.vertices;
  19890. var originalFaces = oldGeometry.faces;
  19891. var originalVerticesLength = originalPoints.length;
  19892. var newPoints = originalPoints.concat(); // New set of vertices to work on
  19893. var facePoints = [], // these are new points on exisiting faces
  19894. edgePoints = {}; // these are new points on exisiting edges
  19895. var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them
  19896. // TODO: handle this correctly.
  19897. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  19898. function debugCoreStuff() {
  19899. console.log('facePoints', facePoints, 'edgePoints', edgePoints);
  19900. console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap);
  19901. }
  19902. function getUV(vertexNo, oldFaceNo) {
  19903. var j,jl;
  19904. var key = vertexNo+':'+oldFaceNo;
  19905. var theUV = uvForVertices[key];
  19906. if (!theUV) {
  19907. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  19908. debug('face pt');
  19909. } else {
  19910. debug('edge pt');
  19911. }
  19912. warn('warning, UV not found for', key);
  19913. return null;
  19914. }
  19915. return theUV;
  19916. // Original faces -> Vertex Nos.
  19917. // new Facepoint -> Vertex Nos.
  19918. // edge Points
  19919. }
  19920. function addUV(vertexNo, oldFaceNo, value) {
  19921. var key = vertexNo+':'+oldFaceNo;
  19922. if (!(key in uvForVertices)) {
  19923. uvForVertices[key] = value;
  19924. } else {
  19925. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  19926. }
  19927. }
  19928. // Step 1
  19929. // For each face, add a face point
  19930. // Set each face point to be the centroid of all original points for the respective face.
  19931. // debug(oldGeometry);
  19932. var i, il, j, jl, face;
  19933. // For Uvs
  19934. var uvs = oldGeometry.faceVertexUvs[0];
  19935. var abcd = 'abcd', vertice;
  19936. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  19937. if (scope.supportUVs)
  19938. for (i=0, il = uvs.length; i<il; i++ ) {
  19939. for (j=0,jl=uvs[i].length;j<jl;j++) {
  19940. vertice = originalFaces[i][abcd.charAt(j)];
  19941. addUV(vertice, i, uvs[i][j]);
  19942. }
  19943. }
  19944. if (uvs.length == 0) scope.supportUVs = false;
  19945. // Additional UVs check, if we index original
  19946. var uvCount = 0;
  19947. for (var u in uvForVertices) {
  19948. uvCount++;
  19949. }
  19950. if (!uvCount) {
  19951. scope.supportUVs = false;
  19952. debug('no uvs');
  19953. }
  19954. var avgUv ;
  19955. for (i=0, il = originalFaces.length; i<il ;i++) {
  19956. face = originalFaces[ i ];
  19957. facePoints.push( face.centroid );
  19958. newPoints.push( face.centroid );
  19959. if (!scope.supportUVs) continue;
  19960. // Prepare subdivided uv
  19961. avgUv = new THREE.UV();
  19962. if ( face instanceof THREE.Face3 ) {
  19963. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  19964. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  19965. avgUv.u /= 3;
  19966. avgUv.v /= 3;
  19967. } else if ( face instanceof THREE.Face4 ) {
  19968. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  19969. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  19970. avgUv.u /= 4;
  19971. avgUv.v /= 4;
  19972. }
  19973. addUV(originalVerticesLength + i, '', avgUv);
  19974. }
  19975. // Step 2
  19976. // For each edge, add an edge point.
  19977. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  19978. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]}
  19979. var edge, faceIndexA, faceIndexB, avg;
  19980. // debug('edgeFaceMap', edgeFaceMap);
  19981. var edgeCount = 0;
  19982. var edgeVertex, edgeVertexA, edgeVertexB;
  19983. ////
  19984. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  19985. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  19986. function addVertexEdgeMap(vertex, edge) {
  19987. if (vertexEdgeMap[vertex]===undefined) {
  19988. vertexEdgeMap[vertex] = [];
  19989. }
  19990. vertexEdgeMap[vertex].push(edge);
  19991. }
  19992. function addVertexFaceMap(vertex, face, edge) {
  19993. if (vertexFaceMap[vertex]===undefined) {
  19994. vertexFaceMap[vertex] = {};
  19995. }
  19996. vertexFaceMap[vertex][face] = edge;
  19997. // vertexFaceMap[vertex][face] = null;
  19998. }
  19999. // Prepares vertexEdgeMap and vertexFaceMap
  20000. for (i in edgeFaceMap) { // This is for every edge
  20001. edge = edgeFaceMap[i];
  20002. edgeVertex = i.split('_');
  20003. edgeVertexA = edgeVertex[0];
  20004. edgeVertexB = edgeVertex[1];
  20005. // Maps an edgeVertex to connecting edges
  20006. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  20007. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  20008. for (j=0,jl=edge.length;j<jl;j++) {
  20009. face = edge[j];
  20010. addVertexFaceMap(edgeVertexA, face, i);
  20011. addVertexFaceMap(edgeVertexB, face, i);
  20012. }
  20013. // {edge vertex: { face1: edge_key, face2: edge_key.. } }
  20014. // this thing is fishy right now.
  20015. if (edge.length < 2) {
  20016. // edge is "sharp";
  20017. sharpEdges[i] = true;
  20018. sharpVertices[edgeVertexA] = true;
  20019. sharpVertices[edgeVertexB] = true;
  20020. }
  20021. }
  20022. for (i in edgeFaceMap) {
  20023. edge = edgeFaceMap[i];
  20024. faceIndexA = edge[0]; // face index a
  20025. faceIndexB = edge[1]; // face index b
  20026. edgeVertex = i.split('_');
  20027. edgeVertexA = edgeVertex[0];
  20028. edgeVertexB = edgeVertex[1];
  20029. avg = new THREE.Vector3();
  20030. //debug(i, faceIndexB,facePoints[faceIndexB]);
  20031. assert(edge.length > 0, 'an edge without faces?!');
  20032. if (edge.length==1) {
  20033. avg.addSelf(originalPoints[edgeVertexA]);
  20034. avg.addSelf(originalPoints[edgeVertexB]);
  20035. avg.multiplyScalar(0.5);
  20036. sharpVertices[newPoints.length] = true;
  20037. } else {
  20038. avg.addSelf(facePoints[faceIndexA]);
  20039. avg.addSelf(facePoints[faceIndexB]);
  20040. avg.addSelf(originalPoints[edgeVertexA]);
  20041. avg.addSelf(originalPoints[edgeVertexB]);
  20042. avg.multiplyScalar(0.25);
  20043. }
  20044. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  20045. newPoints.push( avg );
  20046. edgeCount ++;
  20047. if (!scope.supportUVs) {
  20048. continue;
  20049. }
  20050. // Prepare subdivided uv
  20051. avgUv = new THREE.UV();
  20052. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  20053. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  20054. avgUv.u /= 2;
  20055. avgUv.v /= 2;
  20056. addUV(edgePoints[i], faceIndexA, avgUv);
  20057. if (edge.length>=2) {
  20058. assert(edge.length == 2, 'did we plan for more than 2 edges?');
  20059. avgUv = new THREE.UV();
  20060. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  20061. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  20062. avgUv.u /= 2;
  20063. avgUv.v /= 2;
  20064. addUV(edgePoints[i], faceIndexB, avgUv);
  20065. }
  20066. }
  20067. debug('-- Step 2 done');
  20068. // Step 3
  20069. // For each face point, add an edge for every edge of the face,
  20070. // connecting the face point to each edge point for the face.
  20071. var facePt, currentVerticeIndex;
  20072. var hashAB, hashBC, hashCD, hashDA, hashCA;
  20073. var abc123 = ['123', '12', '2', '23'];
  20074. var bca123 = ['123', '23', '3', '31'];
  20075. var cab123 = ['123', '31', '1', '12'];
  20076. var abc1234 = ['1234', '12', '2', '23'];
  20077. var bcd1234 = ['1234', '23', '3', '34'];
  20078. var cda1234 = ['1234', '34', '4', '41'];
  20079. var dab1234 = ['1234', '41', '1', '12'];
  20080. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  20081. facePt = facePoints[i];
  20082. face = originalFaces[i];
  20083. currentVerticeIndex = originalVerticesLength+ i;
  20084. if ( face instanceof THREE.Face3 ) {
  20085. // create 3 face4s
  20086. hashAB = orderedKey( face.a, face.b );
  20087. hashBC = orderedKey( face.b, face.c );
  20088. hashCA = orderedKey( face.c, face.a );
  20089. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  20090. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  20091. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  20092. } else if ( face instanceof THREE.Face4 ) {
  20093. // create 4 face4s
  20094. hashAB = orderedKey( face.a, face.b );
  20095. hashBC = orderedKey( face.b, face.c );
  20096. hashCD = orderedKey( face.c, face.d );
  20097. hashDA = orderedKey( face.d, face.a );
  20098. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  20099. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  20100. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  20101. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  20102. } else {
  20103. debug('face should be a face!', face);
  20104. }
  20105. }
  20106. newVertices = newPoints;
  20107. // Step 4
  20108. // For each original point P,
  20109. // take the average F of all n face points for faces touching P,
  20110. // and take the average R of all n edge midpoints for edges touching P,
  20111. // where each edge midpoint is the average of its two endpoint vertices.
  20112. // Move each original point to the point
  20113. var F = new THREE.Vector3();
  20114. var R = new THREE.Vector3();
  20115. var n;
  20116. for (i=0, il = originalPoints.length; i<il; i++) {
  20117. // (F + 2R + (n-3)P) / n
  20118. if (vertexEdgeMap[i]===undefined) continue;
  20119. F.set(0,0,0);
  20120. R.set(0,0,0);
  20121. var newPos = new THREE.Vector3(0,0,0);
  20122. var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?)
  20123. for (j in vertexFaceMap[i]) {
  20124. F.addSelf(facePoints[j]);
  20125. f++;
  20126. }
  20127. var sharpEdgeCount = 0;
  20128. n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges
  20129. // Are we on the border?
  20130. var boundary_case = f != n;
  20131. // if (boundary_case) {
  20132. // console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2);
  20133. // }
  20134. for (j=0;j<n;j++) {
  20135. if (
  20136. sharpEdges[
  20137. orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  20138. ]) {
  20139. sharpEdgeCount++;
  20140. }
  20141. }
  20142. // if ( sharpEdgeCount==2 ) {
  20143. // continue;
  20144. // // Do not move vertex if there's 2 connecting sharp edges.
  20145. // }
  20146. /*
  20147. if (sharpEdgeCount>2) {
  20148. // TODO
  20149. }
  20150. */
  20151. F.divideScalar(f);
  20152. var boundary_edges = 0;
  20153. if (boundary_case) {
  20154. var bb_edge;
  20155. for (j=0; j<n;j++) {
  20156. edge = vertexEdgeMap[i][j];
  20157. bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1
  20158. if (bb_edge) {
  20159. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20160. R.addSelf(midPt);
  20161. boundary_edges++;
  20162. }
  20163. }
  20164. R.divideScalar(4);
  20165. // console.log(j + ' --- ' + n + ' --- ' + boundary_edges);
  20166. assert(boundary_edges == 2, 'should have only 2 boundary edges');
  20167. } else {
  20168. for (j=0; j<n;j++) {
  20169. edge = vertexEdgeMap[i][j];
  20170. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20171. R.addSelf(midPt);
  20172. }
  20173. R.divideScalar(n);
  20174. }
  20175. // Sum the formula
  20176. newPos.addSelf(originalPoints[i]);
  20177. if (boundary_case) {
  20178. newPos.divideScalar(2);
  20179. newPos.addSelf(R);
  20180. } else {
  20181. newPos.multiplyScalar(n - 3);
  20182. newPos.addSelf(F);
  20183. newPos.addSelf(R.multiplyScalar(2));
  20184. newPos.divideScalar(n);
  20185. }
  20186. newVertices[i] = newPos;
  20187. }
  20188. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  20189. newGeometry.vertices = newVertices;
  20190. newGeometry.faces = newFaces;
  20191. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  20192. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  20193. newGeometry.computeCentroids();
  20194. newGeometry.computeFaceNormals();
  20195. newGeometry.computeVertexNormals();
  20196. };
  20197. /**
  20198. * @author alteredq / http://alteredqualia.com/
  20199. */
  20200. THREE.ImmediateRenderObject = function ( ) {
  20201. THREE.Object3D.call( this );
  20202. this.render = function ( renderCallback ) { };
  20203. };
  20204. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20205. /**
  20206. * @author mikael emtinger / http://gomo.se/
  20207. * @author alteredq / http://alteredqualia.com/
  20208. */
  20209. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20210. THREE.Object3D.call( this );
  20211. this.lensFlares = [];
  20212. this.positionScreen = new THREE.Vector3();
  20213. this.customUpdateCallback = undefined;
  20214. if( texture !== undefined ) {
  20215. this.add( texture, size, distance, blending, color );
  20216. }
  20217. };
  20218. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20219. /*
  20220. * Add: adds another flare
  20221. */
  20222. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20223. if( size === undefined ) size = -1;
  20224. if( distance === undefined ) distance = 0;
  20225. if( opacity === undefined ) opacity = 1;
  20226. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20227. if( blending === undefined ) blending = THREE.NormalBlending;
  20228. distance = Math.min( distance, Math.max( 0, distance ) );
  20229. this.lensFlares.push( { texture: texture, // THREE.Texture
  20230. size: size, // size in pixels (-1 = use texture.width)
  20231. distance: distance, // distance (0-1) from light source (0=at light source)
  20232. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20233. scale: 1, // scale
  20234. rotation: 1, // rotation
  20235. opacity: opacity, // opacity
  20236. color: color, // color
  20237. blending: blending } ); // blending
  20238. };
  20239. /*
  20240. * Update lens flares update positions on all flares based on the screen position
  20241. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20242. */
  20243. THREE.LensFlare.prototype.updateLensFlares = function () {
  20244. var f, fl = this.lensFlares.length;
  20245. var flare;
  20246. var vecX = -this.positionScreen.x * 2;
  20247. var vecY = -this.positionScreen.y * 2;
  20248. for( f = 0; f < fl; f ++ ) {
  20249. flare = this.lensFlares[ f ];
  20250. flare.x = this.positionScreen.x + vecX * flare.distance;
  20251. flare.y = this.positionScreen.y + vecY * flare.distance;
  20252. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20253. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20254. }
  20255. };
  20256. /**
  20257. * @author alteredq / http://alteredqualia.com/
  20258. */
  20259. THREE.MorphBlendMesh = function( geometry, material ) {
  20260. THREE.Mesh.call( this, geometry, material );
  20261. this.animationsMap = {};
  20262. this.animationsList = [];
  20263. // prepare default animation
  20264. // (all frames played together in 1 second)
  20265. var numFrames = this.geometry.morphTargets.length;
  20266. var name = "__default";
  20267. var startFrame = 0;
  20268. var endFrame = numFrames - 1;
  20269. var fps = numFrames / 1;
  20270. this.createAnimation( name, startFrame, endFrame, fps );
  20271. this.setAnimationWeight( name, 1 );
  20272. };
  20273. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20274. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20275. var animation = {
  20276. startFrame: start,
  20277. endFrame: end,
  20278. length: end - start + 1,
  20279. fps: fps,
  20280. duration: ( end - start ) / fps,
  20281. lastFrame: 0,
  20282. currentFrame: 0,
  20283. active: false,
  20284. time: 0,
  20285. direction: 1,
  20286. weight: 1,
  20287. directionBackwards: false,
  20288. mirroredLoop: false
  20289. };
  20290. this.animationsMap[ name ] = animation;
  20291. this.animationsList.push( animation );
  20292. };
  20293. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20294. var pattern = /([a-z]+)(\d+)/;
  20295. var firstAnimation, frameRanges = {};
  20296. var geometry = this.geometry;
  20297. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20298. var morph = geometry.morphTargets[ i ];
  20299. var chunks = morph.name.match( pattern );
  20300. if ( chunks && chunks.length > 1 ) {
  20301. var name = chunks[ 1 ];
  20302. var num = chunks[ 2 ];
  20303. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20304. var range = frameRanges[ name ];
  20305. if ( i < range.start ) range.start = i;
  20306. if ( i > range.end ) range.end = i;
  20307. if ( ! firstAnimation ) firstAnimation = name;
  20308. }
  20309. }
  20310. for ( var name in frameRanges ) {
  20311. var range = frameRanges[ name ];
  20312. this.createAnimation( name, range.start, range.end, fps );
  20313. }
  20314. this.firstAnimation = firstAnimation;
  20315. };
  20316. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20317. var animation = this.animationsMap[ name ];
  20318. if ( animation ) {
  20319. animation.direction = 1;
  20320. animation.directionBackwards = false;
  20321. }
  20322. };
  20323. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20324. var animation = this.animationsMap[ name ];
  20325. if ( animation ) {
  20326. animation.direction = -1;
  20327. animation.directionBackwards = true;
  20328. }
  20329. };
  20330. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20331. var animation = this.animationsMap[ name ];
  20332. if ( animation ) {
  20333. animation.fps = fps;
  20334. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20335. }
  20336. };
  20337. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20338. var animation = this.animationsMap[ name ];
  20339. if ( animation ) {
  20340. animation.duration = duration;
  20341. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20342. }
  20343. };
  20344. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20345. var animation = this.animationsMap[ name ];
  20346. if ( animation ) {
  20347. animation.weight = weight;
  20348. }
  20349. };
  20350. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20351. var animation = this.animationsMap[ name ];
  20352. if ( animation ) {
  20353. animation.time = time;
  20354. }
  20355. };
  20356. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20357. var time = 0;
  20358. var animation = this.animationsMap[ name ];
  20359. if ( animation ) {
  20360. time = animation.time;
  20361. }
  20362. return time;
  20363. };
  20364. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20365. var duration = -1;
  20366. var animation = this.animationsMap[ name ];
  20367. if ( animation ) {
  20368. duration = animation.duration;
  20369. }
  20370. return duration;
  20371. };
  20372. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20373. var animation = this.animationsMap[ name ];
  20374. if ( animation ) {
  20375. animation.time = 0;
  20376. animation.active = true;
  20377. } else {
  20378. console.warn( "animation[" + name + "] undefined" );
  20379. }
  20380. };
  20381. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20382. var animation = this.animationsMap[ name ];
  20383. if ( animation ) {
  20384. animation.active = false;
  20385. }
  20386. };
  20387. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20388. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20389. var animation = this.animationsList[ i ];
  20390. if ( ! animation.active ) continue;
  20391. var frameTime = animation.duration / animation.length;
  20392. animation.time += animation.direction * delta;
  20393. if ( animation.mirroredLoop ) {
  20394. if ( animation.time > animation.duration || animation.time < 0 ) {
  20395. animation.direction *= -1;
  20396. if ( animation.time > animation.duration ) {
  20397. animation.time = animation.duration;
  20398. animation.directionBackwards = true;
  20399. }
  20400. if ( animation.time < 0 ) {
  20401. animation.time = 0;
  20402. animation.directionBackwards = false;
  20403. }
  20404. }
  20405. } else {
  20406. animation.time = animation.time % animation.duration;
  20407. if ( animation.time < 0 ) animation.time += animation.duration;
  20408. }
  20409. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20410. var weight = animation.weight;
  20411. if ( keyframe !== animation.currentFrame ) {
  20412. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20413. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20414. this.morphTargetInfluences[ keyframe ] = 0;
  20415. animation.lastFrame = animation.currentFrame;
  20416. animation.currentFrame = keyframe;
  20417. }
  20418. var mix = ( animation.time % frameTime ) / frameTime;
  20419. if ( animation.directionBackwards ) mix = 1 - mix;
  20420. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20421. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20422. }
  20423. };
  20424. /**
  20425. * @author mikael emtinger / http://gomo.se/
  20426. * @author alteredq / http://alteredqualia.com/
  20427. */
  20428. THREE.LensFlarePlugin = function ( ) {
  20429. var _gl, _renderer, _lensFlare = {};
  20430. this.init = function ( renderer ) {
  20431. _gl = renderer.context;
  20432. _renderer = renderer;
  20433. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20434. _lensFlare.faces = new Uint16Array( 6 );
  20435. var i = 0;
  20436. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20437. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20438. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20439. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20440. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20441. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20442. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20443. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20444. i = 0;
  20445. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20446. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20447. // buffers
  20448. _lensFlare.vertexBuffer = _gl.createBuffer();
  20449. _lensFlare.elementBuffer = _gl.createBuffer();
  20450. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20451. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20452. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20453. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20454. // textures
  20455. _lensFlare.tempTexture = _gl.createTexture();
  20456. _lensFlare.occlusionTexture = _gl.createTexture();
  20457. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20458. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20459. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20460. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20461. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20462. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20463. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20464. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20465. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20466. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20467. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20468. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20469. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20470. _lensFlare.hasVertexTexture = false;
  20471. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20472. } else {
  20473. _lensFlare.hasVertexTexture = true;
  20474. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20475. }
  20476. _lensFlare.attributes = {};
  20477. _lensFlare.uniforms = {};
  20478. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20479. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20480. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20481. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20482. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20483. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20484. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20485. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20486. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20487. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20488. };
  20489. /*
  20490. * Render lens flares
  20491. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20492. * reads these back and calculates occlusion.
  20493. * Then _lensFlare.update_lensFlares() is called to re-position and
  20494. * update transparency of flares. Then they are rendered.
  20495. *
  20496. */
  20497. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20498. var flares = scene.__webglFlares,
  20499. nFlares = flares.length;
  20500. if ( ! nFlares ) return;
  20501. var tempPosition = new THREE.Vector3();
  20502. var invAspect = viewportHeight / viewportWidth,
  20503. halfViewportWidth = viewportWidth * 0.5,
  20504. halfViewportHeight = viewportHeight * 0.5;
  20505. var size = 16 / viewportHeight,
  20506. scale = new THREE.Vector2( size * invAspect, size );
  20507. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20508. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20509. var uniforms = _lensFlare.uniforms,
  20510. attributes = _lensFlare.attributes;
  20511. // set _lensFlare program and reset blending
  20512. _gl.useProgram( _lensFlare.program );
  20513. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20514. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20515. // loop through all lens flares to update their occlusion and positions
  20516. // setup gl and common used attribs/unforms
  20517. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20518. _gl.uniform1i( uniforms.map, 1 );
  20519. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20520. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20521. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20522. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20523. _gl.disable( _gl.CULL_FACE );
  20524. _gl.depthMask( false );
  20525. var i, j, jl, flare, sprite;
  20526. for ( i = 0; i < nFlares; i ++ ) {
  20527. size = 16 / viewportHeight;
  20528. scale.set( size * invAspect, size );
  20529. // calc object screen position
  20530. flare = flares[ i ];
  20531. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20532. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  20533. camera.projectionMatrix.multiplyVector3( tempPosition );
  20534. // setup arrays for gl programs
  20535. screenPosition.copy( tempPosition )
  20536. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20537. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20538. // screen cull
  20539. if ( _lensFlare.hasVertexTexture || (
  20540. screenPositionPixels.x > 0 &&
  20541. screenPositionPixels.x < viewportWidth &&
  20542. screenPositionPixels.y > 0 &&
  20543. screenPositionPixels.y < viewportHeight ) ) {
  20544. // save current RGB to temp texture
  20545. _gl.activeTexture( _gl.TEXTURE1 );
  20546. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20547. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20548. // render pink quad
  20549. _gl.uniform1i( uniforms.renderType, 0 );
  20550. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20551. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20552. _gl.disable( _gl.BLEND );
  20553. _gl.enable( _gl.DEPTH_TEST );
  20554. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20555. // copy result to occlusionMap
  20556. _gl.activeTexture( _gl.TEXTURE0 );
  20557. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20558. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20559. // restore graphics
  20560. _gl.uniform1i( uniforms.renderType, 1 );
  20561. _gl.disable( _gl.DEPTH_TEST );
  20562. _gl.activeTexture( _gl.TEXTURE1 );
  20563. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20564. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20565. // update object positions
  20566. flare.positionScreen.copy( screenPosition )
  20567. if ( flare.customUpdateCallback ) {
  20568. flare.customUpdateCallback( flare );
  20569. } else {
  20570. flare.updateLensFlares();
  20571. }
  20572. // render flares
  20573. _gl.uniform1i( uniforms.renderType, 2 );
  20574. _gl.enable( _gl.BLEND );
  20575. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20576. sprite = flare.lensFlares[ j ];
  20577. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20578. screenPosition.x = sprite.x;
  20579. screenPosition.y = sprite.y;
  20580. screenPosition.z = sprite.z;
  20581. size = sprite.size * sprite.scale / viewportHeight;
  20582. scale.x = size * invAspect;
  20583. scale.y = size;
  20584. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20585. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20586. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20587. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20588. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20589. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20590. _renderer.setTexture( sprite.texture, 1 );
  20591. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20592. }
  20593. }
  20594. }
  20595. }
  20596. // restore gl
  20597. _gl.enable( _gl.CULL_FACE );
  20598. _gl.enable( _gl.DEPTH_TEST );
  20599. _gl.depthMask( true );
  20600. };
  20601. function createProgram ( shader ) {
  20602. var program = _gl.createProgram();
  20603. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20604. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20605. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20606. _gl.shaderSource( vertexShader, shader.vertexShader );
  20607. _gl.compileShader( fragmentShader );
  20608. _gl.compileShader( vertexShader );
  20609. _gl.attachShader( program, fragmentShader );
  20610. _gl.attachShader( program, vertexShader );
  20611. _gl.linkProgram( program );
  20612. return program;
  20613. };
  20614. };/**
  20615. * @author alteredq / http://alteredqualia.com/
  20616. */
  20617. THREE.ShadowMapPlugin = function ( ) {
  20618. var _gl,
  20619. _renderer,
  20620. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20621. _frustum = new THREE.Frustum(),
  20622. _projScreenMatrix = new THREE.Matrix4(),
  20623. _min = new THREE.Vector3(),
  20624. _max = new THREE.Vector3();
  20625. this.init = function ( renderer ) {
  20626. _gl = renderer.context;
  20627. _renderer = renderer;
  20628. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20629. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20630. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20631. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20632. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20633. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20634. _depthMaterial._shadowPass = true;
  20635. _depthMaterialMorph._shadowPass = true;
  20636. _depthMaterialSkin._shadowPass = true;
  20637. _depthMaterialMorphSkin._shadowPass = true;
  20638. };
  20639. this.render = function ( scene, camera ) {
  20640. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20641. this.update( scene, camera );
  20642. };
  20643. this.update = function ( scene, camera ) {
  20644. var i, il, j, jl, n,
  20645. shadowMap, shadowMatrix, shadowCamera,
  20646. program, buffer, material,
  20647. webglObject, object, light,
  20648. renderList,
  20649. lights = [],
  20650. k = 0,
  20651. fog = null;
  20652. // set GL state for depth map
  20653. _gl.clearColor( 1, 1, 1, 1 );
  20654. _gl.disable( _gl.BLEND );
  20655. _gl.enable( _gl.CULL_FACE );
  20656. _gl.frontFace( _gl.CCW );
  20657. if ( _renderer.shadowMapCullFrontFaces ) {
  20658. _gl.cullFace( _gl.FRONT );
  20659. } else {
  20660. _gl.cullFace( _gl.BACK );
  20661. }
  20662. _renderer.setDepthTest( true );
  20663. // preprocess lights
  20664. // - skip lights that are not casting shadows
  20665. // - create virtual lights for cascaded shadow maps
  20666. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20667. light = scene.__lights[ i ];
  20668. if ( ! light.castShadow ) continue;
  20669. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20670. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20671. var virtualLight;
  20672. if ( ! light.shadowCascadeArray[ n ] ) {
  20673. virtualLight = createVirtualLight( light, n );
  20674. virtualLight.originalCamera = camera;
  20675. var gyro = new THREE.Gyroscope();
  20676. gyro.position = light.shadowCascadeOffset;
  20677. gyro.add( virtualLight );
  20678. gyro.add( virtualLight.target );
  20679. camera.add( gyro );
  20680. light.shadowCascadeArray[ n ] = virtualLight;
  20681. console.log( "Created virtualLight", virtualLight );
  20682. } else {
  20683. virtualLight = light.shadowCascadeArray[ n ];
  20684. }
  20685. updateVirtualLight( light, n );
  20686. lights[ k ] = virtualLight;
  20687. k ++;
  20688. }
  20689. } else {
  20690. lights[ k ] = light;
  20691. k ++;
  20692. }
  20693. }
  20694. // render depth map
  20695. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20696. light = lights[ i ];
  20697. if ( ! light.shadowMap ) {
  20698. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  20699. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20700. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20701. light.shadowMatrix = new THREE.Matrix4();
  20702. }
  20703. if ( ! light.shadowCamera ) {
  20704. if ( light instanceof THREE.SpotLight ) {
  20705. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20706. } else if ( light instanceof THREE.DirectionalLight ) {
  20707. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20708. } else {
  20709. console.error( "Unsupported light type for shadow" );
  20710. continue;
  20711. }
  20712. scene.add( light.shadowCamera );
  20713. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20714. }
  20715. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20716. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20717. light.shadowCamera.add( light.cameraHelper );
  20718. }
  20719. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20720. updateShadowCamera( camera, light );
  20721. }
  20722. shadowMap = light.shadowMap;
  20723. shadowMatrix = light.shadowMatrix;
  20724. shadowCamera = light.shadowCamera;
  20725. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20726. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20727. shadowCamera.updateMatrixWorld();
  20728. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20729. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20730. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20731. // compute shadow matrix
  20732. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20733. 0.0, 0.5, 0.0, 0.5,
  20734. 0.0, 0.0, 0.5, 0.5,
  20735. 0.0, 0.0, 0.0, 1.0 );
  20736. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  20737. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  20738. // update camera matrices and frustum
  20739. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  20740. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  20741. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  20742. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  20743. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20744. _frustum.setFromMatrix( _projScreenMatrix );
  20745. // render shadow map
  20746. _renderer.setRenderTarget( shadowMap );
  20747. _renderer.clear();
  20748. // set object matrices & frustum culling
  20749. renderList = scene.__webglObjects;
  20750. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20751. webglObject = renderList[ j ];
  20752. object = webglObject.object;
  20753. webglObject.render = false;
  20754. if ( object.visible && object.castShadow ) {
  20755. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20756. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20757. webglObject.render = true;
  20758. }
  20759. }
  20760. }
  20761. // render regular objects
  20762. var objectMaterial, useMorphing, useSkinning;
  20763. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20764. webglObject = renderList[ j ];
  20765. if ( webglObject.render ) {
  20766. object = webglObject.object;
  20767. buffer = webglObject.buffer;
  20768. // culling is overriden globally for all objects
  20769. // while rendering depth map
  20770. // need to deal with MeshFaceMaterial somehow
  20771. // in that case just use the first of material.materials for now
  20772. // (proper solution would require to break objects by materials
  20773. // similarly to regular rendering and then set corresponding
  20774. // depth materials per each chunk instead of just once per object)
  20775. objectMaterial = getObjectMaterial( object );
  20776. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  20777. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  20778. if ( object.customDepthMaterial ) {
  20779. material = object.customDepthMaterial;
  20780. } else if ( useSkinning ) {
  20781. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  20782. } else if ( useMorphing ) {
  20783. material = _depthMaterialMorph;
  20784. } else {
  20785. material = _depthMaterial;
  20786. }
  20787. if ( buffer instanceof THREE.BufferGeometry ) {
  20788. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20789. } else {
  20790. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20791. }
  20792. }
  20793. }
  20794. // set matrices and render immediate objects
  20795. renderList = scene.__webglObjectsImmediate;
  20796. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20797. webglObject = renderList[ j ];
  20798. object = webglObject.object;
  20799. if ( object.visible && object.castShadow ) {
  20800. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20801. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20802. }
  20803. }
  20804. }
  20805. // restore GL state
  20806. var clearColor = _renderer.getClearColor(),
  20807. clearAlpha = _renderer.getClearAlpha();
  20808. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20809. _gl.enable( _gl.BLEND );
  20810. if ( _renderer.shadowMapCullFrontFaces ) {
  20811. _gl.cullFace( _gl.BACK );
  20812. }
  20813. };
  20814. function createVirtualLight( light, cascade ) {
  20815. var virtualLight = new THREE.DirectionalLight();
  20816. virtualLight.isVirtual = true;
  20817. virtualLight.onlyShadow = true;
  20818. virtualLight.castShadow = true;
  20819. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20820. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20821. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20822. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20823. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20824. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20825. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20826. virtualLight.shadowDarkness = light.shadowDarkness;
  20827. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20828. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20829. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20830. virtualLight.pointsWorld = [];
  20831. virtualLight.pointsFrustum = [];
  20832. var pointsWorld = virtualLight.pointsWorld,
  20833. pointsFrustum = virtualLight.pointsFrustum;
  20834. for ( var i = 0; i < 8; i ++ ) {
  20835. pointsWorld[ i ] = new THREE.Vector3();
  20836. pointsFrustum[ i ] = new THREE.Vector3();
  20837. }
  20838. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20839. var farZ = light.shadowCascadeFarZ[ cascade ];
  20840. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20841. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20842. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20843. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20844. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20845. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20846. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20847. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20848. return virtualLight;
  20849. }
  20850. // Synchronize virtual light with the original light
  20851. function updateVirtualLight( light, cascade ) {
  20852. var virtualLight = light.shadowCascadeArray[ cascade ];
  20853. virtualLight.position.copy( light.position );
  20854. virtualLight.target.position.copy( light.target.position );
  20855. virtualLight.lookAt( virtualLight.target );
  20856. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20857. virtualLight.shadowDarkness = light.shadowDarkness;
  20858. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20859. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20860. var farZ = light.shadowCascadeFarZ[ cascade ];
  20861. var pointsFrustum = virtualLight.pointsFrustum;
  20862. pointsFrustum[ 0 ].z = nearZ;
  20863. pointsFrustum[ 1 ].z = nearZ;
  20864. pointsFrustum[ 2 ].z = nearZ;
  20865. pointsFrustum[ 3 ].z = nearZ;
  20866. pointsFrustum[ 4 ].z = farZ;
  20867. pointsFrustum[ 5 ].z = farZ;
  20868. pointsFrustum[ 6 ].z = farZ;
  20869. pointsFrustum[ 7 ].z = farZ;
  20870. }
  20871. // Fit shadow camera's ortho frustum to camera frustum
  20872. function updateShadowCamera( camera, light ) {
  20873. var shadowCamera = light.shadowCamera,
  20874. pointsFrustum = light.pointsFrustum,
  20875. pointsWorld = light.pointsWorld;
  20876. _min.set( Infinity, Infinity, Infinity );
  20877. _max.set( -Infinity, -Infinity, -Infinity );
  20878. for ( var i = 0; i < 8; i ++ ) {
  20879. var p = pointsWorld[ i ];
  20880. p.copy( pointsFrustum[ i ] );
  20881. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  20882. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  20883. if ( p.x < _min.x ) _min.x = p.x;
  20884. if ( p.x > _max.x ) _max.x = p.x;
  20885. if ( p.y < _min.y ) _min.y = p.y;
  20886. if ( p.y > _max.y ) _max.y = p.y;
  20887. if ( p.z < _min.z ) _min.z = p.z;
  20888. if ( p.z > _max.z ) _max.z = p.z;
  20889. }
  20890. shadowCamera.left = _min.x;
  20891. shadowCamera.right = _max.x;
  20892. shadowCamera.top = _max.y;
  20893. shadowCamera.bottom = _min.y;
  20894. // can't really fit near/far
  20895. //shadowCamera.near = _min.z;
  20896. //shadowCamera.far = _max.z;
  20897. shadowCamera.updateProjectionMatrix();
  20898. }
  20899. // For the moment just ignore objects that have multiple materials with different animation methods
  20900. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  20901. function getObjectMaterial( object ) {
  20902. return object.material instanceof THREE.MeshFaceMaterial
  20903. ? object.material.materials[ 0 ]
  20904. : object.material;
  20905. };
  20906. };
  20907. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  20908. /**
  20909. * @author mikael emtinger / http://gomo.se/
  20910. * @author alteredq / http://alteredqualia.com/
  20911. */
  20912. THREE.SpritePlugin = function ( ) {
  20913. var _gl, _renderer, _sprite = {};
  20914. this.init = function ( renderer ) {
  20915. _gl = renderer.context;
  20916. _renderer = renderer;
  20917. _sprite.vertices = new Float32Array( 8 + 8 );
  20918. _sprite.faces = new Uint16Array( 6 );
  20919. var i = 0;
  20920. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  20921. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  20922. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  20923. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  20924. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  20925. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  20926. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  20927. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  20928. i = 0;
  20929. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  20930. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  20931. _sprite.vertexBuffer = _gl.createBuffer();
  20932. _sprite.elementBuffer = _gl.createBuffer();
  20933. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20934. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  20935. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20936. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  20937. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  20938. _sprite.attributes = {};
  20939. _sprite.uniforms = {};
  20940. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  20941. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  20942. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  20943. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  20944. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  20945. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  20946. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  20947. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  20948. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  20949. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  20950. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  20951. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  20952. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  20953. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  20954. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  20955. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  20956. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  20957. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  20958. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  20959. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  20960. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  20961. };
  20962. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20963. var sprites = scene.__webglSprites,
  20964. nSprites = sprites.length;
  20965. if ( ! nSprites ) return;
  20966. var attributes = _sprite.attributes,
  20967. uniforms = _sprite.uniforms;
  20968. var invAspect = viewportHeight / viewportWidth;
  20969. var halfViewportWidth = viewportWidth * 0.5,
  20970. halfViewportHeight = viewportHeight * 0.5;
  20971. // setup gl
  20972. _gl.useProgram( _sprite.program );
  20973. _gl.enableVertexAttribArray( attributes.position );
  20974. _gl.enableVertexAttribArray( attributes.uv );
  20975. _gl.disable( _gl.CULL_FACE );
  20976. _gl.enable( _gl.BLEND );
  20977. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20978. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20979. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20980. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20981. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  20982. _gl.activeTexture( _gl.TEXTURE0 );
  20983. _gl.uniform1i( uniforms.map, 0 );
  20984. var oldFogType = 0;
  20985. var sceneFogType = 0;
  20986. var fog = scene.fog;
  20987. if ( fog ) {
  20988. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  20989. if ( fog instanceof THREE.Fog ) {
  20990. _gl.uniform1f( uniforms.fogNear, fog.near );
  20991. _gl.uniform1f( uniforms.fogFar, fog.far );
  20992. _gl.uniform1i( uniforms.fogType, 1 );
  20993. oldFogType = 1;
  20994. sceneFogType = 1;
  20995. } else if ( fog instanceof THREE.FogExp2 ) {
  20996. _gl.uniform1f( uniforms.fogDensity, fog.density );
  20997. _gl.uniform1i( uniforms.fogType, 2 );
  20998. oldFogType = 2;
  20999. sceneFogType = 2;
  21000. }
  21001. } else {
  21002. _gl.uniform1i( uniforms.fogType, 0 );
  21003. oldFogType = 0;
  21004. sceneFogType = 0;
  21005. }
  21006. // update positions and sort
  21007. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21008. for( i = 0; i < nSprites; i ++ ) {
  21009. sprite = sprites[ i ];
  21010. material = sprite.material;
  21011. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21012. if ( ! material.useScreenCoordinates ) {
  21013. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  21014. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21015. } else {
  21016. sprite.z = - sprite.position.z;
  21017. }
  21018. }
  21019. sprites.sort( painterSortStable );
  21020. // render all sprites
  21021. for( i = 0; i < nSprites; i ++ ) {
  21022. sprite = sprites[ i ];
  21023. material = sprite.material;
  21024. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21025. if ( material.map && material.map.image && material.map.image.width ) {
  21026. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21027. if ( material.useScreenCoordinates ) {
  21028. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21029. _gl.uniform3f(
  21030. uniforms.screenPosition,
  21031. ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21032. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21033. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21034. );
  21035. } else {
  21036. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21037. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21038. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21039. }
  21040. if ( scene.fog && material.fog ) {
  21041. fogType = sceneFogType;
  21042. } else {
  21043. fogType = 0;
  21044. }
  21045. if ( oldFogType !== fogType ) {
  21046. _gl.uniform1i( uniforms.fogType, fogType );
  21047. oldFogType = fogType;
  21048. }
  21049. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21050. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21051. scale[ 1 ] = size * sprite.scale.y;
  21052. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21053. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21054. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21055. _gl.uniform1f( uniforms.opacity, material.opacity );
  21056. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21057. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21058. _gl.uniform2fv( uniforms.scale, scale );
  21059. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21060. _renderer.setDepthTest( material.depthTest );
  21061. _renderer.setDepthWrite( material.depthWrite );
  21062. _renderer.setTexture( material.map, 0 );
  21063. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21064. }
  21065. }
  21066. // restore gl
  21067. _gl.enable( _gl.CULL_FACE );
  21068. };
  21069. function createProgram ( shader ) {
  21070. var program = _gl.createProgram();
  21071. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21072. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21073. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21074. _gl.shaderSource( vertexShader, shader.vertexShader );
  21075. _gl.compileShader( fragmentShader );
  21076. _gl.compileShader( vertexShader );
  21077. _gl.attachShader( program, fragmentShader );
  21078. _gl.attachShader( program, vertexShader );
  21079. _gl.linkProgram( program );
  21080. return program;
  21081. };
  21082. function painterSortStable ( a, b ) {
  21083. if ( a.z !== b.z ) {
  21084. return b.z - a.z;
  21085. } else {
  21086. return b.id - a.id;
  21087. }
  21088. };
  21089. };/**
  21090. * @author alteredq / http://alteredqualia.com/
  21091. */
  21092. THREE.DepthPassPlugin = function ( ) {
  21093. this.enabled = false;
  21094. this.renderTarget = null;
  21095. var _gl,
  21096. _renderer,
  21097. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21098. _frustum = new THREE.Frustum(),
  21099. _projScreenMatrix = new THREE.Matrix4();
  21100. this.init = function ( renderer ) {
  21101. _gl = renderer.context;
  21102. _renderer = renderer;
  21103. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21104. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21105. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21106. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21107. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21108. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21109. _depthMaterial._shadowPass = true;
  21110. _depthMaterialMorph._shadowPass = true;
  21111. _depthMaterialSkin._shadowPass = true;
  21112. _depthMaterialMorphSkin._shadowPass = true;
  21113. };
  21114. this.render = function ( scene, camera ) {
  21115. if ( ! this.enabled ) return;
  21116. this.update( scene, camera );
  21117. };
  21118. this.update = function ( scene, camera ) {
  21119. var i, il, j, jl, n,
  21120. program, buffer, material,
  21121. webglObject, object, light,
  21122. renderList,
  21123. fog = null;
  21124. // set GL state for depth map
  21125. _gl.clearColor( 1, 1, 1, 1 );
  21126. _gl.disable( _gl.BLEND );
  21127. _renderer.setDepthTest( true );
  21128. // update scene
  21129. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21130. // update camera matrices and frustum
  21131. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  21132. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  21133. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21134. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  21135. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  21136. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21137. _frustum.setFromMatrix( _projScreenMatrix );
  21138. // render depth map
  21139. _renderer.setRenderTarget( this.renderTarget );
  21140. _renderer.clear();
  21141. // set object matrices & frustum culling
  21142. renderList = scene.__webglObjects;
  21143. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21144. webglObject = renderList[ j ];
  21145. object = webglObject.object;
  21146. webglObject.render = false;
  21147. if ( object.visible ) {
  21148. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21149. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21150. webglObject.render = true;
  21151. }
  21152. }
  21153. }
  21154. // render regular objects
  21155. var objectMaterial, useMorphing, useSkinning;
  21156. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21157. webglObject = renderList[ j ];
  21158. if ( webglObject.render ) {
  21159. object = webglObject.object;
  21160. buffer = webglObject.buffer;
  21161. // todo: create proper depth material for particles
  21162. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21163. objectMaterial = getObjectMaterial( object );
  21164. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21165. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21166. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21167. if ( object.customDepthMaterial ) {
  21168. material = object.customDepthMaterial;
  21169. } else if ( useSkinning ) {
  21170. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21171. } else if ( useMorphing ) {
  21172. material = _depthMaterialMorph;
  21173. } else {
  21174. material = _depthMaterial;
  21175. }
  21176. if ( buffer instanceof THREE.BufferGeometry ) {
  21177. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21178. } else {
  21179. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21180. }
  21181. }
  21182. }
  21183. // set matrices and render immediate objects
  21184. renderList = scene.__webglObjectsImmediate;
  21185. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21186. webglObject = renderList[ j ];
  21187. object = webglObject.object;
  21188. if ( object.visible ) {
  21189. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21190. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21191. }
  21192. }
  21193. // restore GL state
  21194. var clearColor = _renderer.getClearColor(),
  21195. clearAlpha = _renderer.getClearAlpha();
  21196. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21197. _gl.enable( _gl.BLEND );
  21198. };
  21199. // For the moment just ignore objects that have multiple materials with different animation methods
  21200. // Only the first material will be taken into account for deciding which depth material to use
  21201. function getObjectMaterial( object ) {
  21202. return object.material instanceof THREE.MeshFaceMaterial
  21203. ? object.material.materials[ 0 ]
  21204. : object.material;
  21205. };
  21206. };
  21207. /**
  21208. * @author mikael emtinger / http://gomo.se/
  21209. *
  21210. */
  21211. THREE.ShaderFlares = {
  21212. 'lensFlareVertexTexture': {
  21213. vertexShader: [
  21214. "uniform vec3 screenPosition;",
  21215. "uniform vec2 scale;",
  21216. "uniform float rotation;",
  21217. "uniform int renderType;",
  21218. "uniform sampler2D occlusionMap;",
  21219. "attribute vec2 position;",
  21220. "attribute vec2 uv;",
  21221. "varying vec2 vUV;",
  21222. "varying float vVisibility;",
  21223. "void main() {",
  21224. "vUV = uv;",
  21225. "vec2 pos = position;",
  21226. "if( renderType == 2 ) {",
  21227. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21228. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21229. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21230. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21231. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21232. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21233. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21234. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21235. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21236. "vVisibility = ( visibility.r / 9.0 ) *",
  21237. "( 1.0 - visibility.g / 9.0 ) *",
  21238. "( visibility.b / 9.0 ) *",
  21239. "( 1.0 - visibility.a / 9.0 );",
  21240. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21241. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21242. "}",
  21243. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21244. "}"
  21245. ].join( "\n" ),
  21246. fragmentShader: [
  21247. "precision mediump float;",
  21248. "uniform sampler2D map;",
  21249. "uniform float opacity;",
  21250. "uniform int renderType;",
  21251. "uniform vec3 color;",
  21252. "varying vec2 vUV;",
  21253. "varying float vVisibility;",
  21254. "void main() {",
  21255. // pink square
  21256. "if( renderType == 0 ) {",
  21257. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21258. // restore
  21259. "} else if( renderType == 1 ) {",
  21260. "gl_FragColor = texture2D( map, vUV );",
  21261. // flare
  21262. "} else {",
  21263. "vec4 texture = texture2D( map, vUV );",
  21264. "texture.a *= opacity * vVisibility;",
  21265. "gl_FragColor = texture;",
  21266. "gl_FragColor.rgb *= color;",
  21267. "}",
  21268. "}"
  21269. ].join( "\n" )
  21270. },
  21271. 'lensFlare': {
  21272. vertexShader: [
  21273. "uniform vec3 screenPosition;",
  21274. "uniform vec2 scale;",
  21275. "uniform float rotation;",
  21276. "uniform int renderType;",
  21277. "attribute vec2 position;",
  21278. "attribute vec2 uv;",
  21279. "varying vec2 vUV;",
  21280. "void main() {",
  21281. "vUV = uv;",
  21282. "vec2 pos = position;",
  21283. "if( renderType == 2 ) {",
  21284. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21285. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21286. "}",
  21287. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21288. "}"
  21289. ].join( "\n" ),
  21290. fragmentShader: [
  21291. "precision mediump float;",
  21292. "uniform sampler2D map;",
  21293. "uniform sampler2D occlusionMap;",
  21294. "uniform float opacity;",
  21295. "uniform int renderType;",
  21296. "uniform vec3 color;",
  21297. "varying vec2 vUV;",
  21298. "void main() {",
  21299. // pink square
  21300. "if( renderType == 0 ) {",
  21301. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21302. // restore
  21303. "} else if( renderType == 1 ) {",
  21304. "gl_FragColor = texture2D( map, vUV );",
  21305. // flare
  21306. "} else {",
  21307. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21308. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21309. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21310. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21311. "visibility = ( 1.0 - visibility / 4.0 );",
  21312. "vec4 texture = texture2D( map, vUV );",
  21313. "texture.a *= opacity * visibility;",
  21314. "gl_FragColor = texture;",
  21315. "gl_FragColor.rgb *= color;",
  21316. "}",
  21317. "}"
  21318. ].join( "\n" )
  21319. }
  21320. };
  21321. /**
  21322. * @author mikael emtinger / http://gomo.se/
  21323. * @author alteredq / http://alteredqualia.com/
  21324. *
  21325. */
  21326. THREE.ShaderSprite = {
  21327. 'sprite': {
  21328. vertexShader: [
  21329. "uniform int useScreenCoordinates;",
  21330. "uniform int sizeAttenuation;",
  21331. "uniform vec3 screenPosition;",
  21332. "uniform mat4 modelViewMatrix;",
  21333. "uniform mat4 projectionMatrix;",
  21334. "uniform float rotation;",
  21335. "uniform vec2 scale;",
  21336. "uniform vec2 alignment;",
  21337. "uniform vec2 uvOffset;",
  21338. "uniform vec2 uvScale;",
  21339. "attribute vec2 position;",
  21340. "attribute vec2 uv;",
  21341. "varying vec2 vUV;",
  21342. "void main() {",
  21343. "vUV = uvOffset + uv * uvScale;",
  21344. "vec2 alignedPosition = position + alignment;",
  21345. "vec2 rotatedPosition;",
  21346. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21347. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21348. "vec4 finalPosition;",
  21349. "if( useScreenCoordinates != 0 ) {",
  21350. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21351. "} else {",
  21352. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21353. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21354. "}",
  21355. "gl_Position = finalPosition;",
  21356. "}"
  21357. ].join( "\n" ),
  21358. fragmentShader: [
  21359. "precision mediump float;",
  21360. "uniform vec3 color;",
  21361. "uniform sampler2D map;",
  21362. "uniform float opacity;",
  21363. "uniform int fogType;",
  21364. "uniform vec3 fogColor;",
  21365. "uniform float fogDensity;",
  21366. "uniform float fogNear;",
  21367. "uniform float fogFar;",
  21368. "uniform float alphaTest;",
  21369. "varying vec2 vUV;",
  21370. "void main() {",
  21371. "vec4 texture = texture2D( map, vUV );",
  21372. "if ( texture.a < alphaTest ) discard;",
  21373. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21374. "if ( fogType > 0 ) {",
  21375. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21376. "float fogFactor = 0.0;",
  21377. "if ( fogType == 1 ) {",
  21378. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21379. "} else {",
  21380. "const float LOG2 = 1.442695;",
  21381. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21382. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21383. "}",
  21384. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21385. "}",
  21386. "}"
  21387. ].join( "\n" )
  21388. }
  21389. };
粤ICP备19079148号