three.js 819 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '55dev' };
  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. // GL STATE CONSTANTS
  53. THREE.CullFaceNone = 0;
  54. THREE.CullFaceBack = 1;
  55. THREE.CullFaceFront = 2;
  56. THREE.CullFaceFrontBack = 3;
  57. THREE.FrontFaceDirectionCW = 0;
  58. THREE.FrontFaceDirectionCCW = 1;
  59. // SHADOWING TYPES
  60. THREE.BasicShadowMap = 0;
  61. THREE.PCFShadowMap = 1;
  62. THREE.PCFSoftShadowMap = 2;
  63. // MATERIAL CONSTANTS
  64. // side
  65. THREE.FrontSide = 0;
  66. THREE.BackSide = 1;
  67. THREE.DoubleSide = 2;
  68. // shading
  69. THREE.NoShading = 0;
  70. THREE.FlatShading = 1;
  71. THREE.SmoothShading = 2;
  72. // colors
  73. THREE.NoColors = 0;
  74. THREE.FaceColors = 1;
  75. THREE.VertexColors = 2;
  76. // blending modes
  77. THREE.NoBlending = 0;
  78. THREE.NormalBlending = 1;
  79. THREE.AdditiveBlending = 2;
  80. THREE.SubtractiveBlending = 3;
  81. THREE.MultiplyBlending = 4;
  82. THREE.CustomBlending = 5;
  83. // custom blending equations
  84. // (numbers start from 100 not to clash with other
  85. // mappings to OpenGL constants defined in Texture.js)
  86. THREE.AddEquation = 100;
  87. THREE.SubtractEquation = 101;
  88. THREE.ReverseSubtractEquation = 102;
  89. // custom blending destination factors
  90. THREE.ZeroFactor = 200;
  91. THREE.OneFactor = 201;
  92. THREE.SrcColorFactor = 202;
  93. THREE.OneMinusSrcColorFactor = 203;
  94. THREE.SrcAlphaFactor = 204;
  95. THREE.OneMinusSrcAlphaFactor = 205;
  96. THREE.DstAlphaFactor = 206;
  97. THREE.OneMinusDstAlphaFactor = 207;
  98. // custom blending source factors
  99. //THREE.ZeroFactor = 200;
  100. //THREE.OneFactor = 201;
  101. //THREE.SrcAlphaFactor = 204;
  102. //THREE.OneMinusSrcAlphaFactor = 205;
  103. //THREE.DstAlphaFactor = 206;
  104. //THREE.OneMinusDstAlphaFactor = 207;
  105. THREE.DstColorFactor = 208;
  106. THREE.OneMinusDstColorFactor = 209;
  107. THREE.SrcAlphaSaturateFactor = 210;
  108. // TEXTURE CONSTANTS
  109. THREE.MultiplyOperation = 0;
  110. THREE.MixOperation = 1;
  111. THREE.AddOperation = 2;
  112. // Mapping modes
  113. THREE.UVMapping = function () {};
  114. THREE.CubeReflectionMapping = function () {};
  115. THREE.CubeRefractionMapping = function () {};
  116. THREE.SphericalReflectionMapping = function () {};
  117. THREE.SphericalRefractionMapping = function () {};
  118. // Wrapping modes
  119. THREE.RepeatWrapping = 1000;
  120. THREE.ClampToEdgeWrapping = 1001;
  121. THREE.MirroredRepeatWrapping = 1002;
  122. // Filters
  123. THREE.NearestFilter = 1003;
  124. THREE.NearestMipMapNearestFilter = 1004;
  125. THREE.NearestMipMapLinearFilter = 1005;
  126. THREE.LinearFilter = 1006;
  127. THREE.LinearMipMapNearestFilter = 1007;
  128. THREE.LinearMipMapLinearFilter = 1008;
  129. // Data types
  130. THREE.UnsignedByteType = 1009;
  131. THREE.ByteType = 1010;
  132. THREE.ShortType = 1011;
  133. THREE.UnsignedShortType = 1012;
  134. THREE.IntType = 1013;
  135. THREE.UnsignedIntType = 1014;
  136. THREE.FloatType = 1015;
  137. // Pixel types
  138. //THREE.UnsignedByteType = 1009;
  139. THREE.UnsignedShort4444Type = 1016;
  140. THREE.UnsignedShort5551Type = 1017;
  141. THREE.UnsignedShort565Type = 1018;
  142. // Pixel formats
  143. THREE.AlphaFormat = 1019;
  144. THREE.RGBFormat = 1020;
  145. THREE.RGBAFormat = 1021;
  146. THREE.LuminanceFormat = 1022;
  147. THREE.LuminanceAlphaFormat = 1023;
  148. // Compressed texture formats
  149. THREE.RGB_S3TC_DXT1_Format = 2001;
  150. THREE.RGBA_S3TC_DXT1_Format = 2002;
  151. THREE.RGBA_S3TC_DXT3_Format = 2003;
  152. THREE.RGBA_S3TC_DXT5_Format = 2004;
  153. /*
  154. // Potential future PVRTC compressed texture formats
  155. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  156. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  157. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  158. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  159. */
  160. /**
  161. * @author mrdoob / http://mrdoob.com/
  162. */
  163. THREE.Color = function ( value ) {
  164. if ( value !== undefined ) this.set( value );
  165. return this;
  166. };
  167. THREE.Color.prototype = {
  168. constructor: THREE.Color,
  169. r: 1, g: 1, b: 1,
  170. set: function ( value ) {
  171. switch ( typeof value ) {
  172. case "number":
  173. this.setHex( value );
  174. break;
  175. case "string":
  176. this.setStyle( value );
  177. break;
  178. }
  179. },
  180. setHex: function ( hex ) {
  181. hex = Math.floor( hex );
  182. this.r = ( hex >> 16 & 255 ) / 255;
  183. this.g = ( hex >> 8 & 255 ) / 255;
  184. this.b = ( hex & 255 ) / 255;
  185. return this;
  186. },
  187. setRGB: function ( r, g, b ) {
  188. this.r = r;
  189. this.g = g;
  190. this.b = b;
  191. return this;
  192. },
  193. setHSV: function ( h, s, v ) {
  194. // based on MochiKit implementation by Bob Ippolito
  195. // h,s,v ranges are < 0.0 - 1.0 >
  196. var i, f, p, q, t;
  197. if ( v === 0 ) {
  198. this.r = this.g = this.b = 0;
  199. } else {
  200. i = Math.floor( h * 6 );
  201. f = ( h * 6 ) - i;
  202. p = v * ( 1 - s );
  203. q = v * ( 1 - ( s * f ) );
  204. t = v * ( 1 - ( s * ( 1 - f ) ) );
  205. if ( i === 0 ) {
  206. this.r = v;
  207. this.g = t;
  208. this.b = p;
  209. } else if ( i === 1 ) {
  210. this.r = q;
  211. this.g = v;
  212. this.b = p;
  213. } else if ( i === 2 ) {
  214. this.r = p;
  215. this.g = v;
  216. this.b = t;
  217. } else if ( i === 3 ) {
  218. this.r = p;
  219. this.g = q;
  220. this.b = v;
  221. } else if ( i === 4 ) {
  222. this.r = t;
  223. this.g = p;
  224. this.b = v;
  225. } else if ( i === 5 ) {
  226. this.r = v;
  227. this.g = p;
  228. this.b = q;
  229. }
  230. }
  231. return this;
  232. },
  233. setStyle: function ( style ) {
  234. // rgb(255,0,0)
  235. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  236. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  237. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  238. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  239. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  240. return this;
  241. }
  242. // rgb(100%,0%,0%)
  243. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  244. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  245. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  246. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  247. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  248. return this;
  249. }
  250. // #ff0000
  251. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  252. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  253. this.setHex( parseInt( color[ 1 ], 16 ) );
  254. return this;
  255. }
  256. // #f00
  257. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  258. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  259. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  260. return this;
  261. }
  262. // red
  263. if ( /^(\w+)$/i.test( style ) ) {
  264. this.setHex( THREE.ColorKeywords[ style ] );
  265. return this;
  266. }
  267. },
  268. copy: function ( color ) {
  269. this.r = color.r;
  270. this.g = color.g;
  271. this.b = color.b;
  272. return this;
  273. },
  274. copyGammaToLinear: function ( color ) {
  275. this.r = color.r * color.r;
  276. this.g = color.g * color.g;
  277. this.b = color.b * color.b;
  278. return this;
  279. },
  280. copyLinearToGamma: function ( color ) {
  281. this.r = Math.sqrt( color.r );
  282. this.g = Math.sqrt( color.g );
  283. this.b = Math.sqrt( color.b );
  284. return this;
  285. },
  286. convertGammaToLinear: function () {
  287. var r = this.r, g = this.g, b = this.b;
  288. this.r = r * r;
  289. this.g = g * g;
  290. this.b = b * b;
  291. return this;
  292. },
  293. convertLinearToGamma: function () {
  294. this.r = Math.sqrt( this.r );
  295. this.g = Math.sqrt( this.g );
  296. this.b = Math.sqrt( this.b );
  297. return this;
  298. },
  299. getHex: function () {
  300. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  301. },
  302. getHexString: function () {
  303. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  304. },
  305. getStyle: function () {
  306. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  307. },
  308. getHSV: function ( hsv ) {
  309. // based on MochiKit implementation by Bob Ippolito
  310. // h,s,v ranges are < 0.0 - 1.0 >
  311. var r = this.r;
  312. var g = this.g;
  313. var b = this.b;
  314. var max = Math.max( Math.max( r, g ), b );
  315. var min = Math.min( Math.min( r, g ), b );
  316. var hue;
  317. var saturation;
  318. var value = max;
  319. if ( min === max ) {
  320. hue = 0;
  321. saturation = 0;
  322. } else {
  323. var delta = ( max - min );
  324. saturation = delta / max;
  325. if ( r === max ) {
  326. hue = ( g - b ) / delta;
  327. } else if ( g === max ) {
  328. hue = 2 + ( ( b - r ) / delta );
  329. } else {
  330. hue = 4 + ( ( r - g ) / delta );
  331. }
  332. hue /= 6;
  333. if ( hue < 0 ) {
  334. hue += 1;
  335. }
  336. if ( hue > 1 ) {
  337. hue -= 1;
  338. }
  339. }
  340. if ( hsv === undefined ) {
  341. hsv = { h: 0, s: 0, v: 0 };
  342. }
  343. hsv.h = hue;
  344. hsv.s = saturation;
  345. hsv.v = value;
  346. return hsv;
  347. },
  348. add: function ( color ) {
  349. this.r += color.r;
  350. this.g += color.g;
  351. this.b += color.b;
  352. return this;
  353. },
  354. addColors: function ( color1, color2 ) {
  355. this.r = color1.r + color2.r;
  356. this.g = color1.g + color2.g;
  357. this.b = color1.b + color2.b;
  358. return this;
  359. },
  360. addScalar: function ( s ) {
  361. this.r += s;
  362. this.g += s;
  363. this.b += s;
  364. return this;
  365. },
  366. multiply: function ( color ) {
  367. this.r *= color.r;
  368. this.g *= color.g;
  369. this.b *= color.b;
  370. return this;
  371. },
  372. multiplyScalar: function ( s ) {
  373. this.r *= s;
  374. this.g *= s;
  375. this.b *= s;
  376. return this;
  377. },
  378. lerp: function ( color, alpha ) {
  379. this.r += ( color.r - this.r ) * alpha;
  380. this.g += ( color.g - this.g ) * alpha;
  381. this.b += ( color.b - this.b ) * alpha;
  382. return this;
  383. },
  384. clone: function () {
  385. return new THREE.Color().setRGB( this.r, this.g, this.b );
  386. }
  387. };
  388. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  389. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  390. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  391. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  392. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  393. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  394. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  395. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  396. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  397. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  398. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  399. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  400. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  401. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  402. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  403. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  404. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  405. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  406. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  407. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  408. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  409. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  410. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  411. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  412. /**
  413. * @author mrdoob / http://mrdoob.com/
  414. * @author philogb / http://blog.thejit.org/
  415. * @author egraether / http://egraether.com/
  416. * @author zz85 / http://www.lab4games.net/zz85/blog
  417. */
  418. THREE.Vector2 = function ( x, y ) {
  419. this.x = x || 0;
  420. this.y = y || 0;
  421. };
  422. THREE.Vector2.prototype = {
  423. constructor: THREE.Vector2,
  424. set: function ( x, y ) {
  425. this.x = x;
  426. this.y = y;
  427. return this;
  428. },
  429. setX: function ( x ) {
  430. this.x = x;
  431. return this;
  432. },
  433. setY: function ( y ) {
  434. this.y = y;
  435. return this;
  436. },
  437. setComponent: function ( index, value ) {
  438. switch ( index ) {
  439. case 0: this.x = value; break;
  440. case 1: this.y = value; break;
  441. default: throw new Error( "index is out of range: " + index );
  442. }
  443. },
  444. getComponent: function ( index ) {
  445. switch ( index ) {
  446. case 0: return this.x;
  447. case 1: return this.y;
  448. default: throw new Error( "index is out of range: " + index );
  449. }
  450. },
  451. copy: function ( v ) {
  452. this.x = v.x;
  453. this.y = v.y;
  454. return this;
  455. },
  456. add: function ( v ) {
  457. this.x += v.x;
  458. this.y += v.y;
  459. return this;
  460. },
  461. addVectors: function ( a, b ) {
  462. this.x = a.x + b.x;
  463. this.y = a.y + b.y;
  464. return this;
  465. },
  466. addScalar: function ( s ) {
  467. this.x += s;
  468. this.y += s;
  469. return this;
  470. },
  471. sub: function ( v ) {
  472. this.x -= v.x;
  473. this.y -= v.y;
  474. return this;
  475. },
  476. subVectors: function ( a, b ) {
  477. this.x = a.x - b.x;
  478. this.y = a.y - b.y;
  479. return this;
  480. },
  481. multiplyScalar: function ( s ) {
  482. this.x *= s;
  483. this.y *= s;
  484. return this;
  485. },
  486. divideScalar: function ( s ) {
  487. if ( s !== 0 ) {
  488. this.x /= s;
  489. this.y /= s;
  490. } else {
  491. this.set( 0, 0 );
  492. }
  493. return this;
  494. },
  495. min: function ( v ) {
  496. if ( this.x > v.x ) {
  497. this.x = v.x;
  498. }
  499. if ( this.y > v.y ) {
  500. this.y = v.y;
  501. }
  502. return this;
  503. },
  504. max: function ( v ) {
  505. if ( this.x < v.x ) {
  506. this.x = v.x;
  507. }
  508. if ( this.y < v.y ) {
  509. this.y = v.y;
  510. }
  511. return this;
  512. },
  513. clamp: function ( min, max ) {
  514. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  515. if ( this.x < min.x ) {
  516. this.x = min.x;
  517. } else if ( this.x > max.x ) {
  518. this.x = max.x;
  519. }
  520. if ( this.y < min.y ) {
  521. this.y = min.y;
  522. } else if ( this.y > max.y ) {
  523. this.y = max.y;
  524. }
  525. return this;
  526. },
  527. negate: function() {
  528. return this.multiplyScalar( - 1 );
  529. },
  530. dot: function ( v ) {
  531. return this.x * v.x + this.y * v.y;
  532. },
  533. lengthSq: function () {
  534. return this.x * this.x + this.y * this.y;
  535. },
  536. length: function () {
  537. return Math.sqrt( this.x * this.x + this.y * this.y );
  538. },
  539. normalize: function () {
  540. return this.divideScalar( this.length() );
  541. },
  542. distanceTo: function ( v ) {
  543. return Math.sqrt( this.distanceToSquared( v ) );
  544. },
  545. distanceToSquared: function ( v ) {
  546. var dx = this.x - v.x, dy = this.y - v.y;
  547. return dx * dx + dy * dy;
  548. },
  549. setLength: function ( l ) {
  550. var oldLength = this.length();
  551. if ( oldLength !== 0 && l !== oldLength ) {
  552. this.multiplyScalar( l / oldLength );
  553. }
  554. return this;
  555. },
  556. lerp: function ( v, alpha ) {
  557. this.x += ( v.x - this.x ) * alpha;
  558. this.y += ( v.y - this.y ) * alpha;
  559. return this;
  560. },
  561. equals: function( v ) {
  562. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  563. },
  564. clone: function () {
  565. return new THREE.Vector2( this.x, this.y );
  566. }
  567. };
  568. /**
  569. * @author mrdoob / http://mrdoob.com/
  570. * @author *kile / http://kile.stravaganza.org/
  571. * @author philogb / http://blog.thejit.org/
  572. * @author mikael emtinger / http://gomo.se/
  573. * @author egraether / http://egraether.com/
  574. * @author WestLangley / http://github.com/WestLangley
  575. */
  576. THREE.Vector3 = function ( x, y, z ) {
  577. this.x = x || 0;
  578. this.y = y || 0;
  579. this.z = z || 0;
  580. };
  581. THREE.Vector3.prototype = {
  582. constructor: THREE.Vector3,
  583. set: function ( x, y, z ) {
  584. this.x = x;
  585. this.y = y;
  586. this.z = z;
  587. return this;
  588. },
  589. setX: function ( x ) {
  590. this.x = x;
  591. return this;
  592. },
  593. setY: function ( y ) {
  594. this.y = y;
  595. return this;
  596. },
  597. setZ: function ( z ) {
  598. this.z = z;
  599. return this;
  600. },
  601. setComponent: function ( index, value ) {
  602. switch ( index ) {
  603. case 0: this.x = value; break;
  604. case 1: this.y = value; break;
  605. case 2: this.z = value; break;
  606. default: throw new Error( "index is out of range: " + index );
  607. }
  608. },
  609. getComponent: function ( index ) {
  610. switch ( index ) {
  611. case 0: return this.x;
  612. case 1: return this.y;
  613. case 2: return this.z;
  614. default: throw new Error( "index is out of range: " + index );
  615. }
  616. },
  617. copy: function ( v ) {
  618. this.x = v.x;
  619. this.y = v.y;
  620. this.z = v.z;
  621. return this;
  622. },
  623. add: function ( v ) {
  624. this.x += v.x;
  625. this.y += v.y;
  626. this.z += v.z;
  627. return this;
  628. },
  629. addScalar: function ( s ) {
  630. this.x += s;
  631. this.y += s;
  632. this.z += s;
  633. return this;
  634. },
  635. addVectors: function ( a, b ) {
  636. this.x = a.x + b.x;
  637. this.y = a.y + b.y;
  638. this.z = a.z + b.z;
  639. return this;
  640. },
  641. sub: function ( v ) {
  642. this.x -= v.x;
  643. this.y -= v.y;
  644. this.z -= v.z;
  645. return this;
  646. },
  647. subVectors: function ( a, b ) {
  648. this.x = a.x - b.x;
  649. this.y = a.y - b.y;
  650. this.z = a.z - b.z;
  651. return this;
  652. },
  653. multiply: function ( v ) {
  654. this.x *= v.x;
  655. this.y *= v.y;
  656. this.z *= v.z;
  657. return this;
  658. },
  659. multiplyScalar: function ( s ) {
  660. this.x *= s;
  661. this.y *= s;
  662. this.z *= s;
  663. return this;
  664. },
  665. multiplyVectors: function ( a, b ) {
  666. this.x = a.x * b.x;
  667. this.y = a.y * b.y;
  668. this.z = a.z * b.z;
  669. return this;
  670. },
  671. applyMatrix3: function ( m ) {
  672. var x = this.x;
  673. var y = this.y;
  674. var z = this.z;
  675. var e = m.elements;
  676. this.x = e[0] * x + e[3] * y + e[6] * z;
  677. this.y = e[1] * x + e[4] * y + e[7] * z;
  678. this.z = e[2] * x + e[5] * y + e[8] * z;
  679. return this;
  680. },
  681. applyMatrix4: function ( m ) {
  682. var x = this.x;
  683. var y = this.y;
  684. var z = this.z;
  685. var e = m.elements;
  686. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] );
  687. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  688. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  689. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  690. return this;
  691. },
  692. applyQuaternion: function ( q ) {
  693. var x = this.x;
  694. var y = this.y;
  695. var z = this.z;
  696. var qx = q.x;
  697. var qy = q.y;
  698. var qz = q.z;
  699. var qw = q.w;
  700. // calculate quat * vector
  701. var ix = qw * x + qy * z - qz * y;
  702. var iy = qw * y + qz * x - qx * z;
  703. var iz = qw * z + qx * y - qy * x;
  704. var iw = -qx * x - qy * y - qz * z;
  705. // calculate result * inverse quat
  706. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  707. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  708. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  709. return this;
  710. },
  711. divide: function ( v ) {
  712. this.x /= v.x;
  713. this.y /= v.y;
  714. this.z /= v.z;
  715. return this;
  716. },
  717. divideScalar: function ( s ) {
  718. if ( s !== 0 ) {
  719. this.x /= s;
  720. this.y /= s;
  721. this.z /= s;
  722. } else {
  723. this.x = 0;
  724. this.y = 0;
  725. this.z = 0;
  726. }
  727. return this;
  728. },
  729. min: function ( v ) {
  730. if ( this.x > v.x ) {
  731. this.x = v.x;
  732. }
  733. if ( this.y > v.y ) {
  734. this.y = v.y;
  735. }
  736. if ( this.z > v.z ) {
  737. this.z = v.z;
  738. }
  739. return this;
  740. },
  741. max: function ( v ) {
  742. if ( this.x < v.x ) {
  743. this.x = v.x;
  744. }
  745. if ( this.y < v.y ) {
  746. this.y = v.y;
  747. }
  748. if ( this.z < v.z ) {
  749. this.z = v.z;
  750. }
  751. return this;
  752. },
  753. clamp: function ( min, max ) {
  754. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  755. if ( this.x < min.x ) {
  756. this.x = min.x;
  757. } else if ( this.x > max.x ) {
  758. this.x = max.x;
  759. }
  760. if ( this.y < min.y ) {
  761. this.y = min.y;
  762. } else if ( this.y > max.y ) {
  763. this.y = max.y;
  764. }
  765. if ( this.z < min.z ) {
  766. this.z = min.z;
  767. } else if ( this.z > max.z ) {
  768. this.z = max.z;
  769. }
  770. return this;
  771. },
  772. negate: function() {
  773. return this.multiplyScalar( - 1 );
  774. },
  775. dot: function ( v ) {
  776. return this.x * v.x + this.y * v.y + this.z * v.z;
  777. },
  778. lengthSq: function () {
  779. return this.x * this.x + this.y * this.y + this.z * this.z;
  780. },
  781. length: function () {
  782. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  783. },
  784. lengthManhattan: function () {
  785. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  786. },
  787. normalize: function () {
  788. return this.divideScalar( this.length() );
  789. },
  790. setLength: function ( l ) {
  791. var oldLength = this.length();
  792. if ( oldLength !== 0 && l !== oldLength ) {
  793. this.multiplyScalar( l / oldLength );
  794. }
  795. return this;
  796. },
  797. lerp: function ( v, alpha ) {
  798. this.x += ( v.x - this.x ) * alpha;
  799. this.y += ( v.y - this.y ) * alpha;
  800. this.z += ( v.z - this.z ) * alpha;
  801. return this;
  802. },
  803. cross: function ( v ) {
  804. var x = this.x, y = this.y, z = this.z;
  805. this.x = y * v.z - z * v.y;
  806. this.y = z * v.x - x * v.z;
  807. this.z = x * v.y - y * v.x;
  808. return this;
  809. },
  810. crossVectors: function ( a, b ) {
  811. this.x = a.y * b.z - a.z * b.y;
  812. this.y = a.z * b.x - a.x * b.z;
  813. this.z = a.x * b.y - a.y * b.x;
  814. return this;
  815. },
  816. angleTo: function ( v ) {
  817. return Math.acos( this.dot( v ) / this.length() / v.length() );
  818. },
  819. distanceTo: function ( v ) {
  820. return Math.sqrt( this.distanceToSquared( v ) );
  821. },
  822. distanceToSquared: function ( v ) {
  823. var dx = this.x - v.x;
  824. var dy = this.y - v.y;
  825. var dz = this.z - v.z;
  826. return dx * dx + dy * dy + dz * dz;
  827. },
  828. getPositionFromMatrix: function ( m ) {
  829. this.x = m.elements[12];
  830. this.y = m.elements[13];
  831. this.z = m.elements[14];
  832. return this;
  833. },
  834. setEulerFromRotationMatrix: function ( m, order ) {
  835. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  836. // clamp, to handle numerical problems
  837. function clamp( x ) {
  838. return Math.min( Math.max( x, -1 ), 1 );
  839. }
  840. var te = m.elements;
  841. var m11 = te[0], m12 = te[4], m13 = te[8];
  842. var m21 = te[1], m22 = te[5], m23 = te[9];
  843. var m31 = te[2], m32 = te[6], m33 = te[10];
  844. if ( order === undefined || order === 'XYZ' ) {
  845. this.y = Math.asin( clamp( m13 ) );
  846. if ( Math.abs( m13 ) < 0.99999 ) {
  847. this.x = Math.atan2( - m23, m33 );
  848. this.z = Math.atan2( - m12, m11 );
  849. } else {
  850. this.x = Math.atan2( m32, m22 );
  851. this.z = 0;
  852. }
  853. } else if ( order === 'YXZ' ) {
  854. this.x = Math.asin( - clamp( m23 ) );
  855. if ( Math.abs( m23 ) < 0.99999 ) {
  856. this.y = Math.atan2( m13, m33 );
  857. this.z = Math.atan2( m21, m22 );
  858. } else {
  859. this.y = Math.atan2( - m31, m11 );
  860. this.z = 0;
  861. }
  862. } else if ( order === 'ZXY' ) {
  863. this.x = Math.asin( clamp( m32 ) );
  864. if ( Math.abs( m32 ) < 0.99999 ) {
  865. this.y = Math.atan2( - m31, m33 );
  866. this.z = Math.atan2( - m12, m22 );
  867. } else {
  868. this.y = 0;
  869. this.z = Math.atan2( m21, m11 );
  870. }
  871. } else if ( order === 'ZYX' ) {
  872. this.y = Math.asin( - clamp( m31 ) );
  873. if ( Math.abs( m31 ) < 0.99999 ) {
  874. this.x = Math.atan2( m32, m33 );
  875. this.z = Math.atan2( m21, m11 );
  876. } else {
  877. this.x = 0;
  878. this.z = Math.atan2( - m12, m22 );
  879. }
  880. } else if ( order === 'YZX' ) {
  881. this.z = Math.asin( clamp( m21 ) );
  882. if ( Math.abs( m21 ) < 0.99999 ) {
  883. this.x = Math.atan2( - m23, m22 );
  884. this.y = Math.atan2( - m31, m11 );
  885. } else {
  886. this.x = 0;
  887. this.y = Math.atan2( m13, m33 );
  888. }
  889. } else if ( order === 'XZY' ) {
  890. this.z = Math.asin( - clamp( m12 ) );
  891. if ( Math.abs( m12 ) < 0.99999 ) {
  892. this.x = Math.atan2( m32, m22 );
  893. this.y = Math.atan2( m13, m11 );
  894. } else {
  895. this.x = Math.atan2( - m23, m33 );
  896. this.y = 0;
  897. }
  898. }
  899. return this;
  900. },
  901. setEulerFromQuaternion: function ( q, order ) {
  902. // q is assumed to be normalized
  903. // clamp, to handle numerical problems
  904. function clamp( x ) {
  905. return Math.min( Math.max( x, -1 ), 1 );
  906. }
  907. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  908. var sqx = q.x * q.x;
  909. var sqy = q.y * q.y;
  910. var sqz = q.z * q.z;
  911. var sqw = q.w * q.w;
  912. if ( order === undefined || order === 'XYZ' ) {
  913. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  914. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  915. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  916. } else if ( order === 'YXZ' ) {
  917. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  918. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  919. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  920. } else if ( order === 'ZXY' ) {
  921. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  922. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  923. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  924. } else if ( order === 'ZYX' ) {
  925. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  926. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  927. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  928. } else if ( order === 'YZX' ) {
  929. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  930. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  931. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  932. } else if ( order === 'XZY' ) {
  933. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  934. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  935. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  936. }
  937. return this;
  938. },
  939. getScaleFromMatrix: function ( m ) {
  940. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  941. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  942. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  943. this.x = sx;
  944. this.y = sy;
  945. this.z = sz;
  946. return this;
  947. },
  948. equals: function ( v ) {
  949. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  950. },
  951. clone: function () {
  952. return new THREE.Vector3( this.x, this.y, this.z );
  953. }
  954. };
  955. /**
  956. * @author supereggbert / http://www.paulbrunt.co.uk/
  957. * @author philogb / http://blog.thejit.org/
  958. * @author mikael emtinger / http://gomo.se/
  959. * @author egraether / http://egraether.com/
  960. * @author WestLangley / http://github.com/WestLangley
  961. */
  962. THREE.Vector4 = function ( x, y, z, w ) {
  963. this.x = x || 0;
  964. this.y = y || 0;
  965. this.z = z || 0;
  966. this.w = ( w !== undefined ) ? w : 1;
  967. };
  968. THREE.Vector4.prototype = {
  969. constructor: THREE.Vector4,
  970. set: function ( x, y, z, w ) {
  971. this.x = x;
  972. this.y = y;
  973. this.z = z;
  974. this.w = w;
  975. return this;
  976. },
  977. setX: function ( x ) {
  978. this.x = x;
  979. return this;
  980. },
  981. setY: function ( y ) {
  982. this.y = y;
  983. return this;
  984. },
  985. setZ: function ( z ) {
  986. this.z = z;
  987. return this;
  988. },
  989. setW: function ( w ) {
  990. this.w = w;
  991. return this;
  992. },
  993. setComponent: function ( index, value ) {
  994. switch ( index ) {
  995. case 0: this.x = value; break;
  996. case 1: this.y = value; break;
  997. case 2: this.z = value; break;
  998. case 3: this.w = value; break;
  999. default: throw new Error( "index is out of range: " + index );
  1000. }
  1001. },
  1002. getComponent: function ( index ) {
  1003. switch ( index ) {
  1004. case 0: return this.x;
  1005. case 1: return this.y;
  1006. case 2: return this.z;
  1007. case 3: return this.w;
  1008. default: throw new Error( "index is out of range: " + index );
  1009. }
  1010. },
  1011. copy: function ( v ) {
  1012. this.x = v.x;
  1013. this.y = v.y;
  1014. this.z = v.z;
  1015. this.w = ( v.w !== undefined ) ? v.w : 1;
  1016. return this;
  1017. },
  1018. add: function ( v ) {
  1019. this.x += v.x;
  1020. this.y += v.y;
  1021. this.z += v.z;
  1022. this.w += v.w;
  1023. return this;
  1024. },
  1025. addScalar: function ( s ) {
  1026. this.x += s;
  1027. this.y += s;
  1028. this.z += s;
  1029. this.w += s;
  1030. return this;
  1031. },
  1032. addVectors: function ( a, b ) {
  1033. this.x = a.x + b.x;
  1034. this.y = a.y + b.y;
  1035. this.z = a.z + b.z;
  1036. this.w = a.w + b.w;
  1037. return this;
  1038. },
  1039. sub: function ( v ) {
  1040. this.x -= v.x;
  1041. this.y -= v.y;
  1042. this.z -= v.z;
  1043. this.w -= v.w;
  1044. return this;
  1045. },
  1046. subVectors: function ( a, b ) {
  1047. this.x = a.x - b.x;
  1048. this.y = a.y - b.y;
  1049. this.z = a.z - b.z;
  1050. this.w = a.w - b.w;
  1051. return this;
  1052. },
  1053. multiplyScalar: function ( s ) {
  1054. this.x *= s;
  1055. this.y *= s;
  1056. this.z *= s;
  1057. this.w *= s;
  1058. return this;
  1059. },
  1060. applyMatrix4: function ( m ) {
  1061. var x = this.x;
  1062. var y = this.y;
  1063. var z = this.z;
  1064. var w = this.w;
  1065. var e = m.elements;
  1066. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1067. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1068. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1069. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1070. return this;
  1071. },
  1072. divideScalar: function ( s ) {
  1073. if ( s !== 0 ) {
  1074. this.x /= s;
  1075. this.y /= s;
  1076. this.z /= s;
  1077. this.w /= s;
  1078. } else {
  1079. this.x = 0;
  1080. this.y = 0;
  1081. this.z = 0;
  1082. this.w = 1;
  1083. }
  1084. return this;
  1085. },
  1086. min: function ( v ) {
  1087. if ( this.x > v.x ) {
  1088. this.x = v.x;
  1089. }
  1090. if ( this.y > v.y ) {
  1091. this.y = v.y;
  1092. }
  1093. if ( this.z > v.z ) {
  1094. this.z = v.z;
  1095. }
  1096. if ( this.w > v.w ) {
  1097. this.w = v.w;
  1098. }
  1099. return this;
  1100. },
  1101. max: function ( v ) {
  1102. if ( this.x < v.x ) {
  1103. this.x = v.x;
  1104. }
  1105. if ( this.y < v.y ) {
  1106. this.y = v.y;
  1107. }
  1108. if ( this.z < v.z ) {
  1109. this.z = v.z;
  1110. }
  1111. if ( this.w < v.w ) {
  1112. this.w = v.w;
  1113. }
  1114. return this;
  1115. },
  1116. clamp: function ( min, max ) {
  1117. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1118. if ( this.x < min.x ) {
  1119. this.x = min.x;
  1120. } else if ( this.x > max.x ) {
  1121. this.x = max.x;
  1122. }
  1123. if ( this.y < min.y ) {
  1124. this.y = min.y;
  1125. } else if ( this.y > max.y ) {
  1126. this.y = max.y;
  1127. }
  1128. if ( this.z < min.z ) {
  1129. this.z = min.z;
  1130. } else if ( this.z > max.z ) {
  1131. this.z = max.z;
  1132. }
  1133. if ( this.w < min.w ) {
  1134. this.w = min.w;
  1135. } else if ( this.w > max.w ) {
  1136. this.w = max.w;
  1137. }
  1138. return this;
  1139. },
  1140. negate: function() {
  1141. return this.multiplyScalar( -1 );
  1142. },
  1143. dot: function ( v ) {
  1144. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1145. },
  1146. lengthSq: function () {
  1147. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1148. },
  1149. length: function () {
  1150. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1151. },
  1152. lengthManhattan: function () {
  1153. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1154. },
  1155. normalize: function () {
  1156. return this.divideScalar( this.length() );
  1157. },
  1158. setLength: function ( l ) {
  1159. var oldLength = this.length();
  1160. if ( oldLength !== 0 && l !== oldLength ) {
  1161. this.multiplyScalar( l / oldLength );
  1162. }
  1163. return this;
  1164. },
  1165. lerp: function ( v, alpha ) {
  1166. this.x += ( v.x - this.x ) * alpha;
  1167. this.y += ( v.y - this.y ) * alpha;
  1168. this.z += ( v.z - this.z ) * alpha;
  1169. this.w += ( v.w - this.w ) * alpha;
  1170. return this;
  1171. },
  1172. equals: function ( v ) {
  1173. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1174. },
  1175. clone: function () {
  1176. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1177. },
  1178. setAxisAngleFromQuaternion: function ( q ) {
  1179. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1180. // q is assumed to be normalized
  1181. this.w = 2 * Math.acos( q.w );
  1182. var s = Math.sqrt( 1 - q.w * q.w );
  1183. if ( s < 0.0001 ) {
  1184. this.x = 1;
  1185. this.y = 0;
  1186. this.z = 0;
  1187. } else {
  1188. this.x = q.x / s;
  1189. this.y = q.y / s;
  1190. this.z = q.z / s;
  1191. }
  1192. return this;
  1193. },
  1194. setAxisAngleFromRotationMatrix: function ( m ) {
  1195. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1196. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1197. var angle, x, y, z, // variables for result
  1198. epsilon = 0.01, // margin to allow for rounding errors
  1199. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1200. te = m.elements,
  1201. m11 = te[0], m12 = te[4], m13 = te[8],
  1202. m21 = te[1], m22 = te[5], m23 = te[9],
  1203. m31 = te[2], m32 = te[6], m33 = te[10];
  1204. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1205. && ( Math.abs( m13 - m31 ) < epsilon )
  1206. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1207. // singularity found
  1208. // first check for identity matrix which must have +1 for all terms
  1209. // in leading diagonal and zero in other terms
  1210. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1211. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1212. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1213. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1214. // this singularity is identity matrix so angle = 0
  1215. this.set( 1, 0, 0, 0 );
  1216. return this; // zero angle, arbitrary axis
  1217. }
  1218. // otherwise this singularity is angle = 180
  1219. angle = Math.PI;
  1220. var xx = ( m11 + 1 ) / 2;
  1221. var yy = ( m22 + 1 ) / 2;
  1222. var zz = ( m33 + 1 ) / 2;
  1223. var xy = ( m12 + m21 ) / 4;
  1224. var xz = ( m13 + m31 ) / 4;
  1225. var yz = ( m23 + m32 ) / 4;
  1226. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1227. if ( xx < epsilon ) {
  1228. x = 0;
  1229. y = 0.707106781;
  1230. z = 0.707106781;
  1231. } else {
  1232. x = Math.sqrt( xx );
  1233. y = xy / x;
  1234. z = xz / x;
  1235. }
  1236. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1237. if ( yy < epsilon ) {
  1238. x = 0.707106781;
  1239. y = 0;
  1240. z = 0.707106781;
  1241. } else {
  1242. y = Math.sqrt( yy );
  1243. x = xy / y;
  1244. z = yz / y;
  1245. }
  1246. } else { // m33 is the largest diagonal term so base result on this
  1247. if ( zz < epsilon ) {
  1248. x = 0.707106781;
  1249. y = 0.707106781;
  1250. z = 0;
  1251. } else {
  1252. z = Math.sqrt( zz );
  1253. x = xz / z;
  1254. y = yz / z;
  1255. }
  1256. }
  1257. this.set( x, y, z, angle );
  1258. return this; // return 180 deg rotation
  1259. }
  1260. // as we have reached here there are no singularities so we can handle normally
  1261. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1262. + ( m13 - m31 ) * ( m13 - m31 )
  1263. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1264. if ( Math.abs( s ) < 0.001 ) s = 1;
  1265. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1266. // caught by singularity test above, but I've left it in just in case
  1267. this.x = ( m32 - m23 ) / s;
  1268. this.y = ( m13 - m31 ) / s;
  1269. this.z = ( m21 - m12 ) / s;
  1270. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1271. return this;
  1272. }
  1273. };
  1274. /**
  1275. * @author bhouston / http://exocortex.com
  1276. */
  1277. THREE.Box2 = function ( min, max ) {
  1278. this.min = min !== undefined ? min.clone() : new THREE.Vector2( Infinity, Infinity );
  1279. this.max = max !== undefined ? max.clone() : new THREE.Vector2( -Infinity, -Infinity );
  1280. };
  1281. THREE.Box2.prototype = {
  1282. constructor: THREE.Box2,
  1283. set: function ( min, max ) {
  1284. this.min.copy( min );
  1285. this.max.copy( max );
  1286. return this;
  1287. },
  1288. setFromPoints: function ( points ) {
  1289. if ( points.length > 0 ) {
  1290. var point = points[ 0 ];
  1291. this.min.copy( point );
  1292. this.max.copy( point );
  1293. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1294. point = points[ i ];
  1295. if ( point.x < this.min.x ) {
  1296. this.min.x = point.x;
  1297. } else if ( point.x > this.max.x ) {
  1298. this.max.x = point.x;
  1299. }
  1300. if ( point.y < this.min.y ) {
  1301. this.min.y = point.y;
  1302. } else if ( point.y > this.max.y ) {
  1303. this.max.y = point.y;
  1304. }
  1305. }
  1306. } else {
  1307. this.makeEmpty();
  1308. }
  1309. return this;
  1310. },
  1311. setFromCenterAndSize: function ( center, size ) {
  1312. var halfSize = THREE.Box2.__v1.copy( size ).multiplyScalar( 0.5 );
  1313. this.min.copy( center ).sub( halfSize );
  1314. this.max.copy( center ).add( halfSize );
  1315. return this;
  1316. },
  1317. copy: function ( box ) {
  1318. this.min.copy( box.min );
  1319. this.max.copy( box.max );
  1320. return this;
  1321. },
  1322. makeEmpty: function () {
  1323. this.min.x = this.min.y = Infinity;
  1324. this.max.x = this.max.y = -Infinity;
  1325. return this;
  1326. },
  1327. empty: function () {
  1328. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1329. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1330. },
  1331. center: function ( optionalTarget ) {
  1332. var result = optionalTarget || new THREE.Vector2();
  1333. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1334. },
  1335. size: function ( optionalTarget ) {
  1336. var result = optionalTarget || new THREE.Vector2();
  1337. return result.subVectors( this.max, this.min );
  1338. },
  1339. expandByPoint: function ( point ) {
  1340. this.min.min( point );
  1341. this.max.max( point );
  1342. return this;
  1343. },
  1344. expandByVector: function ( vector ) {
  1345. this.min.sub( vector );
  1346. this.max.add( vector );
  1347. return this;
  1348. },
  1349. expandByScalar: function ( scalar ) {
  1350. this.min.addScalar( -scalar );
  1351. this.max.addScalar( scalar );
  1352. return this;
  1353. },
  1354. containsPoint: function ( point ) {
  1355. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1356. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) ) {
  1357. return true;
  1358. }
  1359. return false;
  1360. },
  1361. containsBox: function ( box ) {
  1362. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1363. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1364. return true;
  1365. }
  1366. return false;
  1367. },
  1368. getParameter: function ( point ) {
  1369. // This can potentially have a divide by zero if the box
  1370. // has a size dimension of 0.
  1371. return new THREE.Vector2(
  1372. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1373. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1374. );
  1375. },
  1376. isIntersectionBox: function ( box ) {
  1377. // using 6 splitting planes to rule out intersections.
  1378. if ( ( box.max.x < this.min.x ) ||
  1379. ( box.min.x > this.max.x ) ||
  1380. ( box.max.y < this.min.y ) ||
  1381. ( box.min.y > this.max.y ) ) {
  1382. return false;
  1383. }
  1384. return true;
  1385. },
  1386. clampPoint: function ( point, optionalTarget ) {
  1387. var result = optionalTarget || new THREE.Vector2();
  1388. return result.copy( point ).clamp( this.min, this.max );
  1389. },
  1390. distanceToPoint: function ( point ) {
  1391. var clampedPoint = THREE.Box2.__v1.copy( point ).clamp( this.min, this.max );
  1392. return clampedPoint.sub( point ).length();
  1393. },
  1394. intersect: function ( box ) {
  1395. this.min.max( box.min );
  1396. this.max.min( box.max );
  1397. return this;
  1398. },
  1399. union: function ( box ) {
  1400. this.min.min( box.min );
  1401. this.max.max( box.max );
  1402. return this;
  1403. },
  1404. translate: function ( offset ) {
  1405. this.min.add( offset );
  1406. this.max.add( offset );
  1407. return this;
  1408. },
  1409. equals: function ( box ) {
  1410. return box.min.equals( this.min ) && box.max.equals( this.max );
  1411. },
  1412. clone: function () {
  1413. return new THREE.Box2().copy( this );
  1414. }
  1415. };
  1416. THREE.Box2.__v1 = new THREE.Vector2();
  1417. /**
  1418. * @author bhouston / http://exocortex.com
  1419. */
  1420. THREE.Box3 = function ( min, max ) {
  1421. this.min = min !== undefined ? min.clone() : new THREE.Vector3( Infinity, Infinity, Infinity );
  1422. this.max = max !== undefined ? max.clone() : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1423. };
  1424. THREE.Box3.prototype = {
  1425. constructor: THREE.Box3,
  1426. set: function ( min, max ) {
  1427. this.min.copy( min );
  1428. this.max.copy( max );
  1429. return this;
  1430. },
  1431. setFromPoints: function ( points ) {
  1432. if ( points.length > 0 ) {
  1433. var p = points[ 0 ];
  1434. this.min.copy( p );
  1435. this.max.copy( p );
  1436. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1437. p = points[ i ];
  1438. if ( p.x < this.min.x ) {
  1439. this.min.x = p.x;
  1440. } else if ( p.x > this.max.x ) {
  1441. this.max.x = p.x;
  1442. }
  1443. if ( p.y < this.min.y ) {
  1444. this.min.y = p.y;
  1445. } else if ( p.y > this.max.y ) {
  1446. this.max.y = p.y;
  1447. }
  1448. if ( p.z < this.min.z ) {
  1449. this.min.z = p.z;
  1450. } else if ( p.z > this.max.z ) {
  1451. this.max.z = p.z;
  1452. }
  1453. }
  1454. } else {
  1455. this.makeEmpty();
  1456. }
  1457. return this;
  1458. },
  1459. setFromCenterAndSize: function ( center, size ) {
  1460. var halfSize = THREE.Box3.__v1.copy( size ).multiplyScalar( 0.5 );
  1461. this.min.copy( center ).sub( halfSize );
  1462. this.max.copy( center ).add( halfSize );
  1463. return this;
  1464. },
  1465. copy: function ( box ) {
  1466. this.min.copy( box.min );
  1467. this.max.copy( box.max );
  1468. return this;
  1469. },
  1470. makeEmpty: function () {
  1471. this.min.x = this.min.y = this.min.z = Infinity;
  1472. this.max.x = this.max.y = this.max.z = -Infinity;
  1473. return this;
  1474. },
  1475. empty: function () {
  1476. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1477. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1478. },
  1479. center: function ( optionalTarget ) {
  1480. var result = optionalTarget || new THREE.Vector3();
  1481. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1482. },
  1483. size: function ( optionalTarget ) {
  1484. var result = optionalTarget || new THREE.Vector3();
  1485. return result.subVectors( this.max, this.min );
  1486. },
  1487. expandByPoint: function ( point ) {
  1488. this.min.min( point );
  1489. this.max.max( point );
  1490. return this;
  1491. },
  1492. expandByVector: function ( vector ) {
  1493. this.min.sub( vector );
  1494. this.max.add( vector );
  1495. return this;
  1496. },
  1497. expandByScalar: function ( scalar ) {
  1498. this.min.addScalar( -scalar );
  1499. this.max.addScalar( scalar );
  1500. return this;
  1501. },
  1502. containsPoint: function ( point ) {
  1503. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1504. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) &&
  1505. ( this.min.z <= point.z ) && ( point.z <= this.max.z ) ) {
  1506. return true;
  1507. }
  1508. return false;
  1509. },
  1510. containsBox: function ( box ) {
  1511. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1512. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1513. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1514. return true;
  1515. }
  1516. return false;
  1517. },
  1518. getParameter: function ( point ) {
  1519. // This can potentially have a divide by zero if the box
  1520. // has a size dimension of 0.
  1521. return new THREE.Vector3(
  1522. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1523. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1524. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1525. );
  1526. },
  1527. isIntersectionBox: function ( box ) {
  1528. // using 6 splitting planes to rule out intersections.
  1529. if ( ( box.max.x < this.min.x ) || ( box.min.x > this.max.x ) ||
  1530. ( box.max.y < this.min.y ) || ( box.min.y > this.max.y ) ||
  1531. ( box.max.z < this.min.z ) || ( box.min.z > this.max.z ) ) {
  1532. return false;
  1533. }
  1534. return true;
  1535. },
  1536. clampPoint: function ( point, optionalTarget ) {
  1537. var result = optionalTarget || new THREE.Vector3();
  1538. return new THREE.Vector3().copy( point ).clamp( this.min, this.max );
  1539. },
  1540. distanceToPoint: function ( point ) {
  1541. var clampedPoint = THREE.Box3.__v1.copy( point ).clamp( this.min, this.max );
  1542. return clampedPoint.sub( point ).length();
  1543. },
  1544. getBoundingSphere: function ( optionalTarget ) {
  1545. var result = optionalTarget || new THREE.Sphere();
  1546. result.center = this.center();
  1547. result.radius = this.size( THREE.Box3.__v0 ).length() * 0.5;
  1548. return result;
  1549. },
  1550. intersect: function ( box ) {
  1551. this.min.max( box.min );
  1552. this.max.min( box.max );
  1553. return this;
  1554. },
  1555. union: function ( box ) {
  1556. this.min.min( box.min );
  1557. this.max.max( box.max );
  1558. return this;
  1559. },
  1560. transform: function ( matrix ) {
  1561. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1562. var newPoints = [
  1563. THREE.Box3.__v0.set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ),
  1564. THREE.Box3.__v0.set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ), // 000
  1565. THREE.Box3.__v1.set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ), // 001
  1566. THREE.Box3.__v2.set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ), // 010
  1567. THREE.Box3.__v3.set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ), // 011
  1568. THREE.Box3.__v4.set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ), // 100
  1569. THREE.Box3.__v5.set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ), // 101
  1570. THREE.Box3.__v6.set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ), // 110
  1571. THREE.Box3.__v7.set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ) // 111
  1572. ];
  1573. this.makeEmpty();
  1574. this.setFromPoints( newPoints );
  1575. return this;
  1576. },
  1577. translate: function ( offset ) {
  1578. this.min.add( offset );
  1579. this.max.add( offset );
  1580. return this;
  1581. },
  1582. equals: function ( box ) {
  1583. return box.min.equals( this.min ) && box.max.equals( this.max );
  1584. },
  1585. clone: function () {
  1586. return new THREE.Box3().copy( this );
  1587. }
  1588. };
  1589. THREE.Box3.__v0 = new THREE.Vector3();
  1590. THREE.Box3.__v1 = new THREE.Vector3();
  1591. THREE.Box3.__v2 = new THREE.Vector3();
  1592. THREE.Box3.__v3 = new THREE.Vector3();
  1593. THREE.Box3.__v4 = new THREE.Vector3();
  1594. THREE.Box3.__v5 = new THREE.Vector3();
  1595. THREE.Box3.__v6 = new THREE.Vector3();
  1596. THREE.Box3.__v7 = new THREE.Vector3();
  1597. /**
  1598. * @author alteredq / http://alteredqualia.com/
  1599. * @author WestLangley / http://github.com/WestLangley
  1600. * @author bhouston / http://exocortex.com
  1601. */
  1602. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1603. this.elements = new Float32Array(9);
  1604. this.set(
  1605. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  1606. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  1607. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  1608. );
  1609. };
  1610. THREE.Matrix3.prototype = {
  1611. constructor: THREE.Matrix3,
  1612. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1613. var te = this.elements;
  1614. te[0] = n11; te[3] = n12; te[6] = n13;
  1615. te[1] = n21; te[4] = n22; te[7] = n23;
  1616. te[2] = n31; te[5] = n32; te[8] = n33;
  1617. return this;
  1618. },
  1619. identity: function () {
  1620. this.set(
  1621. 1, 0, 0,
  1622. 0, 1, 0,
  1623. 0, 0, 1
  1624. );
  1625. return this;
  1626. },
  1627. copy: function ( m ) {
  1628. var me = m.elements;
  1629. this.set(
  1630. me[0], me[3], me[6],
  1631. me[1], me[4], me[7],
  1632. me[2], me[5], me[8]
  1633. );
  1634. return this;
  1635. },
  1636. multiplyVector3Array: function ( a ) {
  1637. var tmp = THREE.Matrix3.__v1;
  1638. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1639. tmp.x = a[ i ];
  1640. tmp.y = a[ i + 1 ];
  1641. tmp.z = a[ i + 2 ];
  1642. this.multiplyVector3( tmp );
  1643. a[ i ] = tmp.x;
  1644. a[ i + 1 ] = tmp.y;
  1645. a[ i + 2 ] = tmp.z;
  1646. }
  1647. return a;
  1648. },
  1649. multiplyScalar: function ( s ) {
  1650. var te = this.elements;
  1651. te[0] *= s; te[3] *= s; te[6] *= s;
  1652. te[1] *= s; te[4] *= s; te[7] *= s;
  1653. te[2] *= s; te[5] *= s; te[8] *= s;
  1654. return this;
  1655. },
  1656. determinant: function () {
  1657. var te = this.elements;
  1658. var a = te[0], b = te[1], c = te[2],
  1659. d = te[3], e = te[4], f = te[5],
  1660. g = te[6], h = te[7], i = te[8];
  1661. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  1662. },
  1663. getInverse: function ( matrix, throwOnInvertible ) {
  1664. // input: THREE.Matrix4
  1665. // ( based on http://code.google.com/p/webgl-mjs/ )
  1666. var me = matrix.elements;
  1667. var te = this.elements;
  1668. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  1669. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  1670. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  1671. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  1672. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  1673. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  1674. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  1675. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  1676. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  1677. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  1678. // no inverse
  1679. if ( det === 0 ) {
  1680. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  1681. if ( throwOnInvertible || false ) {
  1682. throw new Error( msg );
  1683. } else {
  1684. console.warn( msg );
  1685. }
  1686. this.identity();
  1687. return this;
  1688. }
  1689. this.multiplyScalar( 1.0 / det );
  1690. return this;
  1691. },
  1692. transpose: function () {
  1693. var tmp, m = this.elements;
  1694. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  1695. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  1696. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  1697. return this;
  1698. },
  1699. transposeIntoArray: function ( r ) {
  1700. var m = this.elements;
  1701. r[ 0 ] = m[ 0 ];
  1702. r[ 1 ] = m[ 3 ];
  1703. r[ 2 ] = m[ 6 ];
  1704. r[ 3 ] = m[ 1 ];
  1705. r[ 4 ] = m[ 4 ];
  1706. r[ 5 ] = m[ 7 ];
  1707. r[ 6 ] = m[ 2 ];
  1708. r[ 7 ] = m[ 5 ];
  1709. r[ 8 ] = m[ 8 ];
  1710. return this;
  1711. },
  1712. clone: function () {
  1713. var te = this.elements;
  1714. return new THREE.Matrix3(
  1715. te[0], te[3], te[6],
  1716. te[1], te[4], te[7],
  1717. te[2], te[5], te[8]
  1718. );
  1719. }
  1720. };
  1721. THREE.Matrix3.__v1 = new THREE.Vector3();
  1722. /**
  1723. * @author mrdoob / http://mrdoob.com/
  1724. * @author supereggbert / http://www.paulbrunt.co.uk/
  1725. * @author philogb / http://blog.thejit.org/
  1726. * @author jordi_ros / http://plattsoft.com
  1727. * @author D1plo1d / http://github.com/D1plo1d
  1728. * @author alteredq / http://alteredqualia.com/
  1729. * @author mikael emtinger / http://gomo.se/
  1730. * @author timknip / http://www.floorplanner.com/
  1731. * @author bhouston / http://exocortex.com
  1732. */
  1733. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1734. this.elements = new Float32Array( 16 );
  1735. this.set(
  1736. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1737. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1738. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1739. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1740. );
  1741. };
  1742. THREE.Matrix4.prototype = {
  1743. constructor: THREE.Matrix4,
  1744. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1745. var te = this.elements;
  1746. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1747. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1748. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1749. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1750. return this;
  1751. },
  1752. identity: function () {
  1753. this.set(
  1754. 1, 0, 0, 0,
  1755. 0, 1, 0, 0,
  1756. 0, 0, 1, 0,
  1757. 0, 0, 0, 1
  1758. );
  1759. return this;
  1760. },
  1761. copy: function ( m ) {
  1762. var me = m.elements;
  1763. this.set(
  1764. me[0], me[4], me[8], me[12],
  1765. me[1], me[5], me[9], me[13],
  1766. me[2], me[6], me[10], me[14],
  1767. me[3], me[7], me[11], me[15]
  1768. );
  1769. return this;
  1770. },
  1771. setRotationFromEuler: function ( v, order ) {
  1772. var te = this.elements;
  1773. var x = v.x, y = v.y, z = v.z;
  1774. var a = Math.cos( x ), b = Math.sin( x );
  1775. var c = Math.cos( y ), d = Math.sin( y );
  1776. var e = Math.cos( z ), f = Math.sin( z );
  1777. if ( order === undefined || order === 'XYZ' ) {
  1778. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1779. te[0] = c * e;
  1780. te[4] = - c * f;
  1781. te[8] = d;
  1782. te[1] = af + be * d;
  1783. te[5] = ae - bf * d;
  1784. te[9] = - b * c;
  1785. te[2] = bf - ae * d;
  1786. te[6] = be + af * d;
  1787. te[10] = a * c;
  1788. } else if ( order === 'YXZ' ) {
  1789. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1790. te[0] = ce + df * b;
  1791. te[4] = de * b - cf;
  1792. te[8] = a * d;
  1793. te[1] = a * f;
  1794. te[5] = a * e;
  1795. te[9] = - b;
  1796. te[2] = cf * b - de;
  1797. te[6] = df + ce * b;
  1798. te[10] = a * c;
  1799. } else if ( order === 'ZXY' ) {
  1800. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1801. te[0] = ce - df * b;
  1802. te[4] = - a * f;
  1803. te[8] = de + cf * b;
  1804. te[1] = cf + de * b;
  1805. te[5] = a * e;
  1806. te[9] = df - ce * b;
  1807. te[2] = - a * d;
  1808. te[6] = b;
  1809. te[10] = a * c;
  1810. } else if ( order === 'ZYX' ) {
  1811. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1812. te[0] = c * e;
  1813. te[4] = be * d - af;
  1814. te[8] = ae * d + bf;
  1815. te[1] = c * f;
  1816. te[5] = bf * d + ae;
  1817. te[9] = af * d - be;
  1818. te[2] = - d;
  1819. te[6] = b * c;
  1820. te[10] = a * c;
  1821. } else if ( order === 'YZX' ) {
  1822. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1823. te[0] = c * e;
  1824. te[4] = bd - ac * f;
  1825. te[8] = bc * f + ad;
  1826. te[1] = f;
  1827. te[5] = a * e;
  1828. te[9] = - b * e;
  1829. te[2] = - d * e;
  1830. te[6] = ad * f + bc;
  1831. te[10] = ac - bd * f;
  1832. } else if ( order === 'XZY' ) {
  1833. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1834. te[0] = c * e;
  1835. te[4] = - f;
  1836. te[8] = d * e;
  1837. te[1] = ac * f + bd;
  1838. te[5] = a * e;
  1839. te[9] = ad * f - bc;
  1840. te[2] = bc * f - ad;
  1841. te[6] = b * e;
  1842. te[10] = bd * f + ac;
  1843. }
  1844. return this;
  1845. },
  1846. setRotationFromQuaternion: function ( q ) {
  1847. var te = this.elements;
  1848. var x = q.x, y = q.y, z = q.z, w = q.w;
  1849. var x2 = x + x, y2 = y + y, z2 = z + z;
  1850. var xx = x * x2, xy = x * y2, xz = x * z2;
  1851. var yy = y * y2, yz = y * z2, zz = z * z2;
  1852. var wx = w * x2, wy = w * y2, wz = w * z2;
  1853. te[0] = 1 - ( yy + zz );
  1854. te[4] = xy - wz;
  1855. te[8] = xz + wy;
  1856. te[1] = xy + wz;
  1857. te[5] = 1 - ( xx + zz );
  1858. te[9] = yz - wx;
  1859. te[2] = xz - wy;
  1860. te[6] = yz + wx;
  1861. te[10] = 1 - ( xx + yy );
  1862. return this;
  1863. },
  1864. lookAt: function ( eye, target, up ) {
  1865. var te = this.elements;
  1866. var x = THREE.Matrix4.__v1;
  1867. var y = THREE.Matrix4.__v2;
  1868. var z = THREE.Matrix4.__v3;
  1869. z.subVectors( eye, target ).normalize();
  1870. if ( z.length() === 0 ) {
  1871. z.z = 1;
  1872. }
  1873. x.crossVectors( up, z ).normalize();
  1874. if ( x.length() === 0 ) {
  1875. z.x += 0.0001;
  1876. x.crossVectors( up, z ).normalize();
  1877. }
  1878. y.crossVectors( z, x );
  1879. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1880. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1881. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1882. return this;
  1883. },
  1884. multiply: function ( m ) {
  1885. return this.multiplyMatrices( this, m );
  1886. },
  1887. multiplyMatrices: function ( a, b ) {
  1888. var ae = a.elements;
  1889. var be = b.elements;
  1890. var te = this.elements;
  1891. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1892. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1893. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1894. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1895. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1896. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1897. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1898. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1899. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1900. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1901. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1902. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1903. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1904. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1905. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1906. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1907. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1908. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1909. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1910. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1911. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1912. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1913. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1914. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1915. return this;
  1916. },
  1917. multiplyToArray: function ( a, b, r ) {
  1918. var te = this.elements;
  1919. this.multiplyMatrices( a, b );
  1920. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1921. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1922. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1923. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1924. return this;
  1925. },
  1926. multiplyScalar: function ( s ) {
  1927. var te = this.elements;
  1928. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1929. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1930. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1931. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1932. return this;
  1933. },
  1934. multiplyVector3Array: function ( a ) {
  1935. var tmp = THREE.Matrix4.__v1;
  1936. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1937. tmp.x = a[ i ];
  1938. tmp.y = a[ i + 1 ];
  1939. tmp.z = a[ i + 2 ];
  1940. this.multiplyVector3( tmp );
  1941. a[ i ] = tmp.x;
  1942. a[ i + 1 ] = tmp.y;
  1943. a[ i + 2 ] = tmp.z;
  1944. }
  1945. return a;
  1946. },
  1947. rotateAxis: function ( v ) {
  1948. var te = this.elements;
  1949. var vx = v.x, vy = v.y, vz = v.z;
  1950. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1951. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1952. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1953. v.normalize();
  1954. return v;
  1955. },
  1956. crossVector: function ( a ) {
  1957. var te = this.elements;
  1958. var v = new THREE.Vector4();
  1959. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1960. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1961. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1962. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1963. return v;
  1964. },
  1965. determinant: function () {
  1966. var te = this.elements;
  1967. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1968. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1969. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1970. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1971. //TODO: make this more efficient
  1972. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1973. return (
  1974. n41 * (
  1975. +n14 * n23 * n32
  1976. -n13 * n24 * n32
  1977. -n14 * n22 * n33
  1978. +n12 * n24 * n33
  1979. +n13 * n22 * n34
  1980. -n12 * n23 * n34
  1981. ) +
  1982. n42 * (
  1983. +n11 * n23 * n34
  1984. -n11 * n24 * n33
  1985. +n14 * n21 * n33
  1986. -n13 * n21 * n34
  1987. +n13 * n24 * n31
  1988. -n14 * n23 * n31
  1989. ) +
  1990. n43 * (
  1991. +n11 * n24 * n32
  1992. -n11 * n22 * n34
  1993. -n14 * n21 * n32
  1994. +n12 * n21 * n34
  1995. +n14 * n22 * n31
  1996. -n12 * n24 * n31
  1997. ) +
  1998. n44 * (
  1999. -n13 * n22 * n31
  2000. -n11 * n23 * n32
  2001. +n11 * n22 * n33
  2002. +n13 * n21 * n32
  2003. -n12 * n21 * n33
  2004. +n12 * n23 * n31
  2005. )
  2006. );
  2007. },
  2008. transpose: function () {
  2009. var te = this.elements;
  2010. var tmp;
  2011. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2012. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2013. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2014. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2015. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2016. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2017. return this;
  2018. },
  2019. flattenToArray: function ( flat ) {
  2020. var te = this.elements;
  2021. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2022. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2023. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2024. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2025. return flat;
  2026. },
  2027. flattenToArrayOffset: function( flat, offset ) {
  2028. var te = this.elements;
  2029. flat[ offset ] = te[0];
  2030. flat[ offset + 1 ] = te[1];
  2031. flat[ offset + 2 ] = te[2];
  2032. flat[ offset + 3 ] = te[3];
  2033. flat[ offset + 4 ] = te[4];
  2034. flat[ offset + 5 ] = te[5];
  2035. flat[ offset + 6 ] = te[6];
  2036. flat[ offset + 7 ] = te[7];
  2037. flat[ offset + 8 ] = te[8];
  2038. flat[ offset + 9 ] = te[9];
  2039. flat[ offset + 10 ] = te[10];
  2040. flat[ offset + 11 ] = te[11];
  2041. flat[ offset + 12 ] = te[12];
  2042. flat[ offset + 13 ] = te[13];
  2043. flat[ offset + 14 ] = te[14];
  2044. flat[ offset + 15 ] = te[15];
  2045. return flat;
  2046. },
  2047. getPosition: function () {
  2048. var te = this.elements;
  2049. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  2050. },
  2051. setPosition: function ( v ) {
  2052. var te = this.elements;
  2053. te[12] = v.x;
  2054. te[13] = v.y;
  2055. te[14] = v.z;
  2056. return this;
  2057. },
  2058. getColumnX: function () {
  2059. var te = this.elements;
  2060. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  2061. },
  2062. getColumnY: function () {
  2063. var te = this.elements;
  2064. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  2065. },
  2066. getColumnZ: function() {
  2067. var te = this.elements;
  2068. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  2069. },
  2070. getInverse: function ( m, throwOnInvertible ) {
  2071. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2072. var te = this.elements;
  2073. var me = m.elements;
  2074. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2075. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2076. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2077. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2078. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2079. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2080. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2081. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2082. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2083. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2084. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2085. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2086. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2087. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2088. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2089. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2090. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2091. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2092. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2093. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2094. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 4 ] + me[ 2 ] * te[ 8 ] + me[ 3 ] * te[ 12 ];
  2095. if ( det == 0 ) {
  2096. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2097. if ( throwOnInvertible || false ) {
  2098. throw new Error( msg );
  2099. } else {
  2100. console.warn( msg );
  2101. }
  2102. this.identity();
  2103. return this;
  2104. }
  2105. this.multiplyScalar( 1 / det );
  2106. return this;
  2107. },
  2108. compose: function ( translation, rotation, scale ) {
  2109. var te = this.elements;
  2110. var mRotation = THREE.Matrix4.__m1;
  2111. var mScale = THREE.Matrix4.__m2;
  2112. mRotation.identity();
  2113. mRotation.setRotationFromQuaternion( rotation );
  2114. mScale.makeScale( scale );
  2115. this.multiplyMatrices( mRotation, mScale );
  2116. te[12] = translation.x;
  2117. te[13] = translation.y;
  2118. te[14] = translation.z;
  2119. return this;
  2120. },
  2121. decompose: function ( translation, rotation, scale ) {
  2122. var te = this.elements;
  2123. // grab the axis vectors
  2124. var x = THREE.Matrix4.__v1;
  2125. var y = THREE.Matrix4.__v2;
  2126. var z = THREE.Matrix4.__v3;
  2127. x.set( te[0], te[1], te[2] );
  2128. y.set( te[4], te[5], te[6] );
  2129. z.set( te[8], te[9], te[10] );
  2130. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  2131. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  2132. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2133. scale.x = x.length();
  2134. scale.y = y.length();
  2135. scale.z = z.length();
  2136. translation.x = te[12];
  2137. translation.y = te[13];
  2138. translation.z = te[14];
  2139. // scale the rotation part
  2140. var matrix = THREE.Matrix4.__m1;
  2141. matrix.copy( this );
  2142. matrix.elements[0] /= scale.x;
  2143. matrix.elements[1] /= scale.x;
  2144. matrix.elements[2] /= scale.x;
  2145. matrix.elements[4] /= scale.y;
  2146. matrix.elements[5] /= scale.y;
  2147. matrix.elements[6] /= scale.y;
  2148. matrix.elements[8] /= scale.z;
  2149. matrix.elements[9] /= scale.z;
  2150. matrix.elements[10] /= scale.z;
  2151. rotation.setFromRotationMatrix( matrix );
  2152. return [ translation, rotation, scale ];
  2153. },
  2154. extractPosition: function ( m ) {
  2155. var te = this.elements;
  2156. var me = m.elements;
  2157. te[12] = me[12];
  2158. te[13] = me[13];
  2159. te[14] = me[14];
  2160. return this;
  2161. },
  2162. extractRotation: function ( m ) {
  2163. var te = this.elements;
  2164. var me = m.elements;
  2165. var vector = THREE.Matrix4.__v1;
  2166. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  2167. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  2168. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  2169. te[0] = me[0] * scaleX;
  2170. te[1] = me[1] * scaleX;
  2171. te[2] = me[2] * scaleX;
  2172. te[4] = me[4] * scaleY;
  2173. te[5] = me[5] * scaleY;
  2174. te[6] = me[6] * scaleY;
  2175. te[8] = me[8] * scaleZ;
  2176. te[9] = me[9] * scaleZ;
  2177. te[10] = me[10] * scaleZ;
  2178. return this;
  2179. },
  2180. //
  2181. translate: function ( v ) {
  2182. var te = this.elements;
  2183. var x = v.x, y = v.y, z = v.z;
  2184. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  2185. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  2186. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  2187. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  2188. return this;
  2189. },
  2190. rotateX: function ( angle ) {
  2191. var te = this.elements;
  2192. var m12 = te[4];
  2193. var m22 = te[5];
  2194. var m32 = te[6];
  2195. var m42 = te[7];
  2196. var m13 = te[8];
  2197. var m23 = te[9];
  2198. var m33 = te[10];
  2199. var m43 = te[11];
  2200. var c = Math.cos( angle );
  2201. var s = Math.sin( angle );
  2202. te[4] = c * m12 + s * m13;
  2203. te[5] = c * m22 + s * m23;
  2204. te[6] = c * m32 + s * m33;
  2205. te[7] = c * m42 + s * m43;
  2206. te[8] = c * m13 - s * m12;
  2207. te[9] = c * m23 - s * m22;
  2208. te[10] = c * m33 - s * m32;
  2209. te[11] = c * m43 - s * m42;
  2210. return this;
  2211. },
  2212. rotateY: function ( angle ) {
  2213. var te = this.elements;
  2214. var m11 = te[0];
  2215. var m21 = te[1];
  2216. var m31 = te[2];
  2217. var m41 = te[3];
  2218. var m13 = te[8];
  2219. var m23 = te[9];
  2220. var m33 = te[10];
  2221. var m43 = te[11];
  2222. var c = Math.cos( angle );
  2223. var s = Math.sin( angle );
  2224. te[0] = c * m11 - s * m13;
  2225. te[1] = c * m21 - s * m23;
  2226. te[2] = c * m31 - s * m33;
  2227. te[3] = c * m41 - s * m43;
  2228. te[8] = c * m13 + s * m11;
  2229. te[9] = c * m23 + s * m21;
  2230. te[10] = c * m33 + s * m31;
  2231. te[11] = c * m43 + s * m41;
  2232. return this;
  2233. },
  2234. rotateZ: function ( angle ) {
  2235. var te = this.elements;
  2236. var m11 = te[0];
  2237. var m21 = te[1];
  2238. var m31 = te[2];
  2239. var m41 = te[3];
  2240. var m12 = te[4];
  2241. var m22 = te[5];
  2242. var m32 = te[6];
  2243. var m42 = te[7];
  2244. var c = Math.cos( angle );
  2245. var s = Math.sin( angle );
  2246. te[0] = c * m11 + s * m12;
  2247. te[1] = c * m21 + s * m22;
  2248. te[2] = c * m31 + s * m32;
  2249. te[3] = c * m41 + s * m42;
  2250. te[4] = c * m12 - s * m11;
  2251. te[5] = c * m22 - s * m21;
  2252. te[6] = c * m32 - s * m31;
  2253. te[7] = c * m42 - s * m41;
  2254. return this;
  2255. },
  2256. rotateByAxis: function ( axis, angle ) {
  2257. var te = this.elements;
  2258. // optimize by checking axis
  2259. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  2260. return this.rotateX( angle );
  2261. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  2262. return this.rotateY( angle );
  2263. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  2264. return this.rotateZ( angle );
  2265. }
  2266. var x = axis.x, y = axis.y, z = axis.z;
  2267. var n = Math.sqrt(x * x + y * y + z * z);
  2268. x /= n;
  2269. y /= n;
  2270. z /= n;
  2271. var xx = x * x, yy = y * y, zz = z * z;
  2272. var c = Math.cos( angle );
  2273. var s = Math.sin( angle );
  2274. var oneMinusCosine = 1 - c;
  2275. var xy = x * y * oneMinusCosine;
  2276. var xz = x * z * oneMinusCosine;
  2277. var yz = y * z * oneMinusCosine;
  2278. var xs = x * s;
  2279. var ys = y * s;
  2280. var zs = z * s;
  2281. var r11 = xx + (1 - xx) * c;
  2282. var r21 = xy + zs;
  2283. var r31 = xz - ys;
  2284. var r12 = xy - zs;
  2285. var r22 = yy + (1 - yy) * c;
  2286. var r32 = yz + xs;
  2287. var r13 = xz + ys;
  2288. var r23 = yz - xs;
  2289. var r33 = zz + (1 - zz) * c;
  2290. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  2291. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  2292. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  2293. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  2294. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  2295. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  2296. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  2297. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  2298. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  2299. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  2300. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  2301. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  2302. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  2303. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  2304. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  2305. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  2306. return this;
  2307. },
  2308. scale: function ( v ) {
  2309. var te = this.elements;
  2310. var x = v.x, y = v.y, z = v.z;
  2311. te[0] *= x; te[4] *= y; te[8] *= z;
  2312. te[1] *= x; te[5] *= y; te[9] *= z;
  2313. te[2] *= x; te[6] *= y; te[10] *= z;
  2314. te[3] *= x; te[7] *= y; te[11] *= z;
  2315. return this;
  2316. },
  2317. getMaxScaleOnAxis: function () {
  2318. var te = this.elements;
  2319. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2320. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2321. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2322. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2323. },
  2324. //
  2325. makeTranslation: function ( offset ) {
  2326. this.set(
  2327. 1, 0, 0, offset.x,
  2328. 0, 1, 0, offset.y,
  2329. 0, 0, 1, offset.z,
  2330. 0, 0, 0, 1
  2331. );
  2332. return this;
  2333. },
  2334. makeRotationX: function ( theta ) {
  2335. var c = Math.cos( theta ), s = Math.sin( theta );
  2336. this.set(
  2337. 1, 0, 0, 0,
  2338. 0, c, -s, 0,
  2339. 0, s, c, 0,
  2340. 0, 0, 0, 1
  2341. );
  2342. return this;
  2343. },
  2344. makeRotationY: function ( theta ) {
  2345. var c = Math.cos( theta ), s = Math.sin( theta );
  2346. this.set(
  2347. c, 0, s, 0,
  2348. 0, 1, 0, 0,
  2349. -s, 0, c, 0,
  2350. 0, 0, 0, 1
  2351. );
  2352. return this;
  2353. },
  2354. makeRotationZ: function ( theta ) {
  2355. var c = Math.cos( theta ), s = Math.sin( theta );
  2356. this.set(
  2357. c, -s, 0, 0,
  2358. s, c, 0, 0,
  2359. 0, 0, 1, 0,
  2360. 0, 0, 0, 1
  2361. );
  2362. return this;
  2363. },
  2364. makeRotationAxis: function ( axis, angle ) {
  2365. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2366. var c = Math.cos( angle );
  2367. var s = Math.sin( angle );
  2368. var t = 1 - c;
  2369. var x = axis.x, y = axis.y, z = axis.z;
  2370. var tx = t * x, ty = t * y;
  2371. this.set(
  2372. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2373. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2374. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2375. 0, 0, 0, 1
  2376. );
  2377. return this;
  2378. },
  2379. makeScale: function ( factor ) {
  2380. this.set(
  2381. factor.x, 0, 0, 0,
  2382. 0, factor.y, 0, 0,
  2383. 0, 0, factor.z, 0,
  2384. 0, 0, 0, 1
  2385. );
  2386. return this;
  2387. },
  2388. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2389. var te = this.elements;
  2390. var x = 2 * near / ( right - left );
  2391. var y = 2 * near / ( top - bottom );
  2392. var a = ( right + left ) / ( right - left );
  2393. var b = ( top + bottom ) / ( top - bottom );
  2394. var c = - ( far + near ) / ( far - near );
  2395. var d = - 2 * far * near / ( far - near );
  2396. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2397. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2398. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2399. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2400. return this;
  2401. },
  2402. makePerspective: function ( fov, aspect, near, far ) {
  2403. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2404. var ymin = - ymax;
  2405. var xmin = ymin * aspect;
  2406. var xmax = ymax * aspect;
  2407. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2408. },
  2409. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2410. var te = this.elements;
  2411. var w = right - left;
  2412. var h = top - bottom;
  2413. var p = far - near;
  2414. var x = ( right + left ) / w;
  2415. var y = ( top + bottom ) / h;
  2416. var z = ( far + near ) / p;
  2417. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2418. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2419. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2420. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2421. return this;
  2422. },
  2423. clone: function () {
  2424. var te = this.elements;
  2425. return new THREE.Matrix4(
  2426. te[0], te[4], te[8], te[12],
  2427. te[1], te[5], te[9], te[13],
  2428. te[2], te[6], te[10], te[14],
  2429. te[3], te[7], te[11], te[15]
  2430. );
  2431. }
  2432. };
  2433. THREE.Matrix4.__v1 = new THREE.Vector3();
  2434. THREE.Matrix4.__v2 = new THREE.Vector3();
  2435. THREE.Matrix4.__v3 = new THREE.Vector3();
  2436. THREE.Matrix4.__m1 = new THREE.Matrix4();
  2437. THREE.Matrix4.__m2 = new THREE.Matrix4();
  2438. /**
  2439. * @author bhouston / http://exocortex.com
  2440. */
  2441. THREE.Ray = function ( origin, direction ) {
  2442. this.origin = origin !== undefined ? origin.clone() : new THREE.Vector3();
  2443. this.direction = direction !== undefined ? direction.clone() : new THREE.Vector3();
  2444. };
  2445. THREE.Ray.prototype = {
  2446. constructor: THREE.Ray,
  2447. set: function ( origin, direction ) {
  2448. this.origin.copy( origin );
  2449. this.direction.copy( direction );
  2450. return this;
  2451. },
  2452. copy: function ( ray ) {
  2453. this.origin.copy( ray.origin );
  2454. this.direction.copy( ray.direction );
  2455. return this;
  2456. },
  2457. at: function( t, optionalTarget ) {
  2458. var result = optionalTarget || new THREE.Vector3();
  2459. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2460. },
  2461. recast: function ( t ) {
  2462. this.origin.copy( this.at( t, THREE.Ray.__v1 ) );
  2463. return this;
  2464. },
  2465. closestPointToPoint: function ( point, optionalTarget ) {
  2466. var result = optionalTarget || new THREE.Vector3();
  2467. result.subVectors( point, this.origin );
  2468. var directionDistance = result.dot( this.direction );
  2469. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2470. },
  2471. distanceToPoint: function ( point ) {
  2472. var directionDistance = THREE.Ray.__v1.subVectors( point, this.origin ).dot( this.direction );
  2473. THREE.Ray.__v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2474. return THREE.Ray.__v1.distanceTo( point );
  2475. },
  2476. isIntersectionSphere: function( sphere ) {
  2477. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2478. },
  2479. isIntersectionPlane: function ( plane ) {
  2480. // check if the line and plane are non-perpendicular, if they
  2481. // eventually they will intersect.
  2482. var denominator = plane.normal.dot( this.direction );
  2483. if ( denominator != 0 ) {
  2484. return true;
  2485. }
  2486. // line is coplanar, return origin
  2487. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2488. return true;
  2489. }
  2490. return false;
  2491. },
  2492. distanceToPlane: function ( plane ) {
  2493. var denominator = plane.normal.dot( this.direction );
  2494. if ( denominator == 0 ) {
  2495. // line is coplanar, return origin
  2496. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2497. return 0;
  2498. }
  2499. // Unsure if this is the correct method to handle this case.
  2500. return undefined;
  2501. }
  2502. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2503. return t;
  2504. },
  2505. intersectPlane: function ( plane, optionalTarget ) {
  2506. var t = this.distanceToPlane( plane );
  2507. if( t === undefined ) {
  2508. return undefined;
  2509. }
  2510. return this.at( t, optionalTarget );
  2511. },
  2512. transform: function ( matrix4 ) {
  2513. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  2514. this.origin.applyMatrix4( matrix4 );
  2515. this.direction.sub( this.origin );
  2516. return this;
  2517. },
  2518. equals: function ( ray ) {
  2519. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2520. },
  2521. clone: function () {
  2522. return new THREE.Ray().copy( this );
  2523. }
  2524. };
  2525. THREE.Ray.__v1 = new THREE.Vector3();
  2526. THREE.Ray.__v2 = new THREE.Vector3();
  2527. /**
  2528. * @author bhouston / http://exocortex.com
  2529. * @author mrdoob / http://mrdoob.com/
  2530. */
  2531. THREE.Sphere = function ( center, radius ) {
  2532. this.center = center === undefined ? new THREE.Vector3() : center.clone();
  2533. this.radius = radius === undefined ? 0 : radius;
  2534. };
  2535. THREE.Sphere.prototype = {
  2536. constructor: THREE.Sphere,
  2537. set: function ( center, radius ) {
  2538. this.center.copy( center );
  2539. this.radius = radius;
  2540. return this;
  2541. },
  2542. setFromCenterAndPoints: function ( center, points ) {
  2543. var maxRadiusSq = 0;
  2544. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2545. var radiusSq = center.distanceToSquared( points[ i ] );
  2546. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2547. }
  2548. this.center = center;
  2549. this.radius = Math.sqrt( maxRadiusSq );
  2550. return this;
  2551. },
  2552. copy: function ( sphere ) {
  2553. this.center.copy( sphere.center );
  2554. this.radius = sphere.radius;
  2555. return this;
  2556. },
  2557. empty: function () {
  2558. return ( this.radius <= 0 );
  2559. },
  2560. containsPoint: function ( point ) {
  2561. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2562. },
  2563. distanceToPoint: function ( point ) {
  2564. return ( point.distanceTo( this.center ) - this.radius );
  2565. },
  2566. intersectsSphere: function ( sphere ) {
  2567. var radiusSum = this.radius + sphere.radius;
  2568. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2569. },
  2570. clampPoint: function ( point, optionalTarget ) {
  2571. var deltaLengthSq = this.center.distanceToSquared( point );
  2572. var result = optionalTarget || new THREE.Vector3();
  2573. result.copy( point );
  2574. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2575. result.sub( this.center ).normalize();
  2576. result.multiplyScalar( this.radius ).add( this.center );
  2577. }
  2578. return result;
  2579. },
  2580. getBoundingBox: function ( optionalTarget ) {
  2581. var box = optionalTarget || new THREE.Box3();
  2582. box.set( this.center, this.center );
  2583. box.expandByScalar( this.radius );
  2584. return box;
  2585. },
  2586. transform: function ( matrix ) {
  2587. this.center.applyMatrix4( matrix );
  2588. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2589. return this;
  2590. },
  2591. translate: function ( offset ) {
  2592. this.center.add( offset );
  2593. return this;
  2594. },
  2595. equals: function ( sphere ) {
  2596. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2597. },
  2598. clone: function () {
  2599. return new THREE.Sphere().copy( this );
  2600. }
  2601. };
  2602. /**
  2603. * @author mrdoob / http://mrdoob.com/
  2604. * @author alteredq / http://alteredqualia.com/
  2605. * @author bhouston / http://exocortex.com
  2606. */
  2607. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  2608. this.planes = [
  2609. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  2610. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  2611. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  2612. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  2613. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  2614. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  2615. ];
  2616. };
  2617. THREE.Frustum.prototype = {
  2618. set: function ( p0, p1, p2, p3, p4, p5 ) {
  2619. var planes = this.planes;
  2620. planes[0].copy( p0 );
  2621. planes[1].copy( p1 );
  2622. planes[2].copy( p2 );
  2623. planes[3].copy( p3 );
  2624. planes[4].copy( p4 );
  2625. planes[5].copy( p5 );
  2626. return this;
  2627. },
  2628. copy: function ( frustum ) {
  2629. var planes = this.planes;
  2630. for( var i = 0; i < 6; i ++ ) {
  2631. planes[i].copy( frustum.planes[i] );
  2632. }
  2633. return this;
  2634. },
  2635. setFromMatrix: function ( m ) {
  2636. var planes = this.planes;
  2637. var me = m.elements;
  2638. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2639. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2640. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2641. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  2642. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  2643. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  2644. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  2645. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  2646. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  2647. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  2648. return this;
  2649. },
  2650. intersectsObject: function ( object ) {
  2651. // this method is expanded inlined for performance reasons.
  2652. var matrix = object.matrixWorld;
  2653. var planes = this.planes;
  2654. var center = matrix.getPosition();
  2655. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  2656. for ( var i = 0; i < 6; i ++ ) {
  2657. var distance = planes[ i ].distanceToPoint( center );
  2658. if( distance < negRadius ) {
  2659. return false;
  2660. }
  2661. }
  2662. return true;
  2663. },
  2664. intersectsSphere: function ( sphere ) {
  2665. var planes = this.planes;
  2666. var center = sphere.center;
  2667. var negRadius = -sphere.radius;
  2668. for ( var i = 0; i < 6; i ++ ) {
  2669. var distance = planes[ i ].distanceToPoint( center );
  2670. if( distance < negRadius ) {
  2671. return false;
  2672. }
  2673. }
  2674. return true;
  2675. },
  2676. containsPoint: function ( point ) {
  2677. var planes = this.planes;
  2678. for ( var i = 0; i < 6; i ++ ) {
  2679. if( planes[ i ].distanceToPoint( point ) < 0 ) {
  2680. return false;
  2681. }
  2682. }
  2683. return true;
  2684. },
  2685. clone: function () {
  2686. var planes = this.planes;
  2687. return new THREE.Frustum( planes[0], planes[1], planes[2], planes[3], planes[4], planes[5] );
  2688. }
  2689. };
  2690. /**
  2691. * @author bhouston / http://exocortex.com
  2692. */
  2693. THREE.Plane = function ( normal, constant ) {
  2694. this.normal = normal !== undefined ? normal.clone() : new THREE.Vector3( 1, 0, 0 );
  2695. this.constant = constant !== undefined ? constant : 0;
  2696. };
  2697. THREE.Plane.prototype = {
  2698. constructor: THREE.Plane,
  2699. set: function ( normal, constant ) {
  2700. this.normal.copy( normal );
  2701. this.constant = constant;
  2702. return this;
  2703. },
  2704. setComponents: function ( x, y, z, w ) {
  2705. this.normal.set( x, y, z );
  2706. this.constant = w;
  2707. return this;
  2708. },
  2709. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  2710. this.normal.copy( normal ).normalize();
  2711. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  2712. return this;
  2713. },
  2714. setFromCoplanarPoints: function ( a, b, c ) {
  2715. var normal = THREE.Plane.__v1.subVectors( c, b ).cross( THREE.Plane.__v2.subVectors( a, b ) ).normalize();
  2716. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  2717. this.setFromNormalAndCoplanarPoint( normal, a );
  2718. return this;
  2719. },
  2720. copy: function ( plane ) {
  2721. this.normal.copy( plane.normal );
  2722. this.constant = plane.constant;
  2723. return this;
  2724. },
  2725. normalize: function () {
  2726. // Note: will lead to a divide by zero if the plane is invalid.
  2727. var inverseNormalLength = 1.0 / this.normal.length();
  2728. this.normal.multiplyScalar( inverseNormalLength );
  2729. this.constant *= inverseNormalLength;
  2730. return this;
  2731. },
  2732. negate: function () {
  2733. this.constant *= -1;
  2734. this.normal.negate();
  2735. return this;
  2736. },
  2737. distanceToPoint: function ( point ) {
  2738. return this.normal.dot( point ) + this.constant;
  2739. },
  2740. distanceToSphere: function ( sphere ) {
  2741. return this.distanceToPoint( sphere.center ) - sphere.radius;
  2742. },
  2743. projectPoint: function ( point, optionalTarget ) {
  2744. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  2745. },
  2746. orthoPoint: function ( point, optionalTarget ) {
  2747. var perpendicularMagnitude = this.distanceToPoint( point );
  2748. var result = optionalTarget || new THREE.Vector3();
  2749. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  2750. },
  2751. isIntersectionLine: function ( startPoint, endPoint ) {
  2752. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  2753. var startSign = this.distanceToPoint( startPoint );
  2754. var endSign = this.distanceToPoint( endPoint );
  2755. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  2756. },
  2757. intersectLine: function ( startPoint, endPoint, optionalTarget ) {
  2758. var result = optionalTarget || new THREE.Vector3();
  2759. var direction = THREE.Plane.__v1.subVectors( endPoint, startPoint );
  2760. var denominator = this.normal.dot( direction );
  2761. if ( denominator == 0 ) {
  2762. // line is coplanar, return origin
  2763. if( this.distanceToPoint( startPoint ) == 0 ) {
  2764. return result.copy( startPoint );
  2765. }
  2766. // Unsure if this is the correct method to handle this case.
  2767. return undefined;
  2768. }
  2769. var t = - ( startPoint.dot( this.normal ) + this.constant ) / denominator;
  2770. if( t < 0 || t > 1 ) {
  2771. return undefined;
  2772. }
  2773. return result.copy( direction ).multiplyScalar( t ).add( startPoint );
  2774. },
  2775. coplanarPoint: function ( optionalTarget ) {
  2776. var result = optionalTarget || new THREE.Vector3();
  2777. return result.copy( this.normal ).multiplyScalar( - this.constant );
  2778. },
  2779. transform: function ( matrix, optionalNormalMatrix ) {
  2780. // compute new normal based on theory here:
  2781. // http://www.songho.ca/opengl/gl_normaltransform.html
  2782. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getInverse( matrix ).transpose();
  2783. var newNormal = THREE.Plane.__v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  2784. var newCoplanarPoint = this.coplanarPoint( THREE.Plane.__v2 );
  2785. newCoplanarPoint.applyMatrix4( matrix );
  2786. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  2787. return this;
  2788. },
  2789. translate: function ( offset ) {
  2790. this.constant = this.constant - offset.dot( this.normal );
  2791. return this;
  2792. },
  2793. equals: function ( plane ) {
  2794. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  2795. },
  2796. clone: function () {
  2797. return new THREE.Plane().copy( this );
  2798. }
  2799. };
  2800. THREE.Plane.__vZero = new THREE.Vector3( 0, 0, 0 );
  2801. THREE.Plane.__v1 = new THREE.Vector3();
  2802. THREE.Plane.__v2 = new THREE.Vector3();
  2803. /**
  2804. * @author alteredq / http://alteredqualia.com/
  2805. */
  2806. THREE.Math = {
  2807. // Clamp value to range <a, b>
  2808. clamp: function ( x, a, b ) {
  2809. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2810. },
  2811. // Clamp value to range <a, inf)
  2812. clampBottom: function ( x, a ) {
  2813. return x < a ? a : x;
  2814. },
  2815. // Linear mapping from range <a1, a2> to range <b1, b2>
  2816. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2817. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2818. },
  2819. // Random float from <0, 1> with 16 bits of randomness
  2820. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2821. random16: function () {
  2822. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2823. },
  2824. // Random integer from <low, high> interval
  2825. randInt: function ( low, high ) {
  2826. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2827. },
  2828. // Random float from <low, high> interval
  2829. randFloat: function ( low, high ) {
  2830. return low + Math.random() * ( high - low );
  2831. },
  2832. // Random float from <-range/2, range/2> interval
  2833. randFloatSpread: function ( range ) {
  2834. return range * ( 0.5 - Math.random() );
  2835. },
  2836. sign: function ( x ) {
  2837. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2838. },
  2839. degToRad: function ( degrees ) {
  2840. return degrees * THREE.Math.__d2r;
  2841. },
  2842. radToDeg: function ( radians ) {
  2843. return radians * THREE.Math.__r2d;
  2844. }
  2845. };
  2846. THREE.Math.__d2r = Math.PI / 180;
  2847. THREE.Math.__r2d = 180 / Math.PI;
  2848. /**
  2849. * @author mikael emtinger / http://gomo.se/
  2850. * @author alteredq / http://alteredqualia.com/
  2851. * @author WestLangley / http://github.com/WestLangley
  2852. * @author bhouston / http://exocortex.com
  2853. */
  2854. THREE.Quaternion = function( x, y, z, w ) {
  2855. this.x = x || 0;
  2856. this.y = y || 0;
  2857. this.z = z || 0;
  2858. this.w = ( w !== undefined ) ? w : 1;
  2859. };
  2860. THREE.Quaternion.prototype = {
  2861. constructor: THREE.Quaternion,
  2862. set: function ( x, y, z, w ) {
  2863. this.x = x;
  2864. this.y = y;
  2865. this.z = z;
  2866. this.w = w;
  2867. return this;
  2868. },
  2869. copy: function ( q ) {
  2870. this.x = q.x;
  2871. this.y = q.y;
  2872. this.z = q.z;
  2873. this.w = q.w;
  2874. return this;
  2875. },
  2876. setFromEuler: function ( v, order ) {
  2877. // http://www.mathworks.com/matlabcentral/fileexchange/
  2878. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2879. // content/SpinCalc.m
  2880. var c1 = Math.cos( v.x / 2 );
  2881. var c2 = Math.cos( v.y / 2 );
  2882. var c3 = Math.cos( v.z / 2 );
  2883. var s1 = Math.sin( v.x / 2 );
  2884. var s2 = Math.sin( v.y / 2 );
  2885. var s3 = Math.sin( v.z / 2 );
  2886. if ( order === undefined || order === 'XYZ' ) {
  2887. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2888. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2889. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2890. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2891. } else if ( order === 'YXZ' ) {
  2892. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2893. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2894. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2895. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2896. } else if ( order === 'ZXY' ) {
  2897. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2898. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2899. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2900. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2901. } else if ( order === 'ZYX' ) {
  2902. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2903. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2904. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2905. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2906. } else if ( order === 'YZX' ) {
  2907. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2908. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2909. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2910. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2911. } else if ( order === 'XZY' ) {
  2912. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2913. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2914. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2915. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2916. }
  2917. return this;
  2918. },
  2919. setFromAxisAngle: function ( axis, angle ) {
  2920. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2921. // axis have to be normalized
  2922. var halfAngle = angle / 2,
  2923. s = Math.sin( halfAngle );
  2924. this.x = axis.x * s;
  2925. this.y = axis.y * s;
  2926. this.z = axis.z * s;
  2927. this.w = Math.cos( halfAngle );
  2928. return this;
  2929. },
  2930. setFromRotationMatrix: function ( m ) {
  2931. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2932. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2933. var te = m.elements,
  2934. m11 = te[0], m12 = te[4], m13 = te[8],
  2935. m21 = te[1], m22 = te[5], m23 = te[9],
  2936. m31 = te[2], m32 = te[6], m33 = te[10],
  2937. trace = m11 + m22 + m33,
  2938. s;
  2939. if ( trace > 0 ) {
  2940. s = 0.5 / Math.sqrt( trace + 1.0 );
  2941. this.w = 0.25 / s;
  2942. this.x = ( m32 - m23 ) * s;
  2943. this.y = ( m13 - m31 ) * s;
  2944. this.z = ( m21 - m12 ) * s;
  2945. } else if ( m11 > m22 && m11 > m33 ) {
  2946. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2947. this.w = (m32 - m23 ) / s;
  2948. this.x = 0.25 * s;
  2949. this.y = (m12 + m21 ) / s;
  2950. this.z = (m13 + m31 ) / s;
  2951. } else if ( m22 > m33 ) {
  2952. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2953. this.w = (m13 - m31 ) / s;
  2954. this.x = (m12 + m21 ) / s;
  2955. this.y = 0.25 * s;
  2956. this.z = (m23 + m32 ) / s;
  2957. } else {
  2958. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2959. this.w = ( m21 - m12 ) / s;
  2960. this.x = ( m13 + m31 ) / s;
  2961. this.y = ( m23 + m32 ) / s;
  2962. this.z = 0.25 * s;
  2963. }
  2964. return this;
  2965. },
  2966. inverse: function () {
  2967. this.conjugate().normalize();
  2968. return this;
  2969. },
  2970. conjugate: function () {
  2971. this.x *= -1;
  2972. this.y *= -1;
  2973. this.z *= -1;
  2974. return this;
  2975. },
  2976. lengthSq: function () {
  2977. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2978. },
  2979. length: function () {
  2980. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2981. },
  2982. normalize: function () {
  2983. var l = this.length();
  2984. if ( l === 0 ) {
  2985. this.x = 0;
  2986. this.y = 0;
  2987. this.z = 0;
  2988. this.w = 1;
  2989. } else {
  2990. l = 1 / l;
  2991. this.x = this.x * l;
  2992. this.y = this.y * l;
  2993. this.z = this.z * l;
  2994. this.w = this.w * l;
  2995. }
  2996. return this;
  2997. },
  2998. multiply: function ( b ) {
  2999. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3000. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  3001. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  3002. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3003. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3004. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3005. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3006. return this;
  3007. },
  3008. multiplyQuaternions: function ( a, b ) {
  3009. return this.copy( a ).multiply( b );
  3010. },
  3011. slerp: function ( qb, t ) {
  3012. var x = this.x, y = this.y, z = this.z, w = this.w;
  3013. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3014. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  3015. if ( cosHalfTheta < 0 ) {
  3016. this.w = -qb.w;
  3017. this.x = -qb.x;
  3018. this.y = -qb.y;
  3019. this.z = -qb.z;
  3020. cosHalfTheta = -cosHalfTheta;
  3021. } else {
  3022. this.copy( qb );
  3023. }
  3024. if ( cosHalfTheta >= 1.0 ) {
  3025. this.w = w;
  3026. this.x = x;
  3027. this.y = y;
  3028. this.z = z;
  3029. return this;
  3030. }
  3031. var halfTheta = Math.acos( cosHalfTheta );
  3032. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  3033. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  3034. this.w = 0.5 * ( w + this.w );
  3035. this.x = 0.5 * ( x + this.x );
  3036. this.y = 0.5 * ( y + this.y );
  3037. this.z = 0.5 * ( z + this.z );
  3038. return this;
  3039. }
  3040. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3041. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3042. this.w = ( w * ratioA + this.w * ratioB );
  3043. this.x = ( x * ratioA + this.x * ratioB );
  3044. this.y = ( y * ratioA + this.y * ratioB );
  3045. this.z = ( z * ratioA + this.z * ratioB );
  3046. return this;
  3047. },
  3048. equals: function ( v ) {
  3049. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  3050. },
  3051. clone: function () {
  3052. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  3053. }
  3054. }
  3055. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  3056. return qm.copy( qa ).slerp( qb, t );
  3057. }
  3058. /**
  3059. * Spline from Tween.js, slightly optimized (and trashed)
  3060. * http://sole.github.com/tween.js/examples/05_spline.html
  3061. *
  3062. * @author mrdoob / http://mrdoob.com/
  3063. * @author alteredq / http://alteredqualia.com/
  3064. */
  3065. THREE.Spline = function ( points ) {
  3066. this.points = points;
  3067. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3068. point, intPoint, weight, w2, w3,
  3069. pa, pb, pc, pd;
  3070. this.initFromArray = function( a ) {
  3071. this.points = [];
  3072. for ( var i = 0; i < a.length; i++ ) {
  3073. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3074. }
  3075. };
  3076. this.getPoint = function ( k ) {
  3077. point = ( this.points.length - 1 ) * k;
  3078. intPoint = Math.floor( point );
  3079. weight = point - intPoint;
  3080. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3081. c[ 1 ] = intPoint;
  3082. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3083. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3084. pa = this.points[ c[ 0 ] ];
  3085. pb = this.points[ c[ 1 ] ];
  3086. pc = this.points[ c[ 2 ] ];
  3087. pd = this.points[ c[ 3 ] ];
  3088. w2 = weight * weight;
  3089. w3 = weight * w2;
  3090. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3091. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3092. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3093. return v3;
  3094. };
  3095. this.getControlPointsArray = function () {
  3096. var i, p, l = this.points.length,
  3097. coords = [];
  3098. for ( i = 0; i < l; i ++ ) {
  3099. p = this.points[ i ];
  3100. coords[ i ] = [ p.x, p.y, p.z ];
  3101. }
  3102. return coords;
  3103. };
  3104. // approximate length by summing linear segments
  3105. this.getLength = function ( nSubDivisions ) {
  3106. var i, index, nSamples, position,
  3107. point = 0, intPoint = 0, oldIntPoint = 0,
  3108. oldPosition = new THREE.Vector3(),
  3109. tmpVec = new THREE.Vector3(),
  3110. chunkLengths = [],
  3111. totalLength = 0;
  3112. // first point has 0 length
  3113. chunkLengths[ 0 ] = 0;
  3114. if ( !nSubDivisions ) nSubDivisions = 100;
  3115. nSamples = this.points.length * nSubDivisions;
  3116. oldPosition.copy( this.points[ 0 ] );
  3117. for ( i = 1; i < nSamples; i ++ ) {
  3118. index = i / nSamples;
  3119. position = this.getPoint( index );
  3120. tmpVec.copy( position );
  3121. totalLength += tmpVec.distanceTo( oldPosition );
  3122. oldPosition.copy( position );
  3123. point = ( this.points.length - 1 ) * index;
  3124. intPoint = Math.floor( point );
  3125. if ( intPoint != oldIntPoint ) {
  3126. chunkLengths[ intPoint ] = totalLength;
  3127. oldIntPoint = intPoint;
  3128. }
  3129. }
  3130. // last point ends with total length
  3131. chunkLengths[ chunkLengths.length ] = totalLength;
  3132. return { chunks: chunkLengths, total: totalLength };
  3133. };
  3134. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3135. var i, j,
  3136. index, indexCurrent, indexNext,
  3137. linearDistance, realDistance,
  3138. sampling, position,
  3139. newpoints = [],
  3140. tmpVec = new THREE.Vector3(),
  3141. sl = this.getLength();
  3142. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3143. for ( i = 1; i < this.points.length; i++ ) {
  3144. //tmpVec.copy( this.points[ i - 1 ] );
  3145. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3146. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3147. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3148. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3149. indexNext = i / ( this.points.length - 1 );
  3150. for ( j = 1; j < sampling - 1; j++ ) {
  3151. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3152. position = this.getPoint( index );
  3153. newpoints.push( tmpVec.copy( position ).clone() );
  3154. }
  3155. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3156. }
  3157. this.points = newpoints;
  3158. };
  3159. // Catmull-Rom
  3160. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3161. var v0 = ( p2 - p0 ) * 0.5,
  3162. v1 = ( p3 - p1 ) * 0.5;
  3163. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3164. };
  3165. };
  3166. /**
  3167. * @author bhouston / http://exocortex.com
  3168. * @author mrdoob / http://mrdoob.com/
  3169. */
  3170. THREE.Triangle = function ( a, b, c ) {
  3171. this.a = new THREE.Vector3();
  3172. this.b = new THREE.Vector3();
  3173. this.c = new THREE.Vector3();
  3174. if( a !== undefined && b !== undefined && c !== undefined ) {
  3175. this.a.copy( a );
  3176. this.b.copy( b );
  3177. this.c.copy( c );
  3178. }
  3179. };
  3180. THREE.Triangle.normal = function( a, b, c, optionalTarget ) {
  3181. var result = optionalTarget || new THREE.Vector3();
  3182. result.subVectors( c, b );
  3183. THREE.Triangle.__v0.subVectors( a, b );
  3184. result.cross( THREE.Triangle.__v0 );
  3185. var resultLengthSq = result.lengthSq();
  3186. if( resultLengthSq > 0 ) {
  3187. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3188. }
  3189. return result.set( 0, 0, 0 );
  3190. };
  3191. // static/instance method to calculate barycoordinates
  3192. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3193. THREE.Triangle.barycoordFromPoint = function ( point, a, b, c, optionalTarget ) {
  3194. THREE.Triangle.__v0.subVectors( c, a );
  3195. THREE.Triangle.__v1.subVectors( b, a );
  3196. THREE.Triangle.__v2.subVectors( point, a );
  3197. var dot00 = THREE.Triangle.__v0.dot( THREE.Triangle.__v0 );
  3198. var dot01 = THREE.Triangle.__v0.dot( THREE.Triangle.__v1 );
  3199. var dot02 = THREE.Triangle.__v0.dot( THREE.Triangle.__v2 );
  3200. var dot11 = THREE.Triangle.__v1.dot( THREE.Triangle.__v1 );
  3201. var dot12 = THREE.Triangle.__v1.dot( THREE.Triangle.__v2 );
  3202. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3203. var result = optionalTarget || new THREE.Vector3();
  3204. // colinear or singular triangle
  3205. if( denom == 0 ) {
  3206. // arbitrary location outside of triangle?
  3207. // not sure if this is the best idea, maybe should be returning undefined
  3208. return result.set( -2, -1, -1 );
  3209. }
  3210. var invDenom = 1 / denom;
  3211. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3212. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3213. // barycoordinates must always sum to 1
  3214. return result.set( 1 - u - v, v, u );
  3215. };
  3216. THREE.Triangle.containsPoint = function ( point, a, b, c ) {
  3217. // NOTE: need to use __v3 here because __v0, __v1 and __v2 are used in barycoordFromPoint.
  3218. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, THREE.Triangle.__v3 );
  3219. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3220. };
  3221. THREE.Triangle.prototype = {
  3222. constructor: THREE.Triangle,
  3223. set: function ( a, b, c ) {
  3224. this.a.copy( a );
  3225. this.b.copy( b );
  3226. this.c.copy( c );
  3227. return this;
  3228. },
  3229. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3230. this.a.copy( points[i0] );
  3231. this.b.copy( points[i1] );
  3232. this.c.copy( points[i2] );
  3233. return this;
  3234. },
  3235. copy: function ( triangle ) {
  3236. this.a.copy( triangle.a );
  3237. this.b.copy( triangle.b );
  3238. this.c.copy( triangle.c );
  3239. return this;
  3240. },
  3241. area: function () {
  3242. THREE.Triangle.__v0.subVectors( this.c, this.b );
  3243. THREE.Triangle.__v1.subVectors( this.a, this.b );
  3244. return THREE.Triangle.__v0.cross( THREE.Triangle.__v1 ).length() * 0.5;
  3245. },
  3246. midpoint: function ( optionalTarget ) {
  3247. var result = optionalTarget || new THREE.Vector3();
  3248. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3249. },
  3250. normal: function ( optionalTarget ) {
  3251. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3252. },
  3253. plane: function ( optionalTarget ) {
  3254. var result = optionalTarget || new THREE.Plane();
  3255. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3256. },
  3257. barycoordFromPoint: function ( point, optionalTarget ) {
  3258. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3259. },
  3260. containsPoint: function ( point ) {
  3261. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3262. },
  3263. equals: function ( triangle ) {
  3264. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3265. },
  3266. clone: function () {
  3267. return new THREE.Triangle().copy( this );
  3268. }
  3269. };
  3270. THREE.Triangle.__v0 = new THREE.Vector3();
  3271. THREE.Triangle.__v1 = new THREE.Vector3();
  3272. THREE.Triangle.__v2 = new THREE.Vector3();
  3273. THREE.Triangle.__v3 = new THREE.Vector3();
  3274. /**
  3275. * @author mrdoob / http://mrdoob.com/
  3276. */
  3277. THREE.Vertex = function ( v ) {
  3278. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3279. return v;
  3280. };
  3281. /**
  3282. * @author mrdoob / http://mrdoob.com/
  3283. */
  3284. THREE.UV = function ( u, v ) {
  3285. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3286. return new THREE.Vector2( u, v );
  3287. };
  3288. /**
  3289. * @author alteredq / http://alteredqualia.com/
  3290. */
  3291. THREE.Clock = function ( autoStart ) {
  3292. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3293. this.startTime = 0;
  3294. this.oldTime = 0;
  3295. this.elapsedTime = 0;
  3296. this.running = false;
  3297. };
  3298. THREE.Clock.prototype.start = function () {
  3299. this.startTime = Date.now();
  3300. this.oldTime = this.startTime;
  3301. this.running = true;
  3302. };
  3303. THREE.Clock.prototype.stop = function () {
  3304. this.getElapsedTime();
  3305. this.running = false;
  3306. };
  3307. THREE.Clock.prototype.getElapsedTime = function () {
  3308. this.getDelta();
  3309. return this.elapsedTime;
  3310. };
  3311. THREE.Clock.prototype.getDelta = function () {
  3312. var diff = 0;
  3313. if ( this.autoStart && ! this.running ) {
  3314. this.start();
  3315. }
  3316. if ( this.running ) {
  3317. var newTime = Date.now();
  3318. diff = 0.001 * ( newTime - this.oldTime );
  3319. this.oldTime = newTime;
  3320. this.elapsedTime += diff;
  3321. }
  3322. return diff;
  3323. };/**
  3324. * https://github.com/mrdoob/eventdispatcher.js/
  3325. */
  3326. THREE.EventDispatcher = function () {
  3327. var listeners = {};
  3328. this.addEventListener = function ( type, listener ) {
  3329. if ( listeners[ type ] === undefined ) {
  3330. listeners[ type ] = [];
  3331. }
  3332. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3333. listeners[ type ].push( listener );
  3334. }
  3335. };
  3336. this.removeEventListener = function ( type, listener ) {
  3337. var index = listeners[ type ].indexOf( listener );
  3338. if ( index !== - 1 ) {
  3339. listeners[ type ].splice( index, 1 );
  3340. }
  3341. };
  3342. this.dispatchEvent = function ( event ) {
  3343. var listenerArray = listeners[ event.type ];
  3344. if ( listenerArray !== undefined ) {
  3345. event.target = this;
  3346. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3347. listenerArray[ i ].call( this, event );
  3348. }
  3349. }
  3350. };
  3351. };
  3352. /**
  3353. * @author mrdoob / http://mrdoob.com/
  3354. * @author bhouston / http://exocortex.com/
  3355. */
  3356. ( function ( THREE ) {
  3357. THREE.Raycaster = function ( origin, direction, near, far ) {
  3358. this.ray = new THREE.Ray( origin, direction );
  3359. // normalized ray.direction required for accurate distance calculations
  3360. if( this.ray.direction.length() > 0 ) {
  3361. this.ray.direction.normalize();
  3362. }
  3363. this.near = near || 0;
  3364. this.far = far || Infinity;
  3365. };
  3366. var sphere = new THREE.Sphere();
  3367. var localRay = new THREE.Ray();
  3368. var facePlane = new THREE.Plane();
  3369. var intersectPoint = new THREE.Vector3();
  3370. var inverseMatrix = new THREE.Matrix4();
  3371. var descSort = function ( a, b ) {
  3372. return a.distance - b.distance;
  3373. };
  3374. var intersectObject = function ( object, raycaster, intersects ) {
  3375. if ( object instanceof THREE.Particle ) {
  3376. var distance = raycaster.ray.distanceToPoint( object.matrixWorld.getPosition() );
  3377. if ( distance > object.scale.x ) {
  3378. return intersects;
  3379. }
  3380. intersects.push( {
  3381. distance: distance,
  3382. point: object.position,
  3383. face: null,
  3384. object: object
  3385. } );
  3386. } else if ( object instanceof THREE.Mesh ) {
  3387. // Checking boundingSphere distance to ray
  3388. sphere.set(
  3389. object.matrixWorld.getPosition(),
  3390. object.geometry.boundingSphere.radius* object.matrixWorld.getMaxScaleOnAxis() );
  3391. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3392. return intersects;
  3393. }
  3394. // Checking faces
  3395. var geometry = object.geometry;
  3396. var vertices = geometry.vertices;
  3397. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3398. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3399. var side = object.material.side;
  3400. var a, b, c, d;
  3401. var precision = raycaster.precision;
  3402. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  3403. inverseMatrix.getInverse( object.matrixWorld );
  3404. localRay.copy( raycaster.ray ).transform( inverseMatrix );
  3405. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3406. var face = geometry.faces[ f ];
  3407. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3408. if ( material === undefined ) continue;
  3409. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3410. var planeDistance = localRay.distanceToPlane( facePlane );
  3411. // bail if raycaster and plane are parallel
  3412. if ( Math.abs( planeDistance ) < precision ) continue;
  3413. // if negative distance, then plane is behind raycaster
  3414. if ( planeDistance < 0 ) continue;
  3415. // check if we hit the wrong side of a single sided face
  3416. side = material.side;
  3417. if( side !== THREE.DoubleSide ) {
  3418. var planeSign = localRay.direction.dot( facePlane.normal );
  3419. if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3420. }
  3421. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3422. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3423. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3424. if ( face instanceof THREE.Face3 ) {
  3425. a = vertices[ face.a ];
  3426. b = vertices[ face.b ];
  3427. c = vertices[ face.c ];
  3428. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3429. } else if ( face instanceof THREE.Face4 ) {
  3430. a = vertices[ face.a ];
  3431. b = vertices[ face.b ];
  3432. c = vertices[ face.c ];
  3433. d = vertices[ face.d ];
  3434. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3435. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3436. } else {
  3437. // This is added because if we call out of this if/else group when none of the cases
  3438. // match it will add a point to the intersection list erroneously.
  3439. throw Error( "face type not supported" );
  3440. }
  3441. intersects.push( {
  3442. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3443. point: raycaster.ray.at( planeDistance ),
  3444. face: face,
  3445. faceIndex: f,
  3446. object: object
  3447. } );
  3448. }
  3449. }
  3450. };
  3451. var intersectDescendants = function ( object, raycaster, intersects ) {
  3452. var descendants = object.getDescendants();
  3453. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3454. intersectObject( descendants[ i ], raycaster, intersects );
  3455. }
  3456. };
  3457. //
  3458. THREE.Raycaster.prototype.precision = 0.0001;
  3459. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3460. this.ray.set( origin, direction );
  3461. // normalized ray.direction required for accurate distance calculations
  3462. if( this.ray.direction.length() > 0 ) {
  3463. this.ray.direction.normalize();
  3464. }
  3465. };
  3466. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3467. var intersects = [];
  3468. if ( recursive === true ) {
  3469. intersectDescendants( object, this, intersects );
  3470. }
  3471. intersectObject( object, this, intersects );
  3472. intersects.sort( descSort );
  3473. return intersects;
  3474. };
  3475. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3476. var intersects = [];
  3477. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3478. intersectObject( objects[ i ], this, intersects );
  3479. if ( recursive === true ) {
  3480. intersectDescendants( objects[ i ], this, intersects );
  3481. }
  3482. }
  3483. intersects.sort( descSort );
  3484. return intersects;
  3485. };
  3486. }( THREE ) );
  3487. /**
  3488. * @author mrdoob / http://mrdoob.com/
  3489. * @author mikael emtinger / http://gomo.se/
  3490. * @author alteredq / http://alteredqualia.com/
  3491. */
  3492. THREE.Object3D = function () {
  3493. this.id = THREE.Object3DIdCount ++;
  3494. this.name = '';
  3495. this.properties = {};
  3496. this.parent = undefined;
  3497. this.children = [];
  3498. this.up = new THREE.Vector3( 0, 1, 0 );
  3499. this.position = new THREE.Vector3();
  3500. this.rotation = new THREE.Vector3();
  3501. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3502. this.scale = new THREE.Vector3( 1, 1, 1 );
  3503. this.renderDepth = null;
  3504. this.rotationAutoUpdate = true;
  3505. this.matrix = new THREE.Matrix4();
  3506. this.matrixWorld = new THREE.Matrix4();
  3507. this.matrixRotationWorld = new THREE.Matrix4();
  3508. this.matrixAutoUpdate = true;
  3509. this.matrixWorldNeedsUpdate = true;
  3510. this.quaternion = new THREE.Quaternion();
  3511. this.useQuaternion = false;
  3512. this.visible = true;
  3513. this.castShadow = false;
  3514. this.receiveShadow = false;
  3515. this.frustumCulled = true;
  3516. this._vector = new THREE.Vector3();
  3517. };
  3518. THREE.Object3D.prototype = {
  3519. constructor: THREE.Object3D,
  3520. applyMatrix: function ( matrix ) {
  3521. this.matrix.multiplyMatrices( matrix, this.matrix );
  3522. this.scale.getScaleFromMatrix( this.matrix );
  3523. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  3524. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  3525. this.position.getPositionFromMatrix( this.matrix );
  3526. },
  3527. translate: function ( distance, axis ) {
  3528. this.matrix.rotateAxis( axis );
  3529. this.position.add( axis.multiplyScalar( distance ) );
  3530. },
  3531. translateX: function ( distance ) {
  3532. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  3533. },
  3534. translateY: function ( distance ) {
  3535. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  3536. },
  3537. translateZ: function ( distance ) {
  3538. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  3539. },
  3540. localToWorld: function ( vector ) {
  3541. return vector.applyMatrix4( this.matrixWorld );
  3542. },
  3543. worldToLocal: function ( vector ) {
  3544. return vector.applyMatrix4( THREE.Object3D.__m1.getInverse( this.matrixWorld ) );
  3545. },
  3546. lookAt: function ( vector ) {
  3547. // TODO: Add hierarchy support.
  3548. this.matrix.lookAt( vector, this.position, this.up );
  3549. if ( this.rotationAutoUpdate ) {
  3550. if ( this.useQuaternion === false ) {
  3551. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3552. } else {
  3553. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3554. }
  3555. }
  3556. },
  3557. add: function ( object ) {
  3558. if ( object === this ) {
  3559. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3560. return;
  3561. }
  3562. if ( object instanceof THREE.Object3D ) {
  3563. if ( object.parent !== undefined ) {
  3564. object.parent.remove( object );
  3565. }
  3566. object.parent = this;
  3567. this.children.push( object );
  3568. // add to scene
  3569. var scene = this;
  3570. while ( scene.parent !== undefined ) {
  3571. scene = scene.parent;
  3572. }
  3573. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3574. scene.__addObject( object );
  3575. }
  3576. }
  3577. },
  3578. remove: function ( object ) {
  3579. var index = this.children.indexOf( object );
  3580. if ( index !== - 1 ) {
  3581. object.parent = undefined;
  3582. this.children.splice( index, 1 );
  3583. // remove from scene
  3584. var scene = this;
  3585. while ( scene.parent !== undefined ) {
  3586. scene = scene.parent;
  3587. }
  3588. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3589. scene.__removeObject( object );
  3590. }
  3591. }
  3592. },
  3593. traverse: function ( callback ) {
  3594. callback( this );
  3595. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3596. this.children[ i ].traverse( callback );
  3597. }
  3598. },
  3599. getChildByName: function ( name, recursive ) {
  3600. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3601. var child = this.children[ i ];
  3602. if ( child.name === name ) {
  3603. return child;
  3604. }
  3605. if ( recursive === true ) {
  3606. child = child.getChildByName( name, recursive );
  3607. if ( child !== undefined ) {
  3608. return child;
  3609. }
  3610. }
  3611. }
  3612. return undefined;
  3613. },
  3614. getDescendants: function ( array ) {
  3615. if ( array === undefined ) array = [];
  3616. Array.prototype.push.apply( array, this.children );
  3617. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3618. this.children[ i ].getDescendants( array );
  3619. }
  3620. return array;
  3621. },
  3622. updateMatrix: function () {
  3623. this.matrix.setPosition( this.position );
  3624. if ( this.useQuaternion === false ) {
  3625. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  3626. } else {
  3627. this.matrix.setRotationFromQuaternion( this.quaternion );
  3628. }
  3629. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  3630. this.matrix.scale( this.scale );
  3631. }
  3632. this.matrixWorldNeedsUpdate = true;
  3633. },
  3634. updateMatrixWorld: function ( force ) {
  3635. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3636. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3637. if ( this.parent === undefined ) {
  3638. this.matrixWorld.copy( this.matrix );
  3639. } else {
  3640. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  3641. }
  3642. this.matrixWorldNeedsUpdate = false;
  3643. force = true;
  3644. }
  3645. // update children
  3646. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3647. this.children[ i ].updateMatrixWorld( force );
  3648. }
  3649. },
  3650. clone: function ( object ) {
  3651. if ( object === undefined ) object = new THREE.Object3D();
  3652. object.name = this.name;
  3653. object.up.copy( this.up );
  3654. object.position.copy( this.position );
  3655. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3656. object.eulerOrder = this.eulerOrder;
  3657. object.scale.copy( this.scale );
  3658. object.renderDepth = this.renderDepth;
  3659. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3660. object.matrix.copy( this.matrix );
  3661. object.matrixWorld.copy( this.matrixWorld );
  3662. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  3663. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3664. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3665. object.quaternion.copy( this.quaternion );
  3666. object.useQuaternion = this.useQuaternion;
  3667. object.visible = this.visible;
  3668. object.castShadow = this.castShadow;
  3669. object.receiveShadow = this.receiveShadow;
  3670. object.frustumCulled = this.frustumCulled;
  3671. for ( var i = 0; i < this.children.length; i ++ ) {
  3672. var child = this.children[ i ];
  3673. object.add( child.clone() );
  3674. }
  3675. return object;
  3676. }
  3677. };
  3678. THREE.Object3D.__m1 = new THREE.Matrix4();
  3679. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3680. THREE.Object3DIdCount = 0;
  3681. /**
  3682. * @author mrdoob / http://mrdoob.com/
  3683. * @author supereggbert / http://www.paulbrunt.co.uk/
  3684. * @author julianwa / https://github.com/julianwa
  3685. */
  3686. THREE.Projector = function() {
  3687. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3688. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3689. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3690. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3691. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3692. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3693. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3694. _vector3 = new THREE.Vector3(),
  3695. _vector4 = new THREE.Vector4(),
  3696. _viewMatrix = new THREE.Matrix4(),
  3697. _viewProjectionMatrix = new THREE.Matrix4(),
  3698. _modelMatrix,
  3699. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3700. _normalMatrix = new THREE.Matrix3(),
  3701. _normalViewMatrix = new THREE.Matrix3(),
  3702. _centroid = new THREE.Vector3(),
  3703. _frustum = new THREE.Frustum(),
  3704. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3705. _clippedVertex2PositionScreen = new THREE.Vector4(),
  3706. _face3VertexNormals;
  3707. this.projectVector = function ( vector, camera ) {
  3708. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3709. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  3710. return vector.applyMatrix4( _viewProjectionMatrix );
  3711. };
  3712. this.unprojectVector = function ( vector, camera ) {
  3713. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3714. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  3715. return vector.applyMatrix4( _viewProjectionMatrix );
  3716. };
  3717. this.pickingRay = function ( vector, camera ) {
  3718. // set two vectors with opposing z values
  3719. vector.z = -1.0;
  3720. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3721. this.unprojectVector( vector, camera );
  3722. this.unprojectVector( end, camera );
  3723. // find direction from vector to end
  3724. end.sub( vector ).normalize();
  3725. return new THREE.Raycaster( vector, end );
  3726. };
  3727. var projectGraph = function ( root, sortObjects ) {
  3728. _objectCount = 0;
  3729. _renderData.objects.length = 0;
  3730. _renderData.sprites.length = 0;
  3731. _renderData.lights.length = 0;
  3732. var projectObject = function ( parent ) {
  3733. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3734. var object = parent.children[ c ];
  3735. if ( object.visible === false ) continue;
  3736. if ( object instanceof THREE.Light ) {
  3737. _renderData.lights.push( object );
  3738. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3739. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  3740. _object = getNextObjectInPool();
  3741. _object.object = object;
  3742. if ( object.renderDepth !== null ) {
  3743. _object.z = object.renderDepth;
  3744. } else {
  3745. _vector3.copy( object.matrixWorld.getPosition() );
  3746. _vector3.applyMatrix4( _viewProjectionMatrix );
  3747. _object.z = _vector3.z;
  3748. }
  3749. _renderData.objects.push( _object );
  3750. }
  3751. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  3752. _object = getNextObjectInPool();
  3753. _object.object = object;
  3754. // TODO: Find an elegant and performant solution and remove this dupe code.
  3755. if ( object.renderDepth !== null ) {
  3756. _object.z = object.renderDepth;
  3757. } else {
  3758. _vector3.copy( object.matrixWorld.getPosition() );
  3759. _vector3.applyMatrix4( _viewProjectionMatrix );
  3760. _object.z = _vector3.z;
  3761. }
  3762. _renderData.sprites.push( _object );
  3763. } else {
  3764. _object = getNextObjectInPool();
  3765. _object.object = object;
  3766. if ( object.renderDepth !== null ) {
  3767. _object.z = object.renderDepth;
  3768. } else {
  3769. _vector3.copy( object.matrixWorld.getPosition() );
  3770. _vector3.applyMatrix4( _viewProjectionMatrix );
  3771. _object.z = _vector3.z;
  3772. }
  3773. _renderData.objects.push( _object );
  3774. }
  3775. projectObject( object );
  3776. }
  3777. };
  3778. projectObject( root );
  3779. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  3780. return _renderData;
  3781. };
  3782. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  3783. var near = camera.near, far = camera.far, visible = false,
  3784. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  3785. geometry, vertices, vertex, vertexPositionScreen,
  3786. faces, face, faceVertexNormals, faceVertexUvs, uvs,
  3787. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  3788. _face3Count = 0;
  3789. _face4Count = 0;
  3790. _lineCount = 0;
  3791. _particleCount = 0;
  3792. _renderData.elements.length = 0;
  3793. scene.updateMatrixWorld();
  3794. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  3795. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  3796. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  3797. _normalViewMatrix.getInverse( _viewMatrix );
  3798. _normalViewMatrix.transpose();
  3799. _frustum.setFromMatrix( _viewProjectionMatrix );
  3800. _renderData = projectGraph( scene, sortObjects );
  3801. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  3802. object = _renderData.objects[ o ].object;
  3803. _modelMatrix = object.matrixWorld;
  3804. _vertexCount = 0;
  3805. if ( object instanceof THREE.Mesh ) {
  3806. geometry = object.geometry;
  3807. vertices = geometry.vertices;
  3808. faces = geometry.faces;
  3809. faceVertexUvs = geometry.faceVertexUvs;
  3810. _normalMatrix.getInverse( _modelMatrix );
  3811. _normalMatrix.transpose();
  3812. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3813. objectMaterials = isFaceMaterial === true ? object.material : null;
  3814. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  3815. _vertex = getNextVertexInPool();
  3816. _vertex.positionWorld.copy( vertices[ v ] );
  3817. _vertex.positionWorld.applyMatrix4( _modelMatrix );
  3818. _vertex.positionScreen.copy( _vertex.positionWorld );
  3819. _vertex.positionScreen.applyMatrix4( _viewProjectionMatrix );
  3820. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  3821. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  3822. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  3823. }
  3824. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  3825. face = faces[ f ];
  3826. var material = isFaceMaterial === true
  3827. ? objectMaterials.materials[ face.materialIndex ]
  3828. : object.material;
  3829. if ( material === undefined ) continue;
  3830. var side = material.side;
  3831. if ( face instanceof THREE.Face3 ) {
  3832. v1 = _vertexPool[ face.a ];
  3833. v2 = _vertexPool[ face.b ];
  3834. v3 = _vertexPool[ face.c ];
  3835. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  3836. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3837. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  3838. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3839. _face = getNextFace3InPool();
  3840. _face.v1.copy( v1 );
  3841. _face.v2.copy( v2 );
  3842. _face.v3.copy( v3 );
  3843. } else {
  3844. continue;
  3845. }
  3846. } else {
  3847. continue;
  3848. }
  3849. } else if ( face instanceof THREE.Face4 ) {
  3850. v1 = _vertexPool[ face.a ];
  3851. v2 = _vertexPool[ face.b ];
  3852. v3 = _vertexPool[ face.c ];
  3853. v4 = _vertexPool[ face.d ];
  3854. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  3855. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3856. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  3857. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  3858. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  3859. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3860. _face = getNextFace4InPool();
  3861. _face.v1.copy( v1 );
  3862. _face.v2.copy( v2 );
  3863. _face.v3.copy( v3 );
  3864. _face.v4.copy( v4 );
  3865. } else {
  3866. continue;
  3867. }
  3868. } else {
  3869. continue;
  3870. }
  3871. }
  3872. _face.normalModel.copy( face.normal );
  3873. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  3874. _face.normalModel.negate();
  3875. }
  3876. _face.normalModel.applyMatrix3( _normalMatrix );
  3877. _face.normalModel.normalize();
  3878. _face.normalModelView.copy( _face.normalModel );
  3879. _face.normalModelView.applyMatrix3( _normalViewMatrix );
  3880. _face.centroidModel.copy( face.centroid );
  3881. _face.centroidModel.applyMatrix4( _modelMatrix );
  3882. faceVertexNormals = face.vertexNormals;
  3883. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  3884. var normalModel = _face.vertexNormalsModel[ n ];
  3885. normalModel.copy( faceVertexNormals[ n ] );
  3886. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  3887. normalModel.negate();
  3888. }
  3889. normalModel.applyMatrix3( _normalMatrix );
  3890. normalModel.normalize();
  3891. var normalModelView = _face.vertexNormalsModelView[ n ];
  3892. normalModelView.copy( normalModel );
  3893. normalModelView.applyMatrix3( _normalViewMatrix );
  3894. }
  3895. _face.vertexNormalsLength = faceVertexNormals.length;
  3896. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  3897. uvs = faceVertexUvs[ c ][ f ];
  3898. if ( uvs === undefined ) continue;
  3899. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  3900. _face.uvs[ c ][ u ] = uvs[ u ];
  3901. }
  3902. }
  3903. _face.color = face.color;
  3904. _face.material = material;
  3905. _centroid.copy( _face.centroidModel )
  3906. _centroid.applyMatrix4( _viewProjectionMatrix );
  3907. _face.z = _centroid.z;
  3908. _renderData.elements.push( _face );
  3909. }
  3910. } else if ( object instanceof THREE.Line ) {
  3911. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  3912. vertices = object.geometry.vertices;
  3913. v1 = getNextVertexInPool();
  3914. v1.positionScreen.copy( vertices[ 0 ] );
  3915. v1.positionScreen.applyMatrix4( _modelViewProjectionMatrix );
  3916. // Handle LineStrip and LinePieces
  3917. var step = object.type === THREE.LinePieces ? 2 : 1;
  3918. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  3919. v1 = getNextVertexInPool();
  3920. v1.positionScreen.copy( vertices[ v ] );
  3921. v1.positionScreen.applyMatrix4( _modelViewProjectionMatrix );
  3922. if ( ( v + 1 ) % step > 0 ) continue;
  3923. v2 = _vertexPool[ _vertexCount - 2 ];
  3924. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  3925. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  3926. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  3927. // Perform the perspective divide
  3928. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  3929. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  3930. _line = getNextLineInPool();
  3931. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  3932. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  3933. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  3934. _line.material = object.material;
  3935. _renderData.elements.push( _line );
  3936. }
  3937. }
  3938. }
  3939. }
  3940. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  3941. object = _renderData.sprites[ o ].object;
  3942. _modelMatrix = object.matrixWorld;
  3943. if ( object instanceof THREE.Particle ) {
  3944. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  3945. _vector4.applyMatrix4( _viewProjectionMatrix );
  3946. _vector4.z /= _vector4.w;
  3947. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  3948. _particle = getNextParticleInPool();
  3949. _particle.object = object;
  3950. _particle.x = _vector4.x / _vector4.w;
  3951. _particle.y = _vector4.y / _vector4.w;
  3952. _particle.z = _vector4.z;
  3953. _particle.rotation = object.rotation.z;
  3954. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  3955. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  3956. _particle.material = object.material;
  3957. _renderData.elements.push( _particle );
  3958. }
  3959. }
  3960. }
  3961. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  3962. return _renderData;
  3963. };
  3964. // Pools
  3965. function getNextObjectInPool() {
  3966. if ( _objectCount === _objectPoolLength ) {
  3967. var object = new THREE.RenderableObject();
  3968. _objectPool.push( object );
  3969. _objectPoolLength ++;
  3970. _objectCount ++;
  3971. return object;
  3972. }
  3973. return _objectPool[ _objectCount ++ ];
  3974. }
  3975. function getNextVertexInPool() {
  3976. if ( _vertexCount === _vertexPoolLength ) {
  3977. var vertex = new THREE.RenderableVertex();
  3978. _vertexPool.push( vertex );
  3979. _vertexPoolLength ++;
  3980. _vertexCount ++;
  3981. return vertex;
  3982. }
  3983. return _vertexPool[ _vertexCount ++ ];
  3984. }
  3985. function getNextFace3InPool() {
  3986. if ( _face3Count === _face3PoolLength ) {
  3987. var face = new THREE.RenderableFace3();
  3988. _face3Pool.push( face );
  3989. _face3PoolLength ++;
  3990. _face3Count ++;
  3991. return face;
  3992. }
  3993. return _face3Pool[ _face3Count ++ ];
  3994. }
  3995. function getNextFace4InPool() {
  3996. if ( _face4Count === _face4PoolLength ) {
  3997. var face = new THREE.RenderableFace4();
  3998. _face4Pool.push( face );
  3999. _face4PoolLength ++;
  4000. _face4Count ++;
  4001. return face;
  4002. }
  4003. return _face4Pool[ _face4Count ++ ];
  4004. }
  4005. function getNextLineInPool() {
  4006. if ( _lineCount === _linePoolLength ) {
  4007. var line = new THREE.RenderableLine();
  4008. _linePool.push( line );
  4009. _linePoolLength ++;
  4010. _lineCount ++
  4011. return line;
  4012. }
  4013. return _linePool[ _lineCount ++ ];
  4014. }
  4015. function getNextParticleInPool() {
  4016. if ( _particleCount === _particlePoolLength ) {
  4017. var particle = new THREE.RenderableParticle();
  4018. _particlePool.push( particle );
  4019. _particlePoolLength ++;
  4020. _particleCount ++
  4021. return particle;
  4022. }
  4023. return _particlePool[ _particleCount ++ ];
  4024. }
  4025. //
  4026. function painterSort( a, b ) {
  4027. return b.z - a.z;
  4028. }
  4029. function clipLine( s1, s2 ) {
  4030. var alpha1 = 0, alpha2 = 1,
  4031. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4032. // Z = -1 and Z = +1, respectively.
  4033. bc1near = s1.z + s1.w,
  4034. bc2near = s2.z + s2.w,
  4035. bc1far = - s1.z + s1.w,
  4036. bc2far = - s2.z + s2.w;
  4037. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4038. // Both vertices lie entirely within all clip planes.
  4039. return true;
  4040. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4041. // Both vertices lie entirely outside one of the clip planes.
  4042. return false;
  4043. } else {
  4044. // The line segment spans at least one clip plane.
  4045. if ( bc1near < 0 ) {
  4046. // v1 lies outside the near plane, v2 inside
  4047. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4048. } else if ( bc2near < 0 ) {
  4049. // v2 lies outside the near plane, v1 inside
  4050. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4051. }
  4052. if ( bc1far < 0 ) {
  4053. // v1 lies outside the far plane, v2 inside
  4054. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4055. } else if ( bc2far < 0 ) {
  4056. // v2 lies outside the far plane, v2 inside
  4057. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4058. }
  4059. if ( alpha2 < alpha1 ) {
  4060. // The line segment spans two boundaries, but is outside both of them.
  4061. // (This can't happen when we're only clipping against just near/far but good
  4062. // to leave the check here for future usage if other clip planes are added.)
  4063. return false;
  4064. } else {
  4065. // Update the s1 and s2 vertices to match the clipped line segment.
  4066. s1.lerp( s2, alpha1 );
  4067. s2.lerp( s1, 1 - alpha2 );
  4068. return true;
  4069. }
  4070. }
  4071. }
  4072. };
  4073. /**
  4074. * @author mrdoob / http://mrdoob.com/
  4075. * @author alteredq / http://alteredqualia.com/
  4076. */
  4077. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4078. this.a = a;
  4079. this.b = b;
  4080. this.c = c;
  4081. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4082. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4083. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4084. this.vertexColors = color instanceof Array ? color : [];
  4085. this.vertexTangents = [];
  4086. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4087. this.centroid = new THREE.Vector3();
  4088. };
  4089. THREE.Face3.prototype = {
  4090. constructor: THREE.Face3,
  4091. clone: function () {
  4092. var face = new THREE.Face3( this.a, this.b, this.c );
  4093. face.normal.copy( this.normal );
  4094. face.color.copy( this.color );
  4095. face.centroid.copy( this.centroid );
  4096. face.materialIndex = this.materialIndex;
  4097. var i, il;
  4098. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4099. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4100. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4101. return face;
  4102. }
  4103. };
  4104. /**
  4105. * @author mrdoob / http://mrdoob.com/
  4106. * @author alteredq / http://alteredqualia.com/
  4107. */
  4108. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4109. this.a = a;
  4110. this.b = b;
  4111. this.c = c;
  4112. this.d = d;
  4113. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4114. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4115. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4116. this.vertexColors = color instanceof Array ? color : [];
  4117. this.vertexTangents = [];
  4118. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4119. this.centroid = new THREE.Vector3();
  4120. };
  4121. THREE.Face4.prototype = {
  4122. constructor: THREE.Face4,
  4123. clone: function () {
  4124. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4125. face.normal.copy( this.normal );
  4126. face.color.copy( this.color );
  4127. face.centroid.copy( this.centroid );
  4128. face.materialIndex = this.materialIndex;
  4129. var i, il;
  4130. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4131. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4132. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4133. return face;
  4134. }
  4135. };
  4136. /**
  4137. * @author mrdoob / http://mrdoob.com/
  4138. * @author kile / http://kile.stravaganza.org/
  4139. * @author alteredq / http://alteredqualia.com/
  4140. * @author mikael emtinger / http://gomo.se/
  4141. * @author zz85 / http://www.lab4games.net/zz85/blog
  4142. * @author bhouston / http://exocortex.com
  4143. */
  4144. THREE.Geometry = function () {
  4145. THREE.EventDispatcher.call( this );
  4146. this.id = THREE.GeometryIdCount ++;
  4147. this.name = '';
  4148. this.vertices = [];
  4149. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4150. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4151. this.faces = [];
  4152. this.faceUvs = [[]];
  4153. this.faceVertexUvs = [[]];
  4154. this.morphTargets = [];
  4155. this.morphColors = [];
  4156. this.morphNormals = [];
  4157. this.skinWeights = [];
  4158. this.skinIndices = [];
  4159. this.lineDistances = [];
  4160. this.boundingBox = null;
  4161. this.boundingSphere = null;
  4162. this.hasTangents = false;
  4163. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4164. // update flags
  4165. this.verticesNeedUpdate = false;
  4166. this.elementsNeedUpdate = false;
  4167. this.uvsNeedUpdate = false;
  4168. this.normalsNeedUpdate = false;
  4169. this.tangentsNeedUpdate = false;
  4170. this.colorsNeedUpdate = false;
  4171. this.lineDistancesNeedUpdate = false;
  4172. this.buffersNeedUpdate = false;
  4173. };
  4174. THREE.Geometry.prototype = {
  4175. constructor: THREE.Geometry,
  4176. applyMatrix: function ( matrix ) {
  4177. var normalMatrix = new THREE.Matrix3().getInverse( matrix ).transpose();
  4178. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4179. var vertex = this.vertices[ i ];
  4180. vertex.applyMatrix4( matrix );
  4181. }
  4182. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4183. var face = this.faces[ i ];
  4184. face.normal.applyMatrix3( normalMatrix ).normalize();
  4185. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4186. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4187. }
  4188. face.centroid.applyMatrix4( matrix );
  4189. }
  4190. },
  4191. computeCentroids: function () {
  4192. var f, fl, face;
  4193. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4194. face = this.faces[ f ];
  4195. face.centroid.set( 0, 0, 0 );
  4196. if ( face instanceof THREE.Face3 ) {
  4197. face.centroid.add( this.vertices[ face.a ] );
  4198. face.centroid.add( this.vertices[ face.b ] );
  4199. face.centroid.add( this.vertices[ face.c ] );
  4200. face.centroid.divideScalar( 3 );
  4201. } else if ( face instanceof THREE.Face4 ) {
  4202. face.centroid.add( this.vertices[ face.a ] );
  4203. face.centroid.add( this.vertices[ face.b ] );
  4204. face.centroid.add( this.vertices[ face.c ] );
  4205. face.centroid.add( this.vertices[ face.d ] );
  4206. face.centroid.divideScalar( 4 );
  4207. }
  4208. }
  4209. },
  4210. computeFaceNormals: function () {
  4211. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  4212. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4213. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4214. face = this.faces[ f ];
  4215. vA = this.vertices[ face.a ];
  4216. vB = this.vertices[ face.b ];
  4217. vC = this.vertices[ face.c ];
  4218. cb.subVectors( vC, vB );
  4219. ab.subVectors( vA, vB );
  4220. cb.cross( ab );
  4221. cb.normalize();
  4222. face.normal.copy( cb );
  4223. }
  4224. },
  4225. computeVertexNormals: function ( areaWeighted ) {
  4226. var v, vl, f, fl, face, vertices;
  4227. // create internal buffers for reuse when calling this method repeatedly
  4228. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4229. if ( this.__tmpVertices === undefined ) {
  4230. this.__tmpVertices = new Array( this.vertices.length );
  4231. vertices = this.__tmpVertices;
  4232. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4233. vertices[ v ] = new THREE.Vector3();
  4234. }
  4235. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4236. face = this.faces[ f ];
  4237. if ( face instanceof THREE.Face3 ) {
  4238. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4239. } else if ( face instanceof THREE.Face4 ) {
  4240. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4241. }
  4242. }
  4243. } else {
  4244. vertices = this.__tmpVertices;
  4245. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4246. vertices[ v ].set( 0, 0, 0 );
  4247. }
  4248. }
  4249. if ( areaWeighted ) {
  4250. // vertex normals weighted by triangle areas
  4251. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4252. var vA, vB, vC, vD;
  4253. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4254. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4255. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4256. face = this.faces[ f ];
  4257. if ( face instanceof THREE.Face3 ) {
  4258. vA = this.vertices[ face.a ];
  4259. vB = this.vertices[ face.b ];
  4260. vC = this.vertices[ face.c ];
  4261. cb.subVectors( vC, vB );
  4262. ab.subVectors( vA, vB );
  4263. cb.cross( ab );
  4264. vertices[ face.a ].add( cb );
  4265. vertices[ face.b ].add( cb );
  4266. vertices[ face.c ].add( cb );
  4267. } else if ( face instanceof THREE.Face4 ) {
  4268. vA = this.vertices[ face.a ];
  4269. vB = this.vertices[ face.b ];
  4270. vC = this.vertices[ face.c ];
  4271. vD = this.vertices[ face.d ];
  4272. // abd
  4273. db.subVectors( vD, vB );
  4274. ab.subVectors( vA, vB );
  4275. db.cross( ab );
  4276. vertices[ face.a ].add( db );
  4277. vertices[ face.b ].add( db );
  4278. vertices[ face.d ].add( db );
  4279. // bcd
  4280. dc.subVectors( vD, vC );
  4281. bc.subVectors( vB, vC );
  4282. dc.cross( bc );
  4283. vertices[ face.b ].add( dc );
  4284. vertices[ face.c ].add( dc );
  4285. vertices[ face.d ].add( dc );
  4286. }
  4287. }
  4288. } else {
  4289. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4290. face = this.faces[ f ];
  4291. if ( face instanceof THREE.Face3 ) {
  4292. vertices[ face.a ].add( face.normal );
  4293. vertices[ face.b ].add( face.normal );
  4294. vertices[ face.c ].add( face.normal );
  4295. } else if ( face instanceof THREE.Face4 ) {
  4296. vertices[ face.a ].add( face.normal );
  4297. vertices[ face.b ].add( face.normal );
  4298. vertices[ face.c ].add( face.normal );
  4299. vertices[ face.d ].add( face.normal );
  4300. }
  4301. }
  4302. }
  4303. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4304. vertices[ v ].normalize();
  4305. }
  4306. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4307. face = this.faces[ f ];
  4308. if ( face instanceof THREE.Face3 ) {
  4309. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4310. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4311. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4312. } else if ( face instanceof THREE.Face4 ) {
  4313. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4314. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4315. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4316. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4317. }
  4318. }
  4319. },
  4320. computeMorphNormals: function () {
  4321. var i, il, f, fl, face;
  4322. // save original normals
  4323. // - create temp variables on first access
  4324. // otherwise just copy (for faster repeated calls)
  4325. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4326. face = this.faces[ f ];
  4327. if ( ! face.__originalFaceNormal ) {
  4328. face.__originalFaceNormal = face.normal.clone();
  4329. } else {
  4330. face.__originalFaceNormal.copy( face.normal );
  4331. }
  4332. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4333. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4334. if ( ! face.__originalVertexNormals[ i ] ) {
  4335. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4336. } else {
  4337. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4338. }
  4339. }
  4340. }
  4341. // use temp geometry to compute face and vertex normals for each morph
  4342. var tmpGeo = new THREE.Geometry();
  4343. tmpGeo.faces = this.faces;
  4344. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4345. // create on first access
  4346. if ( ! this.morphNormals[ i ] ) {
  4347. this.morphNormals[ i ] = {};
  4348. this.morphNormals[ i ].faceNormals = [];
  4349. this.morphNormals[ i ].vertexNormals = [];
  4350. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4351. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4352. var faceNormal, vertexNormals;
  4353. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4354. face = this.faces[ f ];
  4355. faceNormal = new THREE.Vector3();
  4356. if ( face instanceof THREE.Face3 ) {
  4357. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4358. } else {
  4359. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4360. }
  4361. dstNormalsFace.push( faceNormal );
  4362. dstNormalsVertex.push( vertexNormals );
  4363. }
  4364. }
  4365. var morphNormals = this.morphNormals[ i ];
  4366. // set vertices to morph target
  4367. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4368. // compute morph normals
  4369. tmpGeo.computeFaceNormals();
  4370. tmpGeo.computeVertexNormals();
  4371. // store morph normals
  4372. var faceNormal, vertexNormals;
  4373. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4374. face = this.faces[ f ];
  4375. faceNormal = morphNormals.faceNormals[ f ];
  4376. vertexNormals = morphNormals.vertexNormals[ f ];
  4377. faceNormal.copy( face.normal );
  4378. if ( face instanceof THREE.Face3 ) {
  4379. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4380. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4381. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4382. } else {
  4383. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4384. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4385. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4386. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4387. }
  4388. }
  4389. }
  4390. // restore original normals
  4391. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4392. face = this.faces[ f ];
  4393. face.normal = face.__originalFaceNormal;
  4394. face.vertexNormals = face.__originalVertexNormals;
  4395. }
  4396. },
  4397. computeTangents: function () {
  4398. // based on http://www.terathon.com/code/tangent.html
  4399. // tangents go to vertices
  4400. var f, fl, v, vl, i, il, vertexIndex,
  4401. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4402. x1, x2, y1, y2, z1, z2,
  4403. s1, s2, t1, t2, r, t, test,
  4404. tan1 = [], tan2 = [],
  4405. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4406. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4407. n = new THREE.Vector3(), w;
  4408. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4409. tan1[ v ] = new THREE.Vector3();
  4410. tan2[ v ] = new THREE.Vector3();
  4411. }
  4412. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4413. vA = context.vertices[ a ];
  4414. vB = context.vertices[ b ];
  4415. vC = context.vertices[ c ];
  4416. uvA = uv[ ua ];
  4417. uvB = uv[ ub ];
  4418. uvC = uv[ uc ];
  4419. x1 = vB.x - vA.x;
  4420. x2 = vC.x - vA.x;
  4421. y1 = vB.y - vA.y;
  4422. y2 = vC.y - vA.y;
  4423. z1 = vB.z - vA.z;
  4424. z2 = vC.z - vA.z;
  4425. s1 = uvB.x - uvA.x;
  4426. s2 = uvC.x - uvA.x;
  4427. t1 = uvB.y - uvA.y;
  4428. t2 = uvC.y - uvA.y;
  4429. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4430. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4431. ( t2 * y1 - t1 * y2 ) * r,
  4432. ( t2 * z1 - t1 * z2 ) * r );
  4433. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4434. ( s1 * y2 - s2 * y1 ) * r,
  4435. ( s1 * z2 - s2 * z1 ) * r );
  4436. tan1[ a ].add( sdir );
  4437. tan1[ b ].add( sdir );
  4438. tan1[ c ].add( sdir );
  4439. tan2[ a ].add( tdir );
  4440. tan2[ b ].add( tdir );
  4441. tan2[ c ].add( tdir );
  4442. }
  4443. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4444. face = this.faces[ f ];
  4445. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4446. if ( face instanceof THREE.Face3 ) {
  4447. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4448. } else if ( face instanceof THREE.Face4 ) {
  4449. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4450. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4451. }
  4452. }
  4453. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4454. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4455. face = this.faces[ f ];
  4456. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4457. n.copy( face.vertexNormals[ i ] );
  4458. vertexIndex = face[ faceIndex[ i ] ];
  4459. t = tan1[ vertexIndex ];
  4460. // Gram-Schmidt orthogonalize
  4461. tmp.copy( t );
  4462. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4463. // Calculate handedness
  4464. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4465. test = tmp2.dot( tan2[ vertexIndex ] );
  4466. w = (test < 0.0) ? -1.0 : 1.0;
  4467. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4468. }
  4469. }
  4470. this.hasTangents = true;
  4471. },
  4472. computeLineDistances: function ( ) {
  4473. var d = 0;
  4474. var vertices = this.vertices;
  4475. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4476. if ( i > 0 ) {
  4477. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4478. }
  4479. this.lineDistances[ i ] = d;
  4480. }
  4481. },
  4482. computeBoundingBox: function () {
  4483. if ( this.boundingBox === null ) {
  4484. this.boundingBox = new THREE.Box3();
  4485. }
  4486. this.boundingBox.setFromPoints( this.vertices );
  4487. },
  4488. computeBoundingSphere: function () {
  4489. if ( this.boundingSphere === null ) {
  4490. this.boundingSphere = new THREE.Sphere();
  4491. }
  4492. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4493. },
  4494. /*
  4495. * Checks for duplicate vertices with hashmap.
  4496. * Duplicated vertices are removed
  4497. * and faces' vertices are updated.
  4498. */
  4499. mergeVertices: function () {
  4500. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4501. var unique = [], changes = [];
  4502. var v, key;
  4503. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4504. var precision = Math.pow( 10, precisionPoints );
  4505. var i,il, face;
  4506. var indices, k, j, jl, u;
  4507. // reset cache of vertices as it now will be changing.
  4508. this.__tmpVertices = undefined;
  4509. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4510. v = this.vertices[ i ];
  4511. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4512. if ( verticesMap[ key ] === undefined ) {
  4513. verticesMap[ key ] = i;
  4514. unique.push( this.vertices[ i ] );
  4515. changes[ i ] = unique.length - 1;
  4516. } else {
  4517. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4518. changes[ i ] = changes[ verticesMap[ key ] ];
  4519. }
  4520. };
  4521. // if faces are completely degenerate after merging vertices, we
  4522. // have to remove them from the geometry.
  4523. var faceIndicesToRemove = [];
  4524. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4525. face = this.faces[ i ];
  4526. if ( face instanceof THREE.Face3 ) {
  4527. face.a = changes[ face.a ];
  4528. face.b = changes[ face.b ];
  4529. face.c = changes[ face.c ];
  4530. indices = [ face.a, face.b, face.c ];
  4531. var dupIndex = -1;
  4532. // if any duplicate vertices are found in a Face3
  4533. // we have to remove the face as nothing can be saved
  4534. for ( var n = 0; n < 3; n ++ ) {
  4535. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4536. dupIndex = n;
  4537. faceIndicesToRemove.push( i );
  4538. break;
  4539. }
  4540. }
  4541. } else if ( face instanceof THREE.Face4 ) {
  4542. face.a = changes[ face.a ];
  4543. face.b = changes[ face.b ];
  4544. face.c = changes[ face.c ];
  4545. face.d = changes[ face.d ];
  4546. // check dups in (a, b, c, d) and convert to -> face3
  4547. indices = [ face.a, face.b, face.c, face.d ];
  4548. var dupIndex = -1;
  4549. for ( var n = 0; n < 4; n ++ ) {
  4550. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4551. // if more than one duplicated vertex is found
  4552. // we can't generate any valid Face3's, thus
  4553. // we need to remove this face complete.
  4554. if ( dupIndex >= 0 ) {
  4555. faceIndicesToRemove.push( i );
  4556. }
  4557. dupIndex = n;
  4558. }
  4559. }
  4560. if ( dupIndex >= 0 ) {
  4561. indices.splice( dupIndex, 1 );
  4562. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4563. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4564. u = this.faceVertexUvs[ j ][ i ];
  4565. if ( u ) {
  4566. u.splice( dupIndex, 1 );
  4567. }
  4568. }
  4569. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4570. newFace.vertexNormals = face.vertexNormals;
  4571. newFace.vertexNormals.splice( dupIndex, 1 );
  4572. }
  4573. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4574. newFace.vertexColors = face.vertexColors;
  4575. newFace.vertexColors.splice( dupIndex, 1 );
  4576. }
  4577. this.faces[ i ] = newFace;
  4578. }
  4579. }
  4580. }
  4581. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4582. this.faces.splice( i, 1 );
  4583. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4584. this.faceVertexUvs[ j ].splice( i, 1 );
  4585. }
  4586. }
  4587. // Use unique set of vertices
  4588. var diff = this.vertices.length - unique.length;
  4589. this.vertices = unique;
  4590. return diff;
  4591. },
  4592. clone: function () {
  4593. var geometry = new THREE.Geometry();
  4594. var vertices = this.vertices;
  4595. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4596. geometry.vertices.push( vertices[ i ].clone() );
  4597. }
  4598. var faces = this.faces;
  4599. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4600. geometry.faces.push( faces[ i ].clone() );
  4601. }
  4602. var uvs = this.faceVertexUvs[ 0 ];
  4603. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4604. var uv = uvs[ i ], uvCopy = [];
  4605. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4606. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4607. }
  4608. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4609. }
  4610. return geometry;
  4611. },
  4612. dispose: function () {
  4613. this.dispatchEvent( { type: 'dispose' } );
  4614. }
  4615. };
  4616. THREE.GeometryIdCount = 0;
  4617. /**
  4618. * @author alteredq / http://alteredqualia.com/
  4619. */
  4620. THREE.BufferGeometry = function () {
  4621. THREE.EventDispatcher.call( this );
  4622. this.id = THREE.GeometryIdCount ++;
  4623. // attributes
  4624. this.attributes = {};
  4625. // attributes typed arrays are kept only if dynamic flag is set
  4626. this.dynamic = false;
  4627. // offsets for chunks when using indexed elements
  4628. this.offsets = [];
  4629. // boundings
  4630. this.boundingBox = null;
  4631. this.boundingSphere = null;
  4632. this.hasTangents = false;
  4633. // for compatibility
  4634. this.morphTargets = [];
  4635. };
  4636. THREE.BufferGeometry.prototype = {
  4637. constructor : THREE.BufferGeometry,
  4638. applyMatrix: function ( matrix ) {
  4639. var positionArray;
  4640. var normalArray;
  4641. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4642. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4643. if ( positionArray !== undefined ) {
  4644. matrix.multiplyVector3Array( positionArray );
  4645. this.verticesNeedUpdate = true;
  4646. }
  4647. if ( normalArray !== undefined ) {
  4648. var normalMatrix = new THREE.Matrix3();
  4649. normalMatrix.getInverse( matrix ).transpose();
  4650. normalMatrix.multiplyVector3Array( normalArray );
  4651. this.normalizeNormals();
  4652. this.normalsNeedUpdate = true;
  4653. }
  4654. },
  4655. computeBoundingBox: function () {
  4656. if ( this.boundingBox === null ) {
  4657. this.boundingBox = new THREE.Box3();
  4658. }
  4659. var positions = this.attributes[ "position" ].array;
  4660. if ( positions ) {
  4661. var bb = this.boundingBox;
  4662. var x, y, z;
  4663. if( positions.length >= 3 ) {
  4664. bb.min.x = bb.max.x = positions[ 0 ];
  4665. bb.min.y = bb.max.y = positions[ 1 ];
  4666. bb.min.z = bb.max.z = positions[ 2 ];
  4667. }
  4668. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4669. x = positions[ i ];
  4670. y = positions[ i + 1 ];
  4671. z = positions[ i + 2 ];
  4672. // bounding box
  4673. if ( x < bb.min.x ) {
  4674. bb.min.x = x;
  4675. } else if ( x > bb.max.x ) {
  4676. bb.max.x = x;
  4677. }
  4678. if ( y < bb.min.y ) {
  4679. bb.min.y = y;
  4680. } else if ( y > bb.max.y ) {
  4681. bb.max.y = y;
  4682. }
  4683. if ( z < bb.min.z ) {
  4684. bb.min.z = z;
  4685. } else if ( z > bb.max.z ) {
  4686. bb.max.z = z;
  4687. }
  4688. }
  4689. }
  4690. if ( positions === undefined || positions.length === 0 ) {
  4691. this.boundingBox.min.set( 0, 0, 0 );
  4692. this.boundingBox.max.set( 0, 0, 0 );
  4693. }
  4694. },
  4695. computeBoundingSphere: function () {
  4696. if ( this.boundingSphere === null ) {
  4697. this.boundingSphere = new THREE.Sphere();
  4698. }
  4699. var positions = this.attributes[ "position" ].array;
  4700. if ( positions ) {
  4701. var radiusSq, maxRadiusSq = 0;
  4702. var x, y, z;
  4703. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4704. x = positions[ i ];
  4705. y = positions[ i + 1 ];
  4706. z = positions[ i + 2 ];
  4707. radiusSq = x * x + y * y + z * z;
  4708. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4709. }
  4710. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4711. }
  4712. },
  4713. computeVertexNormals: function () {
  4714. if ( this.attributes[ "position" ] ) {
  4715. var i, il;
  4716. var j, jl;
  4717. var nVertexElements = this.attributes[ "position" ].array.length;
  4718. if ( this.attributes[ "normal" ] === undefined ) {
  4719. this.attributes[ "normal" ] = {
  4720. itemSize: 3,
  4721. array: new Float32Array( nVertexElements ),
  4722. numItems: nVertexElements
  4723. };
  4724. } else {
  4725. // reset existing normals to zero
  4726. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4727. this.attributes[ "normal" ].array[ i ] = 0;
  4728. }
  4729. }
  4730. var positions = this.attributes[ "position" ].array;
  4731. var normals = this.attributes[ "normal" ].array;
  4732. var vA, vB, vC, x, y, z,
  4733. pA = new THREE.Vector3(),
  4734. pB = new THREE.Vector3(),
  4735. pC = new THREE.Vector3(),
  4736. cb = new THREE.Vector3(),
  4737. ab = new THREE.Vector3();
  4738. // indexed elements
  4739. if ( this.attributes[ "index" ] ) {
  4740. var indices = this.attributes[ "index" ].array;
  4741. var offsets = this.offsets;
  4742. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4743. var start = offsets[ j ].start;
  4744. var count = offsets[ j ].count;
  4745. var index = offsets[ j ].index;
  4746. for ( i = start, il = start + count; i < il; i += 3 ) {
  4747. vA = index + indices[ i ];
  4748. vB = index + indices[ i + 1 ];
  4749. vC = index + indices[ i + 2 ];
  4750. x = positions[ vA * 3 ];
  4751. y = positions[ vA * 3 + 1 ];
  4752. z = positions[ vA * 3 + 2 ];
  4753. pA.set( x, y, z );
  4754. x = positions[ vB * 3 ];
  4755. y = positions[ vB * 3 + 1 ];
  4756. z = positions[ vB * 3 + 2 ];
  4757. pB.set( x, y, z );
  4758. x = positions[ vC * 3 ];
  4759. y = positions[ vC * 3 + 1 ];
  4760. z = positions[ vC * 3 + 2 ];
  4761. pC.set( x, y, z );
  4762. cb.subVectors( pC, pB );
  4763. ab.subVectors( pA, pB );
  4764. cb.cross( ab );
  4765. normals[ vA * 3 ] += cb.x;
  4766. normals[ vA * 3 + 1 ] += cb.y;
  4767. normals[ vA * 3 + 2 ] += cb.z;
  4768. normals[ vB * 3 ] += cb.x;
  4769. normals[ vB * 3 + 1 ] += cb.y;
  4770. normals[ vB * 3 + 2 ] += cb.z;
  4771. normals[ vC * 3 ] += cb.x;
  4772. normals[ vC * 3 + 1 ] += cb.y;
  4773. normals[ vC * 3 + 2 ] += cb.z;
  4774. }
  4775. }
  4776. // non-indexed elements (unconnected triangle soup)
  4777. } else {
  4778. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  4779. x = positions[ i ];
  4780. y = positions[ i + 1 ];
  4781. z = positions[ i + 2 ];
  4782. pA.set( x, y, z );
  4783. x = positions[ i + 3 ];
  4784. y = positions[ i + 4 ];
  4785. z = positions[ i + 5 ];
  4786. pB.set( x, y, z );
  4787. x = positions[ i + 6 ];
  4788. y = positions[ i + 7 ];
  4789. z = positions[ i + 8 ];
  4790. pC.set( x, y, z );
  4791. cb.subVectors( pC, pB );
  4792. ab.subVectors( pA, pB );
  4793. cb.cross( ab );
  4794. normals[ i ] = cb.x;
  4795. normals[ i + 1 ] = cb.y;
  4796. normals[ i + 2 ] = cb.z;
  4797. normals[ i + 3 ] = cb.x;
  4798. normals[ i + 4 ] = cb.y;
  4799. normals[ i + 5 ] = cb.z;
  4800. normals[ i + 6 ] = cb.x;
  4801. normals[ i + 7 ] = cb.y;
  4802. normals[ i + 8 ] = cb.z;
  4803. }
  4804. }
  4805. this.normalizeNormals();
  4806. this.normalsNeedUpdate = true;
  4807. }
  4808. },
  4809. normalizeNormals: function () {
  4810. var normals = this.attributes[ "normal" ].array;
  4811. var x, y, z, n;
  4812. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  4813. x = normals[ i ];
  4814. y = normals[ i + 1 ];
  4815. z = normals[ i + 2 ];
  4816. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  4817. normals[ i ] *= n;
  4818. normals[ i + 1 ] *= n;
  4819. normals[ i + 2 ] *= n;
  4820. }
  4821. },
  4822. computeTangents: function () {
  4823. // based on http://www.terathon.com/code/tangent.html
  4824. // (per vertex tangents)
  4825. if ( this.attributes[ "index" ] === undefined ||
  4826. this.attributes[ "position" ] === undefined ||
  4827. this.attributes[ "normal" ] === undefined ||
  4828. this.attributes[ "uv" ] === undefined ) {
  4829. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  4830. return;
  4831. }
  4832. var indices = this.attributes[ "index" ].array;
  4833. var positions = this.attributes[ "position" ].array;
  4834. var normals = this.attributes[ "normal" ].array;
  4835. var uvs = this.attributes[ "uv" ].array;
  4836. var nVertices = positions.length / 3;
  4837. if ( this.attributes[ "tangent" ] === undefined ) {
  4838. var nTangentElements = 4 * nVertices;
  4839. this.attributes[ "tangent" ] = {
  4840. itemSize: 4,
  4841. array: new Float32Array( nTangentElements ),
  4842. numItems: nTangentElements
  4843. };
  4844. }
  4845. var tangents = this.attributes[ "tangent" ].array;
  4846. var tan1 = [], tan2 = [];
  4847. for ( var k = 0; k < nVertices; k ++ ) {
  4848. tan1[ k ] = new THREE.Vector3();
  4849. tan2[ k ] = new THREE.Vector3();
  4850. }
  4851. var xA, yA, zA,
  4852. xB, yB, zB,
  4853. xC, yC, zC,
  4854. uA, vA,
  4855. uB, vB,
  4856. uC, vC,
  4857. x1, x2, y1, y2, z1, z2,
  4858. s1, s2, t1, t2, r;
  4859. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  4860. function handleTriangle( a, b, c ) {
  4861. xA = positions[ a * 3 ];
  4862. yA = positions[ a * 3 + 1 ];
  4863. zA = positions[ a * 3 + 2 ];
  4864. xB = positions[ b * 3 ];
  4865. yB = positions[ b * 3 + 1 ];
  4866. zB = positions[ b * 3 + 2 ];
  4867. xC = positions[ c * 3 ];
  4868. yC = positions[ c * 3 + 1 ];
  4869. zC = positions[ c * 3 + 2 ];
  4870. uA = uvs[ a * 2 ];
  4871. vA = uvs[ a * 2 + 1 ];
  4872. uB = uvs[ b * 2 ];
  4873. vB = uvs[ b * 2 + 1 ];
  4874. uC = uvs[ c * 2 ];
  4875. vC = uvs[ c * 2 + 1 ];
  4876. x1 = xB - xA;
  4877. x2 = xC - xA;
  4878. y1 = yB - yA;
  4879. y2 = yC - yA;
  4880. z1 = zB - zA;
  4881. z2 = zC - zA;
  4882. s1 = uB - uA;
  4883. s2 = uC - uA;
  4884. t1 = vB - vA;
  4885. t2 = vC - vA;
  4886. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4887. sdir.set(
  4888. ( t2 * x1 - t1 * x2 ) * r,
  4889. ( t2 * y1 - t1 * y2 ) * r,
  4890. ( t2 * z1 - t1 * z2 ) * r
  4891. );
  4892. tdir.set(
  4893. ( s1 * x2 - s2 * x1 ) * r,
  4894. ( s1 * y2 - s2 * y1 ) * r,
  4895. ( s1 * z2 - s2 * z1 ) * r
  4896. );
  4897. tan1[ a ].add( sdir );
  4898. tan1[ b ].add( sdir );
  4899. tan1[ c ].add( sdir );
  4900. tan2[ a ].add( tdir );
  4901. tan2[ b ].add( tdir );
  4902. tan2[ c ].add( tdir );
  4903. }
  4904. var i, il;
  4905. var j, jl;
  4906. var iA, iB, iC;
  4907. var offsets = this.offsets;
  4908. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4909. var start = offsets[ j ].start;
  4910. var count = offsets[ j ].count;
  4911. var index = offsets[ j ].index;
  4912. for ( i = start, il = start + count; i < il; i += 3 ) {
  4913. iA = index + indices[ i ];
  4914. iB = index + indices[ i + 1 ];
  4915. iC = index + indices[ i + 2 ];
  4916. handleTriangle( iA, iB, iC );
  4917. }
  4918. }
  4919. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  4920. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  4921. var w, t, test;
  4922. var nx, ny, nz;
  4923. function handleVertex( v ) {
  4924. n.x = normals[ v * 3 ];
  4925. n.y = normals[ v * 3 + 1 ];
  4926. n.z = normals[ v * 3 + 2 ];
  4927. n2.copy( n );
  4928. t = tan1[ v ];
  4929. // Gram-Schmidt orthogonalize
  4930. tmp.copy( t );
  4931. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4932. // Calculate handedness
  4933. tmp2.crossVectors( n2, t );
  4934. test = tmp2.dot( tan2[ v ] );
  4935. w = ( test < 0.0 ) ? -1.0 : 1.0;
  4936. tangents[ v * 4 ] = tmp.x;
  4937. tangents[ v * 4 + 1 ] = tmp.y;
  4938. tangents[ v * 4 + 2 ] = tmp.z;
  4939. tangents[ v * 4 + 3 ] = w;
  4940. }
  4941. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4942. var start = offsets[ j ].start;
  4943. var count = offsets[ j ].count;
  4944. var index = offsets[ j ].index;
  4945. for ( i = start, il = start + count; i < il; i += 3 ) {
  4946. iA = index + indices[ i ];
  4947. iB = index + indices[ i + 1 ];
  4948. iC = index + indices[ i + 2 ];
  4949. handleVertex( iA );
  4950. handleVertex( iB );
  4951. handleVertex( iC );
  4952. }
  4953. }
  4954. this.hasTangents = true;
  4955. this.tangentsNeedUpdate = true;
  4956. },
  4957. dispose: function () {
  4958. this.dispatchEvent( { type: 'dispose' } );
  4959. }
  4960. };
  4961. /**
  4962. * @author mrdoob / http://mrdoob.com/
  4963. * @author mikael emtinger / http://gomo.se/
  4964. */
  4965. THREE.Camera = function () {
  4966. THREE.Object3D.call( this );
  4967. this.matrixWorldInverse = new THREE.Matrix4();
  4968. this.projectionMatrix = new THREE.Matrix4();
  4969. this.projectionMatrixInverse = new THREE.Matrix4();
  4970. };
  4971. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  4972. THREE.Camera.prototype.lookAt = function ( vector ) {
  4973. // TODO: Add hierarchy support.
  4974. this.matrix.lookAt( this.position, vector, this.up );
  4975. if ( this.rotationAutoUpdate === true ) {
  4976. if ( this.useQuaternion === false ) {
  4977. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  4978. } else {
  4979. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  4980. }
  4981. }
  4982. };
  4983. /**
  4984. * @author alteredq / http://alteredqualia.com/
  4985. */
  4986. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  4987. THREE.Camera.call( this );
  4988. this.left = left;
  4989. this.right = right;
  4990. this.top = top;
  4991. this.bottom = bottom;
  4992. this.near = ( near !== undefined ) ? near : 0.1;
  4993. this.far = ( far !== undefined ) ? far : 2000;
  4994. this.updateProjectionMatrix();
  4995. };
  4996. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  4997. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  4998. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  4999. };
  5000. /**
  5001. * @author mrdoob / http://mrdoob.com/
  5002. * @author greggman / http://games.greggman.com/
  5003. * @author zz85 / http://www.lab4games.net/zz85/blog
  5004. */
  5005. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5006. THREE.Camera.call( this );
  5007. this.fov = fov !== undefined ? fov : 50;
  5008. this.aspect = aspect !== undefined ? aspect : 1;
  5009. this.near = near !== undefined ? near : 0.1;
  5010. this.far = far !== undefined ? far : 2000;
  5011. this.updateProjectionMatrix();
  5012. };
  5013. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5014. /**
  5015. * Uses Focal Length (in mm) to estimate and set FOV
  5016. * 35mm (fullframe) camera is used if frame size is not specified;
  5017. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5018. */
  5019. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5020. if ( frameHeight === undefined ) frameHeight = 24;
  5021. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5022. this.updateProjectionMatrix();
  5023. }
  5024. /**
  5025. * Sets an offset in a larger frustum. This is useful for multi-window or
  5026. * multi-monitor/multi-machine setups.
  5027. *
  5028. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5029. * the monitors are in grid like this
  5030. *
  5031. * +---+---+---+
  5032. * | A | B | C |
  5033. * +---+---+---+
  5034. * | D | E | F |
  5035. * +---+---+---+
  5036. *
  5037. * then for each monitor you would call it like this
  5038. *
  5039. * var w = 1920;
  5040. * var h = 1080;
  5041. * var fullWidth = w * 3;
  5042. * var fullHeight = h * 2;
  5043. *
  5044. * --A--
  5045. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5046. * --B--
  5047. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5048. * --C--
  5049. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5050. * --D--
  5051. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5052. * --E--
  5053. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5054. * --F--
  5055. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5056. *
  5057. * Note there is no reason monitors have to be the same size or in a grid.
  5058. */
  5059. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5060. this.fullWidth = fullWidth;
  5061. this.fullHeight = fullHeight;
  5062. this.x = x;
  5063. this.y = y;
  5064. this.width = width;
  5065. this.height = height;
  5066. this.updateProjectionMatrix();
  5067. };
  5068. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5069. if ( this.fullWidth ) {
  5070. var aspect = this.fullWidth / this.fullHeight;
  5071. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5072. var bottom = -top;
  5073. var left = aspect * bottom;
  5074. var right = aspect * top;
  5075. var width = Math.abs( right - left );
  5076. var height = Math.abs( top - bottom );
  5077. this.projectionMatrix.makeFrustum(
  5078. left + this.x * width / this.fullWidth,
  5079. left + ( this.x + this.width ) * width / this.fullWidth,
  5080. top - ( this.y + this.height ) * height / this.fullHeight,
  5081. top - this.y * height / this.fullHeight,
  5082. this.near,
  5083. this.far
  5084. );
  5085. } else {
  5086. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5087. }
  5088. };
  5089. /**
  5090. * @author mrdoob / http://mrdoob.com/
  5091. * @author alteredq / http://alteredqualia.com/
  5092. */
  5093. THREE.Light = function ( hex ) {
  5094. THREE.Object3D.call( this );
  5095. this.color = new THREE.Color( hex );
  5096. };
  5097. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5098. /**
  5099. * @author mrdoob / http://mrdoob.com/
  5100. */
  5101. THREE.AmbientLight = function ( hex ) {
  5102. THREE.Light.call( this, hex );
  5103. };
  5104. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5105. /**
  5106. * @author MPanknin / http://www.redplant.de/
  5107. * @author alteredq / http://alteredqualia.com/
  5108. */
  5109. THREE.AreaLight = function ( hex, intensity ) {
  5110. THREE.Light.call( this, hex );
  5111. this.normal = new THREE.Vector3( 0, -1, 0 );
  5112. this.right = new THREE.Vector3( 1, 0, 0 );
  5113. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5114. this.width = 1.0;
  5115. this.height = 1.0;
  5116. this.constantAttenuation = 1.5;
  5117. this.linearAttenuation = 0.5;
  5118. this.quadraticAttenuation = 0.1;
  5119. };
  5120. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5121. /**
  5122. * @author mrdoob / http://mrdoob.com/
  5123. * @author alteredq / http://alteredqualia.com/
  5124. */
  5125. THREE.DirectionalLight = function ( hex, intensity ) {
  5126. THREE.Light.call( this, hex );
  5127. this.position = new THREE.Vector3( 0, 1, 0 );
  5128. this.target = new THREE.Object3D();
  5129. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5130. this.castShadow = false;
  5131. this.onlyShadow = false;
  5132. //
  5133. this.shadowCameraNear = 50;
  5134. this.shadowCameraFar = 5000;
  5135. this.shadowCameraLeft = -500;
  5136. this.shadowCameraRight = 500;
  5137. this.shadowCameraTop = 500;
  5138. this.shadowCameraBottom = -500;
  5139. this.shadowCameraVisible = false;
  5140. this.shadowBias = 0;
  5141. this.shadowDarkness = 0.5;
  5142. this.shadowMapWidth = 512;
  5143. this.shadowMapHeight = 512;
  5144. //
  5145. this.shadowCascade = false;
  5146. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5147. this.shadowCascadeCount = 2;
  5148. this.shadowCascadeBias = [ 0, 0, 0 ];
  5149. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5150. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5151. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5152. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5153. this.shadowCascadeArray = [];
  5154. //
  5155. this.shadowMap = null;
  5156. this.shadowMapSize = null;
  5157. this.shadowCamera = null;
  5158. this.shadowMatrix = null;
  5159. };
  5160. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5161. /**
  5162. * @author alteredq / http://alteredqualia.com/
  5163. */
  5164. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5165. THREE.Light.call( this, skyColorHex );
  5166. this.groundColor = new THREE.Color( groundColorHex );
  5167. this.position = new THREE.Vector3( 0, 100, 0 );
  5168. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5169. };
  5170. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5171. /**
  5172. * @author mrdoob / http://mrdoob.com/
  5173. */
  5174. THREE.PointLight = function ( hex, intensity, distance ) {
  5175. THREE.Light.call( this, hex );
  5176. this.position = new THREE.Vector3( 0, 0, 0 );
  5177. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5178. this.distance = ( distance !== undefined ) ? distance : 0;
  5179. };
  5180. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5181. /**
  5182. * @author alteredq / http://alteredqualia.com/
  5183. */
  5184. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5185. THREE.Light.call( this, hex );
  5186. this.position = new THREE.Vector3( 0, 1, 0 );
  5187. this.target = new THREE.Object3D();
  5188. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5189. this.distance = ( distance !== undefined ) ? distance : 0;
  5190. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  5191. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5192. this.castShadow = false;
  5193. this.onlyShadow = false;
  5194. //
  5195. this.shadowCameraNear = 50;
  5196. this.shadowCameraFar = 5000;
  5197. this.shadowCameraFov = 50;
  5198. this.shadowCameraVisible = false;
  5199. this.shadowBias = 0;
  5200. this.shadowDarkness = 0.5;
  5201. this.shadowMapWidth = 512;
  5202. this.shadowMapHeight = 512;
  5203. //
  5204. this.shadowMap = null;
  5205. this.shadowMapSize = null;
  5206. this.shadowCamera = null;
  5207. this.shadowMatrix = null;
  5208. };
  5209. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5210. /**
  5211. * @author alteredq / http://alteredqualia.com/
  5212. */
  5213. THREE.Loader = function ( showStatus ) {
  5214. this.showStatus = showStatus;
  5215. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5216. this.onLoadStart = function () {};
  5217. this.onLoadProgress = function () {};
  5218. this.onLoadComplete = function () {};
  5219. };
  5220. THREE.Loader.prototype = {
  5221. constructor: THREE.Loader,
  5222. crossOrigin: 'anonymous',
  5223. addStatusElement: function () {
  5224. var e = document.createElement( "div" );
  5225. e.style.position = "absolute";
  5226. e.style.right = "0px";
  5227. e.style.top = "0px";
  5228. e.style.fontSize = "0.8em";
  5229. e.style.textAlign = "left";
  5230. e.style.background = "rgba(0,0,0,0.25)";
  5231. e.style.color = "#fff";
  5232. e.style.width = "120px";
  5233. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5234. e.style.zIndex = 1000;
  5235. e.innerHTML = "Loading ...";
  5236. return e;
  5237. },
  5238. updateProgress: function ( progress ) {
  5239. var message = "Loaded ";
  5240. if ( progress.total ) {
  5241. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5242. } else {
  5243. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5244. }
  5245. this.statusDomElement.innerHTML = message;
  5246. },
  5247. extractUrlBase: function ( url ) {
  5248. var parts = url.split( '/' );
  5249. parts.pop();
  5250. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5251. },
  5252. initMaterials: function ( materials, texturePath ) {
  5253. var array = [];
  5254. for ( var i = 0; i < materials.length; ++ i ) {
  5255. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5256. }
  5257. return array;
  5258. },
  5259. needsTangents: function ( materials ) {
  5260. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5261. var m = materials[ i ];
  5262. if ( m instanceof THREE.ShaderMaterial ) return true;
  5263. }
  5264. return false;
  5265. },
  5266. createMaterial: function ( m, texturePath ) {
  5267. var _this = this;
  5268. function is_pow2( n ) {
  5269. var l = Math.log( n ) / Math.LN2;
  5270. return Math.floor( l ) == l;
  5271. }
  5272. function nearest_pow2( n ) {
  5273. var l = Math.log( n ) / Math.LN2;
  5274. return Math.pow( 2, Math.round( l ) );
  5275. }
  5276. function load_image( where, url ) {
  5277. var image = new Image();
  5278. image.onload = function () {
  5279. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5280. var width = nearest_pow2( this.width );
  5281. var height = nearest_pow2( this.height );
  5282. where.image.width = width;
  5283. where.image.height = height;
  5284. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5285. } else {
  5286. where.image = this;
  5287. }
  5288. where.needsUpdate = true;
  5289. };
  5290. image.crossOrigin = _this.crossOrigin;
  5291. image.src = url;
  5292. }
  5293. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5294. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  5295. var fullPath = texturePath + "/" + sourceFile;
  5296. if ( isCompressed ) {
  5297. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5298. where[ name ] = texture;
  5299. } else {
  5300. var texture = document.createElement( 'canvas' );
  5301. where[ name ] = new THREE.Texture( texture );
  5302. }
  5303. where[ name ].sourceFile = sourceFile;
  5304. if( repeat ) {
  5305. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5306. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5307. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5308. }
  5309. if ( offset ) {
  5310. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5311. }
  5312. if ( wrap ) {
  5313. var wrapMap = {
  5314. "repeat": THREE.RepeatWrapping,
  5315. "mirror": THREE.MirroredRepeatWrapping
  5316. }
  5317. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5318. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5319. }
  5320. if ( anisotropy ) {
  5321. where[ name ].anisotropy = anisotropy;
  5322. }
  5323. if ( ! isCompressed ) {
  5324. load_image( where[ name ], fullPath );
  5325. }
  5326. }
  5327. function rgb2hex( rgb ) {
  5328. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5329. }
  5330. // defaults
  5331. var mtype = "MeshLambertMaterial";
  5332. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5333. // parameters from model file
  5334. if ( m.shading ) {
  5335. var shading = m.shading.toLowerCase();
  5336. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5337. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5338. }
  5339. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5340. mpars.blending = THREE[ m.blending ];
  5341. }
  5342. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5343. mpars.transparent = m.transparent;
  5344. }
  5345. if ( m.depthTest !== undefined ) {
  5346. mpars.depthTest = m.depthTest;
  5347. }
  5348. if ( m.depthWrite !== undefined ) {
  5349. mpars.depthWrite = m.depthWrite;
  5350. }
  5351. if ( m.visible !== undefined ) {
  5352. mpars.visible = m.visible;
  5353. }
  5354. if ( m.flipSided !== undefined ) {
  5355. mpars.side = THREE.BackSide;
  5356. }
  5357. if ( m.doubleSided !== undefined ) {
  5358. mpars.side = THREE.DoubleSide;
  5359. }
  5360. if ( m.wireframe !== undefined ) {
  5361. mpars.wireframe = m.wireframe;
  5362. }
  5363. if ( m.vertexColors !== undefined ) {
  5364. if ( m.vertexColors === "face" ) {
  5365. mpars.vertexColors = THREE.FaceColors;
  5366. } else if ( m.vertexColors ) {
  5367. mpars.vertexColors = THREE.VertexColors;
  5368. }
  5369. }
  5370. // colors
  5371. if ( m.colorDiffuse ) {
  5372. mpars.color = rgb2hex( m.colorDiffuse );
  5373. } else if ( m.DbgColor ) {
  5374. mpars.color = m.DbgColor;
  5375. }
  5376. if ( m.colorSpecular ) {
  5377. mpars.specular = rgb2hex( m.colorSpecular );
  5378. }
  5379. if ( m.colorAmbient ) {
  5380. mpars.ambient = rgb2hex( m.colorAmbient );
  5381. }
  5382. // modifiers
  5383. if ( m.transparency ) {
  5384. mpars.opacity = m.transparency;
  5385. }
  5386. if ( m.specularCoef ) {
  5387. mpars.shininess = m.specularCoef;
  5388. }
  5389. // textures
  5390. if ( m.mapDiffuse && texturePath ) {
  5391. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5392. }
  5393. if ( m.mapLight && texturePath ) {
  5394. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5395. }
  5396. if ( m.mapBump && texturePath ) {
  5397. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5398. }
  5399. if ( m.mapNormal && texturePath ) {
  5400. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5401. }
  5402. if ( m.mapSpecular && texturePath ) {
  5403. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5404. }
  5405. //
  5406. if ( m.mapBumpScale ) {
  5407. mpars.bumpScale = m.mapBumpScale;
  5408. }
  5409. // special case for normal mapped material
  5410. if ( m.mapNormal ) {
  5411. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5412. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5413. uniforms[ "tNormal" ].value = mpars.normalMap;
  5414. if ( m.mapNormalFactor ) {
  5415. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5416. }
  5417. if ( mpars.map ) {
  5418. uniforms[ "tDiffuse" ].value = mpars.map;
  5419. uniforms[ "enableDiffuse" ].value = true;
  5420. }
  5421. if ( mpars.specularMap ) {
  5422. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5423. uniforms[ "enableSpecular" ].value = true;
  5424. }
  5425. if ( mpars.lightMap ) {
  5426. uniforms[ "tAO" ].value = mpars.lightMap;
  5427. uniforms[ "enableAO" ].value = true;
  5428. }
  5429. // for the moment don't handle displacement texture
  5430. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5431. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5432. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5433. uniforms[ "uShininess" ].value = mpars.shininess;
  5434. if ( mpars.opacity !== undefined ) {
  5435. uniforms[ "uOpacity" ].value = mpars.opacity;
  5436. }
  5437. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5438. var material = new THREE.ShaderMaterial( parameters );
  5439. if ( mpars.transparent ) {
  5440. material.transparent = true;
  5441. }
  5442. } else {
  5443. var material = new THREE[ mtype ]( mpars );
  5444. }
  5445. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5446. return material;
  5447. }
  5448. };
  5449. /**
  5450. * @author alteredq / http://alteredqualia.com/
  5451. */
  5452. THREE.BinaryLoader = function ( showStatus ) {
  5453. THREE.Loader.call( this, showStatus );
  5454. };
  5455. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  5456. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  5457. // - binary models consist of two files: JS and BIN
  5458. // - parameters
  5459. // - url (required)
  5460. // - callback (required)
  5461. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  5462. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  5463. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  5464. // todo: unify load API to for easier SceneLoader use
  5465. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5466. binaryPath = binaryPath && ( typeof binaryPath === "string" ) ? binaryPath : this.extractUrlBase( url );
  5467. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  5468. this.onLoadStart();
  5469. // #1 load JS part via web worker
  5470. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  5471. };
  5472. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  5473. var xhr = new XMLHttpRequest();
  5474. xhr.onreadystatechange = function () {
  5475. if ( xhr.readyState == 4 ) {
  5476. if ( xhr.status == 200 || xhr.status == 0 ) {
  5477. var json = JSON.parse( xhr.responseText );
  5478. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  5479. } else {
  5480. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5481. }
  5482. }
  5483. };
  5484. xhr.open( "GET", url, true );
  5485. xhr.send( null );
  5486. };
  5487. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  5488. var xhr = new XMLHttpRequest(),
  5489. url = binaryPath + "/" + json.buffers;
  5490. var length = 0;
  5491. xhr.onreadystatechange = function () {
  5492. if ( xhr.readyState == 4 ) {
  5493. if ( xhr.status == 200 || xhr.status == 0 ) {
  5494. var buffer = xhr.response;
  5495. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  5496. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  5497. } else {
  5498. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5499. }
  5500. } else if ( xhr.readyState == 3 ) {
  5501. if ( callbackProgress ) {
  5502. if ( length == 0 ) {
  5503. length = xhr.getResponseHeader( "Content-Length" );
  5504. }
  5505. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5506. }
  5507. } else if ( xhr.readyState == 2 ) {
  5508. length = xhr.getResponseHeader( "Content-Length" );
  5509. }
  5510. };
  5511. xhr.open( "GET", url, true );
  5512. xhr.responseType = "arraybuffer";
  5513. xhr.send( null );
  5514. };
  5515. // Binary AJAX parser
  5516. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, jsonMaterials ) {
  5517. var Model = function ( texturePath ) {
  5518. var scope = this,
  5519. currentOffset = 0,
  5520. md,
  5521. normals = [],
  5522. uvs = [],
  5523. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  5524. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  5525. tri_size, quad_size,
  5526. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  5527. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  5528. THREE.Geometry.call( this );
  5529. md = parseMetaData( data, currentOffset );
  5530. currentOffset += md.header_bytes;
  5531. /*
  5532. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5533. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  5534. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5535. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5536. */
  5537. // buffers sizes
  5538. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  5539. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  5540. len_tri_flat = md.ntri_flat * ( tri_size );
  5541. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  5542. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  5543. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  5544. len_quad_flat = md.nquad_flat * ( quad_size );
  5545. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  5546. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  5547. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  5548. // read buffers
  5549. currentOffset += init_vertices( currentOffset );
  5550. currentOffset += init_normals( currentOffset );
  5551. currentOffset += handlePadding( md.nnormals * 3 );
  5552. currentOffset += init_uvs( currentOffset );
  5553. start_tri_flat = currentOffset;
  5554. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  5555. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  5556. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  5557. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  5558. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  5559. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  5560. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  5561. // have to first process faces with uvs
  5562. // so that face and uv indices match
  5563. init_triangles_flat_uv( start_tri_flat_uv );
  5564. init_triangles_smooth_uv( start_tri_smooth_uv );
  5565. init_quads_flat_uv( start_quad_flat_uv );
  5566. init_quads_smooth_uv( start_quad_smooth_uv );
  5567. // now we can process untextured faces
  5568. init_triangles_flat( start_tri_flat );
  5569. init_triangles_smooth( start_tri_smooth );
  5570. init_quads_flat( start_quad_flat );
  5571. init_quads_smooth( start_quad_smooth );
  5572. this.computeCentroids();
  5573. this.computeFaceNormals();
  5574. function handlePadding( n ) {
  5575. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  5576. };
  5577. function parseMetaData( data, offset ) {
  5578. var metaData = {
  5579. 'signature' :parseString( data, offset, 12 ),
  5580. 'header_bytes' :parseUChar8( data, offset + 12 ),
  5581. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  5582. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  5583. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  5584. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  5585. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  5586. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  5587. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  5588. 'nvertices' :parseUInt32( data, offset + 20 ),
  5589. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  5590. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  5591. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  5592. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  5593. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  5594. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  5595. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  5596. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  5597. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  5598. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  5599. };
  5600. /*
  5601. console.log( "signature: " + metaData.signature );
  5602. console.log( "header_bytes: " + metaData.header_bytes );
  5603. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  5604. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  5605. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  5606. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  5607. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  5608. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  5609. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  5610. console.log( "nvertices: " + metaData.nvertices );
  5611. console.log( "nnormals: " + metaData.nnormals );
  5612. console.log( "nuvs: " + metaData.nuvs );
  5613. console.log( "ntri_flat: " + metaData.ntri_flat );
  5614. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  5615. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  5616. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  5617. console.log( "nquad_flat: " + metaData.nquad_flat );
  5618. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  5619. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  5620. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  5621. var total = metaData.header_bytes
  5622. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  5623. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  5624. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  5625. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  5626. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  5627. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  5628. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  5629. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  5630. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  5631. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  5632. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  5633. console.log( "total bytes: " + total );
  5634. */
  5635. return metaData;
  5636. };
  5637. function parseString( data, offset, length ) {
  5638. var charArray = new Uint8Array( data, offset, length );
  5639. var text = "";
  5640. for ( var i = 0; i < length; i ++ ) {
  5641. text += String.fromCharCode( charArray[ offset + i ] );
  5642. }
  5643. return text;
  5644. };
  5645. function parseUChar8( data, offset ) {
  5646. var charArray = new Uint8Array( data, offset, 1 );
  5647. return charArray[ 0 ];
  5648. };
  5649. function parseUInt32( data, offset ) {
  5650. var intArray = new Uint32Array( data, offset, 1 );
  5651. return intArray[ 0 ];
  5652. };
  5653. function init_vertices( start ) {
  5654. var nElements = md.nvertices;
  5655. var coordArray = new Float32Array( data, start, nElements * 3 );
  5656. var i, x, y, z;
  5657. for( i = 0; i < nElements; i ++ ) {
  5658. x = coordArray[ i * 3 ];
  5659. y = coordArray[ i * 3 + 1 ];
  5660. z = coordArray[ i * 3 + 2 ];
  5661. vertex( scope, x, y, z );
  5662. }
  5663. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  5664. };
  5665. function init_normals( start ) {
  5666. var nElements = md.nnormals;
  5667. if ( nElements ) {
  5668. var normalArray = new Int8Array( data, start, nElements * 3 );
  5669. var i, x, y, z;
  5670. for( i = 0; i < nElements; i ++ ) {
  5671. x = normalArray[ i * 3 ];
  5672. y = normalArray[ i * 3 + 1 ];
  5673. z = normalArray[ i * 3 + 2 ];
  5674. normals.push( x/127, y/127, z/127 );
  5675. }
  5676. }
  5677. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  5678. };
  5679. function init_uvs( start ) {
  5680. var nElements = md.nuvs;
  5681. if ( nElements ) {
  5682. var uvArray = new Float32Array( data, start, nElements * 2 );
  5683. var i, u, v;
  5684. for( i = 0; i < nElements; i ++ ) {
  5685. u = uvArray[ i * 2 ];
  5686. v = uvArray[ i * 2 + 1 ];
  5687. uvs.push( u, v );
  5688. }
  5689. }
  5690. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  5691. };
  5692. function init_uvs3( nElements, offset ) {
  5693. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  5694. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  5695. for( i = 0; i < nElements; i ++ ) {
  5696. uva = uvIndexBuffer[ i * 3 ];
  5697. uvb = uvIndexBuffer[ i * 3 + 1 ];
  5698. uvc = uvIndexBuffer[ i * 3 + 2 ];
  5699. u1 = uvs[ uva*2 ];
  5700. v1 = uvs[ uva*2 + 1 ];
  5701. u2 = uvs[ uvb*2 ];
  5702. v2 = uvs[ uvb*2 + 1 ];
  5703. u3 = uvs[ uvc*2 ];
  5704. v3 = uvs[ uvc*2 + 1 ];
  5705. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  5706. }
  5707. };
  5708. function init_uvs4( nElements, offset ) {
  5709. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  5710. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  5711. for( i = 0; i < nElements; i ++ ) {
  5712. uva = uvIndexBuffer[ i * 4 ];
  5713. uvb = uvIndexBuffer[ i * 4 + 1 ];
  5714. uvc = uvIndexBuffer[ i * 4 + 2 ];
  5715. uvd = uvIndexBuffer[ i * 4 + 3 ];
  5716. u1 = uvs[ uva*2 ];
  5717. v1 = uvs[ uva*2 + 1 ];
  5718. u2 = uvs[ uvb*2 ];
  5719. v2 = uvs[ uvb*2 + 1 ];
  5720. u3 = uvs[ uvc*2 ];
  5721. v3 = uvs[ uvc*2 + 1 ];
  5722. u4 = uvs[ uvd*2 ];
  5723. v4 = uvs[ uvd*2 + 1 ];
  5724. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  5725. }
  5726. };
  5727. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  5728. var i, a, b, c, m;
  5729. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  5730. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5731. for( i = 0; i < nElements; i ++ ) {
  5732. a = vertexIndexBuffer[ i * 3 ];
  5733. b = vertexIndexBuffer[ i * 3 + 1 ];
  5734. c = vertexIndexBuffer[ i * 3 + 2 ];
  5735. m = materialIndexBuffer[ i ];
  5736. f3( scope, a, b, c, m );
  5737. }
  5738. };
  5739. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  5740. var i, a, b, c, d, m;
  5741. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  5742. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5743. for( i = 0; i < nElements; i ++ ) {
  5744. a = vertexIndexBuffer[ i * 4 ];
  5745. b = vertexIndexBuffer[ i * 4 + 1 ];
  5746. c = vertexIndexBuffer[ i * 4 + 2 ];
  5747. d = vertexIndexBuffer[ i * 4 + 3 ];
  5748. m = materialIndexBuffer[ i ];
  5749. f4( scope, a, b, c, d, m );
  5750. }
  5751. };
  5752. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  5753. var i, a, b, c, m;
  5754. var na, nb, nc;
  5755. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  5756. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  5757. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5758. for( i = 0; i < nElements; i ++ ) {
  5759. a = vertexIndexBuffer[ i * 3 ];
  5760. b = vertexIndexBuffer[ i * 3 + 1 ];
  5761. c = vertexIndexBuffer[ i * 3 + 2 ];
  5762. na = normalIndexBuffer[ i * 3 ];
  5763. nb = normalIndexBuffer[ i * 3 + 1 ];
  5764. nc = normalIndexBuffer[ i * 3 + 2 ];
  5765. m = materialIndexBuffer[ i ];
  5766. f3n( scope, normals, a, b, c, m, na, nb, nc );
  5767. }
  5768. };
  5769. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  5770. var i, a, b, c, d, m;
  5771. var na, nb, nc, nd;
  5772. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  5773. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  5774. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5775. for( i = 0; i < nElements; i ++ ) {
  5776. a = vertexIndexBuffer[ i * 4 ];
  5777. b = vertexIndexBuffer[ i * 4 + 1 ];
  5778. c = vertexIndexBuffer[ i * 4 + 2 ];
  5779. d = vertexIndexBuffer[ i * 4 + 3 ];
  5780. na = normalIndexBuffer[ i * 4 ];
  5781. nb = normalIndexBuffer[ i * 4 + 1 ];
  5782. nc = normalIndexBuffer[ i * 4 + 2 ];
  5783. nd = normalIndexBuffer[ i * 4 + 3 ];
  5784. m = materialIndexBuffer[ i ];
  5785. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  5786. }
  5787. };
  5788. function init_triangles_flat( start ) {
  5789. var nElements = md.ntri_flat;
  5790. if ( nElements ) {
  5791. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5792. init_faces3_flat( nElements, start, offsetMaterials );
  5793. }
  5794. };
  5795. function init_triangles_flat_uv( start ) {
  5796. var nElements = md.ntri_flat_uv;
  5797. if ( nElements ) {
  5798. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5799. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5800. init_faces3_flat( nElements, start, offsetMaterials );
  5801. init_uvs3( nElements, offsetUvs );
  5802. }
  5803. };
  5804. function init_triangles_smooth( start ) {
  5805. var nElements = md.ntri_smooth;
  5806. if ( nElements ) {
  5807. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5808. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5809. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  5810. }
  5811. };
  5812. function init_triangles_smooth_uv( start ) {
  5813. var nElements = md.ntri_smooth_uv;
  5814. if ( nElements ) {
  5815. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5816. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5817. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5818. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  5819. init_uvs3( nElements, offsetUvs );
  5820. }
  5821. };
  5822. function init_quads_flat( start ) {
  5823. var nElements = md.nquad_flat;
  5824. if ( nElements ) {
  5825. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5826. init_faces4_flat( nElements, start, offsetMaterials );
  5827. }
  5828. };
  5829. function init_quads_flat_uv( start ) {
  5830. var nElements = md.nquad_flat_uv;
  5831. if ( nElements ) {
  5832. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5833. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5834. init_faces4_flat( nElements, start, offsetMaterials );
  5835. init_uvs4( nElements, offsetUvs );
  5836. }
  5837. };
  5838. function init_quads_smooth( start ) {
  5839. var nElements = md.nquad_smooth;
  5840. if ( nElements ) {
  5841. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5842. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5843. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  5844. }
  5845. };
  5846. function init_quads_smooth_uv( start ) {
  5847. var nElements = md.nquad_smooth_uv;
  5848. if ( nElements ) {
  5849. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5850. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5851. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5852. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  5853. init_uvs4( nElements, offsetUvs );
  5854. }
  5855. };
  5856. };
  5857. function vertex ( scope, x, y, z ) {
  5858. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  5859. };
  5860. function f3 ( scope, a, b, c, mi ) {
  5861. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  5862. };
  5863. function f4 ( scope, a, b, c, d, mi ) {
  5864. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  5865. };
  5866. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  5867. var nax = normals[ na*3 ],
  5868. nay = normals[ na*3 + 1 ],
  5869. naz = normals[ na*3 + 2 ],
  5870. nbx = normals[ nb*3 ],
  5871. nby = normals[ nb*3 + 1 ],
  5872. nbz = normals[ nb*3 + 2 ],
  5873. ncx = normals[ nc*3 ],
  5874. ncy = normals[ nc*3 + 1 ],
  5875. ncz = normals[ nc*3 + 2 ];
  5876. scope.faces.push( new THREE.Face3( a, b, c,
  5877. [new THREE.Vector3( nax, nay, naz ),
  5878. new THREE.Vector3( nbx, nby, nbz ),
  5879. new THREE.Vector3( ncx, ncy, ncz )],
  5880. null,
  5881. mi ) );
  5882. };
  5883. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  5884. var nax = normals[ na*3 ],
  5885. nay = normals[ na*3 + 1 ],
  5886. naz = normals[ na*3 + 2 ],
  5887. nbx = normals[ nb*3 ],
  5888. nby = normals[ nb*3 + 1 ],
  5889. nbz = normals[ nb*3 + 2 ],
  5890. ncx = normals[ nc*3 ],
  5891. ncy = normals[ nc*3 + 1 ],
  5892. ncz = normals[ nc*3 + 2 ],
  5893. ndx = normals[ nd*3 ],
  5894. ndy = normals[ nd*3 + 1 ],
  5895. ndz = normals[ nd*3 + 2 ];
  5896. scope.faces.push( new THREE.Face4( a, b, c, d,
  5897. [new THREE.Vector3( nax, nay, naz ),
  5898. new THREE.Vector3( nbx, nby, nbz ),
  5899. new THREE.Vector3( ncx, ncy, ncz ),
  5900. new THREE.Vector3( ndx, ndy, ndz )],
  5901. null,
  5902. mi ) );
  5903. };
  5904. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  5905. where.push( [
  5906. new THREE.Vector2( u1, v1 ),
  5907. new THREE.Vector2( u2, v2 ),
  5908. new THREE.Vector2( u3, v3 )
  5909. ] );
  5910. };
  5911. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  5912. where.push( [
  5913. new THREE.Vector2( u1, v1 ),
  5914. new THREE.Vector2( u2, v2 ),
  5915. new THREE.Vector2( u3, v3 ),
  5916. new THREE.Vector2( u4, v4 )
  5917. ] );
  5918. };
  5919. Model.prototype = Object.create( THREE.Geometry.prototype );
  5920. var geometry = new Model( texturePath );
  5921. var materials = this.initMaterials( jsonMaterials, texturePath );
  5922. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5923. callback( geometry, materials );
  5924. };
  5925. /**
  5926. * @author mrdoob / http://mrdoob.com/
  5927. */
  5928. THREE.ImageLoader = function () {
  5929. THREE.EventDispatcher.call( this );
  5930. this.crossOrigin = null;
  5931. };
  5932. THREE.ImageLoader.prototype = {
  5933. constructor: THREE.ImageLoader,
  5934. load: function ( url, image ) {
  5935. var scope = this;
  5936. if ( image === undefined ) image = new Image();
  5937. image.addEventListener( 'load', function () {
  5938. scope.dispatchEvent( { type: 'load', content: image } );
  5939. }, false );
  5940. image.addEventListener( 'error', function () {
  5941. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5942. }, false );
  5943. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5944. image.src = url;
  5945. }
  5946. }
  5947. /**
  5948. * @author mrdoob / http://mrdoob.com/
  5949. * @author alteredq / http://alteredqualia.com/
  5950. */
  5951. THREE.JSONLoader = function ( showStatus ) {
  5952. THREE.Loader.call( this, showStatus );
  5953. this.withCredentials = false;
  5954. };
  5955. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5956. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5957. var scope = this;
  5958. // todo: unify load API to for easier SceneLoader use
  5959. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5960. this.onLoadStart();
  5961. this.loadAjaxJSON( this, url, callback, texturePath );
  5962. };
  5963. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5964. var xhr = new XMLHttpRequest();
  5965. var length = 0;
  5966. xhr.withCredentials = this.withCredentials;
  5967. xhr.onreadystatechange = function () {
  5968. if ( xhr.readyState === xhr.DONE ) {
  5969. if ( xhr.status === 200 || xhr.status === 0 ) {
  5970. if ( xhr.responseText ) {
  5971. var json = JSON.parse( xhr.responseText );
  5972. context.createModel( json, callback, texturePath );
  5973. } else {
  5974. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5975. }
  5976. // in context of more complex asset initialization
  5977. // do not block on single failed file
  5978. // maybe should go even one more level up
  5979. context.onLoadComplete();
  5980. } else {
  5981. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5982. }
  5983. } else if ( xhr.readyState === xhr.LOADING ) {
  5984. if ( callbackProgress ) {
  5985. if ( length === 0 ) {
  5986. length = xhr.getResponseHeader( "Content-Length" );
  5987. }
  5988. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5989. }
  5990. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5991. length = xhr.getResponseHeader( "Content-Length" );
  5992. }
  5993. };
  5994. xhr.open( "GET", url, true );
  5995. xhr.send( null );
  5996. };
  5997. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5998. var scope = this,
  5999. geometry = new THREE.Geometry(),
  6000. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6001. parseModel( scale );
  6002. parseSkin();
  6003. parseMorphing( scale );
  6004. geometry.computeCentroids();
  6005. geometry.computeFaceNormals();
  6006. function parseModel( scale ) {
  6007. function isBitSet( value, position ) {
  6008. return value & ( 1 << position );
  6009. }
  6010. var i, j, fi,
  6011. offset, zLength, nVertices,
  6012. colorIndex, normalIndex, uvIndex, materialIndex,
  6013. type,
  6014. isQuad,
  6015. hasMaterial,
  6016. hasFaceUv, hasFaceVertexUv,
  6017. hasFaceNormal, hasFaceVertexNormal,
  6018. hasFaceColor, hasFaceVertexColor,
  6019. vertex, face, color, normal,
  6020. uvLayer, uvs, u, v,
  6021. faces = json.faces,
  6022. vertices = json.vertices,
  6023. normals = json.normals,
  6024. colors = json.colors,
  6025. nUvLayers = 0;
  6026. // disregard empty arrays
  6027. for ( i = 0; i < json.uvs.length; i++ ) {
  6028. if ( json.uvs[ i ].length ) nUvLayers ++;
  6029. }
  6030. for ( i = 0; i < nUvLayers; i++ ) {
  6031. geometry.faceUvs[ i ] = [];
  6032. geometry.faceVertexUvs[ i ] = [];
  6033. }
  6034. offset = 0;
  6035. zLength = vertices.length;
  6036. while ( offset < zLength ) {
  6037. vertex = new THREE.Vector3();
  6038. vertex.x = vertices[ offset ++ ] * scale;
  6039. vertex.y = vertices[ offset ++ ] * scale;
  6040. vertex.z = vertices[ offset ++ ] * scale;
  6041. geometry.vertices.push( vertex );
  6042. }
  6043. offset = 0;
  6044. zLength = faces.length;
  6045. while ( offset < zLength ) {
  6046. type = faces[ offset ++ ];
  6047. isQuad = isBitSet( type, 0 );
  6048. hasMaterial = isBitSet( type, 1 );
  6049. hasFaceUv = isBitSet( type, 2 );
  6050. hasFaceVertexUv = isBitSet( type, 3 );
  6051. hasFaceNormal = isBitSet( type, 4 );
  6052. hasFaceVertexNormal = isBitSet( type, 5 );
  6053. hasFaceColor = isBitSet( type, 6 );
  6054. hasFaceVertexColor = isBitSet( type, 7 );
  6055. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6056. if ( isQuad ) {
  6057. face = new THREE.Face4();
  6058. face.a = faces[ offset ++ ];
  6059. face.b = faces[ offset ++ ];
  6060. face.c = faces[ offset ++ ];
  6061. face.d = faces[ offset ++ ];
  6062. nVertices = 4;
  6063. } else {
  6064. face = new THREE.Face3();
  6065. face.a = faces[ offset ++ ];
  6066. face.b = faces[ offset ++ ];
  6067. face.c = faces[ offset ++ ];
  6068. nVertices = 3;
  6069. }
  6070. if ( hasMaterial ) {
  6071. materialIndex = faces[ offset ++ ];
  6072. face.materialIndex = materialIndex;
  6073. }
  6074. // to get face <=> uv index correspondence
  6075. fi = geometry.faces.length;
  6076. if ( hasFaceUv ) {
  6077. for ( i = 0; i < nUvLayers; i++ ) {
  6078. uvLayer = json.uvs[ i ];
  6079. uvIndex = faces[ offset ++ ];
  6080. u = uvLayer[ uvIndex * 2 ];
  6081. v = uvLayer[ uvIndex * 2 + 1 ];
  6082. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  6083. }
  6084. }
  6085. if ( hasFaceVertexUv ) {
  6086. for ( i = 0; i < nUvLayers; i++ ) {
  6087. uvLayer = json.uvs[ i ];
  6088. uvs = [];
  6089. for ( j = 0; j < nVertices; j ++ ) {
  6090. uvIndex = faces[ offset ++ ];
  6091. u = uvLayer[ uvIndex * 2 ];
  6092. v = uvLayer[ uvIndex * 2 + 1 ];
  6093. uvs[ j ] = new THREE.Vector2( u, v );
  6094. }
  6095. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  6096. }
  6097. }
  6098. if ( hasFaceNormal ) {
  6099. normalIndex = faces[ offset ++ ] * 3;
  6100. normal = new THREE.Vector3();
  6101. normal.x = normals[ normalIndex ++ ];
  6102. normal.y = normals[ normalIndex ++ ];
  6103. normal.z = normals[ normalIndex ];
  6104. face.normal = normal;
  6105. }
  6106. if ( hasFaceVertexNormal ) {
  6107. for ( i = 0; i < nVertices; i++ ) {
  6108. normalIndex = faces[ offset ++ ] * 3;
  6109. normal = new THREE.Vector3();
  6110. normal.x = normals[ normalIndex ++ ];
  6111. normal.y = normals[ normalIndex ++ ];
  6112. normal.z = normals[ normalIndex ];
  6113. face.vertexNormals.push( normal );
  6114. }
  6115. }
  6116. if ( hasFaceColor ) {
  6117. colorIndex = faces[ offset ++ ];
  6118. color = new THREE.Color( colors[ colorIndex ] );
  6119. face.color = color;
  6120. }
  6121. if ( hasFaceVertexColor ) {
  6122. for ( i = 0; i < nVertices; i++ ) {
  6123. colorIndex = faces[ offset ++ ];
  6124. color = new THREE.Color( colors[ colorIndex ] );
  6125. face.vertexColors.push( color );
  6126. }
  6127. }
  6128. geometry.faces.push( face );
  6129. }
  6130. };
  6131. function parseSkin() {
  6132. var i, l, x, y, z, w, a, b, c, d;
  6133. if ( json.skinWeights ) {
  6134. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6135. x = json.skinWeights[ i ];
  6136. y = json.skinWeights[ i + 1 ];
  6137. z = 0;
  6138. w = 0;
  6139. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6140. }
  6141. }
  6142. if ( json.skinIndices ) {
  6143. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6144. a = json.skinIndices[ i ];
  6145. b = json.skinIndices[ i + 1 ];
  6146. c = 0;
  6147. d = 0;
  6148. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6149. }
  6150. }
  6151. geometry.bones = json.bones;
  6152. geometry.animation = json.animation;
  6153. };
  6154. function parseMorphing( scale ) {
  6155. if ( json.morphTargets !== undefined ) {
  6156. var i, l, v, vl, dstVertices, srcVertices;
  6157. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6158. geometry.morphTargets[ i ] = {};
  6159. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6160. geometry.morphTargets[ i ].vertices = [];
  6161. dstVertices = geometry.morphTargets[ i ].vertices;
  6162. srcVertices = json.morphTargets [ i ].vertices;
  6163. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6164. var vertex = new THREE.Vector3();
  6165. vertex.x = srcVertices[ v ] * scale;
  6166. vertex.y = srcVertices[ v + 1 ] * scale;
  6167. vertex.z = srcVertices[ v + 2 ] * scale;
  6168. dstVertices.push( vertex );
  6169. }
  6170. }
  6171. }
  6172. if ( json.morphColors !== undefined ) {
  6173. var i, l, c, cl, dstColors, srcColors, color;
  6174. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6175. geometry.morphColors[ i ] = {};
  6176. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6177. geometry.morphColors[ i ].colors = [];
  6178. dstColors = geometry.morphColors[ i ].colors;
  6179. srcColors = json.morphColors [ i ].colors;
  6180. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6181. color = new THREE.Color( 0xffaa00 );
  6182. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6183. dstColors.push( color );
  6184. }
  6185. }
  6186. }
  6187. };
  6188. var materials = this.initMaterials( json.materials, texturePath );
  6189. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  6190. callback( geometry, materials );
  6191. };
  6192. /**
  6193. * @author mrdoob / http://mrdoob.com/
  6194. */
  6195. THREE.LoadingMonitor = function () {
  6196. THREE.EventDispatcher.call( this );
  6197. var scope = this;
  6198. var loaded = 0;
  6199. var total = 0;
  6200. var onLoad = function ( event ) {
  6201. loaded ++;
  6202. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  6203. if ( loaded === total ) {
  6204. scope.dispatchEvent( { type: 'load' } );
  6205. }
  6206. };
  6207. this.add = function ( loader ) {
  6208. total ++;
  6209. loader.addEventListener( 'load', onLoad, false );
  6210. };
  6211. };
  6212. /**
  6213. * @author alteredq / http://alteredqualia.com/
  6214. */
  6215. THREE.SceneLoader = function () {
  6216. this.onLoadStart = function () {};
  6217. this.onLoadProgress = function() {};
  6218. this.onLoadComplete = function () {};
  6219. this.callbackSync = function () {};
  6220. this.callbackProgress = function () {};
  6221. this.geometryHandlerMap = {};
  6222. this.hierarchyHandlerMap = {};
  6223. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6224. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  6225. };
  6226. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  6227. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  6228. var scope = this;
  6229. var xhr = new XMLHttpRequest();
  6230. xhr.onreadystatechange = function () {
  6231. if ( xhr.readyState === 4 ) {
  6232. if ( xhr.status === 200 || xhr.status === 0 ) {
  6233. var json = JSON.parse( xhr.responseText );
  6234. scope.parse( json, callbackFinished, url );
  6235. } else {
  6236. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6237. }
  6238. }
  6239. };
  6240. xhr.open( "GET", url, true );
  6241. xhr.send( null );
  6242. };
  6243. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  6244. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  6245. };
  6246. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  6247. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  6248. };
  6249. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  6250. var scope = this;
  6251. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6252. var geometry, material, camera, fog,
  6253. texture, images, color,
  6254. light, hex, intensity,
  6255. counter_models, counter_textures,
  6256. total_models, total_textures,
  6257. result;
  6258. var target_array = [];
  6259. var data = json;
  6260. // async geometry loaders
  6261. for ( var typeID in this.geometryHandlerMap ) {
  6262. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  6263. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6264. }
  6265. // async hierachy loaders
  6266. for ( var typeID in this.hierarchyHandlerMap ) {
  6267. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  6268. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6269. }
  6270. counter_models = 0;
  6271. counter_textures = 0;
  6272. result = {
  6273. scene: new THREE.Scene(),
  6274. geometries: {},
  6275. face_materials: {},
  6276. materials: {},
  6277. textures: {},
  6278. objects: {},
  6279. cameras: {},
  6280. lights: {},
  6281. fogs: {},
  6282. empties: {}
  6283. };
  6284. if ( data.transform ) {
  6285. var position = data.transform.position,
  6286. rotation = data.transform.rotation,
  6287. scale = data.transform.scale;
  6288. if ( position )
  6289. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  6290. if ( rotation )
  6291. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  6292. if ( scale )
  6293. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  6294. if ( position || rotation || scale ) {
  6295. result.scene.updateMatrix();
  6296. result.scene.updateMatrixWorld();
  6297. }
  6298. }
  6299. function get_url( source_url, url_type ) {
  6300. if ( url_type == "relativeToHTML" ) {
  6301. return source_url;
  6302. } else {
  6303. return urlBase + "/" + source_url;
  6304. }
  6305. };
  6306. // toplevel loader function, delegates to handle_children
  6307. function handle_objects() {
  6308. handle_children( result.scene, data.objects );
  6309. }
  6310. // handle all the children from the loaded json and attach them to given parent
  6311. function handle_children( parent, children ) {
  6312. var mat, dst, pos, rot, scl, quat;
  6313. for ( var objID in children ) {
  6314. // check by id if child has already been handled,
  6315. // if not, create new object
  6316. if ( result.objects[ objID ] === undefined ) {
  6317. var objJSON = children[ objID ];
  6318. var object = null;
  6319. // meshes
  6320. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  6321. if ( objJSON.loading === undefined ) {
  6322. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  6323. "position": 1, "rotation": 1, "scale" : 1,
  6324. "visible": 1, "children": 1, "properties": 1,
  6325. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  6326. var loaderParameters = {};
  6327. for ( var parType in objJSON ) {
  6328. if ( ! ( parType in reservedTypes ) ) {
  6329. loaderParameters[ parType ] = objJSON[ parType ];
  6330. }
  6331. }
  6332. material = result.materials[ objJSON.material ];
  6333. objJSON.loading = true;
  6334. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  6335. // ColladaLoader
  6336. if ( loader.options ) {
  6337. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6338. // UTF8Loader
  6339. // OBJLoader
  6340. } else {
  6341. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6342. }
  6343. }
  6344. } else if ( objJSON.geometry !== undefined ) {
  6345. geometry = result.geometries[ objJSON.geometry ];
  6346. // geometry already loaded
  6347. if ( geometry ) {
  6348. var needsTangents = false;
  6349. material = result.materials[ objJSON.material ];
  6350. needsTangents = material instanceof THREE.ShaderMaterial;
  6351. pos = objJSON.position;
  6352. rot = objJSON.rotation;
  6353. scl = objJSON.scale;
  6354. mat = objJSON.matrix;
  6355. quat = objJSON.quaternion;
  6356. // use materials from the model file
  6357. // if there is no material specified in the object
  6358. if ( ! objJSON.material ) {
  6359. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6360. }
  6361. // use materials from the model file
  6362. // if there is just empty face material
  6363. // (must create new material as each model has its own face material)
  6364. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6365. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6366. }
  6367. if ( material instanceof THREE.MeshFaceMaterial ) {
  6368. for ( var i = 0; i < material.materials.length; i ++ ) {
  6369. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6370. }
  6371. }
  6372. if ( needsTangents ) {
  6373. geometry.computeTangents();
  6374. }
  6375. if ( objJSON.skin ) {
  6376. object = new THREE.SkinnedMesh( geometry, material );
  6377. } else if ( objJSON.morph ) {
  6378. object = new THREE.MorphAnimMesh( geometry, material );
  6379. if ( objJSON.duration !== undefined ) {
  6380. object.duration = objJSON.duration;
  6381. }
  6382. if ( objJSON.time !== undefined ) {
  6383. object.time = objJSON.time;
  6384. }
  6385. if ( objJSON.mirroredLoop !== undefined ) {
  6386. object.mirroredLoop = objJSON.mirroredLoop;
  6387. }
  6388. if ( material.morphNormals ) {
  6389. geometry.computeMorphNormals();
  6390. }
  6391. } else {
  6392. object = new THREE.Mesh( geometry, material );
  6393. }
  6394. object.name = objID;
  6395. if ( mat ) {
  6396. object.matrixAutoUpdate = false;
  6397. object.matrix.set(
  6398. mat[0], mat[1], mat[2], mat[3],
  6399. mat[4], mat[5], mat[6], mat[7],
  6400. mat[8], mat[9], mat[10], mat[11],
  6401. mat[12], mat[13], mat[14], mat[15]
  6402. );
  6403. } else {
  6404. object.position.set( pos[0], pos[1], pos[2] );
  6405. if ( quat ) {
  6406. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6407. object.useQuaternion = true;
  6408. } else {
  6409. object.rotation.set( rot[0], rot[1], rot[2] );
  6410. }
  6411. object.scale.set( scl[0], scl[1], scl[2] );
  6412. }
  6413. object.visible = objJSON.visible;
  6414. object.castShadow = objJSON.castShadow;
  6415. object.receiveShadow = objJSON.receiveShadow;
  6416. parent.add( object );
  6417. result.objects[ objID ] = object;
  6418. }
  6419. // lights
  6420. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6421. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6422. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6423. if ( objJSON.type === "DirectionalLight" ) {
  6424. pos = objJSON.direction;
  6425. light = new THREE.DirectionalLight( hex, intensity );
  6426. light.position.set( pos[0], pos[1], pos[2] );
  6427. if ( objJSON.target ) {
  6428. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6429. // kill existing default target
  6430. // otherwise it gets added to scene when parent gets added
  6431. light.target = null;
  6432. }
  6433. } else if ( objJSON.type === "PointLight" ) {
  6434. pos = objJSON.position;
  6435. dst = objJSON.distance;
  6436. light = new THREE.PointLight( hex, intensity, dst );
  6437. light.position.set( pos[0], pos[1], pos[2] );
  6438. } else if ( objJSON.type === "AmbientLight" ) {
  6439. light = new THREE.AmbientLight( hex );
  6440. }
  6441. parent.add( light );
  6442. light.name = objID;
  6443. result.lights[ objID ] = light;
  6444. result.objects[ objID ] = light;
  6445. // cameras
  6446. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6447. if ( objJSON.type === "PerspectiveCamera" ) {
  6448. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6449. } else if ( objJSON.type === "OrthographicCamera" ) {
  6450. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6451. }
  6452. pos = objJSON.position;
  6453. camera.position.set( pos[0], pos[1], pos[2] );
  6454. parent.add( camera );
  6455. camera.name = objID;
  6456. result.cameras[ objID ] = camera;
  6457. result.objects[ objID ] = camera;
  6458. // pure Object3D
  6459. } else {
  6460. pos = objJSON.position;
  6461. rot = objJSON.rotation;
  6462. scl = objJSON.scale;
  6463. quat = objJSON.quaternion;
  6464. object = new THREE.Object3D();
  6465. object.name = objID;
  6466. object.position.set( pos[0], pos[1], pos[2] );
  6467. if ( quat ) {
  6468. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6469. object.useQuaternion = true;
  6470. } else {
  6471. object.rotation.set( rot[0], rot[1], rot[2] );
  6472. }
  6473. object.scale.set( scl[0], scl[1], scl[2] );
  6474. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6475. parent.add( object );
  6476. result.objects[ objID ] = object;
  6477. result.empties[ objID ] = object;
  6478. }
  6479. if ( object ) {
  6480. if ( objJSON.properties !== undefined ) {
  6481. for ( var key in objJSON.properties ) {
  6482. var value = objJSON.properties[ key ];
  6483. object.properties[ key ] = value;
  6484. }
  6485. }
  6486. if ( objJSON.children !== undefined ) {
  6487. handle_children( object, objJSON.children );
  6488. }
  6489. }
  6490. }
  6491. }
  6492. };
  6493. function handle_mesh( geo, mat, id ) {
  6494. result.geometries[ id ] = geo;
  6495. result.face_materials[ id ] = mat;
  6496. handle_objects();
  6497. };
  6498. function handle_hierarchy( node, id, parent, material, obj ) {
  6499. var p = obj.position;
  6500. var r = obj.rotation;
  6501. var q = obj.quaternion;
  6502. var s = obj.scale;
  6503. node.position.set( p[0], p[1], p[2] );
  6504. if ( q ) {
  6505. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6506. node.useQuaternion = true;
  6507. } else {
  6508. node.rotation.set( r[0], r[1], r[2] );
  6509. }
  6510. node.scale.set( s[0], s[1], s[2] );
  6511. // override children materials
  6512. // if object material was specified in JSON explicitly
  6513. if ( material ) {
  6514. node.traverse( function ( child ) {
  6515. child.material = material;
  6516. } );
  6517. }
  6518. // override children visibility
  6519. // with root node visibility as specified in JSON
  6520. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6521. node.traverse( function ( child ) {
  6522. child.visible = visible;
  6523. } );
  6524. parent.add( node );
  6525. node.name = id;
  6526. result.objects[ id ] = node;
  6527. handle_objects();
  6528. };
  6529. function create_callback_geometry( id ) {
  6530. return function( geo, mat ) {
  6531. handle_mesh( geo, mat, id );
  6532. counter_models -= 1;
  6533. scope.onLoadComplete();
  6534. async_callback_gate();
  6535. }
  6536. };
  6537. function create_callback_hierachy( id, parent, material, obj ) {
  6538. return function( event ) {
  6539. var result;
  6540. // loaders which use EventDispatcher
  6541. if ( event.content ) {
  6542. result = event.content;
  6543. // ColladaLoader
  6544. } else if ( event.dae ) {
  6545. result = event.scene;
  6546. // UTF8Loader
  6547. } else {
  6548. result = event;
  6549. }
  6550. handle_hierarchy( result, id, parent, material, obj );
  6551. counter_models -= 1;
  6552. scope.onLoadComplete();
  6553. async_callback_gate();
  6554. }
  6555. };
  6556. function create_callback_embed( id ) {
  6557. return function( geo, mat ) {
  6558. result.geometries[ id ] = geo;
  6559. result.face_materials[ id ] = mat;
  6560. }
  6561. };
  6562. function async_callback_gate() {
  6563. var progress = {
  6564. totalModels : total_models,
  6565. totalTextures : total_textures,
  6566. loadedModels : total_models - counter_models,
  6567. loadedTextures : total_textures - counter_textures
  6568. };
  6569. scope.callbackProgress( progress, result );
  6570. scope.onLoadProgress();
  6571. if ( counter_models === 0 && counter_textures === 0 ) {
  6572. finalize();
  6573. callbackFinished( result );
  6574. }
  6575. };
  6576. function finalize() {
  6577. // take care of targets which could be asynchronously loaded objects
  6578. for ( var i = 0; i < target_array.length; i ++ ) {
  6579. var ta = target_array[ i ];
  6580. var target = result.objects[ ta.targetName ];
  6581. if ( target ) {
  6582. ta.object.target = target;
  6583. } else {
  6584. // if there was error and target of specified name doesn't exist in the scene file
  6585. // create instead dummy target
  6586. // (target must be added to scene explicitly as parent is already added)
  6587. ta.object.target = new THREE.Object3D();
  6588. result.scene.add( ta.object.target );
  6589. }
  6590. ta.object.target.properties.targetInverse = ta.object;
  6591. }
  6592. };
  6593. var callbackTexture = function ( count ) {
  6594. counter_textures -= count;
  6595. async_callback_gate();
  6596. scope.onLoadComplete();
  6597. };
  6598. // must use this instead of just directly calling callbackTexture
  6599. // because of closure in the calling context loop
  6600. var generateTextureCallback = function ( count ) {
  6601. return function() {
  6602. callbackTexture( count );
  6603. };
  6604. };
  6605. // first go synchronous elements
  6606. // fogs
  6607. var fogID, fogJSON;
  6608. for ( fogID in data.fogs ) {
  6609. fogJSON = data.fogs[ fogID ];
  6610. if ( fogJSON.type === "linear" ) {
  6611. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6612. } else if ( fogJSON.type === "exp2" ) {
  6613. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6614. }
  6615. color = fogJSON.color;
  6616. fog.color.setRGB( color[0], color[1], color[2] );
  6617. result.fogs[ fogID ] = fog;
  6618. }
  6619. // now come potentially asynchronous elements
  6620. // geometries
  6621. // count how many geometries will be loaded asynchronously
  6622. var geoID, geoJSON;
  6623. for ( geoID in data.geometries ) {
  6624. geoJSON = data.geometries[ geoID ];
  6625. if ( geoJSON.type in this.geometryHandlerMap ) {
  6626. counter_models += 1;
  6627. scope.onLoadStart();
  6628. }
  6629. }
  6630. // count how many hierarchies will be loaded asynchronously
  6631. var objID, objJSON;
  6632. for ( objID in data.objects ) {
  6633. objJSON = data.objects[ objID ];
  6634. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6635. counter_models += 1;
  6636. scope.onLoadStart();
  6637. }
  6638. }
  6639. total_models = counter_models;
  6640. for ( geoID in data.geometries ) {
  6641. geoJSON = data.geometries[ geoID ];
  6642. if ( geoJSON.type === "cube" ) {
  6643. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6644. result.geometries[ geoID ] = geometry;
  6645. } else if ( geoJSON.type === "plane" ) {
  6646. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6647. result.geometries[ geoID ] = geometry;
  6648. } else if ( geoJSON.type === "sphere" ) {
  6649. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6650. result.geometries[ geoID ] = geometry;
  6651. } else if ( geoJSON.type === "cylinder" ) {
  6652. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6653. result.geometries[ geoID ] = geometry;
  6654. } else if ( geoJSON.type === "torus" ) {
  6655. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6656. result.geometries[ geoID ] = geometry;
  6657. } else if ( geoJSON.type === "icosahedron" ) {
  6658. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6659. result.geometries[ geoID ] = geometry;
  6660. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6661. var loaderParameters = {};
  6662. for ( var parType in geoJSON ) {
  6663. if ( parType !== "type" && parType !== "url" ) {
  6664. loaderParameters[ parType ] = geoJSON[ parType ];
  6665. }
  6666. }
  6667. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6668. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6669. } else if ( geoJSON.type === "embedded" ) {
  6670. var modelJson = data.embeds[ geoJSON.id ],
  6671. texture_path = "";
  6672. // pass metadata along to jsonLoader so it knows the format version
  6673. modelJson.metadata = data.metadata;
  6674. if ( modelJson ) {
  6675. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6676. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  6677. }
  6678. }
  6679. }
  6680. // textures
  6681. // count how many textures will be loaded asynchronously
  6682. var textureID, textureJSON;
  6683. for ( textureID in data.textures ) {
  6684. textureJSON = data.textures[ textureID ];
  6685. if ( textureJSON.url instanceof Array ) {
  6686. counter_textures += textureJSON.url.length;
  6687. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6688. scope.onLoadStart();
  6689. }
  6690. } else {
  6691. counter_textures += 1;
  6692. scope.onLoadStart();
  6693. }
  6694. }
  6695. total_textures = counter_textures;
  6696. for ( textureID in data.textures ) {
  6697. textureJSON = data.textures[ textureID ];
  6698. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6699. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6700. }
  6701. if ( textureJSON.url instanceof Array ) {
  6702. var count = textureJSON.url.length;
  6703. var url_array = [];
  6704. for( var i = 0; i < count; i ++ ) {
  6705. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6706. }
  6707. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  6708. if ( isCompressed ) {
  6709. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6710. } else {
  6711. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6712. }
  6713. } else {
  6714. var isCompressed = textureJSON.url.toLowerCase().endsWith( ".dds" );
  6715. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6716. var textureCallback = generateTextureCallback( 1 );
  6717. if ( isCompressed ) {
  6718. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6719. } else {
  6720. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6721. }
  6722. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6723. texture.minFilter = THREE[ textureJSON.minFilter ];
  6724. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6725. texture.magFilter = THREE[ textureJSON.magFilter ];
  6726. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6727. if ( textureJSON.repeat ) {
  6728. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6729. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6730. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6731. }
  6732. if ( textureJSON.offset ) {
  6733. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6734. }
  6735. // handle wrap after repeat so that default repeat can be overriden
  6736. if ( textureJSON.wrap ) {
  6737. var wrapMap = {
  6738. "repeat" : THREE.RepeatWrapping,
  6739. "mirror" : THREE.MirroredRepeatWrapping
  6740. }
  6741. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6742. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6743. }
  6744. }
  6745. result.textures[ textureID ] = texture;
  6746. }
  6747. // materials
  6748. var matID, matJSON;
  6749. var parID;
  6750. for ( matID in data.materials ) {
  6751. matJSON = data.materials[ matID ];
  6752. for ( parID in matJSON.parameters ) {
  6753. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6754. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6755. } else if ( parID === "shading" ) {
  6756. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6757. } else if ( parID === "side" ) {
  6758. if ( matJSON.parameters[ parID ] == "double" ) {
  6759. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6760. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6761. matJSON.parameters[ parID ] = THREE.BackSide;
  6762. } else {
  6763. matJSON.parameters[ parID ] = THREE.FrontSide;
  6764. }
  6765. } else if ( parID === "blending" ) {
  6766. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6767. } else if ( parID === "combine" ) {
  6768. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6769. } else if ( parID === "vertexColors" ) {
  6770. if ( matJSON.parameters[ parID ] == "face" ) {
  6771. matJSON.parameters[ parID ] = THREE.FaceColors;
  6772. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6773. } else if ( matJSON.parameters[ parID ] ) {
  6774. matJSON.parameters[ parID ] = THREE.VertexColors;
  6775. }
  6776. } else if ( parID === "wrapRGB" ) {
  6777. var v3 = matJSON.parameters[ parID ];
  6778. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6779. }
  6780. }
  6781. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6782. matJSON.parameters.transparent = true;
  6783. }
  6784. if ( matJSON.parameters.normalMap ) {
  6785. var shader = THREE.ShaderUtils.lib[ "normal" ];
  6786. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6787. var diffuse = matJSON.parameters.color;
  6788. var specular = matJSON.parameters.specular;
  6789. var ambient = matJSON.parameters.ambient;
  6790. var shininess = matJSON.parameters.shininess;
  6791. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6792. if ( matJSON.parameters.normalScale ) {
  6793. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6794. }
  6795. if ( matJSON.parameters.map ) {
  6796. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6797. uniforms[ "enableDiffuse" ].value = true;
  6798. }
  6799. if ( matJSON.parameters.envMap ) {
  6800. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6801. uniforms[ "enableReflection" ].value = true;
  6802. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6803. }
  6804. if ( matJSON.parameters.lightMap ) {
  6805. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6806. uniforms[ "enableAO" ].value = true;
  6807. }
  6808. if ( matJSON.parameters.specularMap ) {
  6809. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6810. uniforms[ "enableSpecular" ].value = true;
  6811. }
  6812. if ( matJSON.parameters.displacementMap ) {
  6813. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6814. uniforms[ "enableDisplacement" ].value = true;
  6815. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6816. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6817. }
  6818. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6819. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6820. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6821. uniforms[ "uShininess" ].value = shininess;
  6822. if ( matJSON.parameters.opacity ) {
  6823. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6824. }
  6825. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6826. material = new THREE.ShaderMaterial( parameters );
  6827. } else {
  6828. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6829. }
  6830. result.materials[ matID ] = material;
  6831. }
  6832. // second pass through all materials to initialize MeshFaceMaterials
  6833. // that could be referring to other materials out of order
  6834. for ( matID in data.materials ) {
  6835. matJSON = data.materials[ matID ];
  6836. if ( matJSON.parameters.materials ) {
  6837. var materialArray = [];
  6838. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6839. var label = matJSON.parameters.materials[ i ];
  6840. materialArray.push( result.materials[ label ] );
  6841. }
  6842. result.materials[ matID ].materials = materialArray;
  6843. }
  6844. }
  6845. // objects ( synchronous init of procedural primitives )
  6846. handle_objects();
  6847. // defaults
  6848. if ( result.cameras && data.defaults.camera ) {
  6849. result.currentCamera = result.cameras[ data.defaults.camera ];
  6850. }
  6851. if ( result.fogs && data.defaults.fog ) {
  6852. result.scene.fog = result.fogs[ data.defaults.fog ];
  6853. }
  6854. color = data.defaults.bgcolor;
  6855. result.bgColor = new THREE.Color();
  6856. result.bgColor.setRGB( color[0], color[1], color[2] );
  6857. result.bgColorAlpha = data.defaults.bgalpha;
  6858. // synchronous callback
  6859. scope.callbackSync( result );
  6860. // just in case there are no async elements
  6861. async_callback_gate();
  6862. };
  6863. /**
  6864. * @author mrdoob / http://mrdoob.com/
  6865. */
  6866. THREE.TextureLoader = function () {
  6867. THREE.EventDispatcher.call( this );
  6868. this.crossOrigin = null;
  6869. };
  6870. THREE.TextureLoader.prototype = {
  6871. constructor: THREE.TextureLoader,
  6872. load: function ( url ) {
  6873. var scope = this;
  6874. var image = new Image();
  6875. image.addEventListener( 'load', function () {
  6876. var texture = new THREE.Texture( image );
  6877. texture.needsUpdate = true;
  6878. scope.dispatchEvent( { type: 'load', content: texture } );
  6879. }, false );
  6880. image.addEventListener( 'error', function () {
  6881. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6882. }, false );
  6883. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6884. image.src = url;
  6885. }
  6886. }
  6887. /**
  6888. * @author mrdoob / http://mrdoob.com/
  6889. * @author alteredq / http://alteredqualia.com/
  6890. */
  6891. THREE.Material = function () {
  6892. THREE.EventDispatcher.call( this );
  6893. this.id = THREE.MaterialIdCount ++;
  6894. this.name = '';
  6895. this.side = THREE.FrontSide;
  6896. this.opacity = 1;
  6897. this.transparent = false;
  6898. this.blending = THREE.NormalBlending;
  6899. this.blendSrc = THREE.SrcAlphaFactor;
  6900. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6901. this.blendEquation = THREE.AddEquation;
  6902. this.depthTest = true;
  6903. this.depthWrite = true;
  6904. this.polygonOffset = false;
  6905. this.polygonOffsetFactor = 0;
  6906. this.polygonOffsetUnits = 0;
  6907. this.alphaTest = 0;
  6908. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6909. this.visible = true;
  6910. this.needsUpdate = true;
  6911. };
  6912. THREE.Material.prototype.setValues = function ( values ) {
  6913. if ( values === undefined ) return;
  6914. for ( var key in values ) {
  6915. var newValue = values[ key ];
  6916. if ( newValue === undefined ) {
  6917. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6918. continue;
  6919. }
  6920. if ( key in this ) {
  6921. var currentValue = this[ key ];
  6922. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6923. currentValue.copy( newValue );
  6924. } else if ( currentValue instanceof THREE.Color ) {
  6925. currentValue.set( newValue );
  6926. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6927. currentValue.copy( newValue );
  6928. } else {
  6929. this[ key ] = newValue;
  6930. }
  6931. }
  6932. }
  6933. };
  6934. THREE.Material.prototype.clone = function ( material ) {
  6935. if ( material === undefined ) material = new THREE.Material();
  6936. material.name = this.name;
  6937. material.side = this.side;
  6938. material.opacity = this.opacity;
  6939. material.transparent = this.transparent;
  6940. material.blending = this.blending;
  6941. material.blendSrc = this.blendSrc;
  6942. material.blendDst = this.blendDst;
  6943. material.blendEquation = this.blendEquation;
  6944. material.depthTest = this.depthTest;
  6945. material.depthWrite = this.depthWrite;
  6946. material.polygonOffset = this.polygonOffset;
  6947. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6948. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6949. material.alphaTest = this.alphaTest;
  6950. material.overdraw = this.overdraw;
  6951. material.visible = this.visible;
  6952. return material;
  6953. };
  6954. THREE.Material.prototype.dispose = function () {
  6955. this.dispatchEvent( { type: 'dispose' } );
  6956. };
  6957. THREE.MaterialIdCount = 0;
  6958. /**
  6959. * @author mrdoob / http://mrdoob.com/
  6960. * @author alteredq / http://alteredqualia.com/
  6961. *
  6962. * parameters = {
  6963. * color: <hex>,
  6964. * opacity: <float>,
  6965. *
  6966. * blending: THREE.NormalBlending,
  6967. * depthTest: <bool>,
  6968. * depthWrite: <bool>,
  6969. *
  6970. * linewidth: <float>,
  6971. * linecap: "round",
  6972. * linejoin: "round",
  6973. *
  6974. * vertexColors: <bool>
  6975. *
  6976. * fog: <bool>
  6977. * }
  6978. */
  6979. THREE.LineBasicMaterial = function ( parameters ) {
  6980. THREE.Material.call( this );
  6981. this.color = new THREE.Color( 0xffffff );
  6982. this.linewidth = 1;
  6983. this.linecap = 'round';
  6984. this.linejoin = 'round';
  6985. this.vertexColors = false;
  6986. this.fog = true;
  6987. this.setValues( parameters );
  6988. };
  6989. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6990. THREE.LineBasicMaterial.prototype.clone = function () {
  6991. var material = new THREE.LineBasicMaterial();
  6992. THREE.Material.prototype.clone.call( this, material );
  6993. material.color.copy( this.color );
  6994. material.linewidth = this.linewidth;
  6995. material.linecap = this.linecap;
  6996. material.linejoin = this.linejoin;
  6997. material.vertexColors = this.vertexColors;
  6998. material.fog = this.fog;
  6999. return material;
  7000. };
  7001. /**
  7002. * @author alteredq / http://alteredqualia.com/
  7003. *
  7004. * parameters = {
  7005. * color: <hex>,
  7006. * opacity: <float>,
  7007. *
  7008. * blending: THREE.NormalBlending,
  7009. * depthTest: <bool>,
  7010. * depthWrite: <bool>,
  7011. *
  7012. * linewidth: <float>,
  7013. *
  7014. * scale: <float>,
  7015. * dashSize: <float>,
  7016. * gapSize: <float>,
  7017. *
  7018. * vertexColors: <bool>
  7019. *
  7020. * fog: <bool>
  7021. * }
  7022. */
  7023. THREE.LineDashedMaterial = function ( parameters ) {
  7024. THREE.Material.call( this );
  7025. this.color = new THREE.Color( 0xffffff );
  7026. this.linewidth = 1;
  7027. this.scale = 1;
  7028. this.dashSize = 3;
  7029. this.gapSize = 1;
  7030. this.vertexColors = false;
  7031. this.fog = true;
  7032. this.setValues( parameters );
  7033. };
  7034. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7035. THREE.LineDashedMaterial.prototype.clone = function () {
  7036. var material = new THREE.LineDashedMaterial();
  7037. THREE.Material.prototype.clone.call( this, material );
  7038. material.color.copy( this.color );
  7039. material.linewidth = this.linewidth;
  7040. material.scale = this.scale;
  7041. material.dashSize = this.dashSize;
  7042. material.gapSize = this.gapSize;
  7043. material.vertexColors = this.vertexColors;
  7044. material.fog = this.fog;
  7045. return material;
  7046. };
  7047. /**
  7048. * @author mrdoob / http://mrdoob.com/
  7049. * @author alteredq / http://alteredqualia.com/
  7050. *
  7051. * parameters = {
  7052. * color: <hex>,
  7053. * opacity: <float>,
  7054. * map: new THREE.Texture( <Image> ),
  7055. *
  7056. * lightMap: new THREE.Texture( <Image> ),
  7057. *
  7058. * specularMap: new THREE.Texture( <Image> ),
  7059. *
  7060. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7061. * combine: THREE.Multiply,
  7062. * reflectivity: <float>,
  7063. * refractionRatio: <float>,
  7064. *
  7065. * shading: THREE.SmoothShading,
  7066. * blending: THREE.NormalBlending,
  7067. * depthTest: <bool>,
  7068. * depthWrite: <bool>,
  7069. *
  7070. * wireframe: <boolean>,
  7071. * wireframeLinewidth: <float>,
  7072. *
  7073. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7074. *
  7075. * skinning: <bool>,
  7076. * morphTargets: <bool>,
  7077. *
  7078. * fog: <bool>
  7079. * }
  7080. */
  7081. THREE.MeshBasicMaterial = function ( parameters ) {
  7082. THREE.Material.call( this );
  7083. this.color = new THREE.Color( 0xffffff ); // emissive
  7084. this.map = null;
  7085. this.lightMap = null;
  7086. this.specularMap = null;
  7087. this.envMap = null;
  7088. this.combine = THREE.MultiplyOperation;
  7089. this.reflectivity = 1;
  7090. this.refractionRatio = 0.98;
  7091. this.fog = true;
  7092. this.shading = THREE.SmoothShading;
  7093. this.wireframe = false;
  7094. this.wireframeLinewidth = 1;
  7095. this.wireframeLinecap = 'round';
  7096. this.wireframeLinejoin = 'round';
  7097. this.vertexColors = THREE.NoColors;
  7098. this.skinning = false;
  7099. this.morphTargets = false;
  7100. this.setValues( parameters );
  7101. };
  7102. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7103. THREE.MeshBasicMaterial.prototype.clone = function () {
  7104. var material = new THREE.MeshBasicMaterial();
  7105. THREE.Material.prototype.clone.call( this, material );
  7106. material.color.copy( this.color );
  7107. material.map = this.map;
  7108. material.lightMap = this.lightMap;
  7109. material.specularMap = this.specularMap;
  7110. material.envMap = this.envMap;
  7111. material.combine = this.combine;
  7112. material.reflectivity = this.reflectivity;
  7113. material.refractionRatio = this.refractionRatio;
  7114. material.fog = this.fog;
  7115. material.shading = this.shading;
  7116. material.wireframe = this.wireframe;
  7117. material.wireframeLinewidth = this.wireframeLinewidth;
  7118. material.wireframeLinecap = this.wireframeLinecap;
  7119. material.wireframeLinejoin = this.wireframeLinejoin;
  7120. material.vertexColors = this.vertexColors;
  7121. material.skinning = this.skinning;
  7122. material.morphTargets = this.morphTargets;
  7123. return material;
  7124. };
  7125. /**
  7126. * @author mrdoob / http://mrdoob.com/
  7127. * @author alteredq / http://alteredqualia.com/
  7128. *
  7129. * parameters = {
  7130. * color: <hex>,
  7131. * ambient: <hex>,
  7132. * emissive: <hex>,
  7133. * opacity: <float>,
  7134. *
  7135. * map: new THREE.Texture( <Image> ),
  7136. *
  7137. * lightMap: new THREE.Texture( <Image> ),
  7138. *
  7139. * specularMap: new THREE.Texture( <Image> ),
  7140. *
  7141. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7142. * combine: THREE.Multiply,
  7143. * reflectivity: <float>,
  7144. * refractionRatio: <float>,
  7145. *
  7146. * shading: THREE.SmoothShading,
  7147. * blending: THREE.NormalBlending,
  7148. * depthTest: <bool>,
  7149. * depthWrite: <bool>,
  7150. *
  7151. * wireframe: <boolean>,
  7152. * wireframeLinewidth: <float>,
  7153. *
  7154. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7155. *
  7156. * skinning: <bool>,
  7157. * morphTargets: <bool>,
  7158. * morphNormals: <bool>,
  7159. *
  7160. * fog: <bool>
  7161. * }
  7162. */
  7163. THREE.MeshLambertMaterial = function ( parameters ) {
  7164. THREE.Material.call( this );
  7165. this.color = new THREE.Color( 0xffffff ); // diffuse
  7166. this.ambient = new THREE.Color( 0xffffff );
  7167. this.emissive = new THREE.Color( 0x000000 );
  7168. this.wrapAround = false;
  7169. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7170. this.map = null;
  7171. this.lightMap = null;
  7172. this.specularMap = null;
  7173. this.envMap = null;
  7174. this.combine = THREE.MultiplyOperation;
  7175. this.reflectivity = 1;
  7176. this.refractionRatio = 0.98;
  7177. this.fog = true;
  7178. this.shading = THREE.SmoothShading;
  7179. this.wireframe = false;
  7180. this.wireframeLinewidth = 1;
  7181. this.wireframeLinecap = 'round';
  7182. this.wireframeLinejoin = 'round';
  7183. this.vertexColors = THREE.NoColors;
  7184. this.skinning = false;
  7185. this.morphTargets = false;
  7186. this.morphNormals = false;
  7187. this.setValues( parameters );
  7188. };
  7189. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7190. THREE.MeshLambertMaterial.prototype.clone = function () {
  7191. var material = new THREE.MeshLambertMaterial();
  7192. THREE.Material.prototype.clone.call( this, material );
  7193. material.color.copy( this.color );
  7194. material.ambient.copy( this.ambient );
  7195. material.emissive.copy( this.emissive );
  7196. material.wrapAround = this.wrapAround;
  7197. material.wrapRGB.copy( this.wrapRGB );
  7198. material.map = this.map;
  7199. material.lightMap = this.lightMap;
  7200. material.specularMap = this.specularMap;
  7201. material.envMap = this.envMap;
  7202. material.combine = this.combine;
  7203. material.reflectivity = this.reflectivity;
  7204. material.refractionRatio = this.refractionRatio;
  7205. material.fog = this.fog;
  7206. material.shading = this.shading;
  7207. material.wireframe = this.wireframe;
  7208. material.wireframeLinewidth = this.wireframeLinewidth;
  7209. material.wireframeLinecap = this.wireframeLinecap;
  7210. material.wireframeLinejoin = this.wireframeLinejoin;
  7211. material.vertexColors = this.vertexColors;
  7212. material.skinning = this.skinning;
  7213. material.morphTargets = this.morphTargets;
  7214. material.morphNormals = this.morphNormals;
  7215. return material;
  7216. };
  7217. /**
  7218. * @author mrdoob / http://mrdoob.com/
  7219. * @author alteredq / http://alteredqualia.com/
  7220. *
  7221. * parameters = {
  7222. * color: <hex>,
  7223. * ambient: <hex>,
  7224. * emissive: <hex>,
  7225. * specular: <hex>,
  7226. * shininess: <float>,
  7227. * opacity: <float>,
  7228. *
  7229. * map: new THREE.Texture( <Image> ),
  7230. *
  7231. * lightMap: new THREE.Texture( <Image> ),
  7232. *
  7233. * bumpMap: new THREE.Texture( <Image> ),
  7234. * bumpScale: <float>,
  7235. *
  7236. * normalMap: new THREE.Texture( <Image> ),
  7237. * normalScale: <Vector2>,
  7238. *
  7239. * specularMap: new THREE.Texture( <Image> ),
  7240. *
  7241. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7242. * combine: THREE.Multiply,
  7243. * reflectivity: <float>,
  7244. * refractionRatio: <float>,
  7245. *
  7246. * shading: THREE.SmoothShading,
  7247. * blending: THREE.NormalBlending,
  7248. * depthTest: <bool>,
  7249. * depthWrite: <bool>,
  7250. *
  7251. * wireframe: <boolean>,
  7252. * wireframeLinewidth: <float>,
  7253. *
  7254. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7255. *
  7256. * skinning: <bool>,
  7257. * morphTargets: <bool>,
  7258. * morphNormals: <bool>,
  7259. *
  7260. * fog: <bool>
  7261. * }
  7262. */
  7263. THREE.MeshPhongMaterial = function ( parameters ) {
  7264. THREE.Material.call( this );
  7265. this.color = new THREE.Color( 0xffffff ); // diffuse
  7266. this.ambient = new THREE.Color( 0xffffff );
  7267. this.emissive = new THREE.Color( 0x000000 );
  7268. this.specular = new THREE.Color( 0x111111 );
  7269. this.shininess = 30;
  7270. this.metal = false;
  7271. this.perPixel = true;
  7272. this.wrapAround = false;
  7273. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7274. this.map = null;
  7275. this.lightMap = null;
  7276. this.bumpMap = null;
  7277. this.bumpScale = 1;
  7278. this.normalMap = null;
  7279. this.normalScale = new THREE.Vector2( 1, 1 );
  7280. this.specularMap = null;
  7281. this.envMap = null;
  7282. this.combine = THREE.MultiplyOperation;
  7283. this.reflectivity = 1;
  7284. this.refractionRatio = 0.98;
  7285. this.fog = true;
  7286. this.shading = THREE.SmoothShading;
  7287. this.wireframe = false;
  7288. this.wireframeLinewidth = 1;
  7289. this.wireframeLinecap = 'round';
  7290. this.wireframeLinejoin = 'round';
  7291. this.vertexColors = THREE.NoColors;
  7292. this.skinning = false;
  7293. this.morphTargets = false;
  7294. this.morphNormals = false;
  7295. this.setValues( parameters );
  7296. };
  7297. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7298. THREE.MeshPhongMaterial.prototype.clone = function () {
  7299. var material = new THREE.MeshPhongMaterial();
  7300. THREE.Material.prototype.clone.call( this, material );
  7301. material.color.copy( this.color );
  7302. material.ambient.copy( this.ambient );
  7303. material.emissive.copy( this.emissive );
  7304. material.specular.copy( this.specular );
  7305. material.shininess = this.shininess;
  7306. material.metal = this.metal;
  7307. material.perPixel = this.perPixel;
  7308. material.wrapAround = this.wrapAround;
  7309. material.wrapRGB.copy( this.wrapRGB );
  7310. material.map = this.map;
  7311. material.lightMap = this.lightMap;
  7312. material.bumpMap = this.bumpMap;
  7313. material.bumpScale = this.bumpScale;
  7314. material.normalMap = this.normalMap;
  7315. material.normalScale.copy( this.normalScale );
  7316. material.specularMap = this.specularMap;
  7317. material.envMap = this.envMap;
  7318. material.combine = this.combine;
  7319. material.reflectivity = this.reflectivity;
  7320. material.refractionRatio = this.refractionRatio;
  7321. material.fog = this.fog;
  7322. material.shading = this.shading;
  7323. material.wireframe = this.wireframe;
  7324. material.wireframeLinewidth = this.wireframeLinewidth;
  7325. material.wireframeLinecap = this.wireframeLinecap;
  7326. material.wireframeLinejoin = this.wireframeLinejoin;
  7327. material.vertexColors = this.vertexColors;
  7328. material.skinning = this.skinning;
  7329. material.morphTargets = this.morphTargets;
  7330. material.morphNormals = this.morphNormals;
  7331. return material;
  7332. };
  7333. /**
  7334. * @author mrdoob / http://mrdoob.com/
  7335. * @author alteredq / http://alteredqualia.com/
  7336. *
  7337. * parameters = {
  7338. * opacity: <float>,
  7339. *
  7340. * blending: THREE.NormalBlending,
  7341. * depthTest: <bool>,
  7342. * depthWrite: <bool>,
  7343. *
  7344. * wireframe: <boolean>,
  7345. * wireframeLinewidth: <float>
  7346. * }
  7347. */
  7348. THREE.MeshDepthMaterial = function ( parameters ) {
  7349. THREE.Material.call( this );
  7350. this.wireframe = false;
  7351. this.wireframeLinewidth = 1;
  7352. this.setValues( parameters );
  7353. };
  7354. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7355. THREE.MeshDepthMaterial.prototype.clone = function () {
  7356. var material = new THREE.LineBasicMaterial();
  7357. THREE.Material.prototype.clone.call( this, material );
  7358. material.wireframe = this.wireframe;
  7359. material.wireframeLinewidth = this.wireframeLinewidth;
  7360. return material;
  7361. };
  7362. /**
  7363. * @author mrdoob / http://mrdoob.com/
  7364. *
  7365. * parameters = {
  7366. * opacity: <float>,
  7367. *
  7368. * shading: THREE.FlatShading,
  7369. * blending: THREE.NormalBlending,
  7370. * depthTest: <bool>,
  7371. * depthWrite: <bool>,
  7372. *
  7373. * wireframe: <boolean>,
  7374. * wireframeLinewidth: <float>
  7375. * }
  7376. */
  7377. THREE.MeshNormalMaterial = function ( parameters ) {
  7378. THREE.Material.call( this, parameters );
  7379. this.shading = THREE.FlatShading;
  7380. this.wireframe = false;
  7381. this.wireframeLinewidth = 1;
  7382. this.setValues( parameters );
  7383. };
  7384. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7385. THREE.MeshNormalMaterial.prototype.clone = function () {
  7386. var material = new THREE.MeshNormalMaterial();
  7387. THREE.Material.prototype.clone.call( this, material );
  7388. material.shading = this.shading;
  7389. material.wireframe = this.wireframe;
  7390. material.wireframeLinewidth = this.wireframeLinewidth;
  7391. return material;
  7392. };
  7393. /**
  7394. * @author mrdoob / http://mrdoob.com/
  7395. */
  7396. THREE.MeshFaceMaterial = function ( materials ) {
  7397. this.materials = materials instanceof Array ? materials : [];
  7398. };
  7399. THREE.MeshFaceMaterial.prototype.clone = function () {
  7400. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7401. };
  7402. /**
  7403. * @author mrdoob / http://mrdoob.com/
  7404. * @author alteredq / http://alteredqualia.com/
  7405. *
  7406. * parameters = {
  7407. * color: <hex>,
  7408. * opacity: <float>,
  7409. * map: new THREE.Texture( <Image> ),
  7410. *
  7411. * size: <float>,
  7412. *
  7413. * blending: THREE.NormalBlending,
  7414. * depthTest: <bool>,
  7415. * depthWrite: <bool>,
  7416. *
  7417. * vertexColors: <bool>,
  7418. *
  7419. * fog: <bool>
  7420. * }
  7421. */
  7422. THREE.ParticleBasicMaterial = function ( parameters ) {
  7423. THREE.Material.call( this );
  7424. this.color = new THREE.Color( 0xffffff );
  7425. this.map = null;
  7426. this.size = 1;
  7427. this.sizeAttenuation = true;
  7428. this.vertexColors = false;
  7429. this.fog = true;
  7430. this.setValues( parameters );
  7431. };
  7432. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7433. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7434. var material = new THREE.ParticleBasicMaterial();
  7435. THREE.Material.prototype.clone.call( this, material );
  7436. material.color.copy( this.color );
  7437. material.map = this.map;
  7438. material.size = this.size;
  7439. material.sizeAttenuation = this.sizeAttenuation;
  7440. material.vertexColors = this.vertexColors;
  7441. material.fog = this.fog;
  7442. return material;
  7443. };
  7444. /**
  7445. * @author mrdoob / http://mrdoob.com/
  7446. *
  7447. * parameters = {
  7448. * color: <hex>,
  7449. * program: <function>,
  7450. * opacity: <float>,
  7451. * blending: THREE.NormalBlending
  7452. * }
  7453. */
  7454. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7455. THREE.Material.call( this );
  7456. this.color = new THREE.Color( 0xffffff );
  7457. this.program = function ( context, color ) {};
  7458. this.setValues( parameters );
  7459. };
  7460. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7461. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7462. var material = new THREE.ParticleCanvasMaterial();
  7463. THREE.Material.prototype.clone.call( this, material );
  7464. material.color.copy( this.color );
  7465. material.program = this.program;
  7466. return material;
  7467. };
  7468. /**
  7469. * @author alteredq / http://alteredqualia.com/
  7470. *
  7471. * parameters = {
  7472. * fragmentShader: <string>,
  7473. * vertexShader: <string>,
  7474. *
  7475. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7476. *
  7477. * defines: { "label" : "value" },
  7478. *
  7479. * shading: THREE.SmoothShading,
  7480. * blending: THREE.NormalBlending,
  7481. * depthTest: <bool>,
  7482. * depthWrite: <bool>,
  7483. *
  7484. * wireframe: <boolean>,
  7485. * wireframeLinewidth: <float>,
  7486. *
  7487. * lights: <bool>,
  7488. *
  7489. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7490. *
  7491. * skinning: <bool>,
  7492. * morphTargets: <bool>,
  7493. * morphNormals: <bool>,
  7494. *
  7495. * fog: <bool>
  7496. * }
  7497. */
  7498. THREE.ShaderMaterial = function ( parameters ) {
  7499. THREE.Material.call( this );
  7500. this.fragmentShader = "void main() {}";
  7501. this.vertexShader = "void main() {}";
  7502. this.uniforms = {};
  7503. this.defines = {};
  7504. this.attributes = null;
  7505. this.shading = THREE.SmoothShading;
  7506. this.wireframe = false;
  7507. this.wireframeLinewidth = 1;
  7508. this.fog = false; // set to use scene fog
  7509. this.lights = false; // set to use scene lights
  7510. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7511. this.skinning = false; // set to use skinning attribute streams
  7512. this.morphTargets = false; // set to use morph targets
  7513. this.morphNormals = false; // set to use morph normals
  7514. this.setValues( parameters );
  7515. };
  7516. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7517. THREE.ShaderMaterial.prototype.clone = function () {
  7518. var material = new THREE.ShaderMaterial();
  7519. THREE.Material.prototype.clone.call( this, material );
  7520. material.fragmentShader = this.fragmentShader;
  7521. material.vertexShader = this.vertexShader;
  7522. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7523. material.attributes = this.attributes;
  7524. material.defines = this.defines;
  7525. material.shading = this.shading;
  7526. material.wireframe = this.wireframe;
  7527. material.wireframeLinewidth = this.wireframeLinewidth;
  7528. material.fog = this.fog;
  7529. material.lights = this.lights;
  7530. material.vertexColors = this.vertexColors;
  7531. material.skinning = this.skinning;
  7532. material.morphTargets = this.morphTargets;
  7533. material.morphNormals = this.morphNormals;
  7534. return material;
  7535. };
  7536. /**
  7537. * @author alteredq / http://alteredqualia.com/
  7538. *
  7539. * parameters = {
  7540. * color: <hex>,
  7541. * opacity: <float>,
  7542. * map: new THREE.Texture( <Image> ),
  7543. *
  7544. * blending: THREE.NormalBlending,
  7545. * depthTest: <bool>,
  7546. * depthWrite: <bool>,
  7547. *
  7548. * useScreenCoordinates: <bool>,
  7549. * sizeAttenuation: <bool>,
  7550. * scaleByViewport: <bool>,
  7551. * alignment: THREE.SpriteAlignment.center,
  7552. *
  7553. * uvOffset: new THREE.Vector2(),
  7554. * uvScale: new THREE.Vector2(),
  7555. *
  7556. * fog: <bool>
  7557. * }
  7558. */
  7559. THREE.SpriteMaterial = function ( parameters ) {
  7560. THREE.Material.call( this );
  7561. // defaults
  7562. this.color = new THREE.Color( 0xffffff );
  7563. this.map = new THREE.Texture();
  7564. this.useScreenCoordinates = true;
  7565. this.depthTest = !this.useScreenCoordinates;
  7566. this.sizeAttenuation = !this.useScreenCoordinates;
  7567. this.scaleByViewport = !this.sizeAttenuation;
  7568. this.alignment = THREE.SpriteAlignment.center.clone();
  7569. this.fog = false;
  7570. this.uvOffset = new THREE.Vector2( 0, 0 );
  7571. this.uvScale = new THREE.Vector2( 1, 1 );
  7572. // set parameters
  7573. this.setValues( parameters );
  7574. // override coupled defaults if not specified explicitly by parameters
  7575. parameters = parameters || {};
  7576. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7577. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7578. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7579. };
  7580. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7581. THREE.SpriteMaterial.prototype.clone = function () {
  7582. var material = new THREE.SpriteMaterial();
  7583. THREE.Material.prototype.clone.call( this, material );
  7584. material.color.copy( this.color );
  7585. material.map = this.map;
  7586. material.useScreenCoordinates = this.useScreenCoordinates;
  7587. material.sizeAttenuation = this.sizeAttenuation;
  7588. material.scaleByViewport = this.scaleByViewport;
  7589. material.alignment.copy( this.alignment );
  7590. material.uvOffset.copy( this.uvOffset );
  7591. material.uvScale.copy( this.uvScale );
  7592. material.fog = this.fog;
  7593. return material;
  7594. };
  7595. // Alignment enums
  7596. THREE.SpriteAlignment = {};
  7597. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7598. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7599. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7600. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7601. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7602. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7603. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7604. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7605. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7606. /**
  7607. * @author mrdoob / http://mrdoob.com/
  7608. * @author alteredq / http://alteredqualia.com/
  7609. * @author szimek / https://github.com/szimek/
  7610. */
  7611. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7612. THREE.EventDispatcher.call( this );
  7613. this.id = THREE.TextureIdCount ++;
  7614. this.name = '';
  7615. this.image = image;
  7616. this.mipmaps = [];
  7617. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7618. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7619. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7620. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7621. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7622. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7623. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7624. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7625. this.offset = new THREE.Vector2( 0, 0 );
  7626. this.repeat = new THREE.Vector2( 1, 1 );
  7627. this.generateMipmaps = true;
  7628. this.premultiplyAlpha = false;
  7629. this.flipY = true;
  7630. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7631. this.needsUpdate = false;
  7632. this.onUpdate = null;
  7633. };
  7634. THREE.Texture.prototype = {
  7635. constructor: THREE.Texture,
  7636. clone: function ( texture ) {
  7637. if ( texture === undefined ) texture = new THREE.Texture();
  7638. texture.image = this.image;
  7639. texture.mipmaps = this.mipmaps.slice(0);
  7640. texture.mapping = this.mapping;
  7641. texture.wrapS = this.wrapS;
  7642. texture.wrapT = this.wrapT;
  7643. texture.magFilter = this.magFilter;
  7644. texture.minFilter = this.minFilter;
  7645. texture.anisotropy = this.anisotropy;
  7646. texture.format = this.format;
  7647. texture.type = this.type;
  7648. texture.offset.copy( this.offset );
  7649. texture.repeat.copy( this.repeat );
  7650. texture.generateMipmaps = this.generateMipmaps;
  7651. texture.premultiplyAlpha = this.premultiplyAlpha;
  7652. texture.flipY = this.flipY;
  7653. texture.unpackAlignment = this.unpackAlignment;
  7654. return texture;
  7655. },
  7656. dispose: function () {
  7657. this.dispatchEvent( { type: 'dispose' } );
  7658. }
  7659. };
  7660. THREE.TextureIdCount = 0;
  7661. /**
  7662. * @author alteredq / http://alteredqualia.com/
  7663. */
  7664. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7665. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7666. this.image = { width: width, height: height };
  7667. this.mipmaps = mipmaps;
  7668. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7669. };
  7670. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7671. THREE.CompressedTexture.prototype.clone = function () {
  7672. var texture = new THREE.CompressedTexture();
  7673. THREE.Texture.prototype.clone.call( this, texture );
  7674. return texture;
  7675. };
  7676. /**
  7677. * @author alteredq / http://alteredqualia.com/
  7678. */
  7679. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7680. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7681. this.image = { data: data, width: width, height: height };
  7682. };
  7683. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7684. THREE.DataTexture.prototype.clone = function () {
  7685. var texture = new THREE.DataTexture();
  7686. THREE.Texture.prototype.clone.call( this, texture );
  7687. return texture;
  7688. };
  7689. /**
  7690. * @author mrdoob / http://mrdoob.com/
  7691. */
  7692. THREE.Particle = function ( material ) {
  7693. THREE.Object3D.call( this );
  7694. this.material = material;
  7695. };
  7696. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7697. THREE.Particle.prototype.clone = function ( object ) {
  7698. if ( object === undefined ) object = new THREE.Particle( this.material );
  7699. THREE.Object3D.prototype.clone.call( this, object );
  7700. return object;
  7701. };
  7702. /**
  7703. * @author alteredq / http://alteredqualia.com/
  7704. */
  7705. THREE.ParticleSystem = function ( geometry, material ) {
  7706. THREE.Object3D.call( this );
  7707. this.geometry = geometry;
  7708. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7709. this.sortParticles = false;
  7710. if ( this.geometry ) {
  7711. // calc bound radius
  7712. if( this.geometry.boundingSphere === null ) {
  7713. this.geometry.computeBoundingSphere();
  7714. }
  7715. }
  7716. this.frustumCulled = false;
  7717. };
  7718. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7719. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7720. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7721. object.sortParticles = this.sortParticles;
  7722. THREE.Object3D.prototype.clone.call( this, object );
  7723. return object;
  7724. };
  7725. /**
  7726. * @author mrdoob / http://mrdoob.com/
  7727. */
  7728. THREE.Line = function ( geometry, material, type ) {
  7729. THREE.Object3D.call( this );
  7730. this.geometry = geometry;
  7731. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7732. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7733. if ( this.geometry ) {
  7734. if ( ! this.geometry.boundingSphere ) {
  7735. this.geometry.computeBoundingSphere();
  7736. }
  7737. }
  7738. };
  7739. THREE.LineStrip = 0;
  7740. THREE.LinePieces = 1;
  7741. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7742. THREE.Line.prototype.clone = function ( object ) {
  7743. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7744. THREE.Object3D.prototype.clone.call( this, object );
  7745. return object;
  7746. };
  7747. /**
  7748. * @author mrdoob / http://mrdoob.com/
  7749. * @author alteredq / http://alteredqualia.com/
  7750. * @author mikael emtinger / http://gomo.se/
  7751. */
  7752. THREE.Mesh = function ( geometry, material ) {
  7753. THREE.Object3D.call( this );
  7754. this.geometry = geometry;
  7755. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7756. if ( this.geometry ) {
  7757. // calc bound radius
  7758. if ( this.geometry.boundingSphere === null ) {
  7759. this.geometry.computeBoundingSphere();
  7760. }
  7761. // setup morph targets
  7762. if ( this.geometry.morphTargets.length ) {
  7763. this.morphTargetBase = -1;
  7764. this.morphTargetForcedOrder = [];
  7765. this.morphTargetInfluences = [];
  7766. this.morphTargetDictionary = {};
  7767. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  7768. this.morphTargetInfluences.push( 0 );
  7769. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7770. }
  7771. }
  7772. }
  7773. }
  7774. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7775. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7776. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7777. return this.morphTargetDictionary[ name ];
  7778. }
  7779. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7780. return 0;
  7781. };
  7782. THREE.Mesh.prototype.clone = function ( object ) {
  7783. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7784. THREE.Object3D.prototype.clone.call( this, object );
  7785. return object;
  7786. };
  7787. /**
  7788. * @author mikael emtinger / http://gomo.se/
  7789. * @author alteredq / http://alteredqualia.com/
  7790. */
  7791. THREE.Bone = function( belongsToSkin ) {
  7792. THREE.Object3D.call( this );
  7793. this.skin = belongsToSkin;
  7794. this.skinMatrix = new THREE.Matrix4();
  7795. };
  7796. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7797. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  7798. // update local
  7799. if ( this.matrixAutoUpdate ) {
  7800. forceUpdate |= this.updateMatrix();
  7801. }
  7802. // update skin matrix
  7803. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7804. if( parentSkinMatrix ) {
  7805. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  7806. } else {
  7807. this.skinMatrix.copy( this.matrix );
  7808. }
  7809. this.matrixWorldNeedsUpdate = false;
  7810. forceUpdate = true;
  7811. }
  7812. // update children
  7813. var child, i, l = this.children.length;
  7814. for ( i = 0; i < l; i ++ ) {
  7815. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7816. }
  7817. };
  7818. /**
  7819. * @author mikael emtinger / http://gomo.se/
  7820. * @author alteredq / http://alteredqualia.com/
  7821. */
  7822. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7823. THREE.Mesh.call( this, geometry, material );
  7824. //
  7825. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7826. // init bones
  7827. this.identityMatrix = new THREE.Matrix4();
  7828. this.bones = [];
  7829. this.boneMatrices = [];
  7830. var b, bone, gbone, p, q, s;
  7831. if ( this.geometry && this.geometry.bones !== undefined ) {
  7832. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7833. gbone = this.geometry.bones[ b ];
  7834. p = gbone.pos;
  7835. q = gbone.rotq;
  7836. s = gbone.scl;
  7837. bone = this.addBone();
  7838. bone.name = gbone.name;
  7839. bone.position.set( p[0], p[1], p[2] );
  7840. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7841. bone.useQuaternion = true;
  7842. if ( s !== undefined ) {
  7843. bone.scale.set( s[0], s[1], s[2] );
  7844. } else {
  7845. bone.scale.set( 1, 1, 1 );
  7846. }
  7847. }
  7848. for ( b = 0; b < this.bones.length; b ++ ) {
  7849. gbone = this.geometry.bones[ b ];
  7850. bone = this.bones[ b ];
  7851. if ( gbone.parent === -1 ) {
  7852. this.add( bone );
  7853. } else {
  7854. this.bones[ gbone.parent ].add( bone );
  7855. }
  7856. }
  7857. //
  7858. var nBones = this.bones.length;
  7859. if ( this.useVertexTexture ) {
  7860. // layout (1 matrix = 4 pixels)
  7861. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7862. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7863. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7864. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7865. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7866. var size;
  7867. if ( nBones > 256 )
  7868. size = 64;
  7869. else if ( nBones > 64 )
  7870. size = 32;
  7871. else if ( nBones > 16 )
  7872. size = 16;
  7873. else
  7874. size = 8;
  7875. this.boneTextureWidth = size;
  7876. this.boneTextureHeight = size;
  7877. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7878. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7879. this.boneTexture.minFilter = THREE.NearestFilter;
  7880. this.boneTexture.magFilter = THREE.NearestFilter;
  7881. this.boneTexture.generateMipmaps = false;
  7882. this.boneTexture.flipY = false;
  7883. } else {
  7884. this.boneMatrices = new Float32Array( 16 * nBones );
  7885. }
  7886. this.pose();
  7887. }
  7888. };
  7889. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7890. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7891. if ( bone === undefined ) {
  7892. bone = new THREE.Bone( this );
  7893. }
  7894. this.bones.push( bone );
  7895. return bone;
  7896. };
  7897. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7898. this.matrixAutoUpdate && this.updateMatrix();
  7899. // update matrixWorld
  7900. if ( this.matrixWorldNeedsUpdate || force ) {
  7901. if ( this.parent ) {
  7902. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  7903. } else {
  7904. this.matrixWorld.copy( this.matrix );
  7905. }
  7906. this.matrixWorldNeedsUpdate = false;
  7907. force = true;
  7908. }
  7909. // update children
  7910. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7911. var child = this.children[ i ];
  7912. if ( child instanceof THREE.Bone ) {
  7913. child.update( this.identityMatrix, false );
  7914. } else {
  7915. child.updateMatrixWorld( true );
  7916. }
  7917. }
  7918. // make a snapshot of the bones' rest position
  7919. if ( this.boneInverses == undefined ) {
  7920. this.boneInverses = [];
  7921. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7922. var inverse = new THREE.Matrix4();
  7923. inverse.getInverse( this.bones[ b ].skinMatrix );
  7924. this.boneInverses.push( inverse );
  7925. }
  7926. }
  7927. // flatten bone matrices to array
  7928. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7929. // compute the offset between the current and the original transform;
  7930. //TODO: we could get rid of this multiplication step if the skinMatrix
  7931. // was already representing the offset; however, this requires some
  7932. // major changes to the animation system
  7933. THREE.SkinnedMesh.offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7934. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7935. }
  7936. if ( this.useVertexTexture ) {
  7937. this.boneTexture.needsUpdate = true;
  7938. }
  7939. };
  7940. THREE.SkinnedMesh.prototype.pose = function () {
  7941. this.updateMatrixWorld( true );
  7942. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7943. // normalize weights
  7944. var sw = this.geometry.skinWeights[ i ];
  7945. var scale = 1.0 / sw.lengthManhattan();
  7946. if ( scale !== Infinity ) {
  7947. sw.multiplyScalar( scale );
  7948. } else {
  7949. sw.set( 1 ); // this will be normalized by the shader anyway
  7950. }
  7951. }
  7952. };
  7953. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7954. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7955. THREE.Mesh.prototype.clone.call( this, object );
  7956. return object;
  7957. };
  7958. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7959. /**
  7960. * @author alteredq / http://alteredqualia.com/
  7961. */
  7962. THREE.MorphAnimMesh = function ( geometry, material ) {
  7963. THREE.Mesh.call( this, geometry, material );
  7964. // API
  7965. this.duration = 1000; // milliseconds
  7966. this.mirroredLoop = false;
  7967. this.time = 0;
  7968. // internals
  7969. this.lastKeyframe = 0;
  7970. this.currentKeyframe = 0;
  7971. this.direction = 1;
  7972. this.directionBackwards = false;
  7973. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7974. };
  7975. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7976. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7977. this.startKeyframe = start;
  7978. this.endKeyframe = end;
  7979. this.length = this.endKeyframe - this.startKeyframe + 1;
  7980. };
  7981. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7982. this.direction = 1;
  7983. this.directionBackwards = false;
  7984. };
  7985. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7986. this.direction = -1;
  7987. this.directionBackwards = true;
  7988. };
  7989. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7990. var geometry = this.geometry;
  7991. if ( ! geometry.animations ) geometry.animations = {};
  7992. var firstAnimation, animations = geometry.animations;
  7993. var pattern = /([a-z]+)(\d+)/;
  7994. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7995. var morph = geometry.morphTargets[ i ];
  7996. var parts = morph.name.match( pattern );
  7997. if ( parts && parts.length > 1 ) {
  7998. var label = parts[ 1 ];
  7999. var num = parts[ 2 ];
  8000. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8001. var animation = animations[ label ];
  8002. if ( i < animation.start ) animation.start = i;
  8003. if ( i > animation.end ) animation.end = i;
  8004. if ( ! firstAnimation ) firstAnimation = label;
  8005. }
  8006. }
  8007. geometry.firstAnimation = firstAnimation;
  8008. };
  8009. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8010. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8011. this.geometry.animations[ label ] = { start: start, end: end };
  8012. };
  8013. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8014. var animation = this.geometry.animations[ label ];
  8015. if ( animation ) {
  8016. this.setFrameRange( animation.start, animation.end );
  8017. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8018. this.time = 0;
  8019. } else {
  8020. console.warn( "animation[" + label + "] undefined" );
  8021. }
  8022. };
  8023. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8024. var frameTime = this.duration / this.length;
  8025. this.time += this.direction * delta;
  8026. if ( this.mirroredLoop ) {
  8027. if ( this.time > this.duration || this.time < 0 ) {
  8028. this.direction *= -1;
  8029. if ( this.time > this.duration ) {
  8030. this.time = this.duration;
  8031. this.directionBackwards = true;
  8032. }
  8033. if ( this.time < 0 ) {
  8034. this.time = 0;
  8035. this.directionBackwards = false;
  8036. }
  8037. }
  8038. } else {
  8039. this.time = this.time % this.duration;
  8040. if ( this.time < 0 ) this.time += this.duration;
  8041. }
  8042. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8043. if ( keyframe !== this.currentKeyframe ) {
  8044. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8045. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8046. this.morphTargetInfluences[ keyframe ] = 0;
  8047. this.lastKeyframe = this.currentKeyframe;
  8048. this.currentKeyframe = keyframe;
  8049. }
  8050. var mix = ( this.time % frameTime ) / frameTime;
  8051. if ( this.directionBackwards ) {
  8052. mix = 1 - mix;
  8053. }
  8054. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8055. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8056. };
  8057. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8058. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8059. object.duration = this.duration;
  8060. object.mirroredLoop = this.mirroredLoop;
  8061. object.time = this.time;
  8062. object.lastKeyframe = this.lastKeyframe;
  8063. object.currentKeyframe = this.currentKeyframe;
  8064. object.direction = this.direction;
  8065. object.directionBackwards = this.directionBackwards;
  8066. THREE.Mesh.prototype.clone.call( this, object );
  8067. return object;
  8068. };
  8069. /**
  8070. * @author alteredq / http://alteredqualia.com/
  8071. */
  8072. THREE.Ribbon = function ( geometry, material ) {
  8073. THREE.Object3D.call( this );
  8074. this.geometry = geometry;
  8075. this.material = material;
  8076. };
  8077. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  8078. THREE.Ribbon.prototype.clone = function ( object ) {
  8079. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  8080. THREE.Object3D.prototype.clone.call( this, object );
  8081. return object;
  8082. };
  8083. /**
  8084. * @author mikael emtinger / http://gomo.se/
  8085. * @author alteredq / http://alteredqualia.com/
  8086. * @author mrdoob / http://mrdoob.com/
  8087. */
  8088. THREE.LOD = function () {
  8089. THREE.Object3D.call( this );
  8090. this.LODs = [];
  8091. };
  8092. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8093. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  8094. if ( visibleAtDistance === undefined ) {
  8095. visibleAtDistance = 0;
  8096. }
  8097. visibleAtDistance = Math.abs( visibleAtDistance );
  8098. for ( var l = 0; l < this.LODs.length; l ++ ) {
  8099. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  8100. break;
  8101. }
  8102. }
  8103. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  8104. this.add( object3D );
  8105. };
  8106. THREE.LOD.prototype.update = function ( camera ) {
  8107. if ( this.LODs.length > 1 ) {
  8108. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  8109. var inverse = camera.matrixWorldInverse;
  8110. 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] );
  8111. this.LODs[ 0 ].object3D.visible = true;
  8112. for ( var l = 1; l < this.LODs.length; l ++ ) {
  8113. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  8114. this.LODs[ l - 1 ].object3D.visible = false;
  8115. this.LODs[ l ].object3D.visible = true;
  8116. } else {
  8117. break;
  8118. }
  8119. }
  8120. for( ; l < this.LODs.length; l ++ ) {
  8121. this.LODs[ l ].object3D.visible = false;
  8122. }
  8123. }
  8124. };
  8125. THREE.LOD.prototype.clone = function () {
  8126. // TODO
  8127. };
  8128. /**
  8129. * @author mikael emtinger / http://gomo.se/
  8130. * @author alteredq / http://alteredqualia.com/
  8131. */
  8132. THREE.Sprite = function ( material ) {
  8133. THREE.Object3D.call( this );
  8134. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8135. this.rotation3d = this.rotation;
  8136. this.rotation = 0;
  8137. };
  8138. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8139. /*
  8140. * Custom update matrix
  8141. */
  8142. THREE.Sprite.prototype.updateMatrix = function () {
  8143. this.matrix.setPosition( this.position );
  8144. this.rotation3d.set( 0, 0, this.rotation );
  8145. this.matrix.setRotationFromEuler( this.rotation3d );
  8146. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  8147. this.matrix.scale( this.scale );
  8148. }
  8149. this.matrixWorldNeedsUpdate = true;
  8150. };
  8151. THREE.Sprite.prototype.clone = function ( object ) {
  8152. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8153. THREE.Object3D.prototype.clone.call( this, object );
  8154. return object;
  8155. };
  8156. /**
  8157. * @author mrdoob / http://mrdoob.com/
  8158. */
  8159. THREE.Scene = function () {
  8160. THREE.Object3D.call( this );
  8161. this.fog = null;
  8162. this.overrideMaterial = null;
  8163. this.matrixAutoUpdate = false;
  8164. this.__objects = [];
  8165. this.__lights = [];
  8166. this.__objectsAdded = [];
  8167. this.__objectsRemoved = [];
  8168. };
  8169. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8170. THREE.Scene.prototype.__addObject = function ( object ) {
  8171. if ( object instanceof THREE.Light ) {
  8172. if ( this.__lights.indexOf( object ) === - 1 ) {
  8173. this.__lights.push( object );
  8174. }
  8175. if ( object.target && object.target.parent === undefined ) {
  8176. this.add( object.target );
  8177. }
  8178. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8179. if ( this.__objects.indexOf( object ) === - 1 ) {
  8180. this.__objects.push( object );
  8181. this.__objectsAdded.push( object );
  8182. // check if previously removed
  8183. var i = this.__objectsRemoved.indexOf( object );
  8184. if ( i !== -1 ) {
  8185. this.__objectsRemoved.splice( i, 1 );
  8186. }
  8187. }
  8188. }
  8189. for ( var c = 0; c < object.children.length; c ++ ) {
  8190. this.__addObject( object.children[ c ] );
  8191. }
  8192. };
  8193. THREE.Scene.prototype.__removeObject = function ( object ) {
  8194. if ( object instanceof THREE.Light ) {
  8195. var i = this.__lights.indexOf( object );
  8196. if ( i !== -1 ) {
  8197. this.__lights.splice( i, 1 );
  8198. }
  8199. } else if ( !( object instanceof THREE.Camera ) ) {
  8200. var i = this.__objects.indexOf( object );
  8201. if( i !== -1 ) {
  8202. this.__objects.splice( i, 1 );
  8203. this.__objectsRemoved.push( object );
  8204. // check if previously added
  8205. var ai = this.__objectsAdded.indexOf( object );
  8206. if ( ai !== -1 ) {
  8207. this.__objectsAdded.splice( ai, 1 );
  8208. }
  8209. }
  8210. }
  8211. for ( var c = 0; c < object.children.length; c ++ ) {
  8212. this.__removeObject( object.children[ c ] );
  8213. }
  8214. };
  8215. /**
  8216. * @author mrdoob / http://mrdoob.com/
  8217. * @author alteredq / http://alteredqualia.com/
  8218. */
  8219. THREE.Fog = function ( hex, near, far ) {
  8220. this.name = '';
  8221. this.color = new THREE.Color( hex );
  8222. this.near = ( near !== undefined ) ? near : 1;
  8223. this.far = ( far !== undefined ) ? far : 1000;
  8224. };
  8225. THREE.Fog.prototype.clone = function () {
  8226. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8227. };
  8228. /**
  8229. * @author mrdoob / http://mrdoob.com/
  8230. * @author alteredq / http://alteredqualia.com/
  8231. */
  8232. THREE.FogExp2 = function ( hex, density ) {
  8233. this.name = '';
  8234. this.color = new THREE.Color( hex );
  8235. this.density = ( density !== undefined ) ? density : 0.00025;
  8236. };
  8237. THREE.FogExp2.prototype.clone = function () {
  8238. return new THREE.FogExp2( this.color.getHex(), this.density );
  8239. };
  8240. /**
  8241. * @author mrdoob / http://mrdoob.com/
  8242. */
  8243. THREE.CanvasRenderer = function ( parameters ) {
  8244. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8245. parameters = parameters || {};
  8246. var _this = this,
  8247. _renderData, _elements, _lights,
  8248. _projector = new THREE.Projector(),
  8249. _canvas = parameters.canvas !== undefined
  8250. ? parameters.canvas
  8251. : document.createElement( 'canvas' ),
  8252. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8253. _context = _canvas.getContext( '2d' ),
  8254. _clearColor = new THREE.Color( 0x000000 ),
  8255. _clearOpacity = 0,
  8256. _contextGlobalAlpha = 1,
  8257. _contextGlobalCompositeOperation = 0,
  8258. _contextStrokeStyle = null,
  8259. _contextFillStyle = null,
  8260. _contextLineWidth = null,
  8261. _contextLineCap = null,
  8262. _contextLineJoin = null,
  8263. _v1, _v2, _v3, _v4,
  8264. _v5 = new THREE.RenderableVertex(),
  8265. _v6 = new THREE.RenderableVertex(),
  8266. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8267. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8268. _color = new THREE.Color(),
  8269. _color1 = new THREE.Color(),
  8270. _color2 = new THREE.Color(),
  8271. _color3 = new THREE.Color(),
  8272. _color4 = new THREE.Color(),
  8273. _diffuseColor = new THREE.Color(),
  8274. _emissiveColor = new THREE.Color(),
  8275. _lightColor = new THREE.Color(),
  8276. _patterns = {}, _imagedatas = {},
  8277. _near, _far,
  8278. _image, _uvs,
  8279. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8280. _clipBox = new THREE.Box2(),
  8281. _clearBox = new THREE.Box2(),
  8282. _elemBox = new THREE.Box2(),
  8283. _enableLighting = false,
  8284. _ambientLight = new THREE.Color(),
  8285. _directionalLights = new THREE.Color(),
  8286. _pointLights = new THREE.Color(),
  8287. _pi2 = Math.PI * 2,
  8288. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8289. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8290. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8291. _pixelMap = document.createElement( 'canvas' );
  8292. _pixelMap.width = _pixelMap.height = 2;
  8293. _pixelMapContext = _pixelMap.getContext( '2d' );
  8294. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8295. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8296. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8297. _pixelMapData = _pixelMapImage.data;
  8298. _gradientMap = document.createElement( 'canvas' );
  8299. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8300. _gradientMapContext = _gradientMap.getContext( '2d' );
  8301. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8302. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8303. _gradientMapQuality --; // Fix UVs
  8304. this.domElement = _canvas;
  8305. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8306. ? parameters.devicePixelRatio
  8307. : window.devicePixelRatio !== undefined
  8308. ? window.devicePixelRatio
  8309. : 1;
  8310. this.autoClear = true;
  8311. this.sortObjects = true;
  8312. this.sortElements = true;
  8313. this.info = {
  8314. render: {
  8315. vertices: 0,
  8316. faces: 0
  8317. }
  8318. }
  8319. this.setSize = function ( width, height ) {
  8320. _canvasWidth = width * this.devicePixelRatio;
  8321. _canvasHeight = height * this.devicePixelRatio;
  8322. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8323. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8324. _canvas.width = _canvasWidth;
  8325. _canvas.height = _canvasHeight;
  8326. _canvas.style.width = width + 'px';
  8327. _canvas.style.height = height + 'px';
  8328. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8329. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8330. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8331. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8332. _contextGlobalAlpha = 1;
  8333. _contextGlobalCompositeOperation = 0;
  8334. _contextStrokeStyle = null;
  8335. _contextFillStyle = null;
  8336. _contextLineWidth = null;
  8337. _contextLineCap = null;
  8338. _contextLineJoin = null;
  8339. };
  8340. this.setClearColor = function ( color, opacity ) {
  8341. _clearColor.copy( color );
  8342. _clearOpacity = opacity !== undefined ? opacity : 1;
  8343. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8344. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8345. };
  8346. this.setClearColorHex = function ( hex, opacity ) {
  8347. _clearColor.setHex( hex );
  8348. _clearOpacity = opacity !== undefined ? opacity : 1;
  8349. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8350. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8351. };
  8352. this.getMaxAnisotropy = function () {
  8353. return 0;
  8354. };
  8355. this.clear = function () {
  8356. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8357. if ( _clearBox.empty() === false ) {
  8358. _clearBox.intersect( _clipBox );
  8359. _clearBox.expandByScalar( 2 );
  8360. if ( _clearOpacity < 1 ) {
  8361. _context.clearRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  8362. }
  8363. if ( _clearOpacity > 0 ) {
  8364. setBlending( THREE.NormalBlending );
  8365. setOpacity( 1 );
  8366. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  8367. _context.fillRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  8368. }
  8369. _clearBox.makeEmpty();
  8370. }
  8371. };
  8372. this.render = function ( scene, camera ) {
  8373. if ( camera instanceof THREE.Camera === false ) {
  8374. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8375. return;
  8376. }
  8377. if ( this.autoClear === true ) {
  8378. this.clear();
  8379. }
  8380. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8381. _this.info.render.vertices = 0;
  8382. _this.info.render.faces = 0;
  8383. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8384. _elements = _renderData.elements;
  8385. _lights = _renderData.lights;
  8386. /* DEBUG
  8387. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  8388. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8389. */
  8390. _enableLighting = _lights.length > 0;
  8391. if ( _enableLighting === true ) {
  8392. calculateLights();
  8393. }
  8394. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8395. var element = _elements[ e ];
  8396. var material = element.material;
  8397. if ( material === undefined || material.visible === false ) continue;
  8398. _elemBox.makeEmpty();
  8399. if ( element instanceof THREE.RenderableParticle ) {
  8400. _v1 = element;
  8401. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8402. renderParticle( _v1, element, material, scene );
  8403. } else if ( element instanceof THREE.RenderableLine ) {
  8404. _v1 = element.v1; _v2 = element.v2;
  8405. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8406. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8407. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  8408. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8409. renderLine( _v1, _v2, element, material, scene );
  8410. }
  8411. } else if ( element instanceof THREE.RenderableFace3 ) {
  8412. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8413. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8414. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8415. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8416. if ( material.overdraw === true ) {
  8417. expand( _v1.positionScreen, _v2.positionScreen );
  8418. expand( _v2.positionScreen, _v3.positionScreen );
  8419. expand( _v3.positionScreen, _v1.positionScreen );
  8420. }
  8421. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  8422. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8423. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  8424. }
  8425. } else if ( element instanceof THREE.RenderableFace4 ) {
  8426. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8427. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8428. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8429. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8430. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8431. _v5.positionScreen.copy( _v2.positionScreen );
  8432. _v6.positionScreen.copy( _v4.positionScreen );
  8433. if ( material.overdraw === true ) {
  8434. expand( _v1.positionScreen, _v2.positionScreen );
  8435. expand( _v2.positionScreen, _v4.positionScreen );
  8436. expand( _v4.positionScreen, _v1.positionScreen );
  8437. expand( _v3.positionScreen, _v5.positionScreen );
  8438. expand( _v3.positionScreen, _v6.positionScreen );
  8439. }
  8440. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  8441. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8442. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8443. }
  8444. }
  8445. /* DEBUG
  8446. _context.lineWidth = 1;
  8447. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  8448. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8449. */
  8450. _clearBox.union( _elemBox );
  8451. }
  8452. /* DEBUG
  8453. _context.lineWidth = 1;
  8454. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  8455. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8456. */
  8457. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8458. //
  8459. function calculateLights() {
  8460. _ambientLight.setRGB( 0, 0, 0 );
  8461. _directionalLights.setRGB( 0, 0, 0 );
  8462. _pointLights.setRGB( 0, 0, 0 );
  8463. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8464. var light = _lights[ l ];
  8465. var lightColor = light.color;
  8466. if ( light instanceof THREE.AmbientLight ) {
  8467. _ambientLight.add( lightColor );
  8468. } else if ( light instanceof THREE.DirectionalLight ) {
  8469. // for particles
  8470. _directionalLights.add( lightColor );
  8471. } else if ( light instanceof THREE.PointLight ) {
  8472. // for particles
  8473. _pointLights.add( lightColor );
  8474. }
  8475. }
  8476. }
  8477. function calculateLight( position, normal, color ) {
  8478. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8479. var light = _lights[ l ];
  8480. _lightColor.copy( light.color );
  8481. if ( light instanceof THREE.DirectionalLight ) {
  8482. var lightPosition = light.matrixWorld.getPosition().normalize();
  8483. var amount = normal.dot( lightPosition );
  8484. if ( amount <= 0 ) continue;
  8485. amount *= light.intensity;
  8486. color.add( _lightColor.multiplyScalar( amount ) );
  8487. } else if ( light instanceof THREE.PointLight ) {
  8488. var lightPosition = light.matrixWorld.getPosition();
  8489. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8490. if ( amount <= 0 ) continue;
  8491. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8492. if ( amount == 0 ) continue;
  8493. amount *= light.intensity;
  8494. color.add( _lightColor.multiplyScalar( amount ) );
  8495. }
  8496. }
  8497. }
  8498. function renderParticle( v1, element, material, scene ) {
  8499. setOpacity( material.opacity );
  8500. setBlending( material.blending );
  8501. var width, height, scaleX, scaleY,
  8502. bitmap, bitmapWidth, bitmapHeight;
  8503. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8504. if ( material.map === null ) {
  8505. scaleX = element.object.scale.x;
  8506. scaleY = element.object.scale.y;
  8507. // TODO: Be able to disable this
  8508. scaleX *= element.scale.x * _canvasWidthHalf;
  8509. scaleY *= element.scale.y * _canvasHeightHalf;
  8510. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8511. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8512. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8513. return;
  8514. }
  8515. setFillStyle( material.color.getStyle() );
  8516. _context.save();
  8517. _context.translate( v1.x, v1.y );
  8518. _context.rotate( - element.rotation );
  8519. _context.scale( scaleX, scaleY );
  8520. _context.fillRect( -1, -1, 2, 2 );
  8521. _context.restore();
  8522. } else {
  8523. bitmap = material.map.image;
  8524. bitmapWidth = bitmap.width >> 1;
  8525. bitmapHeight = bitmap.height >> 1;
  8526. scaleX = element.scale.x * _canvasWidthHalf;
  8527. scaleY = element.scale.y * _canvasHeightHalf;
  8528. width = scaleX * bitmapWidth;
  8529. height = scaleY * bitmapHeight;
  8530. // TODO: Rotations break this...
  8531. _elemBox.min.set( v1.x - width, v1.y - height );
  8532. _elemBox.max.set( v1.x + width, v1.y + height );
  8533. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8534. return;
  8535. }
  8536. _context.save();
  8537. _context.translate( v1.x, v1.y );
  8538. _context.rotate( - element.rotation );
  8539. _context.scale( scaleX, - scaleY );
  8540. _context.translate( - bitmapWidth, - bitmapHeight );
  8541. _context.drawImage( bitmap, 0, 0 );
  8542. _context.restore();
  8543. }
  8544. /* DEBUG
  8545. setStrokeStyle( 'rgb(255,255,0)' );
  8546. _context.beginPath();
  8547. _context.moveTo( v1.x - 10, v1.y );
  8548. _context.lineTo( v1.x + 10, v1.y );
  8549. _context.moveTo( v1.x, v1.y - 10 );
  8550. _context.lineTo( v1.x, v1.y + 10 );
  8551. _context.stroke();
  8552. */
  8553. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8554. width = element.scale.x * _canvasWidthHalf;
  8555. height = element.scale.y * _canvasHeightHalf;
  8556. _elemBox.min.set( v1.x - width, v1.y - height );
  8557. _elemBox.max.set( v1.x + width, v1.y + height );
  8558. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8559. return;
  8560. }
  8561. setStrokeStyle( material.color.getStyle() );
  8562. setFillStyle( material.color.getStyle() );
  8563. _context.save();
  8564. _context.translate( v1.x, v1.y );
  8565. _context.rotate( - element.rotation );
  8566. _context.scale( width, height );
  8567. material.program( _context );
  8568. _context.restore();
  8569. }
  8570. }
  8571. function renderLine( v1, v2, element, material, scene ) {
  8572. setOpacity( material.opacity );
  8573. setBlending( material.blending );
  8574. _context.beginPath();
  8575. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8576. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8577. if ( material instanceof THREE.LineBasicMaterial ) {
  8578. setLineWidth( material.linewidth );
  8579. setLineCap( material.linecap );
  8580. setLineJoin( material.linejoin );
  8581. setStrokeStyle( material.color.getStyle() );
  8582. _context.stroke();
  8583. _elemBox.expandByScalar( material.linewidth * 2 );
  8584. }
  8585. }
  8586. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  8587. _this.info.render.vertices += 3;
  8588. _this.info.render.faces ++;
  8589. setOpacity( material.opacity );
  8590. setBlending( material.blending );
  8591. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8592. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8593. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8594. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8595. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  8596. _diffuseColor.copy( material.color );
  8597. _emissiveColor.copy( material.emissive );
  8598. if ( material.vertexColors === THREE.FaceColors ) {
  8599. _diffuseColor.multiply( element.color );
  8600. }
  8601. if ( _enableLighting === true ) {
  8602. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8603. _color1.copy( _ambientLight );
  8604. _color2.copy( _ambientLight );
  8605. _color3.copy( _ambientLight );
  8606. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8607. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8608. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8609. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8610. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8611. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8612. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8613. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8614. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8615. } else {
  8616. _color.copy( _ambientLight );
  8617. calculateLight( element.centroidModel, element.normalModel, _color );
  8618. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8619. material.wireframe === true
  8620. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8621. : fillPath( _color );
  8622. }
  8623. } else {
  8624. material.wireframe === true
  8625. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8626. : fillPath( material.color );
  8627. }
  8628. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8629. if ( material.map !== null ) {
  8630. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8631. _uvs = element.uvs[ 0 ];
  8632. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].x, _uvs[ uv1 ].y, _uvs[ uv2 ].x, _uvs[ uv2 ].y, _uvs[ uv3 ].x, _uvs[ uv3 ].y, material.map );
  8633. }
  8634. } else if ( material.envMap !== null ) {
  8635. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8636. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8637. _uv1x = 0.5 * _vector3.x + 0.5;
  8638. _uv1y = 0.5 * _vector3.y + 0.5;
  8639. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8640. _uv2x = 0.5 * _vector3.x + 0.5;
  8641. _uv2y = 0.5 * _vector3.y + 0.5;
  8642. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8643. _uv3x = 0.5 * _vector3.x + 0.5;
  8644. _uv3y = 0.5 * _vector3.y + 0.5;
  8645. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8646. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8647. }*/
  8648. } else {
  8649. _color.copy( material.color );
  8650. if ( material.vertexColors === THREE.FaceColors ) {
  8651. _color.multiply( element.color );
  8652. }
  8653. material.wireframe === true
  8654. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8655. : fillPath( _color );
  8656. }
  8657. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8658. _near = camera.near;
  8659. _far = camera.far;
  8660. var depth;
  8661. depth = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8662. _color1.setRGB( depth, depth, depth );
  8663. depth = 1 - smoothstep( v2.positionScreen.z, _near, _far )
  8664. _color2.setRGB( depth, depth, depth );
  8665. depth = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8666. _color3.setRGB( depth, depth, depth );
  8667. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8668. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8669. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8670. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8671. var normal;
  8672. if ( material.shading == THREE.FlatShading ) {
  8673. normal = element.normalModelView;
  8674. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8675. material.wireframe === true
  8676. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8677. : fillPath( _color );
  8678. } else if ( material.shading == THREE.SmoothShading ) {
  8679. normal = element.vertexNormalsModelView[ uv1 ];
  8680. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8681. normal = element.vertexNormalsModelView[ uv2 ];
  8682. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8683. normal = element.vertexNormalsModelView[ uv3 ];
  8684. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8685. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8686. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8687. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8688. }
  8689. }
  8690. }
  8691. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  8692. _this.info.render.vertices += 4;
  8693. _this.info.render.faces ++;
  8694. setOpacity( material.opacity );
  8695. setBlending( material.blending );
  8696. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8697. // Let renderFace3() handle this
  8698. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  8699. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  8700. return;
  8701. }
  8702. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8703. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8704. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8705. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8706. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8707. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8708. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8709. _diffuseColor.copy( material.color );
  8710. _emissiveColor.copy( material.emissive );
  8711. if ( material.vertexColors === THREE.FaceColors ) {
  8712. _diffuseColor.multiply( element.color );
  8713. }
  8714. if ( _enableLighting === true ) {
  8715. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8716. _color1.copy( _ambientLight );
  8717. _color2.copy( _ambientLight );
  8718. _color3.copy( _ambientLight );
  8719. _color4.copy( _ambientLight );
  8720. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8721. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8722. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8723. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8724. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8725. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8726. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8727. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  8728. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8729. // TODO: UVs are incorrect, v4->v3?
  8730. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8731. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8732. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8733. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8734. } else {
  8735. _color.copy( _ambientLight );
  8736. calculateLight( element.centroidModel, element.normalModel, _color );
  8737. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8738. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8739. material.wireframe === true
  8740. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8741. : fillPath( _color );
  8742. }
  8743. } else {
  8744. _color.addColors( _diffuseColor, _emissiveColor );
  8745. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8746. material.wireframe === true
  8747. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8748. : fillPath( _color );
  8749. }
  8750. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8751. _color.copy( material.color );
  8752. if ( material.vertexColors === THREE.FaceColors ) {
  8753. _color.multiply( element.color );
  8754. }
  8755. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8756. material.wireframe === true
  8757. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8758. : fillPath( _color );
  8759. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8760. var normal;
  8761. if ( material.shading == THREE.FlatShading ) {
  8762. normal = element.normalModelView;
  8763. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8764. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8765. material.wireframe === true
  8766. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8767. : fillPath( _color );
  8768. } else if ( material.shading == THREE.SmoothShading ) {
  8769. normal = element.vertexNormalsModelView[ 0 ];
  8770. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8771. normal = element.vertexNormalsModelView[ 1 ];
  8772. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8773. normal = element.vertexNormalsModelView[ 3 ];
  8774. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8775. normal = element.vertexNormalsModelView[ 2 ];
  8776. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8777. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8778. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8779. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8780. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8781. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8782. }
  8783. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8784. _near = camera.near;
  8785. _far = camera.far;
  8786. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8787. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8788. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  8789. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8790. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8791. // TODO: UVs are incorrect, v4->v3?
  8792. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8793. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8794. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8795. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8796. }
  8797. }
  8798. //
  8799. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8800. _context.beginPath();
  8801. _context.moveTo( x0, y0 );
  8802. _context.lineTo( x1, y1 );
  8803. _context.lineTo( x2, y2 );
  8804. _context.closePath();
  8805. }
  8806. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8807. _context.beginPath();
  8808. _context.moveTo( x0, y0 );
  8809. _context.lineTo( x1, y1 );
  8810. _context.lineTo( x2, y2 );
  8811. _context.lineTo( x3, y3 );
  8812. _context.closePath();
  8813. }
  8814. function strokePath( color, linewidth, linecap, linejoin ) {
  8815. setLineWidth( linewidth );
  8816. setLineCap( linecap );
  8817. setLineJoin( linejoin );
  8818. setStrokeStyle( color.getStyle() );
  8819. _context.stroke();
  8820. _elemBox.expandByScalar( linewidth * 2 );
  8821. }
  8822. function fillPath( color ) {
  8823. setFillStyle( color.getStyle() );
  8824. _context.fill();
  8825. }
  8826. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8827. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8828. if ( texture.needsUpdate === true ) {
  8829. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8830. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8831. _patterns[ texture.id ] = _context.createPattern(
  8832. texture.image, repeatX === true && repeatY === true
  8833. ? 'repeat'
  8834. : repeatX === true && repeatY === false
  8835. ? 'repeat-x'
  8836. : repeatX === false && repeatY === true
  8837. ? 'repeat-y'
  8838. : 'no-repeat'
  8839. );
  8840. texture.needsUpdate = false;
  8841. }
  8842. _patterns[ texture.id ] === undefined
  8843. ? setFillStyle( 'rgba(0,0,0,1)' )
  8844. : setFillStyle( _patterns[ texture.id ] );
  8845. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8846. var a, b, c, d, e, f, det, idet,
  8847. offsetX = texture.offset.x / texture.repeat.x,
  8848. offsetY = texture.offset.y / texture.repeat.y,
  8849. width = texture.image.width * texture.repeat.x,
  8850. height = texture.image.height * texture.repeat.y;
  8851. u0 = ( u0 + offsetX ) * width;
  8852. v0 = ( 1.0 - v0 + offsetY ) * height;
  8853. u1 = ( u1 + offsetX ) * width;
  8854. v1 = ( 1.0 - v1 + offsetY ) * height;
  8855. u2 = ( u2 + offsetX ) * width;
  8856. v2 = ( 1.0 - v2 + offsetY ) * height;
  8857. x1 -= x0; y1 -= y0;
  8858. x2 -= x0; y2 -= y0;
  8859. u1 -= u0; v1 -= v0;
  8860. u2 -= u0; v2 -= v0;
  8861. det = u1 * v2 - u2 * v1;
  8862. if ( det === 0 ) {
  8863. if ( _imagedatas[ texture.id ] === undefined ) {
  8864. var canvas = document.createElement( 'canvas' )
  8865. canvas.width = texture.image.width;
  8866. canvas.height = texture.image.height;
  8867. var context = canvas.getContext( '2d' );
  8868. context.drawImage( texture.image, 0, 0 );
  8869. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8870. }
  8871. var data = _imagedatas[ texture.id ];
  8872. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8873. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8874. fillPath( _color );
  8875. return;
  8876. }
  8877. idet = 1 / det;
  8878. a = ( v2 * x1 - v1 * x2 ) * idet;
  8879. b = ( v2 * y1 - v1 * y2 ) * idet;
  8880. c = ( u1 * x2 - u2 * x1 ) * idet;
  8881. d = ( u1 * y2 - u2 * y1 ) * idet;
  8882. e = x0 - a * u0 - c * v0;
  8883. f = y0 - b * u0 - d * v0;
  8884. _context.save();
  8885. _context.transform( a, b, c, d, e, f );
  8886. _context.fill();
  8887. _context.restore();
  8888. }
  8889. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8890. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8891. var a, b, c, d, e, f, det, idet,
  8892. width = image.width - 1,
  8893. height = image.height - 1;
  8894. u0 *= width; v0 *= height;
  8895. u1 *= width; v1 *= height;
  8896. u2 *= width; v2 *= height;
  8897. x1 -= x0; y1 -= y0;
  8898. x2 -= x0; y2 -= y0;
  8899. u1 -= u0; v1 -= v0;
  8900. u2 -= u0; v2 -= v0;
  8901. det = u1 * v2 - u2 * v1;
  8902. idet = 1 / det;
  8903. a = ( v2 * x1 - v1 * x2 ) * idet;
  8904. b = ( v2 * y1 - v1 * y2 ) * idet;
  8905. c = ( u1 * x2 - u2 * x1 ) * idet;
  8906. d = ( u1 * y2 - u2 * y1 ) * idet;
  8907. e = x0 - a * u0 - c * v0;
  8908. f = y0 - b * u0 - d * v0;
  8909. _context.save();
  8910. _context.transform( a, b, c, d, e, f );
  8911. _context.clip();
  8912. _context.drawImage( image, 0, 0 );
  8913. _context.restore();
  8914. }
  8915. function getGradientTexture( color1, color2, color3, color4 ) {
  8916. // http://mrdoob.com/blog/post/710
  8917. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8918. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8919. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8920. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8921. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8922. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8923. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8924. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8925. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8926. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8927. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8928. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8929. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8930. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8931. return _gradientMap;
  8932. }
  8933. function smoothstep( value, min, max ) {
  8934. var x = ( value - min ) / ( max - min );
  8935. return x * x * ( 3 - 2 * x );
  8936. }
  8937. // Hide anti-alias gaps
  8938. function expand( v1, v2 ) {
  8939. var x = v2.x - v1.x, y = v2.y - v1.y,
  8940. det = x * x + y * y, idet;
  8941. if ( det === 0 ) return;
  8942. idet = 1 / Math.sqrt( det );
  8943. x *= idet; y *= idet;
  8944. v2.x += x; v2.y += y;
  8945. v1.x -= x; v1.y -= y;
  8946. }
  8947. };
  8948. // Context cached methods.
  8949. function setOpacity( value ) {
  8950. if ( _contextGlobalAlpha !== value ) {
  8951. _context.globalAlpha = value;
  8952. _contextGlobalAlpha = value;
  8953. }
  8954. }
  8955. function setBlending( value ) {
  8956. if ( _contextGlobalCompositeOperation !== value ) {
  8957. if ( value === THREE.NormalBlending ) {
  8958. _context.globalCompositeOperation = 'source-over';
  8959. } else if ( value === THREE.AdditiveBlending ) {
  8960. _context.globalCompositeOperation = 'lighter';
  8961. } else if ( value === THREE.SubtractiveBlending ) {
  8962. _context.globalCompositeOperation = 'darker';
  8963. }
  8964. _contextGlobalCompositeOperation = value;
  8965. }
  8966. }
  8967. function setLineWidth( value ) {
  8968. if ( _contextLineWidth !== value ) {
  8969. _context.lineWidth = value;
  8970. _contextLineWidth = value;
  8971. }
  8972. }
  8973. function setLineCap( value ) {
  8974. // "butt", "round", "square"
  8975. if ( _contextLineCap !== value ) {
  8976. _context.lineCap = value;
  8977. _contextLineCap = value;
  8978. }
  8979. }
  8980. function setLineJoin( value ) {
  8981. // "round", "bevel", "miter"
  8982. if ( _contextLineJoin !== value ) {
  8983. _context.lineJoin = value;
  8984. _contextLineJoin = value;
  8985. }
  8986. }
  8987. function setStrokeStyle( value ) {
  8988. if ( _contextStrokeStyle !== value ) {
  8989. _context.strokeStyle = value;
  8990. _contextStrokeStyle = value;
  8991. }
  8992. }
  8993. function setFillStyle( value ) {
  8994. if ( _contextFillStyle !== value ) {
  8995. _context.fillStyle = value;
  8996. _contextFillStyle = value;
  8997. }
  8998. }
  8999. };
  9000. /**
  9001. * @author alteredq / http://alteredqualia.com/
  9002. * @author mrdoob / http://mrdoob.com/
  9003. * @author mikael emtinger / http://gomo.se/
  9004. */
  9005. THREE.ShaderChunk = {
  9006. // FOG
  9007. fog_pars_fragment: [
  9008. "#ifdef USE_FOG",
  9009. "uniform vec3 fogColor;",
  9010. "#ifdef FOG_EXP2",
  9011. "uniform float fogDensity;",
  9012. "#else",
  9013. "uniform float fogNear;",
  9014. "uniform float fogFar;",
  9015. "#endif",
  9016. "#endif"
  9017. ].join("\n"),
  9018. fog_fragment: [
  9019. "#ifdef USE_FOG",
  9020. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9021. "#ifdef FOG_EXP2",
  9022. "const float LOG2 = 1.442695;",
  9023. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9024. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9025. "#else",
  9026. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9027. "#endif",
  9028. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9029. "#endif"
  9030. ].join("\n"),
  9031. // ENVIRONMENT MAP
  9032. envmap_pars_fragment: [
  9033. "#ifdef USE_ENVMAP",
  9034. "uniform float reflectivity;",
  9035. "uniform samplerCube envMap;",
  9036. "uniform float flipEnvMap;",
  9037. "uniform int combine;",
  9038. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9039. "uniform bool useRefract;",
  9040. "uniform float refractionRatio;",
  9041. "#else",
  9042. "varying vec3 vReflect;",
  9043. "#endif",
  9044. "#endif"
  9045. ].join("\n"),
  9046. envmap_fragment: [
  9047. "#ifdef USE_ENVMAP",
  9048. "vec3 reflectVec;",
  9049. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9050. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9051. "if ( useRefract ) {",
  9052. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9053. "} else { ",
  9054. "reflectVec = reflect( cameraToVertex, normal );",
  9055. "}",
  9056. "#else",
  9057. "reflectVec = vReflect;",
  9058. "#endif",
  9059. "#ifdef DOUBLE_SIDED",
  9060. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9061. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9062. "#else",
  9063. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9064. "#endif",
  9065. "#ifdef GAMMA_INPUT",
  9066. "cubeColor.xyz *= cubeColor.xyz;",
  9067. "#endif",
  9068. "if ( combine == 1 ) {",
  9069. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9070. "} else if ( combine == 2 ) {",
  9071. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9072. "} else {",
  9073. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9074. "}",
  9075. "#endif"
  9076. ].join("\n"),
  9077. envmap_pars_vertex: [
  9078. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9079. "varying vec3 vReflect;",
  9080. "uniform float refractionRatio;",
  9081. "uniform bool useRefract;",
  9082. "#endif"
  9083. ].join("\n"),
  9084. worldpos_vertex : [
  9085. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9086. "#ifdef USE_SKINNING",
  9087. "vec4 worldPosition = modelMatrix * skinned;",
  9088. "#endif",
  9089. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9090. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9091. "#endif",
  9092. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9093. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9094. "#endif",
  9095. "#endif"
  9096. ].join("\n"),
  9097. envmap_vertex : [
  9098. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9099. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9100. "worldNormal = normalize( worldNormal );",
  9101. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9102. "if ( useRefract ) {",
  9103. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9104. "} else {",
  9105. "vReflect = reflect( cameraToVertex, worldNormal );",
  9106. "}",
  9107. "#endif"
  9108. ].join("\n"),
  9109. // COLOR MAP (particles)
  9110. map_particle_pars_fragment: [
  9111. "#ifdef USE_MAP",
  9112. "uniform sampler2D map;",
  9113. "#endif"
  9114. ].join("\n"),
  9115. map_particle_fragment: [
  9116. "#ifdef USE_MAP",
  9117. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9118. "#endif"
  9119. ].join("\n"),
  9120. // COLOR MAP (triangles)
  9121. map_pars_vertex: [
  9122. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9123. "varying vec2 vUv;",
  9124. "uniform vec4 offsetRepeat;",
  9125. "#endif"
  9126. ].join("\n"),
  9127. map_pars_fragment: [
  9128. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9129. "varying vec2 vUv;",
  9130. "#endif",
  9131. "#ifdef USE_MAP",
  9132. "uniform sampler2D map;",
  9133. "#endif"
  9134. ].join("\n"),
  9135. map_vertex: [
  9136. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9137. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9138. "#endif"
  9139. ].join("\n"),
  9140. map_fragment: [
  9141. "#ifdef USE_MAP",
  9142. "vec4 texelColor = texture2D( map, vUv );",
  9143. "#ifdef GAMMA_INPUT",
  9144. "texelColor.xyz *= texelColor.xyz;",
  9145. "#endif",
  9146. "gl_FragColor = gl_FragColor * texelColor;",
  9147. "#endif"
  9148. ].join("\n"),
  9149. // LIGHT MAP
  9150. lightmap_pars_fragment: [
  9151. "#ifdef USE_LIGHTMAP",
  9152. "varying vec2 vUv2;",
  9153. "uniform sampler2D lightMap;",
  9154. "#endif"
  9155. ].join("\n"),
  9156. lightmap_pars_vertex: [
  9157. "#ifdef USE_LIGHTMAP",
  9158. "varying vec2 vUv2;",
  9159. "#endif"
  9160. ].join("\n"),
  9161. lightmap_fragment: [
  9162. "#ifdef USE_LIGHTMAP",
  9163. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9164. "#endif"
  9165. ].join("\n"),
  9166. lightmap_vertex: [
  9167. "#ifdef USE_LIGHTMAP",
  9168. "vUv2 = uv2;",
  9169. "#endif"
  9170. ].join("\n"),
  9171. // BUMP MAP
  9172. bumpmap_pars_fragment: [
  9173. "#ifdef USE_BUMPMAP",
  9174. "uniform sampler2D bumpMap;",
  9175. "uniform float bumpScale;",
  9176. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9177. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9178. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9179. "vec2 dHdxy_fwd() {",
  9180. "vec2 dSTdx = dFdx( vUv );",
  9181. "vec2 dSTdy = dFdy( vUv );",
  9182. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9183. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9184. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9185. "return vec2( dBx, dBy );",
  9186. "}",
  9187. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9188. "vec3 vSigmaX = dFdx( surf_pos );",
  9189. "vec3 vSigmaY = dFdy( surf_pos );",
  9190. "vec3 vN = surf_norm;", // normalized
  9191. "vec3 R1 = cross( vSigmaY, vN );",
  9192. "vec3 R2 = cross( vN, vSigmaX );",
  9193. "float fDet = dot( vSigmaX, R1 );",
  9194. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9195. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9196. "}",
  9197. "#endif"
  9198. ].join("\n"),
  9199. // NORMAL MAP
  9200. normalmap_pars_fragment: [
  9201. "#ifdef USE_NORMALMAP",
  9202. "uniform sampler2D normalMap;",
  9203. "uniform vec2 normalScale;",
  9204. // Per-Pixel Tangent Space Normal Mapping
  9205. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9206. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9207. "vec3 q0 = dFdx( eye_pos.xyz );",
  9208. "vec3 q1 = dFdy( eye_pos.xyz );",
  9209. "vec2 st0 = dFdx( vUv.st );",
  9210. "vec2 st1 = dFdy( vUv.st );",
  9211. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9212. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9213. "vec3 N = normalize( surf_norm );",
  9214. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9215. "mapN.xy = normalScale * mapN.xy;",
  9216. "mat3 tsn = mat3( S, T, N );",
  9217. "return normalize( tsn * mapN );",
  9218. "}",
  9219. "#endif"
  9220. ].join("\n"),
  9221. // SPECULAR MAP
  9222. specularmap_pars_fragment: [
  9223. "#ifdef USE_SPECULARMAP",
  9224. "uniform sampler2D specularMap;",
  9225. "#endif"
  9226. ].join("\n"),
  9227. specularmap_fragment: [
  9228. "float specularStrength;",
  9229. "#ifdef USE_SPECULARMAP",
  9230. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9231. "specularStrength = texelSpecular.r;",
  9232. "#else",
  9233. "specularStrength = 1.0;",
  9234. "#endif"
  9235. ].join("\n"),
  9236. // LIGHTS LAMBERT
  9237. lights_lambert_pars_vertex: [
  9238. "uniform vec3 ambient;",
  9239. "uniform vec3 diffuse;",
  9240. "uniform vec3 emissive;",
  9241. "uniform vec3 ambientLightColor;",
  9242. "#if MAX_DIR_LIGHTS > 0",
  9243. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9244. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9245. "#endif",
  9246. "#if MAX_HEMI_LIGHTS > 0",
  9247. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9248. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9249. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9250. "#endif",
  9251. "#if MAX_POINT_LIGHTS > 0",
  9252. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9253. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9254. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9255. "#endif",
  9256. "#if MAX_SPOT_LIGHTS > 0",
  9257. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9258. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9259. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9260. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9261. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9262. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9263. "#endif",
  9264. "#ifdef WRAP_AROUND",
  9265. "uniform vec3 wrapRGB;",
  9266. "#endif"
  9267. ].join("\n"),
  9268. lights_lambert_vertex: [
  9269. "vLightFront = vec3( 0.0 );",
  9270. "#ifdef DOUBLE_SIDED",
  9271. "vLightBack = vec3( 0.0 );",
  9272. "#endif",
  9273. "transformedNormal = normalize( transformedNormal );",
  9274. "#if MAX_DIR_LIGHTS > 0",
  9275. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9276. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9277. "vec3 dirVector = normalize( lDirection.xyz );",
  9278. "float dotProduct = dot( transformedNormal, dirVector );",
  9279. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9280. "#ifdef DOUBLE_SIDED",
  9281. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9282. "#ifdef WRAP_AROUND",
  9283. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9284. "#endif",
  9285. "#endif",
  9286. "#ifdef WRAP_AROUND",
  9287. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9288. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9289. "#ifdef DOUBLE_SIDED",
  9290. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9291. "#endif",
  9292. "#endif",
  9293. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9294. "#ifdef DOUBLE_SIDED",
  9295. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9296. "#endif",
  9297. "}",
  9298. "#endif",
  9299. "#if MAX_POINT_LIGHTS > 0",
  9300. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9301. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9302. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9303. "float lDistance = 1.0;",
  9304. "if ( pointLightDistance[ i ] > 0.0 )",
  9305. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9306. "lVector = normalize( lVector );",
  9307. "float dotProduct = dot( transformedNormal, lVector );",
  9308. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9309. "#ifdef DOUBLE_SIDED",
  9310. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9311. "#ifdef WRAP_AROUND",
  9312. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9313. "#endif",
  9314. "#endif",
  9315. "#ifdef WRAP_AROUND",
  9316. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9317. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9318. "#ifdef DOUBLE_SIDED",
  9319. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9320. "#endif",
  9321. "#endif",
  9322. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9323. "#ifdef DOUBLE_SIDED",
  9324. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9325. "#endif",
  9326. "}",
  9327. "#endif",
  9328. "#if MAX_SPOT_LIGHTS > 0",
  9329. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9330. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9331. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9332. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9333. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9334. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9335. "float lDistance = 1.0;",
  9336. "if ( spotLightDistance[ i ] > 0.0 )",
  9337. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9338. "lVector = normalize( lVector );",
  9339. "float dotProduct = dot( transformedNormal, lVector );",
  9340. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9341. "#ifdef DOUBLE_SIDED",
  9342. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9343. "#ifdef WRAP_AROUND",
  9344. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9345. "#endif",
  9346. "#endif",
  9347. "#ifdef WRAP_AROUND",
  9348. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9349. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9350. "#ifdef DOUBLE_SIDED",
  9351. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9352. "#endif",
  9353. "#endif",
  9354. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9355. "#ifdef DOUBLE_SIDED",
  9356. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9357. "#endif",
  9358. "}",
  9359. "}",
  9360. "#endif",
  9361. "#if MAX_HEMI_LIGHTS > 0",
  9362. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9363. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9364. "vec3 lVector = normalize( lDirection.xyz );",
  9365. "float dotProduct = dot( transformedNormal, lVector );",
  9366. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9367. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9368. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9369. "#ifdef DOUBLE_SIDED",
  9370. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9371. "#endif",
  9372. "}",
  9373. "#endif",
  9374. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9375. "#ifdef DOUBLE_SIDED",
  9376. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9377. "#endif"
  9378. ].join("\n"),
  9379. // LIGHTS PHONG
  9380. lights_phong_pars_vertex: [
  9381. "#ifndef PHONG_PER_PIXEL",
  9382. "#if MAX_POINT_LIGHTS > 0",
  9383. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9384. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9385. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9386. "#endif",
  9387. "#if MAX_SPOT_LIGHTS > 0",
  9388. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9389. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9390. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9391. "#endif",
  9392. "#endif",
  9393. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9394. "varying vec3 vWorldPosition;",
  9395. "#endif"
  9396. ].join("\n"),
  9397. lights_phong_vertex: [
  9398. "#ifndef PHONG_PER_PIXEL",
  9399. "#if MAX_POINT_LIGHTS > 0",
  9400. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9401. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9402. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9403. "float lDistance = 1.0;",
  9404. "if ( pointLightDistance[ i ] > 0.0 )",
  9405. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9406. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9407. "}",
  9408. "#endif",
  9409. "#if MAX_SPOT_LIGHTS > 0",
  9410. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9411. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9412. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9413. "float lDistance = 1.0;",
  9414. "if ( spotLightDistance[ i ] > 0.0 )",
  9415. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9416. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9417. "}",
  9418. "#endif",
  9419. "#endif",
  9420. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9421. "vWorldPosition = worldPosition.xyz;",
  9422. "#endif"
  9423. ].join("\n"),
  9424. lights_phong_pars_fragment: [
  9425. "uniform vec3 ambientLightColor;",
  9426. "#if MAX_DIR_LIGHTS > 0",
  9427. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9428. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9429. "#endif",
  9430. "#if MAX_HEMI_LIGHTS > 0",
  9431. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9432. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9433. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9434. "#endif",
  9435. "#if MAX_POINT_LIGHTS > 0",
  9436. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9437. "#ifdef PHONG_PER_PIXEL",
  9438. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9439. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9440. "#else",
  9441. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9442. "#endif",
  9443. "#endif",
  9444. "#if MAX_SPOT_LIGHTS > 0",
  9445. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9446. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9447. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9448. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9449. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9450. "#ifdef PHONG_PER_PIXEL",
  9451. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9452. "#else",
  9453. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9454. "#endif",
  9455. "#endif",
  9456. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9457. "varying vec3 vWorldPosition;",
  9458. "#endif",
  9459. "#ifdef WRAP_AROUND",
  9460. "uniform vec3 wrapRGB;",
  9461. "#endif",
  9462. "varying vec3 vViewPosition;",
  9463. "varying vec3 vNormal;"
  9464. ].join("\n"),
  9465. lights_phong_fragment: [
  9466. "vec3 normal = normalize( vNormal );",
  9467. "vec3 viewPosition = normalize( vViewPosition );",
  9468. "#ifdef DOUBLE_SIDED",
  9469. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9470. "#endif",
  9471. "#ifdef USE_NORMALMAP",
  9472. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9473. "#elif defined( USE_BUMPMAP )",
  9474. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9475. "#endif",
  9476. "#if MAX_POINT_LIGHTS > 0",
  9477. "vec3 pointDiffuse = vec3( 0.0 );",
  9478. "vec3 pointSpecular = vec3( 0.0 );",
  9479. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9480. "#ifdef PHONG_PER_PIXEL",
  9481. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9482. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9483. "float lDistance = 1.0;",
  9484. "if ( pointLightDistance[ i ] > 0.0 )",
  9485. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9486. "lVector = normalize( lVector );",
  9487. "#else",
  9488. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9489. "float lDistance = vPointLight[ i ].w;",
  9490. "#endif",
  9491. // diffuse
  9492. "float dotProduct = dot( normal, lVector );",
  9493. "#ifdef WRAP_AROUND",
  9494. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9495. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9496. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9497. "#else",
  9498. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9499. "#endif",
  9500. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9501. // specular
  9502. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9503. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9504. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9505. "#ifdef PHYSICALLY_BASED_SHADING",
  9506. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9507. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9508. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9509. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9510. "#else",
  9511. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9512. "#endif",
  9513. "}",
  9514. "#endif",
  9515. "#if MAX_SPOT_LIGHTS > 0",
  9516. "vec3 spotDiffuse = vec3( 0.0 );",
  9517. "vec3 spotSpecular = vec3( 0.0 );",
  9518. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9519. "#ifdef PHONG_PER_PIXEL",
  9520. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9521. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9522. "float lDistance = 1.0;",
  9523. "if ( spotLightDistance[ i ] > 0.0 )",
  9524. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9525. "lVector = normalize( lVector );",
  9526. "#else",
  9527. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9528. "float lDistance = vSpotLight[ i ].w;",
  9529. "#endif",
  9530. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9531. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9532. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9533. // diffuse
  9534. "float dotProduct = dot( normal, lVector );",
  9535. "#ifdef WRAP_AROUND",
  9536. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9537. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9538. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9539. "#else",
  9540. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9541. "#endif",
  9542. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9543. // specular
  9544. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9545. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9546. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9547. "#ifdef PHYSICALLY_BASED_SHADING",
  9548. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9549. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9550. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9551. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9552. "#else",
  9553. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9554. "#endif",
  9555. "}",
  9556. "}",
  9557. "#endif",
  9558. "#if MAX_DIR_LIGHTS > 0",
  9559. "vec3 dirDiffuse = vec3( 0.0 );",
  9560. "vec3 dirSpecular = vec3( 0.0 );" ,
  9561. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9562. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9563. "vec3 dirVector = normalize( lDirection.xyz );",
  9564. // diffuse
  9565. "float dotProduct = dot( normal, dirVector );",
  9566. "#ifdef WRAP_AROUND",
  9567. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9568. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9569. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9570. "#else",
  9571. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9572. "#endif",
  9573. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9574. // specular
  9575. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9576. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9577. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9578. "#ifdef PHYSICALLY_BASED_SHADING",
  9579. /*
  9580. // fresnel term from skin shader
  9581. "const float F0 = 0.128;",
  9582. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9583. "float exponential = pow( base, 5.0 );",
  9584. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9585. */
  9586. /*
  9587. // fresnel term from fresnel shader
  9588. "const float mFresnelBias = 0.08;",
  9589. "const float mFresnelScale = 0.3;",
  9590. "const float mFresnelPower = 5.0;",
  9591. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9592. */
  9593. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9594. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9595. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9596. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9597. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9598. "#else",
  9599. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9600. "#endif",
  9601. "}",
  9602. "#endif",
  9603. "#if MAX_HEMI_LIGHTS > 0",
  9604. "vec3 hemiDiffuse = vec3( 0.0 );",
  9605. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9606. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9607. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9608. "vec3 lVector = normalize( lDirection.xyz );",
  9609. // diffuse
  9610. "float dotProduct = dot( normal, lVector );",
  9611. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9612. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9613. "hemiDiffuse += diffuse * hemiColor;",
  9614. // specular (sky light)
  9615. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9616. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9617. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9618. // specular (ground light)
  9619. "vec3 lVectorGround = -lVector;",
  9620. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9621. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9622. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9623. "#ifdef PHYSICALLY_BASED_SHADING",
  9624. "float dotProductGround = dot( normal, lVectorGround );",
  9625. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9626. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9627. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9628. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9629. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9630. "#else",
  9631. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9632. "#endif",
  9633. "}",
  9634. "#endif",
  9635. "vec3 totalDiffuse = vec3( 0.0 );",
  9636. "vec3 totalSpecular = vec3( 0.0 );",
  9637. "#if MAX_DIR_LIGHTS > 0",
  9638. "totalDiffuse += dirDiffuse;",
  9639. "totalSpecular += dirSpecular;",
  9640. "#endif",
  9641. "#if MAX_HEMI_LIGHTS > 0",
  9642. "totalDiffuse += hemiDiffuse;",
  9643. "totalSpecular += hemiSpecular;",
  9644. "#endif",
  9645. "#if MAX_POINT_LIGHTS > 0",
  9646. "totalDiffuse += pointDiffuse;",
  9647. "totalSpecular += pointSpecular;",
  9648. "#endif",
  9649. "#if MAX_SPOT_LIGHTS > 0",
  9650. "totalDiffuse += spotDiffuse;",
  9651. "totalSpecular += spotSpecular;",
  9652. "#endif",
  9653. "#ifdef METAL",
  9654. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9655. "#else",
  9656. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9657. "#endif"
  9658. ].join("\n"),
  9659. // VERTEX COLORS
  9660. color_pars_fragment: [
  9661. "#ifdef USE_COLOR",
  9662. "varying vec3 vColor;",
  9663. "#endif"
  9664. ].join("\n"),
  9665. color_fragment: [
  9666. "#ifdef USE_COLOR",
  9667. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9668. "#endif"
  9669. ].join("\n"),
  9670. color_pars_vertex: [
  9671. "#ifdef USE_COLOR",
  9672. "varying vec3 vColor;",
  9673. "#endif"
  9674. ].join("\n"),
  9675. color_vertex: [
  9676. "#ifdef USE_COLOR",
  9677. "#ifdef GAMMA_INPUT",
  9678. "vColor = color * color;",
  9679. "#else",
  9680. "vColor = color;",
  9681. "#endif",
  9682. "#endif"
  9683. ].join("\n"),
  9684. // SKINNING
  9685. skinning_pars_vertex: [
  9686. "#ifdef USE_SKINNING",
  9687. "#ifdef BONE_TEXTURE",
  9688. "uniform sampler2D boneTexture;",
  9689. "mat4 getBoneMatrix( const in float i ) {",
  9690. "float j = i * 4.0;",
  9691. "float x = mod( j, N_BONE_PIXEL_X );",
  9692. "float y = floor( j / N_BONE_PIXEL_X );",
  9693. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9694. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9695. "y = dy * ( y + 0.5 );",
  9696. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9697. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9698. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9699. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9700. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9701. "return bone;",
  9702. "}",
  9703. "#else",
  9704. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9705. "mat4 getBoneMatrix( const in float i ) {",
  9706. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9707. "return bone;",
  9708. "}",
  9709. "#endif",
  9710. "#endif"
  9711. ].join("\n"),
  9712. skinbase_vertex: [
  9713. "#ifdef USE_SKINNING",
  9714. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9715. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9716. "#endif"
  9717. ].join("\n"),
  9718. skinning_vertex: [
  9719. "#ifdef USE_SKINNING",
  9720. "#ifdef USE_MORPHTARGETS",
  9721. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9722. "#else",
  9723. "vec4 skinVertex = vec4( position, 1.0 );",
  9724. "#endif",
  9725. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9726. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9727. "#endif"
  9728. ].join("\n"),
  9729. // MORPHING
  9730. morphtarget_pars_vertex: [
  9731. "#ifdef USE_MORPHTARGETS",
  9732. "#ifndef USE_MORPHNORMALS",
  9733. "uniform float morphTargetInfluences[ 8 ];",
  9734. "#else",
  9735. "uniform float morphTargetInfluences[ 4 ];",
  9736. "#endif",
  9737. "#endif"
  9738. ].join("\n"),
  9739. morphtarget_vertex: [
  9740. "#ifdef USE_MORPHTARGETS",
  9741. "vec3 morphed = vec3( 0.0 );",
  9742. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9743. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9744. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9745. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9746. "#ifndef USE_MORPHNORMALS",
  9747. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9748. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9749. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9750. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9751. "#endif",
  9752. "morphed += position;",
  9753. "#endif"
  9754. ].join("\n"),
  9755. default_vertex : [
  9756. "vec4 mvPosition;",
  9757. "#ifdef USE_SKINNING",
  9758. "mvPosition = modelViewMatrix * skinned;",
  9759. "#endif",
  9760. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9761. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9762. "#endif",
  9763. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9764. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9765. "#endif",
  9766. "gl_Position = projectionMatrix * mvPosition;"
  9767. ].join("\n"),
  9768. morphnormal_vertex: [
  9769. "#ifdef USE_MORPHNORMALS",
  9770. "vec3 morphedNormal = vec3( 0.0 );",
  9771. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9772. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9773. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9774. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9775. "morphedNormal += normal;",
  9776. "#endif"
  9777. ].join("\n"),
  9778. skinnormal_vertex: [
  9779. "#ifdef USE_SKINNING",
  9780. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9781. "skinMatrix += skinWeight.y * boneMatY;",
  9782. "#ifdef USE_MORPHNORMALS",
  9783. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9784. "#else",
  9785. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9786. "#endif",
  9787. "#endif"
  9788. ].join("\n"),
  9789. defaultnormal_vertex: [
  9790. "vec3 objectNormal;",
  9791. "#ifdef USE_SKINNING",
  9792. "objectNormal = skinnedNormal.xyz;",
  9793. "#endif",
  9794. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9795. "objectNormal = morphedNormal;",
  9796. "#endif",
  9797. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9798. "objectNormal = normal;",
  9799. "#endif",
  9800. "#ifdef FLIP_SIDED",
  9801. "objectNormal = -objectNormal;",
  9802. "#endif",
  9803. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9804. ].join("\n"),
  9805. // SHADOW MAP
  9806. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9807. // http://spidergl.org/example.php?id=6
  9808. // http://fabiensanglard.net/shadowmapping
  9809. shadowmap_pars_fragment: [
  9810. "#ifdef USE_SHADOWMAP",
  9811. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9812. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9813. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9814. "uniform float shadowBias[ MAX_SHADOWS ];",
  9815. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9816. "float unpackDepth( const in vec4 rgba_depth ) {",
  9817. "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 );",
  9818. "float depth = dot( rgba_depth, bit_shift );",
  9819. "return depth;",
  9820. "}",
  9821. "#endif"
  9822. ].join("\n"),
  9823. shadowmap_fragment: [
  9824. "#ifdef USE_SHADOWMAP",
  9825. "#ifdef SHADOWMAP_DEBUG",
  9826. "vec3 frustumColors[3];",
  9827. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9828. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9829. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9830. "#endif",
  9831. "#ifdef SHADOWMAP_CASCADE",
  9832. "int inFrustumCount = 0;",
  9833. "#endif",
  9834. "float fDepth;",
  9835. "vec3 shadowColor = vec3( 1.0 );",
  9836. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9837. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9838. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9839. // "if ( all( something, something ) )" using this instead
  9840. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9841. "bool inFrustum = all( inFrustumVec );",
  9842. // don't shadow pixels outside of light frustum
  9843. // use just first frustum (for cascades)
  9844. // don't shadow pixels behind far plane of light frustum
  9845. "#ifdef SHADOWMAP_CASCADE",
  9846. "inFrustumCount += int( inFrustum );",
  9847. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9848. "#else",
  9849. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9850. "#endif",
  9851. "bool frustumTest = all( frustumTestVec );",
  9852. "if ( frustumTest ) {",
  9853. "shadowCoord.z += shadowBias[ i ];",
  9854. "#if defined( SHADOWMAP_TYPE_PCF )",
  9855. // Percentage-close filtering
  9856. // (9 pixel kernel)
  9857. // http://fabiensanglard.net/shadowmappingPCF/
  9858. "float shadow = 0.0;",
  9859. /*
  9860. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9861. // must enroll loop manually
  9862. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9863. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9864. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9865. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9866. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9867. "float fDepth = unpackDepth( rgbaDepth );",
  9868. "if ( fDepth < shadowCoord.z )",
  9869. "shadow += 1.0;",
  9870. "}",
  9871. "shadow /= 9.0;",
  9872. */
  9873. "const float shadowDelta = 1.0 / 9.0;",
  9874. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9875. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9876. "float dx0 = -1.25 * xPixelOffset;",
  9877. "float dy0 = -1.25 * yPixelOffset;",
  9878. "float dx1 = 1.25 * xPixelOffset;",
  9879. "float dy1 = 1.25 * yPixelOffset;",
  9880. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9881. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9882. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9883. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9884. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9885. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9886. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9887. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9888. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9889. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9890. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9891. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9892. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9893. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9894. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9895. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9896. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9897. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9898. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9899. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9900. // Percentage-close filtering
  9901. // (9 pixel kernel)
  9902. // http://fabiensanglard.net/shadowmappingPCF/
  9903. "float shadow = 0.0;",
  9904. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9905. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9906. "float dx0 = -1.0 * xPixelOffset;",
  9907. "float dy0 = -1.0 * yPixelOffset;",
  9908. "float dx1 = 1.0 * xPixelOffset;",
  9909. "float dy1 = 1.0 * yPixelOffset;",
  9910. "mat3 shadowKernel;",
  9911. "mat3 depthKernel;",
  9912. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9913. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9914. "else shadowKernel[0][0] = 0.0;",
  9915. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9916. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9917. "else shadowKernel[0][1] = 0.0;",
  9918. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9919. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9920. "else shadowKernel[0][2] = 0.0;",
  9921. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9922. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9923. "else shadowKernel[1][0] = 0.0;",
  9924. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9925. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9926. "else shadowKernel[1][1] = 0.0;",
  9927. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9928. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9929. "else shadowKernel[1][2] = 0.0;",
  9930. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9931. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9932. "else shadowKernel[2][0] = 0.0;",
  9933. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9934. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9935. "else shadowKernel[2][1] = 0.0;",
  9936. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9937. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9938. "else shadowKernel[2][2] = 0.0;",
  9939. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9940. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9941. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9942. "vec4 shadowValues;",
  9943. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9944. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9945. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9946. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9947. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9948. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9949. "#else",
  9950. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9951. "float fDepth = unpackDepth( rgbaDepth );",
  9952. "if ( fDepth < shadowCoord.z )",
  9953. // spot with multiple shadows is darker
  9954. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9955. // spot with multiple shadows has the same color as single shadow spot
  9956. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9957. "#endif",
  9958. "}",
  9959. "#ifdef SHADOWMAP_DEBUG",
  9960. "#ifdef SHADOWMAP_CASCADE",
  9961. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9962. "#else",
  9963. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9964. "#endif",
  9965. "#endif",
  9966. "}",
  9967. "#ifdef GAMMA_OUTPUT",
  9968. "shadowColor *= shadowColor;",
  9969. "#endif",
  9970. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9971. "#endif"
  9972. ].join("\n"),
  9973. shadowmap_pars_vertex: [
  9974. "#ifdef USE_SHADOWMAP",
  9975. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9976. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9977. "#endif"
  9978. ].join("\n"),
  9979. shadowmap_vertex: [
  9980. "#ifdef USE_SHADOWMAP",
  9981. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9982. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9983. "}",
  9984. "#endif"
  9985. ].join("\n"),
  9986. // ALPHATEST
  9987. alphatest_fragment: [
  9988. "#ifdef ALPHATEST",
  9989. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9990. "#endif"
  9991. ].join("\n"),
  9992. // LINEAR SPACE
  9993. linear_to_gamma_fragment: [
  9994. "#ifdef GAMMA_OUTPUT",
  9995. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9996. "#endif"
  9997. ].join("\n")
  9998. };
  9999. THREE.UniformsUtils = {
  10000. merge: function ( uniforms ) {
  10001. var u, p, tmp, merged = {};
  10002. for ( u = 0; u < uniforms.length; u ++ ) {
  10003. tmp = this.clone( uniforms[ u ] );
  10004. for ( p in tmp ) {
  10005. merged[ p ] = tmp[ p ];
  10006. }
  10007. }
  10008. return merged;
  10009. },
  10010. clone: function ( uniforms_src ) {
  10011. var u, p, parameter, parameter_src, uniforms_dst = {};
  10012. for ( u in uniforms_src ) {
  10013. uniforms_dst[ u ] = {};
  10014. for ( p in uniforms_src[ u ] ) {
  10015. parameter_src = uniforms_src[ u ][ p ];
  10016. if ( parameter_src instanceof THREE.Color ||
  10017. parameter_src instanceof THREE.Vector2 ||
  10018. parameter_src instanceof THREE.Vector3 ||
  10019. parameter_src instanceof THREE.Vector4 ||
  10020. parameter_src instanceof THREE.Matrix4 ||
  10021. parameter_src instanceof THREE.Texture ) {
  10022. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10023. } else if ( parameter_src instanceof Array ) {
  10024. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10025. } else {
  10026. uniforms_dst[ u ][ p ] = parameter_src;
  10027. }
  10028. }
  10029. }
  10030. return uniforms_dst;
  10031. }
  10032. };
  10033. THREE.UniformsLib = {
  10034. common: {
  10035. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10036. "opacity" : { type: "f", value: 1.0 },
  10037. "map" : { type: "t", value: null },
  10038. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10039. "lightMap" : { type: "t", value: null },
  10040. "specularMap" : { type: "t", value: null },
  10041. "envMap" : { type: "t", value: null },
  10042. "flipEnvMap" : { type: "f", value: -1 },
  10043. "useRefract" : { type: "i", value: 0 },
  10044. "reflectivity" : { type: "f", value: 1.0 },
  10045. "refractionRatio" : { type: "f", value: 0.98 },
  10046. "combine" : { type: "i", value: 0 },
  10047. "morphTargetInfluences" : { type: "f", value: 0 }
  10048. },
  10049. bump: {
  10050. "bumpMap" : { type: "t", value: null },
  10051. "bumpScale" : { type: "f", value: 1 }
  10052. },
  10053. normalmap: {
  10054. "normalMap" : { type: "t", value: null },
  10055. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10056. },
  10057. fog : {
  10058. "fogDensity" : { type: "f", value: 0.00025 },
  10059. "fogNear" : { type: "f", value: 1 },
  10060. "fogFar" : { type: "f", value: 2000 },
  10061. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10062. },
  10063. lights: {
  10064. "ambientLightColor" : { type: "fv", value: [] },
  10065. "directionalLightDirection" : { type: "fv", value: [] },
  10066. "directionalLightColor" : { type: "fv", value: [] },
  10067. "hemisphereLightDirection" : { type: "fv", value: [] },
  10068. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10069. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10070. "pointLightColor" : { type: "fv", value: [] },
  10071. "pointLightPosition" : { type: "fv", value: [] },
  10072. "pointLightDistance" : { type: "fv1", value: [] },
  10073. "spotLightColor" : { type: "fv", value: [] },
  10074. "spotLightPosition" : { type: "fv", value: [] },
  10075. "spotLightDirection" : { type: "fv", value: [] },
  10076. "spotLightDistance" : { type: "fv1", value: [] },
  10077. "spotLightAngleCos" : { type: "fv1", value: [] },
  10078. "spotLightExponent" : { type: "fv1", value: [] }
  10079. },
  10080. particle: {
  10081. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10082. "opacity" : { type: "f", value: 1.0 },
  10083. "size" : { type: "f", value: 1.0 },
  10084. "scale" : { type: "f", value: 1.0 },
  10085. "map" : { type: "t", value: null },
  10086. "fogDensity" : { type: "f", value: 0.00025 },
  10087. "fogNear" : { type: "f", value: 1 },
  10088. "fogFar" : { type: "f", value: 2000 },
  10089. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10090. },
  10091. shadowmap: {
  10092. "shadowMap": { type: "tv", value: [] },
  10093. "shadowMapSize": { type: "v2v", value: [] },
  10094. "shadowBias" : { type: "fv1", value: [] },
  10095. "shadowDarkness": { type: "fv1", value: [] },
  10096. "shadowMatrix" : { type: "m4v", value: [] }
  10097. }
  10098. };
  10099. THREE.ShaderLib = {
  10100. 'depth': {
  10101. uniforms: {
  10102. "mNear": { type: "f", value: 1.0 },
  10103. "mFar" : { type: "f", value: 2000.0 },
  10104. "opacity" : { type: "f", value: 1.0 }
  10105. },
  10106. vertexShader: [
  10107. "void main() {",
  10108. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10109. "}"
  10110. ].join("\n"),
  10111. fragmentShader: [
  10112. "uniform float mNear;",
  10113. "uniform float mFar;",
  10114. "uniform float opacity;",
  10115. "void main() {",
  10116. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10117. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10118. "gl_FragColor = vec4( vec3( color ), opacity );",
  10119. "}"
  10120. ].join("\n")
  10121. },
  10122. 'normal': {
  10123. uniforms: {
  10124. "opacity" : { type: "f", value: 1.0 }
  10125. },
  10126. vertexShader: [
  10127. "varying vec3 vNormal;",
  10128. "void main() {",
  10129. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10130. "vNormal = normalize( normalMatrix * normal );",
  10131. "gl_Position = projectionMatrix * mvPosition;",
  10132. "}"
  10133. ].join("\n"),
  10134. fragmentShader: [
  10135. "uniform float opacity;",
  10136. "varying vec3 vNormal;",
  10137. "void main() {",
  10138. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10139. "}"
  10140. ].join("\n")
  10141. },
  10142. 'basic': {
  10143. uniforms: THREE.UniformsUtils.merge( [
  10144. THREE.UniformsLib[ "common" ],
  10145. THREE.UniformsLib[ "fog" ],
  10146. THREE.UniformsLib[ "shadowmap" ]
  10147. ] ),
  10148. vertexShader: [
  10149. THREE.ShaderChunk[ "map_pars_vertex" ],
  10150. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10151. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10152. THREE.ShaderChunk[ "color_pars_vertex" ],
  10153. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10154. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10155. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10156. "void main() {",
  10157. THREE.ShaderChunk[ "map_vertex" ],
  10158. THREE.ShaderChunk[ "lightmap_vertex" ],
  10159. THREE.ShaderChunk[ "color_vertex" ],
  10160. THREE.ShaderChunk[ "skinbase_vertex" ],
  10161. "#ifdef USE_ENVMAP",
  10162. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10163. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10164. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10165. "#endif",
  10166. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10167. THREE.ShaderChunk[ "skinning_vertex" ],
  10168. THREE.ShaderChunk[ "default_vertex" ],
  10169. THREE.ShaderChunk[ "worldpos_vertex" ],
  10170. THREE.ShaderChunk[ "envmap_vertex" ],
  10171. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10172. "}"
  10173. ].join("\n"),
  10174. fragmentShader: [
  10175. "uniform vec3 diffuse;",
  10176. "uniform float opacity;",
  10177. THREE.ShaderChunk[ "color_pars_fragment" ],
  10178. THREE.ShaderChunk[ "map_pars_fragment" ],
  10179. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10180. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10181. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10182. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10183. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10184. "void main() {",
  10185. "gl_FragColor = vec4( diffuse, opacity );",
  10186. THREE.ShaderChunk[ "map_fragment" ],
  10187. THREE.ShaderChunk[ "alphatest_fragment" ],
  10188. THREE.ShaderChunk[ "specularmap_fragment" ],
  10189. THREE.ShaderChunk[ "lightmap_fragment" ],
  10190. THREE.ShaderChunk[ "color_fragment" ],
  10191. THREE.ShaderChunk[ "envmap_fragment" ],
  10192. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10193. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10194. THREE.ShaderChunk[ "fog_fragment" ],
  10195. "}"
  10196. ].join("\n")
  10197. },
  10198. 'lambert': {
  10199. uniforms: THREE.UniformsUtils.merge( [
  10200. THREE.UniformsLib[ "common" ],
  10201. THREE.UniformsLib[ "fog" ],
  10202. THREE.UniformsLib[ "lights" ],
  10203. THREE.UniformsLib[ "shadowmap" ],
  10204. {
  10205. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10206. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10207. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10208. }
  10209. ] ),
  10210. vertexShader: [
  10211. "#define LAMBERT",
  10212. "varying vec3 vLightFront;",
  10213. "#ifdef DOUBLE_SIDED",
  10214. "varying vec3 vLightBack;",
  10215. "#endif",
  10216. THREE.ShaderChunk[ "map_pars_vertex" ],
  10217. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10218. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10219. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10220. THREE.ShaderChunk[ "color_pars_vertex" ],
  10221. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10222. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10223. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10224. "void main() {",
  10225. THREE.ShaderChunk[ "map_vertex" ],
  10226. THREE.ShaderChunk[ "lightmap_vertex" ],
  10227. THREE.ShaderChunk[ "color_vertex" ],
  10228. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10229. THREE.ShaderChunk[ "skinbase_vertex" ],
  10230. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10231. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10232. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10233. THREE.ShaderChunk[ "skinning_vertex" ],
  10234. THREE.ShaderChunk[ "default_vertex" ],
  10235. THREE.ShaderChunk[ "worldpos_vertex" ],
  10236. THREE.ShaderChunk[ "envmap_vertex" ],
  10237. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10238. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10239. "}"
  10240. ].join("\n"),
  10241. fragmentShader: [
  10242. "uniform float opacity;",
  10243. "varying vec3 vLightFront;",
  10244. "#ifdef DOUBLE_SIDED",
  10245. "varying vec3 vLightBack;",
  10246. "#endif",
  10247. THREE.ShaderChunk[ "color_pars_fragment" ],
  10248. THREE.ShaderChunk[ "map_pars_fragment" ],
  10249. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10250. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10251. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10252. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10253. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10254. "void main() {",
  10255. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10256. THREE.ShaderChunk[ "map_fragment" ],
  10257. THREE.ShaderChunk[ "alphatest_fragment" ],
  10258. THREE.ShaderChunk[ "specularmap_fragment" ],
  10259. "#ifdef DOUBLE_SIDED",
  10260. //"float isFront = float( gl_FrontFacing );",
  10261. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10262. "if ( gl_FrontFacing )",
  10263. "gl_FragColor.xyz *= vLightFront;",
  10264. "else",
  10265. "gl_FragColor.xyz *= vLightBack;",
  10266. "#else",
  10267. "gl_FragColor.xyz *= vLightFront;",
  10268. "#endif",
  10269. THREE.ShaderChunk[ "lightmap_fragment" ],
  10270. THREE.ShaderChunk[ "color_fragment" ],
  10271. THREE.ShaderChunk[ "envmap_fragment" ],
  10272. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10273. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10274. THREE.ShaderChunk[ "fog_fragment" ],
  10275. "}"
  10276. ].join("\n")
  10277. },
  10278. 'phong': {
  10279. uniforms: THREE.UniformsUtils.merge( [
  10280. THREE.UniformsLib[ "common" ],
  10281. THREE.UniformsLib[ "bump" ],
  10282. THREE.UniformsLib[ "normalmap" ],
  10283. THREE.UniformsLib[ "fog" ],
  10284. THREE.UniformsLib[ "lights" ],
  10285. THREE.UniformsLib[ "shadowmap" ],
  10286. {
  10287. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10288. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10289. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10290. "shininess": { type: "f", value: 30 },
  10291. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10292. }
  10293. ] ),
  10294. vertexShader: [
  10295. "#define PHONG",
  10296. "varying vec3 vViewPosition;",
  10297. "varying vec3 vNormal;",
  10298. THREE.ShaderChunk[ "map_pars_vertex" ],
  10299. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10300. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10301. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10302. THREE.ShaderChunk[ "color_pars_vertex" ],
  10303. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10304. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10305. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10306. "void main() {",
  10307. THREE.ShaderChunk[ "map_vertex" ],
  10308. THREE.ShaderChunk[ "lightmap_vertex" ],
  10309. THREE.ShaderChunk[ "color_vertex" ],
  10310. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10311. THREE.ShaderChunk[ "skinbase_vertex" ],
  10312. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10313. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10314. "vNormal = normalize( transformedNormal );",
  10315. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10316. THREE.ShaderChunk[ "skinning_vertex" ],
  10317. THREE.ShaderChunk[ "default_vertex" ],
  10318. "vViewPosition = -mvPosition.xyz;",
  10319. THREE.ShaderChunk[ "worldpos_vertex" ],
  10320. THREE.ShaderChunk[ "envmap_vertex" ],
  10321. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10322. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10323. "}"
  10324. ].join("\n"),
  10325. fragmentShader: [
  10326. "uniform vec3 diffuse;",
  10327. "uniform float opacity;",
  10328. "uniform vec3 ambient;",
  10329. "uniform vec3 emissive;",
  10330. "uniform vec3 specular;",
  10331. "uniform float shininess;",
  10332. THREE.ShaderChunk[ "color_pars_fragment" ],
  10333. THREE.ShaderChunk[ "map_pars_fragment" ],
  10334. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10335. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10336. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10337. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10338. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10339. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10340. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10341. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10342. "void main() {",
  10343. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10344. THREE.ShaderChunk[ "map_fragment" ],
  10345. THREE.ShaderChunk[ "alphatest_fragment" ],
  10346. THREE.ShaderChunk[ "specularmap_fragment" ],
  10347. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10348. THREE.ShaderChunk[ "lightmap_fragment" ],
  10349. THREE.ShaderChunk[ "color_fragment" ],
  10350. THREE.ShaderChunk[ "envmap_fragment" ],
  10351. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10352. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10353. THREE.ShaderChunk[ "fog_fragment" ],
  10354. "}"
  10355. ].join("\n")
  10356. },
  10357. 'particle_basic': {
  10358. uniforms: THREE.UniformsUtils.merge( [
  10359. THREE.UniformsLib[ "particle" ],
  10360. THREE.UniformsLib[ "shadowmap" ]
  10361. ] ),
  10362. vertexShader: [
  10363. "uniform float size;",
  10364. "uniform float scale;",
  10365. THREE.ShaderChunk[ "color_pars_vertex" ],
  10366. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10367. "void main() {",
  10368. THREE.ShaderChunk[ "color_vertex" ],
  10369. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10370. "#ifdef USE_SIZEATTENUATION",
  10371. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10372. "#else",
  10373. "gl_PointSize = size;",
  10374. "#endif",
  10375. "gl_Position = projectionMatrix * mvPosition;",
  10376. THREE.ShaderChunk[ "worldpos_vertex" ],
  10377. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10378. "}"
  10379. ].join("\n"),
  10380. fragmentShader: [
  10381. "uniform vec3 psColor;",
  10382. "uniform float opacity;",
  10383. THREE.ShaderChunk[ "color_pars_fragment" ],
  10384. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10385. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10386. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10387. "void main() {",
  10388. "gl_FragColor = vec4( psColor, opacity );",
  10389. THREE.ShaderChunk[ "map_particle_fragment" ],
  10390. THREE.ShaderChunk[ "alphatest_fragment" ],
  10391. THREE.ShaderChunk[ "color_fragment" ],
  10392. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10393. THREE.ShaderChunk[ "fog_fragment" ],
  10394. "}"
  10395. ].join("\n")
  10396. },
  10397. 'dashed': {
  10398. uniforms: THREE.UniformsUtils.merge( [
  10399. THREE.UniformsLib[ "common" ],
  10400. THREE.UniformsLib[ "fog" ],
  10401. {
  10402. "scale": { type: "f", value: 1 },
  10403. "dashSize": { type: "f", value: 1 },
  10404. "totalSize": { type: "f", value: 2 }
  10405. }
  10406. ] ),
  10407. vertexShader: [
  10408. "uniform float scale;",
  10409. "attribute float lineDistance;",
  10410. "varying float vLineDistance;",
  10411. THREE.ShaderChunk[ "color_pars_vertex" ],
  10412. "void main() {",
  10413. THREE.ShaderChunk[ "color_vertex" ],
  10414. "vLineDistance = scale * lineDistance;",
  10415. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10416. "gl_Position = projectionMatrix * mvPosition;",
  10417. "}"
  10418. ].join("\n"),
  10419. fragmentShader: [
  10420. "uniform vec3 diffuse;",
  10421. "uniform float opacity;",
  10422. "uniform float dashSize;",
  10423. "uniform float totalSize;",
  10424. "varying float vLineDistance;",
  10425. THREE.ShaderChunk[ "color_pars_fragment" ],
  10426. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10427. "void main() {",
  10428. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10429. "discard;",
  10430. "}",
  10431. "gl_FragColor = vec4( diffuse, opacity );",
  10432. THREE.ShaderChunk[ "color_fragment" ],
  10433. THREE.ShaderChunk[ "fog_fragment" ],
  10434. "}"
  10435. ].join("\n")
  10436. },
  10437. // Depth encoding into RGBA texture
  10438. // based on SpiderGL shadow map example
  10439. // http://spidergl.org/example.php?id=6
  10440. // originally from
  10441. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10442. // see also here:
  10443. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10444. 'depthRGBA': {
  10445. uniforms: {},
  10446. vertexShader: [
  10447. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10448. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10449. "void main() {",
  10450. THREE.ShaderChunk[ "skinbase_vertex" ],
  10451. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10452. THREE.ShaderChunk[ "skinning_vertex" ],
  10453. THREE.ShaderChunk[ "default_vertex" ],
  10454. "}"
  10455. ].join("\n"),
  10456. fragmentShader: [
  10457. "vec4 pack_depth( const in float depth ) {",
  10458. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10459. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10460. "vec4 res = fract( depth * bit_shift );",
  10461. "res -= res.xxyz * bit_mask;",
  10462. "return res;",
  10463. "}",
  10464. "void main() {",
  10465. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10466. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10467. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10468. //"gl_FragData[ 0 ] = pack_depth( z );",
  10469. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10470. "}"
  10471. ].join("\n")
  10472. }
  10473. };
  10474. /**
  10475. * @author supereggbert / http://www.paulbrunt.co.uk/
  10476. * @author mrdoob / http://mrdoob.com/
  10477. * @author alteredq / http://alteredqualia.com/
  10478. * @author szimek / https://github.com/szimek/
  10479. */
  10480. THREE.WebGLRenderer = function ( parameters ) {
  10481. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10482. parameters = parameters || {};
  10483. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10484. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10485. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10486. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10487. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10488. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10489. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10490. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  10491. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  10492. // public properties
  10493. this.domElement = _canvas;
  10494. this.context = null;
  10495. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  10496. ? parameters.devicePixelRatio
  10497. : window.devicePixelRatio !== undefined
  10498. ? window.devicePixelRatio
  10499. : 1;
  10500. // clearing
  10501. this.autoClear = true;
  10502. this.autoClearColor = true;
  10503. this.autoClearDepth = true;
  10504. this.autoClearStencil = true;
  10505. // scene graph
  10506. this.sortObjects = true;
  10507. this.autoUpdateObjects = true;
  10508. this.autoUpdateScene = true;
  10509. // physically based shading
  10510. this.gammaInput = false;
  10511. this.gammaOutput = false;
  10512. this.physicallyBasedShading = false;
  10513. // shadow map
  10514. this.shadowMapEnabled = false;
  10515. this.shadowMapAutoUpdate = true;
  10516. this.shadowMapType = THREE.PCFShadowMap;
  10517. this.shadowMapCullFace = THREE.CullFaceFront;
  10518. this.shadowMapDebug = false;
  10519. this.shadowMapCascade = false;
  10520. // morphs
  10521. this.maxMorphTargets = 8;
  10522. this.maxMorphNormals = 4;
  10523. // flags
  10524. this.autoScaleCubemaps = true;
  10525. // custom render plugins
  10526. this.renderPluginsPre = [];
  10527. this.renderPluginsPost = [];
  10528. // info
  10529. this.info = {
  10530. memory: {
  10531. programs: 0,
  10532. geometries: 0,
  10533. textures: 0
  10534. },
  10535. render: {
  10536. calls: 0,
  10537. vertices: 0,
  10538. faces: 0,
  10539. points: 0
  10540. }
  10541. };
  10542. // internal properties
  10543. var _this = this,
  10544. _programs = [],
  10545. _programs_counter = 0,
  10546. // internal state cache
  10547. _currentProgram = null,
  10548. _currentFramebuffer = null,
  10549. _currentMaterialId = -1,
  10550. _currentGeometryGroupHash = null,
  10551. _currentCamera = null,
  10552. _geometryGroupCounter = 0,
  10553. _usedTextureUnits = 0,
  10554. // GL state cache
  10555. _oldDoubleSided = -1,
  10556. _oldFlipSided = -1,
  10557. _oldBlending = -1,
  10558. _oldBlendEquation = -1,
  10559. _oldBlendSrc = -1,
  10560. _oldBlendDst = -1,
  10561. _oldDepthTest = -1,
  10562. _oldDepthWrite = -1,
  10563. _oldPolygonOffset = null,
  10564. _oldPolygonOffsetFactor = null,
  10565. _oldPolygonOffsetUnits = null,
  10566. _oldLineWidth = null,
  10567. _viewportX = 0,
  10568. _viewportY = 0,
  10569. _viewportWidth = 0,
  10570. _viewportHeight = 0,
  10571. _currentWidth = 0,
  10572. _currentHeight = 0,
  10573. _enabledAttributes = {},
  10574. // frustum
  10575. _frustum = new THREE.Frustum(),
  10576. // camera matrices cache
  10577. _projScreenMatrix = new THREE.Matrix4(),
  10578. _projScreenMatrixPS = new THREE.Matrix4(),
  10579. _vector3 = new THREE.Vector3(),
  10580. // light arrays cache
  10581. _direction = new THREE.Vector3(),
  10582. _lightsNeedUpdate = true,
  10583. _lights = {
  10584. ambient: [ 0, 0, 0 ],
  10585. directional: { length: 0, colors: new Array(), positions: new Array() },
  10586. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  10587. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  10588. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  10589. };
  10590. // initialize
  10591. var _gl;
  10592. var _glExtensionTextureFloat;
  10593. var _glExtensionStandardDerivatives;
  10594. var _glExtensionTextureFilterAnisotropic;
  10595. var _glExtensionCompressedTextureS3TC;
  10596. initGL();
  10597. setDefaultGLState();
  10598. this.context = _gl;
  10599. // GPU capabilities
  10600. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10601. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10602. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10603. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10604. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10605. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  10606. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  10607. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  10608. //
  10609. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10610. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10611. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  10612. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10613. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10614. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  10615. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  10616. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  10617. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  10618. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  10619. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  10620. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  10621. // clamp precision to maximum available
  10622. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10623. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10624. if ( _precision === "highp" && ! highpAvailable ) {
  10625. if ( mediumpAvailable ) {
  10626. _precision = "mediump";
  10627. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  10628. } else {
  10629. _precision = "lowp";
  10630. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  10631. }
  10632. }
  10633. if ( _precision === "mediump" && ! mediumpAvailable ) {
  10634. _precision = "lowp";
  10635. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  10636. }
  10637. // API
  10638. this.getContext = function () {
  10639. return _gl;
  10640. };
  10641. this.supportsVertexTextures = function () {
  10642. return _supportsVertexTextures;
  10643. };
  10644. this.getMaxAnisotropy = function () {
  10645. return _maxAnisotropy;
  10646. };
  10647. this.getPrecision = function () {
  10648. return _precision;
  10649. };
  10650. this.setSize = function ( width, height ) {
  10651. _canvas.width = width * this.devicePixelRatio;
  10652. _canvas.height = height * this.devicePixelRatio;
  10653. _canvas.style.width = width + 'px';
  10654. _canvas.style.height = height + 'px';
  10655. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  10656. };
  10657. this.setViewport = function ( x, y, width, height ) {
  10658. _viewportX = x !== undefined ? x : 0;
  10659. _viewportY = y !== undefined ? y : 0;
  10660. _viewportWidth = width !== undefined ? width : _canvas.width;
  10661. _viewportHeight = height !== undefined ? height : _canvas.height;
  10662. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10663. };
  10664. this.setScissor = function ( x, y, width, height ) {
  10665. _gl.scissor( x, y, width, height );
  10666. };
  10667. this.enableScissorTest = function ( enable ) {
  10668. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10669. };
  10670. // Clearing
  10671. this.setClearColorHex = function ( hex, alpha ) {
  10672. _clearColor.setHex( hex );
  10673. _clearAlpha = alpha;
  10674. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10675. };
  10676. this.setClearColor = function ( color, alpha ) {
  10677. _clearColor.copy( color );
  10678. _clearAlpha = alpha;
  10679. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10680. };
  10681. this.getClearColor = function () {
  10682. return _clearColor;
  10683. };
  10684. this.getClearAlpha = function () {
  10685. return _clearAlpha;
  10686. };
  10687. this.clear = function ( color, depth, stencil ) {
  10688. var bits = 0;
  10689. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10690. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10691. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10692. _gl.clear( bits );
  10693. };
  10694. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10695. this.setRenderTarget( renderTarget );
  10696. this.clear( color, depth, stencil );
  10697. };
  10698. // Plugins
  10699. this.addPostPlugin = function ( plugin ) {
  10700. plugin.init( this );
  10701. this.renderPluginsPost.push( plugin );
  10702. };
  10703. this.addPrePlugin = function ( plugin ) {
  10704. plugin.init( this );
  10705. this.renderPluginsPre.push( plugin );
  10706. };
  10707. // Rendering
  10708. this.updateShadowMap = function ( scene, camera ) {
  10709. _currentProgram = null;
  10710. _oldBlending = -1;
  10711. _oldDepthTest = -1;
  10712. _oldDepthWrite = -1;
  10713. _currentGeometryGroupHash = -1;
  10714. _currentMaterialId = -1;
  10715. _lightsNeedUpdate = true;
  10716. _oldDoubleSided = -1;
  10717. _oldFlipSided = -1;
  10718. this.shadowMapPlugin.update( scene, camera );
  10719. };
  10720. // Internal functions
  10721. // Buffer allocation
  10722. function createParticleBuffers ( geometry ) {
  10723. geometry.__webglVertexBuffer = _gl.createBuffer();
  10724. geometry.__webglColorBuffer = _gl.createBuffer();
  10725. _this.info.memory.geometries ++;
  10726. };
  10727. function createLineBuffers ( geometry ) {
  10728. geometry.__webglVertexBuffer = _gl.createBuffer();
  10729. geometry.__webglColorBuffer = _gl.createBuffer();
  10730. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10731. _this.info.memory.geometries ++;
  10732. };
  10733. function createRibbonBuffers ( geometry ) {
  10734. geometry.__webglVertexBuffer = _gl.createBuffer();
  10735. geometry.__webglColorBuffer = _gl.createBuffer();
  10736. geometry.__webglNormalBuffer = _gl.createBuffer();
  10737. _this.info.memory.geometries ++;
  10738. };
  10739. function createMeshBuffers ( geometryGroup ) {
  10740. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10741. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10742. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10743. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10744. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10745. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10746. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10747. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10748. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10749. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10750. var m, ml;
  10751. if ( geometryGroup.numMorphTargets ) {
  10752. geometryGroup.__webglMorphTargetsBuffers = [];
  10753. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10754. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10755. }
  10756. }
  10757. if ( geometryGroup.numMorphNormals ) {
  10758. geometryGroup.__webglMorphNormalsBuffers = [];
  10759. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10760. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10761. }
  10762. }
  10763. _this.info.memory.geometries ++;
  10764. };
  10765. // Events
  10766. var onGeometryDispose = function ( event ) {
  10767. var geometry = event.target;
  10768. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10769. deallocateGeometry( geometry );
  10770. _this.info.memory.geometries --;
  10771. };
  10772. var onTextureDispose = function ( event ) {
  10773. var texture = event.target;
  10774. texture.removeEventListener( 'dispose', onTextureDispose );
  10775. deallocateTexture( texture );
  10776. _this.info.memory.textures --;
  10777. };
  10778. var onRenderTargetDispose = function ( event ) {
  10779. var renderTarget = event.target;
  10780. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10781. deallocateRenderTarget( renderTarget );
  10782. _this.info.memory.textures --;
  10783. };
  10784. var onMaterialDispose = function ( event ) {
  10785. var material = event.target;
  10786. material.removeEventListener( 'dispose', onMaterialDispose );
  10787. deallocateMaterial( material );
  10788. };
  10789. // Buffer deallocation
  10790. var deallocateGeometry = function ( geometry ) {
  10791. geometry.__webglInit = undefined;
  10792. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10793. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10794. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  10795. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  10796. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  10797. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  10798. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  10799. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  10800. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  10801. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  10802. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10803. // geometry groups
  10804. if ( geometry.geometryGroups !== undefined ) {
  10805. for ( var g in geometry.geometryGroups ) {
  10806. var geometryGroup = geometry.geometryGroups[ g ];
  10807. if ( geometryGroup.numMorphTargets !== undefined ) {
  10808. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10809. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10810. }
  10811. }
  10812. if ( geometryGroup.numMorphNormals !== undefined ) {
  10813. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10814. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10815. }
  10816. }
  10817. deleteCustomAttributesBuffers( geometryGroup );
  10818. }
  10819. }
  10820. deleteCustomAttributesBuffers( geometry );
  10821. };
  10822. var deallocateTexture = function ( texture ) {
  10823. if ( texture.image && texture.image.__webglTextureCube ) {
  10824. // cube texture
  10825. _gl.deleteTexture( texture.image.__webglTextureCube );
  10826. } else {
  10827. // 2D texture
  10828. if ( ! texture.__webglInit ) return;
  10829. texture.__webglInit = false;
  10830. _gl.deleteTexture( texture.__webglTexture );
  10831. }
  10832. };
  10833. var deallocateRenderTarget = function ( renderTarget ) {
  10834. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  10835. _gl.deleteTexture( renderTarget.__webglTexture );
  10836. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  10837. for ( var i = 0; i < 6; i ++ ) {
  10838. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  10839. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  10840. }
  10841. } else {
  10842. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  10843. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  10844. }
  10845. };
  10846. var deallocateMaterial = function ( material ) {
  10847. var program = material.program;
  10848. if ( program === undefined ) return;
  10849. material.program = undefined;
  10850. // only deallocate GL program if this was the last use of shared program
  10851. // assumed there is only single copy of any program in the _programs list
  10852. // (that's how it's constructed)
  10853. var i, il, programInfo;
  10854. var deleteProgram = false;
  10855. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10856. programInfo = _programs[ i ];
  10857. if ( programInfo.program === program ) {
  10858. programInfo.usedTimes --;
  10859. if ( programInfo.usedTimes === 0 ) {
  10860. deleteProgram = true;
  10861. }
  10862. break;
  10863. }
  10864. }
  10865. if ( deleteProgram === true ) {
  10866. // avoid using array.splice, this is costlier than creating new array from scratch
  10867. var newPrograms = [];
  10868. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10869. programInfo = _programs[ i ];
  10870. if ( programInfo.program !== program ) {
  10871. newPrograms.push( programInfo );
  10872. }
  10873. }
  10874. _programs = newPrograms;
  10875. _gl.deleteProgram( program );
  10876. _this.info.memory.programs --;
  10877. }
  10878. };
  10879. //
  10880. /*
  10881. function deleteParticleBuffers ( geometry ) {
  10882. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10883. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10884. deleteCustomAttributesBuffers( geometry );
  10885. _this.info.memory.geometries --;
  10886. };
  10887. function deleteLineBuffers ( geometry ) {
  10888. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10889. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10890. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10891. deleteCustomAttributesBuffers( geometry );
  10892. _this.info.memory.geometries --;
  10893. };
  10894. function deleteRibbonBuffers ( geometry ) {
  10895. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10896. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10897. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10898. deleteCustomAttributesBuffers( geometry );
  10899. _this.info.memory.geometries --;
  10900. };
  10901. function deleteMeshBuffers ( geometryGroup ) {
  10902. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  10903. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  10904. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  10905. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  10906. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  10907. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  10908. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  10909. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  10910. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  10911. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  10912. var m, ml;
  10913. if ( geometryGroup.numMorphTargets ) {
  10914. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10915. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10916. }
  10917. }
  10918. if ( geometryGroup.numMorphNormals ) {
  10919. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10920. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10921. }
  10922. }
  10923. deleteCustomAttributesBuffers( geometryGroup );
  10924. _this.info.memory.geometries --;
  10925. };
  10926. */
  10927. function deleteCustomAttributesBuffers( geometry ) {
  10928. if ( geometry.__webglCustomAttributesList ) {
  10929. for ( var id in geometry.__webglCustomAttributesList ) {
  10930. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  10931. }
  10932. }
  10933. };
  10934. // Buffer initialization
  10935. function initCustomAttributes ( geometry, object ) {
  10936. var nvertices = geometry.vertices.length;
  10937. var material = object.material;
  10938. if ( material.attributes ) {
  10939. if ( geometry.__webglCustomAttributesList === undefined ) {
  10940. geometry.__webglCustomAttributesList = [];
  10941. }
  10942. for ( var a in material.attributes ) {
  10943. var attribute = material.attributes[ a ];
  10944. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10945. attribute.__webglInitialized = true;
  10946. var size = 1; // "f" and "i"
  10947. if ( attribute.type === "v2" ) size = 2;
  10948. else if ( attribute.type === "v3" ) size = 3;
  10949. else if ( attribute.type === "v4" ) size = 4;
  10950. else if ( attribute.type === "c" ) size = 3;
  10951. attribute.size = size;
  10952. attribute.array = new Float32Array( nvertices * size );
  10953. attribute.buffer = _gl.createBuffer();
  10954. attribute.buffer.belongsToAttribute = a;
  10955. attribute.needsUpdate = true;
  10956. }
  10957. geometry.__webglCustomAttributesList.push( attribute );
  10958. }
  10959. }
  10960. };
  10961. function initParticleBuffers ( geometry, object ) {
  10962. var nvertices = geometry.vertices.length;
  10963. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10964. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10965. geometry.__sortArray = [];
  10966. geometry.__webglParticleCount = nvertices;
  10967. initCustomAttributes ( geometry, object );
  10968. };
  10969. function initLineBuffers ( geometry, object ) {
  10970. var nvertices = geometry.vertices.length;
  10971. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10972. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10973. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  10974. geometry.__webglLineCount = nvertices;
  10975. initCustomAttributes ( geometry, object );
  10976. };
  10977. function initRibbonBuffers ( geometry, object ) {
  10978. var nvertices = geometry.vertices.length;
  10979. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10980. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10981. geometry.__normalArray = new Float32Array( nvertices * 3 );
  10982. geometry.__webglVertexCount = nvertices;
  10983. initCustomAttributes ( geometry, object );
  10984. };
  10985. function initMeshBuffers ( geometryGroup, object ) {
  10986. var geometry = object.geometry,
  10987. faces3 = geometryGroup.faces3,
  10988. faces4 = geometryGroup.faces4,
  10989. nvertices = faces3.length * 3 + faces4.length * 4,
  10990. ntris = faces3.length * 1 + faces4.length * 2,
  10991. nlines = faces3.length * 3 + faces4.length * 4,
  10992. material = getBufferMaterial( object, geometryGroup ),
  10993. uvType = bufferGuessUVType( material ),
  10994. normalType = bufferGuessNormalType( material ),
  10995. vertexColorType = bufferGuessVertexColorType( material );
  10996. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  10997. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  10998. if ( normalType ) {
  10999. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11000. }
  11001. if ( geometry.hasTangents ) {
  11002. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11003. }
  11004. if ( vertexColorType ) {
  11005. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11006. }
  11007. if ( uvType ) {
  11008. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  11009. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11010. }
  11011. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  11012. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11013. }
  11014. }
  11015. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11016. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11017. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11018. }
  11019. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11020. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11021. var m, ml;
  11022. if ( geometryGroup.numMorphTargets ) {
  11023. geometryGroup.__morphTargetsArrays = [];
  11024. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11025. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11026. }
  11027. }
  11028. if ( geometryGroup.numMorphNormals ) {
  11029. geometryGroup.__morphNormalsArrays = [];
  11030. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11031. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11032. }
  11033. }
  11034. geometryGroup.__webglFaceCount = ntris * 3;
  11035. geometryGroup.__webglLineCount = nlines * 2;
  11036. // custom attributes
  11037. if ( material.attributes ) {
  11038. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11039. geometryGroup.__webglCustomAttributesList = [];
  11040. }
  11041. for ( var a in material.attributes ) {
  11042. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11043. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11044. var originalAttribute = material.attributes[ a ];
  11045. var attribute = {};
  11046. for ( var property in originalAttribute ) {
  11047. attribute[ property ] = originalAttribute[ property ];
  11048. }
  11049. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11050. attribute.__webglInitialized = true;
  11051. var size = 1; // "f" and "i"
  11052. if( attribute.type === "v2" ) size = 2;
  11053. else if( attribute.type === "v3" ) size = 3;
  11054. else if( attribute.type === "v4" ) size = 4;
  11055. else if( attribute.type === "c" ) size = 3;
  11056. attribute.size = size;
  11057. attribute.array = new Float32Array( nvertices * size );
  11058. attribute.buffer = _gl.createBuffer();
  11059. attribute.buffer.belongsToAttribute = a;
  11060. originalAttribute.needsUpdate = true;
  11061. attribute.__original = originalAttribute;
  11062. }
  11063. geometryGroup.__webglCustomAttributesList.push( attribute );
  11064. }
  11065. }
  11066. geometryGroup.__inittedArrays = true;
  11067. };
  11068. function getBufferMaterial( object, geometryGroup ) {
  11069. return object.material instanceof THREE.MeshFaceMaterial
  11070. ? object.material.materials[ geometryGroup.materialIndex ]
  11071. : object.material;
  11072. };
  11073. function materialNeedsSmoothNormals ( material ) {
  11074. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  11075. };
  11076. function bufferGuessNormalType ( material ) {
  11077. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  11078. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  11079. return false;
  11080. }
  11081. if ( materialNeedsSmoothNormals( material ) ) {
  11082. return THREE.SmoothShading;
  11083. } else {
  11084. return THREE.FlatShading;
  11085. }
  11086. };
  11087. function bufferGuessVertexColorType ( material ) {
  11088. if ( material.vertexColors ) {
  11089. return material.vertexColors;
  11090. }
  11091. return false;
  11092. };
  11093. function bufferGuessUVType ( material ) {
  11094. // material must use some texture to require uvs
  11095. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  11096. return true;
  11097. }
  11098. return false;
  11099. };
  11100. //
  11101. function initDirectBuffers( geometry ) {
  11102. var a, attribute, type;
  11103. for ( a in geometry.attributes ) {
  11104. if ( a === "index" ) {
  11105. type = _gl.ELEMENT_ARRAY_BUFFER;
  11106. } else {
  11107. type = _gl.ARRAY_BUFFER;
  11108. }
  11109. attribute = geometry.attributes[ a ];
  11110. attribute.buffer = _gl.createBuffer();
  11111. _gl.bindBuffer( type, attribute.buffer );
  11112. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  11113. }
  11114. };
  11115. // Buffer setting
  11116. function setParticleBuffers ( geometry, hint, object ) {
  11117. var v, c, vertex, offset, index, color,
  11118. vertices = geometry.vertices,
  11119. vl = vertices.length,
  11120. colors = geometry.colors,
  11121. cl = colors.length,
  11122. vertexArray = geometry.__vertexArray,
  11123. colorArray = geometry.__colorArray,
  11124. sortArray = geometry.__sortArray,
  11125. dirtyVertices = geometry.verticesNeedUpdate,
  11126. dirtyElements = geometry.elementsNeedUpdate,
  11127. dirtyColors = geometry.colorsNeedUpdate,
  11128. customAttributes = geometry.__webglCustomAttributesList,
  11129. i, il,
  11130. a, ca, cal, value,
  11131. customAttribute;
  11132. if ( object.sortParticles ) {
  11133. _projScreenMatrixPS.copy( _projScreenMatrix );
  11134. _projScreenMatrixPS.multiply( object.matrixWorld );
  11135. for ( v = 0; v < vl; v ++ ) {
  11136. vertex = vertices[ v ];
  11137. _vector3.copy( vertex );
  11138. _vector3.applyMatrix4( _projScreenMatrixPS );
  11139. sortArray[ v ] = [ _vector3.z, v ];
  11140. }
  11141. sortArray.sort( numericalSort );
  11142. for ( v = 0; v < vl; v ++ ) {
  11143. vertex = vertices[ sortArray[v][1] ];
  11144. offset = v * 3;
  11145. vertexArray[ offset ] = vertex.x;
  11146. vertexArray[ offset + 1 ] = vertex.y;
  11147. vertexArray[ offset + 2 ] = vertex.z;
  11148. }
  11149. for ( c = 0; c < cl; c ++ ) {
  11150. offset = c * 3;
  11151. color = colors[ sortArray[c][1] ];
  11152. colorArray[ offset ] = color.r;
  11153. colorArray[ offset + 1 ] = color.g;
  11154. colorArray[ offset + 2 ] = color.b;
  11155. }
  11156. if ( customAttributes ) {
  11157. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11158. customAttribute = customAttributes[ i ];
  11159. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  11160. offset = 0;
  11161. cal = customAttribute.value.length;
  11162. if ( customAttribute.size === 1 ) {
  11163. for ( ca = 0; ca < cal; ca ++ ) {
  11164. index = sortArray[ ca ][ 1 ];
  11165. customAttribute.array[ ca ] = customAttribute.value[ index ];
  11166. }
  11167. } else if ( customAttribute.size === 2 ) {
  11168. for ( ca = 0; ca < cal; ca ++ ) {
  11169. index = sortArray[ ca ][ 1 ];
  11170. value = customAttribute.value[ index ];
  11171. customAttribute.array[ offset ] = value.x;
  11172. customAttribute.array[ offset + 1 ] = value.y;
  11173. offset += 2;
  11174. }
  11175. } else if ( customAttribute.size === 3 ) {
  11176. if ( customAttribute.type === "c" ) {
  11177. for ( ca = 0; ca < cal; ca ++ ) {
  11178. index = sortArray[ ca ][ 1 ];
  11179. value = customAttribute.value[ index ];
  11180. customAttribute.array[ offset ] = value.r;
  11181. customAttribute.array[ offset + 1 ] = value.g;
  11182. customAttribute.array[ offset + 2 ] = value.b;
  11183. offset += 3;
  11184. }
  11185. } else {
  11186. for ( ca = 0; ca < cal; ca ++ ) {
  11187. index = sortArray[ ca ][ 1 ];
  11188. value = customAttribute.value[ index ];
  11189. customAttribute.array[ offset ] = value.x;
  11190. customAttribute.array[ offset + 1 ] = value.y;
  11191. customAttribute.array[ offset + 2 ] = value.z;
  11192. offset += 3;
  11193. }
  11194. }
  11195. } else if ( customAttribute.size === 4 ) {
  11196. for ( ca = 0; ca < cal; ca ++ ) {
  11197. index = sortArray[ ca ][ 1 ];
  11198. value = customAttribute.value[ index ];
  11199. customAttribute.array[ offset ] = value.x;
  11200. customAttribute.array[ offset + 1 ] = value.y;
  11201. customAttribute.array[ offset + 2 ] = value.z;
  11202. customAttribute.array[ offset + 3 ] = value.w;
  11203. offset += 4;
  11204. }
  11205. }
  11206. }
  11207. }
  11208. } else {
  11209. if ( dirtyVertices ) {
  11210. for ( v = 0; v < vl; v ++ ) {
  11211. vertex = vertices[ v ];
  11212. offset = v * 3;
  11213. vertexArray[ offset ] = vertex.x;
  11214. vertexArray[ offset + 1 ] = vertex.y;
  11215. vertexArray[ offset + 2 ] = vertex.z;
  11216. }
  11217. }
  11218. if ( dirtyColors ) {
  11219. for ( c = 0; c < cl; c ++ ) {
  11220. color = colors[ c ];
  11221. offset = c * 3;
  11222. colorArray[ offset ] = color.r;
  11223. colorArray[ offset + 1 ] = color.g;
  11224. colorArray[ offset + 2 ] = color.b;
  11225. }
  11226. }
  11227. if ( customAttributes ) {
  11228. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11229. customAttribute = customAttributes[ i ];
  11230. if ( customAttribute.needsUpdate &&
  11231. ( customAttribute.boundTo === undefined ||
  11232. customAttribute.boundTo === "vertices") ) {
  11233. cal = customAttribute.value.length;
  11234. offset = 0;
  11235. if ( customAttribute.size === 1 ) {
  11236. for ( ca = 0; ca < cal; ca ++ ) {
  11237. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11238. }
  11239. } else if ( customAttribute.size === 2 ) {
  11240. for ( ca = 0; ca < cal; ca ++ ) {
  11241. value = customAttribute.value[ ca ];
  11242. customAttribute.array[ offset ] = value.x;
  11243. customAttribute.array[ offset + 1 ] = value.y;
  11244. offset += 2;
  11245. }
  11246. } else if ( customAttribute.size === 3 ) {
  11247. if ( customAttribute.type === "c" ) {
  11248. for ( ca = 0; ca < cal; ca ++ ) {
  11249. value = customAttribute.value[ ca ];
  11250. customAttribute.array[ offset ] = value.r;
  11251. customAttribute.array[ offset + 1 ] = value.g;
  11252. customAttribute.array[ offset + 2 ] = value.b;
  11253. offset += 3;
  11254. }
  11255. } else {
  11256. for ( ca = 0; ca < cal; ca ++ ) {
  11257. value = customAttribute.value[ ca ];
  11258. customAttribute.array[ offset ] = value.x;
  11259. customAttribute.array[ offset + 1 ] = value.y;
  11260. customAttribute.array[ offset + 2 ] = value.z;
  11261. offset += 3;
  11262. }
  11263. }
  11264. } else if ( customAttribute.size === 4 ) {
  11265. for ( ca = 0; ca < cal; ca ++ ) {
  11266. value = customAttribute.value[ ca ];
  11267. customAttribute.array[ offset ] = value.x;
  11268. customAttribute.array[ offset + 1 ] = value.y;
  11269. customAttribute.array[ offset + 2 ] = value.z;
  11270. customAttribute.array[ offset + 3 ] = value.w;
  11271. offset += 4;
  11272. }
  11273. }
  11274. }
  11275. }
  11276. }
  11277. }
  11278. if ( dirtyVertices || object.sortParticles ) {
  11279. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11280. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11281. }
  11282. if ( dirtyColors || object.sortParticles ) {
  11283. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11284. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11285. }
  11286. if ( customAttributes ) {
  11287. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11288. customAttribute = customAttributes[ i ];
  11289. if ( customAttribute.needsUpdate || object.sortParticles ) {
  11290. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11291. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11292. }
  11293. }
  11294. }
  11295. };
  11296. function setLineBuffers ( geometry, hint ) {
  11297. var v, c, d, vertex, offset, color,
  11298. vertices = geometry.vertices,
  11299. colors = geometry.colors,
  11300. lineDistances = geometry.lineDistances,
  11301. vl = vertices.length,
  11302. cl = colors.length,
  11303. dl = lineDistances.length,
  11304. vertexArray = geometry.__vertexArray,
  11305. colorArray = geometry.__colorArray,
  11306. lineDistanceArray = geometry.__lineDistanceArray,
  11307. dirtyVertices = geometry.verticesNeedUpdate,
  11308. dirtyColors = geometry.colorsNeedUpdate,
  11309. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11310. customAttributes = geometry.__webglCustomAttributesList,
  11311. i, il,
  11312. a, ca, cal, value,
  11313. customAttribute;
  11314. if ( dirtyVertices ) {
  11315. for ( v = 0; v < vl; v ++ ) {
  11316. vertex = vertices[ v ];
  11317. offset = v * 3;
  11318. vertexArray[ offset ] = vertex.x;
  11319. vertexArray[ offset + 1 ] = vertex.y;
  11320. vertexArray[ offset + 2 ] = vertex.z;
  11321. }
  11322. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11323. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11324. }
  11325. if ( dirtyColors ) {
  11326. for ( c = 0; c < cl; c ++ ) {
  11327. color = colors[ c ];
  11328. offset = c * 3;
  11329. colorArray[ offset ] = color.r;
  11330. colorArray[ offset + 1 ] = color.g;
  11331. colorArray[ offset + 2 ] = color.b;
  11332. }
  11333. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11334. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11335. }
  11336. if ( dirtyLineDistances ) {
  11337. for ( d = 0; d < dl; d ++ ) {
  11338. lineDistanceArray[ d ] = lineDistances[ d ];
  11339. }
  11340. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11341. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11342. }
  11343. if ( customAttributes ) {
  11344. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11345. customAttribute = customAttributes[ i ];
  11346. if ( customAttribute.needsUpdate &&
  11347. ( customAttribute.boundTo === undefined ||
  11348. customAttribute.boundTo === "vertices" ) ) {
  11349. offset = 0;
  11350. cal = customAttribute.value.length;
  11351. if ( customAttribute.size === 1 ) {
  11352. for ( ca = 0; ca < cal; ca ++ ) {
  11353. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11354. }
  11355. } else if ( customAttribute.size === 2 ) {
  11356. for ( ca = 0; ca < cal; ca ++ ) {
  11357. value = customAttribute.value[ ca ];
  11358. customAttribute.array[ offset ] = value.x;
  11359. customAttribute.array[ offset + 1 ] = value.y;
  11360. offset += 2;
  11361. }
  11362. } else if ( customAttribute.size === 3 ) {
  11363. if ( customAttribute.type === "c" ) {
  11364. for ( ca = 0; ca < cal; ca ++ ) {
  11365. value = customAttribute.value[ ca ];
  11366. customAttribute.array[ offset ] = value.r;
  11367. customAttribute.array[ offset + 1 ] = value.g;
  11368. customAttribute.array[ offset + 2 ] = value.b;
  11369. offset += 3;
  11370. }
  11371. } else {
  11372. for ( ca = 0; ca < cal; ca ++ ) {
  11373. value = customAttribute.value[ ca ];
  11374. customAttribute.array[ offset ] = value.x;
  11375. customAttribute.array[ offset + 1 ] = value.y;
  11376. customAttribute.array[ offset + 2 ] = value.z;
  11377. offset += 3;
  11378. }
  11379. }
  11380. } else if ( customAttribute.size === 4 ) {
  11381. for ( ca = 0; ca < cal; ca ++ ) {
  11382. value = customAttribute.value[ ca ];
  11383. customAttribute.array[ offset ] = value.x;
  11384. customAttribute.array[ offset + 1 ] = value.y;
  11385. customAttribute.array[ offset + 2 ] = value.z;
  11386. customAttribute.array[ offset + 3 ] = value.w;
  11387. offset += 4;
  11388. }
  11389. }
  11390. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11391. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11392. }
  11393. }
  11394. }
  11395. };
  11396. function setRibbonBuffers ( geometry, hint ) {
  11397. var v, c, n, vertex, offset, color, normal,
  11398. i, il, ca, cal, customAttribute, value,
  11399. vertices = geometry.vertices,
  11400. colors = geometry.colors,
  11401. normals = geometry.normals,
  11402. vl = vertices.length,
  11403. cl = colors.length,
  11404. nl = normals.length,
  11405. vertexArray = geometry.__vertexArray,
  11406. colorArray = geometry.__colorArray,
  11407. normalArray = geometry.__normalArray,
  11408. dirtyVertices = geometry.verticesNeedUpdate,
  11409. dirtyColors = geometry.colorsNeedUpdate,
  11410. dirtyNormals = geometry.normalsNeedUpdate,
  11411. customAttributes = geometry.__webglCustomAttributesList;
  11412. if ( dirtyVertices ) {
  11413. for ( v = 0; v < vl; v ++ ) {
  11414. vertex = vertices[ v ];
  11415. offset = v * 3;
  11416. vertexArray[ offset ] = vertex.x;
  11417. vertexArray[ offset + 1 ] = vertex.y;
  11418. vertexArray[ offset + 2 ] = vertex.z;
  11419. }
  11420. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11421. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11422. }
  11423. if ( dirtyColors ) {
  11424. for ( c = 0; c < cl; c ++ ) {
  11425. color = colors[ c ];
  11426. offset = c * 3;
  11427. colorArray[ offset ] = color.r;
  11428. colorArray[ offset + 1 ] = color.g;
  11429. colorArray[ offset + 2 ] = color.b;
  11430. }
  11431. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11432. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11433. }
  11434. if ( dirtyNormals ) {
  11435. for ( n = 0; n < nl; n ++ ) {
  11436. normal = normals[ n ];
  11437. offset = n * 3;
  11438. normalArray[ offset ] = normal.x;
  11439. normalArray[ offset + 1 ] = normal.y;
  11440. normalArray[ offset + 2 ] = normal.z;
  11441. }
  11442. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11443. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11444. }
  11445. if ( customAttributes ) {
  11446. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11447. customAttribute = customAttributes[ i ];
  11448. if ( customAttribute.needsUpdate &&
  11449. ( customAttribute.boundTo === undefined ||
  11450. customAttribute.boundTo === "vertices" ) ) {
  11451. offset = 0;
  11452. cal = customAttribute.value.length;
  11453. if ( customAttribute.size === 1 ) {
  11454. for ( ca = 0; ca < cal; ca ++ ) {
  11455. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11456. }
  11457. } else if ( customAttribute.size === 2 ) {
  11458. for ( ca = 0; ca < cal; ca ++ ) {
  11459. value = customAttribute.value[ ca ];
  11460. customAttribute.array[ offset ] = value.x;
  11461. customAttribute.array[ offset + 1 ] = value.y;
  11462. offset += 2;
  11463. }
  11464. } else if ( customAttribute.size === 3 ) {
  11465. if ( customAttribute.type === "c" ) {
  11466. for ( ca = 0; ca < cal; ca ++ ) {
  11467. value = customAttribute.value[ ca ];
  11468. customAttribute.array[ offset ] = value.r;
  11469. customAttribute.array[ offset + 1 ] = value.g;
  11470. customAttribute.array[ offset + 2 ] = value.b;
  11471. offset += 3;
  11472. }
  11473. } else {
  11474. for ( ca = 0; ca < cal; ca ++ ) {
  11475. value = customAttribute.value[ ca ];
  11476. customAttribute.array[ offset ] = value.x;
  11477. customAttribute.array[ offset + 1 ] = value.y;
  11478. customAttribute.array[ offset + 2 ] = value.z;
  11479. offset += 3;
  11480. }
  11481. }
  11482. } else if ( customAttribute.size === 4 ) {
  11483. for ( ca = 0; ca < cal; ca ++ ) {
  11484. value = customAttribute.value[ ca ];
  11485. customAttribute.array[ offset ] = value.x;
  11486. customAttribute.array[ offset + 1 ] = value.y;
  11487. customAttribute.array[ offset + 2 ] = value.z;
  11488. customAttribute.array[ offset + 3 ] = value.w;
  11489. offset += 4;
  11490. }
  11491. }
  11492. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11493. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11494. }
  11495. }
  11496. }
  11497. };
  11498. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11499. if ( ! geometryGroup.__inittedArrays ) {
  11500. return;
  11501. }
  11502. var normalType = bufferGuessNormalType( material ),
  11503. vertexColorType = bufferGuessVertexColorType( material ),
  11504. uvType = bufferGuessUVType( material ),
  11505. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  11506. var f, fl, fi, face,
  11507. vertexNormals, faceNormal, normal,
  11508. vertexColors, faceColor,
  11509. vertexTangents,
  11510. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11511. c1, c2, c3, c4,
  11512. sw1, sw2, sw3, sw4,
  11513. si1, si2, si3, si4,
  11514. sa1, sa2, sa3, sa4,
  11515. sb1, sb2, sb3, sb4,
  11516. m, ml, i, il,
  11517. vn, uvi, uv2i,
  11518. vk, vkl, vka,
  11519. nka, chf, faceVertexNormals,
  11520. a,
  11521. vertexIndex = 0,
  11522. offset = 0,
  11523. offset_uv = 0,
  11524. offset_uv2 = 0,
  11525. offset_face = 0,
  11526. offset_normal = 0,
  11527. offset_tangent = 0,
  11528. offset_line = 0,
  11529. offset_color = 0,
  11530. offset_skin = 0,
  11531. offset_morphTarget = 0,
  11532. offset_custom = 0,
  11533. offset_customSrc = 0,
  11534. value,
  11535. vertexArray = geometryGroup.__vertexArray,
  11536. uvArray = geometryGroup.__uvArray,
  11537. uv2Array = geometryGroup.__uv2Array,
  11538. normalArray = geometryGroup.__normalArray,
  11539. tangentArray = geometryGroup.__tangentArray,
  11540. colorArray = geometryGroup.__colorArray,
  11541. skinIndexArray = geometryGroup.__skinIndexArray,
  11542. skinWeightArray = geometryGroup.__skinWeightArray,
  11543. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11544. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11545. customAttributes = geometryGroup.__webglCustomAttributesList,
  11546. customAttribute,
  11547. faceArray = geometryGroup.__faceArray,
  11548. lineArray = geometryGroup.__lineArray,
  11549. geometry = object.geometry, // this is shared for all chunks
  11550. dirtyVertices = geometry.verticesNeedUpdate,
  11551. dirtyElements = geometry.elementsNeedUpdate,
  11552. dirtyUvs = geometry.uvsNeedUpdate,
  11553. dirtyNormals = geometry.normalsNeedUpdate,
  11554. dirtyTangents = geometry.tangentsNeedUpdate,
  11555. dirtyColors = geometry.colorsNeedUpdate,
  11556. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11557. vertices = geometry.vertices,
  11558. chunk_faces3 = geometryGroup.faces3,
  11559. chunk_faces4 = geometryGroup.faces4,
  11560. obj_faces = geometry.faces,
  11561. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11562. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11563. obj_colors = geometry.colors,
  11564. obj_skinIndices = geometry.skinIndices,
  11565. obj_skinWeights = geometry.skinWeights,
  11566. morphTargets = geometry.morphTargets,
  11567. morphNormals = geometry.morphNormals;
  11568. if ( dirtyVertices ) {
  11569. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11570. face = obj_faces[ chunk_faces3[ f ] ];
  11571. v1 = vertices[ face.a ];
  11572. v2 = vertices[ face.b ];
  11573. v3 = vertices[ face.c ];
  11574. vertexArray[ offset ] = v1.x;
  11575. vertexArray[ offset + 1 ] = v1.y;
  11576. vertexArray[ offset + 2 ] = v1.z;
  11577. vertexArray[ offset + 3 ] = v2.x;
  11578. vertexArray[ offset + 4 ] = v2.y;
  11579. vertexArray[ offset + 5 ] = v2.z;
  11580. vertexArray[ offset + 6 ] = v3.x;
  11581. vertexArray[ offset + 7 ] = v3.y;
  11582. vertexArray[ offset + 8 ] = v3.z;
  11583. offset += 9;
  11584. }
  11585. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11586. face = obj_faces[ chunk_faces4[ f ] ];
  11587. v1 = vertices[ face.a ];
  11588. v2 = vertices[ face.b ];
  11589. v3 = vertices[ face.c ];
  11590. v4 = vertices[ face.d ];
  11591. vertexArray[ offset ] = v1.x;
  11592. vertexArray[ offset + 1 ] = v1.y;
  11593. vertexArray[ offset + 2 ] = v1.z;
  11594. vertexArray[ offset + 3 ] = v2.x;
  11595. vertexArray[ offset + 4 ] = v2.y;
  11596. vertexArray[ offset + 5 ] = v2.z;
  11597. vertexArray[ offset + 6 ] = v3.x;
  11598. vertexArray[ offset + 7 ] = v3.y;
  11599. vertexArray[ offset + 8 ] = v3.z;
  11600. vertexArray[ offset + 9 ] = v4.x;
  11601. vertexArray[ offset + 10 ] = v4.y;
  11602. vertexArray[ offset + 11 ] = v4.z;
  11603. offset += 12;
  11604. }
  11605. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11606. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11607. }
  11608. if ( dirtyMorphTargets ) {
  11609. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11610. offset_morphTarget = 0;
  11611. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11612. chf = chunk_faces3[ f ];
  11613. face = obj_faces[ chf ];
  11614. // morph positions
  11615. v1 = morphTargets[ vk ].vertices[ face.a ];
  11616. v2 = morphTargets[ vk ].vertices[ face.b ];
  11617. v3 = morphTargets[ vk ].vertices[ face.c ];
  11618. vka = morphTargetsArrays[ vk ];
  11619. vka[ offset_morphTarget ] = v1.x;
  11620. vka[ offset_morphTarget + 1 ] = v1.y;
  11621. vka[ offset_morphTarget + 2 ] = v1.z;
  11622. vka[ offset_morphTarget + 3 ] = v2.x;
  11623. vka[ offset_morphTarget + 4 ] = v2.y;
  11624. vka[ offset_morphTarget + 5 ] = v2.z;
  11625. vka[ offset_morphTarget + 6 ] = v3.x;
  11626. vka[ offset_morphTarget + 7 ] = v3.y;
  11627. vka[ offset_morphTarget + 8 ] = v3.z;
  11628. // morph normals
  11629. if ( material.morphNormals ) {
  11630. if ( needsSmoothNormals ) {
  11631. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11632. n1 = faceVertexNormals.a;
  11633. n2 = faceVertexNormals.b;
  11634. n3 = faceVertexNormals.c;
  11635. } else {
  11636. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11637. n2 = n1;
  11638. n3 = n1;
  11639. }
  11640. nka = morphNormalsArrays[ vk ];
  11641. nka[ offset_morphTarget ] = n1.x;
  11642. nka[ offset_morphTarget + 1 ] = n1.y;
  11643. nka[ offset_morphTarget + 2 ] = n1.z;
  11644. nka[ offset_morphTarget + 3 ] = n2.x;
  11645. nka[ offset_morphTarget + 4 ] = n2.y;
  11646. nka[ offset_morphTarget + 5 ] = n2.z;
  11647. nka[ offset_morphTarget + 6 ] = n3.x;
  11648. nka[ offset_morphTarget + 7 ] = n3.y;
  11649. nka[ offset_morphTarget + 8 ] = n3.z;
  11650. }
  11651. //
  11652. offset_morphTarget += 9;
  11653. }
  11654. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11655. chf = chunk_faces4[ f ];
  11656. face = obj_faces[ chf ];
  11657. // morph positions
  11658. v1 = morphTargets[ vk ].vertices[ face.a ];
  11659. v2 = morphTargets[ vk ].vertices[ face.b ];
  11660. v3 = morphTargets[ vk ].vertices[ face.c ];
  11661. v4 = morphTargets[ vk ].vertices[ face.d ];
  11662. vka = morphTargetsArrays[ vk ];
  11663. vka[ offset_morphTarget ] = v1.x;
  11664. vka[ offset_morphTarget + 1 ] = v1.y;
  11665. vka[ offset_morphTarget + 2 ] = v1.z;
  11666. vka[ offset_morphTarget + 3 ] = v2.x;
  11667. vka[ offset_morphTarget + 4 ] = v2.y;
  11668. vka[ offset_morphTarget + 5 ] = v2.z;
  11669. vka[ offset_morphTarget + 6 ] = v3.x;
  11670. vka[ offset_morphTarget + 7 ] = v3.y;
  11671. vka[ offset_morphTarget + 8 ] = v3.z;
  11672. vka[ offset_morphTarget + 9 ] = v4.x;
  11673. vka[ offset_morphTarget + 10 ] = v4.y;
  11674. vka[ offset_morphTarget + 11 ] = v4.z;
  11675. // morph normals
  11676. if ( material.morphNormals ) {
  11677. if ( needsSmoothNormals ) {
  11678. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11679. n1 = faceVertexNormals.a;
  11680. n2 = faceVertexNormals.b;
  11681. n3 = faceVertexNormals.c;
  11682. n4 = faceVertexNormals.d;
  11683. } else {
  11684. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11685. n2 = n1;
  11686. n3 = n1;
  11687. n4 = n1;
  11688. }
  11689. nka = morphNormalsArrays[ vk ];
  11690. nka[ offset_morphTarget ] = n1.x;
  11691. nka[ offset_morphTarget + 1 ] = n1.y;
  11692. nka[ offset_morphTarget + 2 ] = n1.z;
  11693. nka[ offset_morphTarget + 3 ] = n2.x;
  11694. nka[ offset_morphTarget + 4 ] = n2.y;
  11695. nka[ offset_morphTarget + 5 ] = n2.z;
  11696. nka[ offset_morphTarget + 6 ] = n3.x;
  11697. nka[ offset_morphTarget + 7 ] = n3.y;
  11698. nka[ offset_morphTarget + 8 ] = n3.z;
  11699. nka[ offset_morphTarget + 9 ] = n4.x;
  11700. nka[ offset_morphTarget + 10 ] = n4.y;
  11701. nka[ offset_morphTarget + 11 ] = n4.z;
  11702. }
  11703. //
  11704. offset_morphTarget += 12;
  11705. }
  11706. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11707. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11708. if ( material.morphNormals ) {
  11709. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11710. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11711. }
  11712. }
  11713. }
  11714. if ( obj_skinWeights.length ) {
  11715. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11716. face = obj_faces[ chunk_faces3[ f ] ];
  11717. // weights
  11718. sw1 = obj_skinWeights[ face.a ];
  11719. sw2 = obj_skinWeights[ face.b ];
  11720. sw3 = obj_skinWeights[ face.c ];
  11721. skinWeightArray[ offset_skin ] = sw1.x;
  11722. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11723. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11724. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11725. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11726. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11727. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11728. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11729. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11730. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11731. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11732. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11733. // indices
  11734. si1 = obj_skinIndices[ face.a ];
  11735. si2 = obj_skinIndices[ face.b ];
  11736. si3 = obj_skinIndices[ face.c ];
  11737. skinIndexArray[ offset_skin ] = si1.x;
  11738. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11739. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11740. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11741. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11742. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11743. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11744. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11745. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11746. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11747. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11748. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11749. offset_skin += 12;
  11750. }
  11751. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11752. face = obj_faces[ chunk_faces4[ f ] ];
  11753. // weights
  11754. sw1 = obj_skinWeights[ face.a ];
  11755. sw2 = obj_skinWeights[ face.b ];
  11756. sw3 = obj_skinWeights[ face.c ];
  11757. sw4 = obj_skinWeights[ face.d ];
  11758. skinWeightArray[ offset_skin ] = sw1.x;
  11759. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11760. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11761. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11762. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11763. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11764. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11765. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11766. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11767. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11768. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11769. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11770. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  11771. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  11772. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  11773. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  11774. // indices
  11775. si1 = obj_skinIndices[ face.a ];
  11776. si2 = obj_skinIndices[ face.b ];
  11777. si3 = obj_skinIndices[ face.c ];
  11778. si4 = obj_skinIndices[ face.d ];
  11779. skinIndexArray[ offset_skin ] = si1.x;
  11780. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11781. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11782. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11783. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11784. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11785. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11786. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11787. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11788. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11789. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11790. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11791. skinIndexArray[ offset_skin + 12 ] = si4.x;
  11792. skinIndexArray[ offset_skin + 13 ] = si4.y;
  11793. skinIndexArray[ offset_skin + 14 ] = si4.z;
  11794. skinIndexArray[ offset_skin + 15 ] = si4.w;
  11795. offset_skin += 16;
  11796. }
  11797. if ( offset_skin > 0 ) {
  11798. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11799. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11800. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11801. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11802. }
  11803. }
  11804. if ( dirtyColors && vertexColorType ) {
  11805. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11806. face = obj_faces[ chunk_faces3[ f ] ];
  11807. vertexColors = face.vertexColors;
  11808. faceColor = face.color;
  11809. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  11810. c1 = vertexColors[ 0 ];
  11811. c2 = vertexColors[ 1 ];
  11812. c3 = vertexColors[ 2 ];
  11813. } else {
  11814. c1 = faceColor;
  11815. c2 = faceColor;
  11816. c3 = faceColor;
  11817. }
  11818. colorArray[ offset_color ] = c1.r;
  11819. colorArray[ offset_color + 1 ] = c1.g;
  11820. colorArray[ offset_color + 2 ] = c1.b;
  11821. colorArray[ offset_color + 3 ] = c2.r;
  11822. colorArray[ offset_color + 4 ] = c2.g;
  11823. colorArray[ offset_color + 5 ] = c2.b;
  11824. colorArray[ offset_color + 6 ] = c3.r;
  11825. colorArray[ offset_color + 7 ] = c3.g;
  11826. colorArray[ offset_color + 8 ] = c3.b;
  11827. offset_color += 9;
  11828. }
  11829. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11830. face = obj_faces[ chunk_faces4[ f ] ];
  11831. vertexColors = face.vertexColors;
  11832. faceColor = face.color;
  11833. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  11834. c1 = vertexColors[ 0 ];
  11835. c2 = vertexColors[ 1 ];
  11836. c3 = vertexColors[ 2 ];
  11837. c4 = vertexColors[ 3 ];
  11838. } else {
  11839. c1 = faceColor;
  11840. c2 = faceColor;
  11841. c3 = faceColor;
  11842. c4 = faceColor;
  11843. }
  11844. colorArray[ offset_color ] = c1.r;
  11845. colorArray[ offset_color + 1 ] = c1.g;
  11846. colorArray[ offset_color + 2 ] = c1.b;
  11847. colorArray[ offset_color + 3 ] = c2.r;
  11848. colorArray[ offset_color + 4 ] = c2.g;
  11849. colorArray[ offset_color + 5 ] = c2.b;
  11850. colorArray[ offset_color + 6 ] = c3.r;
  11851. colorArray[ offset_color + 7 ] = c3.g;
  11852. colorArray[ offset_color + 8 ] = c3.b;
  11853. colorArray[ offset_color + 9 ] = c4.r;
  11854. colorArray[ offset_color + 10 ] = c4.g;
  11855. colorArray[ offset_color + 11 ] = c4.b;
  11856. offset_color += 12;
  11857. }
  11858. if ( offset_color > 0 ) {
  11859. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11860. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11861. }
  11862. }
  11863. if ( dirtyTangents && geometry.hasTangents ) {
  11864. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11865. face = obj_faces[ chunk_faces3[ f ] ];
  11866. vertexTangents = face.vertexTangents;
  11867. t1 = vertexTangents[ 0 ];
  11868. t2 = vertexTangents[ 1 ];
  11869. t3 = vertexTangents[ 2 ];
  11870. tangentArray[ offset_tangent ] = t1.x;
  11871. tangentArray[ offset_tangent + 1 ] = t1.y;
  11872. tangentArray[ offset_tangent + 2 ] = t1.z;
  11873. tangentArray[ offset_tangent + 3 ] = t1.w;
  11874. tangentArray[ offset_tangent + 4 ] = t2.x;
  11875. tangentArray[ offset_tangent + 5 ] = t2.y;
  11876. tangentArray[ offset_tangent + 6 ] = t2.z;
  11877. tangentArray[ offset_tangent + 7 ] = t2.w;
  11878. tangentArray[ offset_tangent + 8 ] = t3.x;
  11879. tangentArray[ offset_tangent + 9 ] = t3.y;
  11880. tangentArray[ offset_tangent + 10 ] = t3.z;
  11881. tangentArray[ offset_tangent + 11 ] = t3.w;
  11882. offset_tangent += 12;
  11883. }
  11884. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11885. face = obj_faces[ chunk_faces4[ f ] ];
  11886. vertexTangents = face.vertexTangents;
  11887. t1 = vertexTangents[ 0 ];
  11888. t2 = vertexTangents[ 1 ];
  11889. t3 = vertexTangents[ 2 ];
  11890. t4 = vertexTangents[ 3 ];
  11891. tangentArray[ offset_tangent ] = t1.x;
  11892. tangentArray[ offset_tangent + 1 ] = t1.y;
  11893. tangentArray[ offset_tangent + 2 ] = t1.z;
  11894. tangentArray[ offset_tangent + 3 ] = t1.w;
  11895. tangentArray[ offset_tangent + 4 ] = t2.x;
  11896. tangentArray[ offset_tangent + 5 ] = t2.y;
  11897. tangentArray[ offset_tangent + 6 ] = t2.z;
  11898. tangentArray[ offset_tangent + 7 ] = t2.w;
  11899. tangentArray[ offset_tangent + 8 ] = t3.x;
  11900. tangentArray[ offset_tangent + 9 ] = t3.y;
  11901. tangentArray[ offset_tangent + 10 ] = t3.z;
  11902. tangentArray[ offset_tangent + 11 ] = t3.w;
  11903. tangentArray[ offset_tangent + 12 ] = t4.x;
  11904. tangentArray[ offset_tangent + 13 ] = t4.y;
  11905. tangentArray[ offset_tangent + 14 ] = t4.z;
  11906. tangentArray[ offset_tangent + 15 ] = t4.w;
  11907. offset_tangent += 16;
  11908. }
  11909. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11910. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  11911. }
  11912. if ( dirtyNormals && normalType ) {
  11913. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11914. face = obj_faces[ chunk_faces3[ f ] ];
  11915. vertexNormals = face.vertexNormals;
  11916. faceNormal = face.normal;
  11917. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  11918. for ( i = 0; i < 3; i ++ ) {
  11919. vn = vertexNormals[ i ];
  11920. normalArray[ offset_normal ] = vn.x;
  11921. normalArray[ offset_normal + 1 ] = vn.y;
  11922. normalArray[ offset_normal + 2 ] = vn.z;
  11923. offset_normal += 3;
  11924. }
  11925. } else {
  11926. for ( i = 0; i < 3; i ++ ) {
  11927. normalArray[ offset_normal ] = faceNormal.x;
  11928. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11929. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11930. offset_normal += 3;
  11931. }
  11932. }
  11933. }
  11934. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11935. face = obj_faces[ chunk_faces4[ f ] ];
  11936. vertexNormals = face.vertexNormals;
  11937. faceNormal = face.normal;
  11938. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  11939. for ( i = 0; i < 4; i ++ ) {
  11940. vn = vertexNormals[ i ];
  11941. normalArray[ offset_normal ] = vn.x;
  11942. normalArray[ offset_normal + 1 ] = vn.y;
  11943. normalArray[ offset_normal + 2 ] = vn.z;
  11944. offset_normal += 3;
  11945. }
  11946. } else {
  11947. for ( i = 0; i < 4; i ++ ) {
  11948. normalArray[ offset_normal ] = faceNormal.x;
  11949. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11950. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11951. offset_normal += 3;
  11952. }
  11953. }
  11954. }
  11955. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11956. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11957. }
  11958. if ( dirtyUvs && obj_uvs && uvType ) {
  11959. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11960. fi = chunk_faces3[ f ];
  11961. uv = obj_uvs[ fi ];
  11962. if ( uv === undefined ) continue;
  11963. for ( i = 0; i < 3; i ++ ) {
  11964. uvi = uv[ i ];
  11965. uvArray[ offset_uv ] = uvi.x;
  11966. uvArray[ offset_uv + 1 ] = uvi.y;
  11967. offset_uv += 2;
  11968. }
  11969. }
  11970. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11971. fi = chunk_faces4[ f ];
  11972. uv = obj_uvs[ fi ];
  11973. if ( uv === undefined ) continue;
  11974. for ( i = 0; i < 4; i ++ ) {
  11975. uvi = uv[ i ];
  11976. uvArray[ offset_uv ] = uvi.x;
  11977. uvArray[ offset_uv + 1 ] = uvi.y;
  11978. offset_uv += 2;
  11979. }
  11980. }
  11981. if ( offset_uv > 0 ) {
  11982. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11983. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  11984. }
  11985. }
  11986. if ( dirtyUvs && obj_uvs2 && uvType ) {
  11987. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11988. fi = chunk_faces3[ f ];
  11989. uv2 = obj_uvs2[ fi ];
  11990. if ( uv2 === undefined ) continue;
  11991. for ( i = 0; i < 3; i ++ ) {
  11992. uv2i = uv2[ i ];
  11993. uv2Array[ offset_uv2 ] = uv2i.x;
  11994. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11995. offset_uv2 += 2;
  11996. }
  11997. }
  11998. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11999. fi = chunk_faces4[ f ];
  12000. uv2 = obj_uvs2[ fi ];
  12001. if ( uv2 === undefined ) continue;
  12002. for ( i = 0; i < 4; i ++ ) {
  12003. uv2i = uv2[ i ];
  12004. uv2Array[ offset_uv2 ] = uv2i.x;
  12005. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12006. offset_uv2 += 2;
  12007. }
  12008. }
  12009. if ( offset_uv2 > 0 ) {
  12010. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12011. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12012. }
  12013. }
  12014. if ( dirtyElements ) {
  12015. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12016. faceArray[ offset_face ] = vertexIndex;
  12017. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12018. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12019. offset_face += 3;
  12020. lineArray[ offset_line ] = vertexIndex;
  12021. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12022. lineArray[ offset_line + 2 ] = vertexIndex;
  12023. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12024. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12025. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12026. offset_line += 6;
  12027. vertexIndex += 3;
  12028. }
  12029. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12030. faceArray[ offset_face ] = vertexIndex;
  12031. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12032. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  12033. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  12034. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  12035. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  12036. offset_face += 6;
  12037. lineArray[ offset_line ] = vertexIndex;
  12038. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12039. lineArray[ offset_line + 2 ] = vertexIndex;
  12040. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  12041. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12042. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12043. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  12044. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  12045. offset_line += 8;
  12046. vertexIndex += 4;
  12047. }
  12048. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12049. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12050. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12051. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12052. }
  12053. if ( customAttributes ) {
  12054. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12055. customAttribute = customAttributes[ i ];
  12056. if ( ! customAttribute.__original.needsUpdate ) continue;
  12057. offset_custom = 0;
  12058. offset_customSrc = 0;
  12059. if ( customAttribute.size === 1 ) {
  12060. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12061. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12062. face = obj_faces[ chunk_faces3[ f ] ];
  12063. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12064. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12065. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12066. offset_custom += 3;
  12067. }
  12068. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12069. face = obj_faces[ chunk_faces4[ f ] ];
  12070. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12071. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12072. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12073. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  12074. offset_custom += 4;
  12075. }
  12076. } else if ( customAttribute.boundTo === "faces" ) {
  12077. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12078. value = customAttribute.value[ chunk_faces3[ f ] ];
  12079. customAttribute.array[ offset_custom ] = value;
  12080. customAttribute.array[ offset_custom + 1 ] = value;
  12081. customAttribute.array[ offset_custom + 2 ] = value;
  12082. offset_custom += 3;
  12083. }
  12084. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12085. value = customAttribute.value[ chunk_faces4[ f ] ];
  12086. customAttribute.array[ offset_custom ] = value;
  12087. customAttribute.array[ offset_custom + 1 ] = value;
  12088. customAttribute.array[ offset_custom + 2 ] = value;
  12089. customAttribute.array[ offset_custom + 3 ] = value;
  12090. offset_custom += 4;
  12091. }
  12092. }
  12093. } else if ( customAttribute.size === 2 ) {
  12094. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12095. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12096. face = obj_faces[ chunk_faces3[ f ] ];
  12097. v1 = customAttribute.value[ face.a ];
  12098. v2 = customAttribute.value[ face.b ];
  12099. v3 = customAttribute.value[ face.c ];
  12100. customAttribute.array[ offset_custom ] = v1.x;
  12101. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12102. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12103. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12104. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12105. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12106. offset_custom += 6;
  12107. }
  12108. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12109. face = obj_faces[ chunk_faces4[ f ] ];
  12110. v1 = customAttribute.value[ face.a ];
  12111. v2 = customAttribute.value[ face.b ];
  12112. v3 = customAttribute.value[ face.c ];
  12113. v4 = customAttribute.value[ face.d ];
  12114. customAttribute.array[ offset_custom ] = v1.x;
  12115. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12116. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12117. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12118. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12119. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12120. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12121. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12122. offset_custom += 8;
  12123. }
  12124. } else if ( customAttribute.boundTo === "faces" ) {
  12125. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12126. value = customAttribute.value[ chunk_faces3[ f ] ];
  12127. v1 = value;
  12128. v2 = value;
  12129. v3 = value;
  12130. customAttribute.array[ offset_custom ] = v1.x;
  12131. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12132. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12133. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12134. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12135. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12136. offset_custom += 6;
  12137. }
  12138. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12139. value = customAttribute.value[ chunk_faces4[ f ] ];
  12140. v1 = value;
  12141. v2 = value;
  12142. v3 = value;
  12143. v4 = value;
  12144. customAttribute.array[ offset_custom ] = v1.x;
  12145. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12146. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12147. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12148. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12149. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12150. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12151. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12152. offset_custom += 8;
  12153. }
  12154. }
  12155. } else if ( customAttribute.size === 3 ) {
  12156. var pp;
  12157. if ( customAttribute.type === "c" ) {
  12158. pp = [ "r", "g", "b" ];
  12159. } else {
  12160. pp = [ "x", "y", "z" ];
  12161. }
  12162. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12163. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12164. face = obj_faces[ chunk_faces3[ f ] ];
  12165. v1 = customAttribute.value[ face.a ];
  12166. v2 = customAttribute.value[ face.b ];
  12167. v3 = customAttribute.value[ face.c ];
  12168. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12169. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12170. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12171. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12172. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12173. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12174. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12175. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12176. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12177. offset_custom += 9;
  12178. }
  12179. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12180. face = obj_faces[ chunk_faces4[ f ] ];
  12181. v1 = customAttribute.value[ face.a ];
  12182. v2 = customAttribute.value[ face.b ];
  12183. v3 = customAttribute.value[ face.c ];
  12184. v4 = customAttribute.value[ face.d ];
  12185. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12186. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12187. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12188. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12189. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12190. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12191. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12192. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12193. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12194. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12195. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12196. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12197. offset_custom += 12;
  12198. }
  12199. } else if ( customAttribute.boundTo === "faces" ) {
  12200. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12201. value = customAttribute.value[ chunk_faces3[ f ] ];
  12202. v1 = value;
  12203. v2 = value;
  12204. v3 = value;
  12205. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12206. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12207. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12208. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12209. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12210. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12211. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12212. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12213. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12214. offset_custom += 9;
  12215. }
  12216. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12217. value = customAttribute.value[ chunk_faces4[ f ] ];
  12218. v1 = value;
  12219. v2 = value;
  12220. v3 = value;
  12221. v4 = value;
  12222. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12223. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12224. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12225. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12226. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12227. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12228. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12229. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12230. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12231. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12232. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12233. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12234. offset_custom += 12;
  12235. }
  12236. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12237. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12238. value = customAttribute.value[ chunk_faces3[ f ] ];
  12239. v1 = value[ 0 ];
  12240. v2 = value[ 1 ];
  12241. v3 = value[ 2 ];
  12242. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12243. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12244. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12245. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12246. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12247. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12248. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12249. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12250. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12251. offset_custom += 9;
  12252. }
  12253. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12254. value = customAttribute.value[ chunk_faces4[ f ] ];
  12255. v1 = value[ 0 ];
  12256. v2 = value[ 1 ];
  12257. v3 = value[ 2 ];
  12258. v4 = value[ 3 ];
  12259. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12260. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12261. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12262. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12263. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12264. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12265. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12266. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12267. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12268. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12269. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12270. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12271. offset_custom += 12;
  12272. }
  12273. }
  12274. } else if ( customAttribute.size === 4 ) {
  12275. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12276. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12277. face = obj_faces[ chunk_faces3[ f ] ];
  12278. v1 = customAttribute.value[ face.a ];
  12279. v2 = customAttribute.value[ face.b ];
  12280. v3 = customAttribute.value[ face.c ];
  12281. customAttribute.array[ offset_custom ] = v1.x;
  12282. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12283. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12284. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12285. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12286. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12287. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12288. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12289. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12290. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12291. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12292. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12293. offset_custom += 12;
  12294. }
  12295. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12296. face = obj_faces[ chunk_faces4[ f ] ];
  12297. v1 = customAttribute.value[ face.a ];
  12298. v2 = customAttribute.value[ face.b ];
  12299. v3 = customAttribute.value[ face.c ];
  12300. v4 = customAttribute.value[ face.d ];
  12301. customAttribute.array[ offset_custom ] = v1.x;
  12302. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12303. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12304. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12305. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12306. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12307. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12308. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12309. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12310. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12311. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12312. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12313. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12314. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12315. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12316. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12317. offset_custom += 16;
  12318. }
  12319. } else if ( customAttribute.boundTo === "faces" ) {
  12320. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12321. value = customAttribute.value[ chunk_faces3[ f ] ];
  12322. v1 = value;
  12323. v2 = value;
  12324. v3 = value;
  12325. customAttribute.array[ offset_custom ] = v1.x;
  12326. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12327. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12328. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12329. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12330. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12331. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12332. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12333. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12334. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12335. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12336. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12337. offset_custom += 12;
  12338. }
  12339. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12340. value = customAttribute.value[ chunk_faces4[ f ] ];
  12341. v1 = value;
  12342. v2 = value;
  12343. v3 = value;
  12344. v4 = value;
  12345. customAttribute.array[ offset_custom ] = v1.x;
  12346. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12347. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12348. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12349. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12350. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12351. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12352. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12353. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12354. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12355. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12356. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12357. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12358. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12359. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12360. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12361. offset_custom += 16;
  12362. }
  12363. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12364. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12365. value = customAttribute.value[ chunk_faces3[ f ] ];
  12366. v1 = value[ 0 ];
  12367. v2 = value[ 1 ];
  12368. v3 = value[ 2 ];
  12369. customAttribute.array[ offset_custom ] = v1.x;
  12370. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12371. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12372. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12373. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12374. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12375. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12376. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12377. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12378. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12379. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12380. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12381. offset_custom += 12;
  12382. }
  12383. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12384. value = customAttribute.value[ chunk_faces4[ f ] ];
  12385. v1 = value[ 0 ];
  12386. v2 = value[ 1 ];
  12387. v3 = value[ 2 ];
  12388. v4 = value[ 3 ];
  12389. customAttribute.array[ offset_custom ] = v1.x;
  12390. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12391. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12392. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12393. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12394. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12395. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12396. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12397. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12398. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12399. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12400. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12401. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12402. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12403. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12404. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12405. offset_custom += 16;
  12406. }
  12407. }
  12408. }
  12409. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12410. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12411. }
  12412. }
  12413. if ( dispose ) {
  12414. delete geometryGroup.__inittedArrays;
  12415. delete geometryGroup.__colorArray;
  12416. delete geometryGroup.__normalArray;
  12417. delete geometryGroup.__tangentArray;
  12418. delete geometryGroup.__uvArray;
  12419. delete geometryGroup.__uv2Array;
  12420. delete geometryGroup.__faceArray;
  12421. delete geometryGroup.__vertexArray;
  12422. delete geometryGroup.__lineArray;
  12423. delete geometryGroup.__skinIndexArray;
  12424. delete geometryGroup.__skinWeightArray;
  12425. }
  12426. };
  12427. function setDirectBuffers ( geometry, hint, dispose ) {
  12428. var attributes = geometry.attributes;
  12429. var index = attributes[ "index" ];
  12430. var position = attributes[ "position" ];
  12431. var normal = attributes[ "normal" ];
  12432. var uv = attributes[ "uv" ];
  12433. var color = attributes[ "color" ];
  12434. var tangent = attributes[ "tangent" ];
  12435. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  12436. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12437. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  12438. }
  12439. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  12440. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12441. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  12442. }
  12443. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  12444. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12445. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  12446. }
  12447. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  12448. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12449. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  12450. }
  12451. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  12452. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12453. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  12454. }
  12455. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  12456. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12457. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  12458. }
  12459. if ( dispose ) {
  12460. for ( var i in geometry.attributes ) {
  12461. delete geometry.attributes[ i ].array;
  12462. }
  12463. }
  12464. };
  12465. // Buffer rendering
  12466. this.renderBufferImmediate = function ( object, program, material ) {
  12467. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12468. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12469. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12470. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12471. if ( object.hasPositions ) {
  12472. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12473. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12474. _gl.enableVertexAttribArray( program.attributes.position );
  12475. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12476. }
  12477. if ( object.hasNormals ) {
  12478. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12479. if ( material.shading === THREE.FlatShading ) {
  12480. var nx, ny, nz,
  12481. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12482. normalArray,
  12483. i, il = object.count * 3;
  12484. for( i = 0; i < il; i += 9 ) {
  12485. normalArray = object.normalArray;
  12486. nax = normalArray[ i ];
  12487. nay = normalArray[ i + 1 ];
  12488. naz = normalArray[ i + 2 ];
  12489. nbx = normalArray[ i + 3 ];
  12490. nby = normalArray[ i + 4 ];
  12491. nbz = normalArray[ i + 5 ];
  12492. ncx = normalArray[ i + 6 ];
  12493. ncy = normalArray[ i + 7 ];
  12494. ncz = normalArray[ i + 8 ];
  12495. nx = ( nax + nbx + ncx ) / 3;
  12496. ny = ( nay + nby + ncy ) / 3;
  12497. nz = ( naz + nbz + ncz ) / 3;
  12498. normalArray[ i ] = nx;
  12499. normalArray[ i + 1 ] = ny;
  12500. normalArray[ i + 2 ] = nz;
  12501. normalArray[ i + 3 ] = nx;
  12502. normalArray[ i + 4 ] = ny;
  12503. normalArray[ i + 5 ] = nz;
  12504. normalArray[ i + 6 ] = nx;
  12505. normalArray[ i + 7 ] = ny;
  12506. normalArray[ i + 8 ] = nz;
  12507. }
  12508. }
  12509. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12510. _gl.enableVertexAttribArray( program.attributes.normal );
  12511. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12512. }
  12513. if ( object.hasUvs && material.map ) {
  12514. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12515. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12516. _gl.enableVertexAttribArray( program.attributes.uv );
  12517. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12518. }
  12519. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12520. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12521. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12522. _gl.enableVertexAttribArray( program.attributes.color );
  12523. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12524. }
  12525. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12526. object.count = 0;
  12527. };
  12528. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12529. if ( material.visible === false ) return;
  12530. var program, attributes, linewidth, primitives, a, attribute;
  12531. program = setProgram( camera, lights, fog, material, object );
  12532. attributes = program.attributes;
  12533. var updateBuffers = false,
  12534. wireframeBit = material.wireframe ? 1 : 0,
  12535. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12536. if ( geometryHash !== _currentGeometryGroupHash ) {
  12537. _currentGeometryGroupHash = geometryHash;
  12538. updateBuffers = true;
  12539. }
  12540. if ( updateBuffers ) {
  12541. disableAttributes();
  12542. }
  12543. // render mesh
  12544. if ( object instanceof THREE.Mesh ) {
  12545. var index = geometry.attributes[ "index" ];
  12546. // indexed triangles
  12547. if ( index ) {
  12548. var offsets = geometry.offsets;
  12549. // if there is more than 1 chunk
  12550. // must set attribute pointers to use new offsets for each chunk
  12551. // even if geometry and materials didn't change
  12552. if ( offsets.length > 1 ) updateBuffers = true;
  12553. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12554. var startIndex = offsets[ i ].index;
  12555. if ( updateBuffers ) {
  12556. // vertices
  12557. var position = geometry.attributes[ "position" ];
  12558. var positionSize = position.itemSize;
  12559. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12560. enableAttribute( attributes.position );
  12561. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  12562. // normals
  12563. var normal = geometry.attributes[ "normal" ];
  12564. if ( attributes.normal >= 0 && normal ) {
  12565. var normalSize = normal.itemSize;
  12566. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12567. enableAttribute( attributes.normal );
  12568. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  12569. }
  12570. // uvs
  12571. var uv = geometry.attributes[ "uv" ];
  12572. if ( attributes.uv >= 0 && uv ) {
  12573. var uvSize = uv.itemSize;
  12574. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12575. enableAttribute( attributes.uv );
  12576. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  12577. }
  12578. // colors
  12579. var color = geometry.attributes[ "color" ];
  12580. if ( attributes.color >= 0 && color ) {
  12581. var colorSize = color.itemSize;
  12582. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12583. enableAttribute( attributes.color );
  12584. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  12585. }
  12586. // tangents
  12587. var tangent = geometry.attributes[ "tangent" ];
  12588. if ( attributes.tangent >= 0 && tangent ) {
  12589. var tangentSize = tangent.itemSize;
  12590. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12591. enableAttribute( attributes.tangent );
  12592. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  12593. }
  12594. // indices
  12595. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12596. }
  12597. // render indexed triangles
  12598. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  12599. _this.info.render.calls ++;
  12600. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12601. _this.info.render.faces += offsets[ i ].count / 3;
  12602. }
  12603. // non-indexed triangles
  12604. } else {
  12605. if ( updateBuffers ) {
  12606. // vertices
  12607. var position = geometry.attributes[ "position" ];
  12608. var positionSize = position.itemSize;
  12609. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12610. enableAttribute( attributes.position );
  12611. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12612. // normals
  12613. var normal = geometry.attributes[ "normal" ];
  12614. if ( attributes.normal >= 0 && normal ) {
  12615. var normalSize = normal.itemSize;
  12616. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12617. enableAttribute( attributes.normal );
  12618. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  12619. }
  12620. // uvs
  12621. var uv = geometry.attributes[ "uv" ];
  12622. if ( attributes.uv >= 0 && uv ) {
  12623. var uvSize = uv.itemSize;
  12624. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12625. enableAttribute( attributes.uv );
  12626. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  12627. }
  12628. // colors
  12629. var color = geometry.attributes[ "color" ];
  12630. if ( attributes.color >= 0 && color ) {
  12631. var colorSize = color.itemSize;
  12632. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12633. enableAttribute( attributes.color );
  12634. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12635. }
  12636. // tangents
  12637. var tangent = geometry.attributes[ "tangent" ];
  12638. if ( attributes.tangent >= 0 && tangent ) {
  12639. var tangentSize = tangent.itemSize;
  12640. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12641. enableAttribute( attributes.tangent );
  12642. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  12643. }
  12644. }
  12645. // render non-indexed triangles
  12646. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  12647. _this.info.render.calls ++;
  12648. _this.info.render.vertices += position.numItems / 3;
  12649. _this.info.render.faces += position.numItems / 3 / 3;
  12650. }
  12651. // render particles
  12652. } else if ( object instanceof THREE.ParticleSystem ) {
  12653. if ( updateBuffers ) {
  12654. // vertices
  12655. var position = geometry.attributes[ "position" ];
  12656. var positionSize = position.itemSize;
  12657. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12658. enableAttribute( attributes.position );
  12659. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12660. // colors
  12661. var color = geometry.attributes[ "color" ];
  12662. if ( attributes.color >= 0 && color ) {
  12663. var colorSize = color.itemSize;
  12664. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12665. enableAttribute( attributes.color );
  12666. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12667. }
  12668. // render particles
  12669. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  12670. _this.info.render.calls ++;
  12671. _this.info.render.points += position.numItems / 3;
  12672. }
  12673. }
  12674. };
  12675. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12676. if ( material.visible === false ) return;
  12677. var program, attributes, linewidth, primitives, a, attribute, i, il;
  12678. program = setProgram( camera, lights, fog, material, object );
  12679. attributes = program.attributes;
  12680. var updateBuffers = false,
  12681. wireframeBit = material.wireframe ? 1 : 0,
  12682. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12683. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  12684. _currentGeometryGroupHash = geometryGroupHash;
  12685. updateBuffers = true;
  12686. }
  12687. if ( updateBuffers ) {
  12688. disableAttributes();
  12689. }
  12690. // vertices
  12691. if ( !material.morphTargets && attributes.position >= 0 ) {
  12692. if ( updateBuffers ) {
  12693. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12694. enableAttribute( attributes.position );
  12695. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12696. }
  12697. } else {
  12698. if ( object.morphTargetBase ) {
  12699. setupMorphTargets( material, geometryGroup, object );
  12700. }
  12701. }
  12702. if ( updateBuffers ) {
  12703. // custom attributes
  12704. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12705. if ( geometryGroup.__webglCustomAttributesList ) {
  12706. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12707. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12708. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12709. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12710. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12711. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12712. }
  12713. }
  12714. }
  12715. // colors
  12716. if ( attributes.color >= 0 ) {
  12717. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12718. enableAttribute( attributes.color );
  12719. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12720. }
  12721. // normals
  12722. if ( attributes.normal >= 0 ) {
  12723. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12724. enableAttribute( attributes.normal );
  12725. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12726. }
  12727. // tangents
  12728. if ( attributes.tangent >= 0 ) {
  12729. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12730. enableAttribute( attributes.tangent );
  12731. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12732. }
  12733. // uvs
  12734. if ( attributes.uv >= 0 ) {
  12735. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12736. enableAttribute( attributes.uv );
  12737. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12738. }
  12739. if ( attributes.uv2 >= 0 ) {
  12740. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12741. enableAttribute( attributes.uv2 );
  12742. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12743. }
  12744. if ( material.skinning &&
  12745. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12746. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12747. enableAttribute( attributes.skinIndex );
  12748. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12749. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12750. enableAttribute( attributes.skinWeight );
  12751. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12752. }
  12753. // line distances
  12754. if ( attributes.lineDistance >= 0 ) {
  12755. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12756. enableAttribute( attributes.lineDistance );
  12757. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12758. }
  12759. }
  12760. // render mesh
  12761. if ( object instanceof THREE.Mesh ) {
  12762. // wireframe
  12763. if ( material.wireframe ) {
  12764. setLineWidth( material.wireframeLinewidth );
  12765. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12766. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  12767. // triangles
  12768. } else {
  12769. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12770. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  12771. }
  12772. _this.info.render.calls ++;
  12773. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12774. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12775. // render lines
  12776. } else if ( object instanceof THREE.Line ) {
  12777. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12778. setLineWidth( material.linewidth );
  12779. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  12780. _this.info.render.calls ++;
  12781. // render particles
  12782. } else if ( object instanceof THREE.ParticleSystem ) {
  12783. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12784. _this.info.render.calls ++;
  12785. _this.info.render.points += geometryGroup.__webglParticleCount;
  12786. // render ribbon
  12787. } else if ( object instanceof THREE.Ribbon ) {
  12788. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  12789. _this.info.render.calls ++;
  12790. }
  12791. };
  12792. function enableAttribute( attribute ) {
  12793. if ( ! _enabledAttributes[ attribute ] ) {
  12794. _gl.enableVertexAttribArray( attribute );
  12795. _enabledAttributes[ attribute ] = true;
  12796. }
  12797. };
  12798. function disableAttributes() {
  12799. for ( var attribute in _enabledAttributes ) {
  12800. if ( _enabledAttributes[ attribute ] ) {
  12801. _gl.disableVertexAttribArray( attribute );
  12802. _enabledAttributes[ attribute ] = false;
  12803. }
  12804. }
  12805. };
  12806. function setupMorphTargets ( material, geometryGroup, object ) {
  12807. // set base
  12808. var attributes = material.program.attributes;
  12809. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  12810. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  12811. enableAttribute( attributes.position );
  12812. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12813. } else if ( attributes.position >= 0 ) {
  12814. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12815. enableAttribute( attributes.position );
  12816. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12817. }
  12818. if ( object.morphTargetForcedOrder.length ) {
  12819. // set forced order
  12820. var m = 0;
  12821. var order = object.morphTargetForcedOrder;
  12822. var influences = object.morphTargetInfluences;
  12823. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  12824. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12825. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  12826. enableAttribute( attributes[ "morphTarget" + m ] );
  12827. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12828. }
  12829. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12830. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  12831. enableAttribute( attributes[ "morphNormal" + m ] );
  12832. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12833. }
  12834. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  12835. m ++;
  12836. }
  12837. } else {
  12838. // find the most influencing
  12839. var influence, activeInfluenceIndices = [];
  12840. var influences = object.morphTargetInfluences;
  12841. var i, il = influences.length;
  12842. for ( i = 0; i < il; i ++ ) {
  12843. influence = influences[ i ];
  12844. if ( influence > 0 ) {
  12845. activeInfluenceIndices.push( [ influence, i ] );
  12846. }
  12847. }
  12848. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  12849. activeInfluenceIndices.sort( numericalSort );
  12850. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  12851. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  12852. activeInfluenceIndices.sort( numericalSort );
  12853. } else if ( activeInfluenceIndices.length === 0 ) {
  12854. activeInfluenceIndices.push( [ 0, 0 ] );
  12855. };
  12856. var influenceIndex, m = 0;
  12857. while ( m < material.numSupportedMorphTargets ) {
  12858. if ( activeInfluenceIndices[ m ] ) {
  12859. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  12860. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12861. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  12862. enableAttribute( attributes[ "morphTarget" + m ] );
  12863. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12864. }
  12865. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12866. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  12867. enableAttribute( attributes[ "morphNormal" + m ] );
  12868. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12869. }
  12870. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  12871. } else {
  12872. /*
  12873. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12874. if ( material.morphNormals ) {
  12875. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12876. }
  12877. */
  12878. object.__webglMorphTargetInfluences[ m ] = 0;
  12879. }
  12880. m ++;
  12881. }
  12882. }
  12883. // load updated influences uniform
  12884. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  12885. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  12886. }
  12887. };
  12888. // Sorting
  12889. function painterSortStable ( a, b ) {
  12890. if ( a.z !== b.z ) {
  12891. return b.z - a.z;
  12892. } else {
  12893. return b.id - a.id;
  12894. }
  12895. };
  12896. function numericalSort ( a, b ) {
  12897. return b[ 0 ] - a[ 0 ];
  12898. };
  12899. // Rendering
  12900. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12901. if ( camera instanceof THREE.Camera === false ) {
  12902. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12903. return;
  12904. }
  12905. var i, il,
  12906. webglObject, object,
  12907. renderList,
  12908. lights = scene.__lights,
  12909. fog = scene.fog;
  12910. // reset caching for this frame
  12911. _currentMaterialId = -1;
  12912. _lightsNeedUpdate = true;
  12913. // update scene graph
  12914. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  12915. // update camera matrices and frustum
  12916. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12917. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12918. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12919. _frustum.setFromMatrix( _projScreenMatrix );
  12920. // update WebGL objects
  12921. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  12922. // custom render plugins (pre pass)
  12923. renderPlugins( this.renderPluginsPre, scene, camera );
  12924. //
  12925. _this.info.render.calls = 0;
  12926. _this.info.render.vertices = 0;
  12927. _this.info.render.faces = 0;
  12928. _this.info.render.points = 0;
  12929. this.setRenderTarget( renderTarget );
  12930. if ( this.autoClear || forceClear ) {
  12931. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12932. }
  12933. // set matrices for regular objects (frustum culled)
  12934. renderList = scene.__webglObjects;
  12935. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12936. webglObject = renderList[ i ];
  12937. object = webglObject.object;
  12938. webglObject.render = false;
  12939. if ( object.visible ) {
  12940. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  12941. setupMatrices( object, camera );
  12942. unrollBufferMaterial( webglObject );
  12943. webglObject.render = true;
  12944. if ( this.sortObjects === true ) {
  12945. if ( object.renderDepth !== null ) {
  12946. webglObject.z = object.renderDepth;
  12947. } else {
  12948. _vector3.copy( object.matrixWorld.getPosition() );
  12949. _vector3.applyMatrix4( _projScreenMatrix );
  12950. webglObject.z = _vector3.z;
  12951. }
  12952. webglObject.id = object.id;
  12953. }
  12954. }
  12955. }
  12956. }
  12957. if ( this.sortObjects ) {
  12958. renderList.sort( painterSortStable );
  12959. }
  12960. // set matrices for immediate objects
  12961. renderList = scene.__webglObjectsImmediate;
  12962. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12963. webglObject = renderList[ i ];
  12964. object = webglObject.object;
  12965. if ( object.visible ) {
  12966. setupMatrices( object, camera );
  12967. unrollImmediateBufferMaterial( webglObject );
  12968. }
  12969. }
  12970. if ( scene.overrideMaterial ) {
  12971. var material = scene.overrideMaterial;
  12972. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12973. this.setDepthTest( material.depthTest );
  12974. this.setDepthWrite( material.depthWrite );
  12975. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12976. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  12977. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  12978. } else {
  12979. var material = null;
  12980. // opaque pass (front-to-back order)
  12981. this.setBlending( THREE.NoBlending );
  12982. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  12983. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  12984. // transparent pass (back-to-front order)
  12985. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  12986. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  12987. }
  12988. // custom render plugins (post pass)
  12989. renderPlugins( this.renderPluginsPost, scene, camera );
  12990. // Generate mipmap if we're using any kind of mipmap filtering
  12991. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12992. updateRenderTargetMipmap( renderTarget );
  12993. }
  12994. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12995. this.setDepthTest( true );
  12996. this.setDepthWrite( true );
  12997. // _gl.finish();
  12998. };
  12999. function renderPlugins( plugins, scene, camera ) {
  13000. if ( ! plugins.length ) return;
  13001. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13002. // reset state for plugin (to start from clean slate)
  13003. _currentProgram = null;
  13004. _currentCamera = null;
  13005. _oldBlending = -1;
  13006. _oldDepthTest = -1;
  13007. _oldDepthWrite = -1;
  13008. _oldDoubleSided = -1;
  13009. _oldFlipSided = -1;
  13010. _currentGeometryGroupHash = -1;
  13011. _currentMaterialId = -1;
  13012. _lightsNeedUpdate = true;
  13013. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13014. // reset state after plugin (anything could have changed)
  13015. _currentProgram = null;
  13016. _currentCamera = null;
  13017. _oldBlending = -1;
  13018. _oldDepthTest = -1;
  13019. _oldDepthWrite = -1;
  13020. _oldDoubleSided = -1;
  13021. _oldFlipSided = -1;
  13022. _currentGeometryGroupHash = -1;
  13023. _currentMaterialId = -1;
  13024. _lightsNeedUpdate = true;
  13025. }
  13026. };
  13027. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13028. var webglObject, object, buffer, material, start, end, delta;
  13029. if ( reverse ) {
  13030. start = renderList.length - 1;
  13031. end = -1;
  13032. delta = -1;
  13033. } else {
  13034. start = 0;
  13035. end = renderList.length;
  13036. delta = 1;
  13037. }
  13038. for ( var i = start; i !== end; i += delta ) {
  13039. webglObject = renderList[ i ];
  13040. if ( webglObject.render ) {
  13041. object = webglObject.object;
  13042. buffer = webglObject.buffer;
  13043. if ( overrideMaterial ) {
  13044. material = overrideMaterial;
  13045. } else {
  13046. material = webglObject[ materialType ];
  13047. if ( ! material ) continue;
  13048. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13049. _this.setDepthTest( material.depthTest );
  13050. _this.setDepthWrite( material.depthWrite );
  13051. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13052. }
  13053. _this.setMaterialFaces( material );
  13054. if ( buffer instanceof THREE.BufferGeometry ) {
  13055. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13056. } else {
  13057. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13058. }
  13059. }
  13060. }
  13061. };
  13062. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13063. var webglObject, object, material, program;
  13064. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13065. webglObject = renderList[ i ];
  13066. object = webglObject.object;
  13067. if ( object.visible ) {
  13068. if ( overrideMaterial ) {
  13069. material = overrideMaterial;
  13070. } else {
  13071. material = webglObject[ materialType ];
  13072. if ( ! material ) continue;
  13073. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13074. _this.setDepthTest( material.depthTest );
  13075. _this.setDepthWrite( material.depthWrite );
  13076. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13077. }
  13078. _this.renderImmediateObject( camera, lights, fog, material, object );
  13079. }
  13080. }
  13081. };
  13082. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13083. var program = setProgram( camera, lights, fog, material, object );
  13084. _currentGeometryGroupHash = -1;
  13085. _this.setMaterialFaces( material );
  13086. if ( object.immediateRenderCallback ) {
  13087. object.immediateRenderCallback( program, _gl, _frustum );
  13088. } else {
  13089. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13090. }
  13091. };
  13092. function unrollImmediateBufferMaterial ( globject ) {
  13093. var object = globject.object,
  13094. material = object.material;
  13095. if ( material.transparent ) {
  13096. globject.transparent = material;
  13097. globject.opaque = null;
  13098. } else {
  13099. globject.opaque = material;
  13100. globject.transparent = null;
  13101. }
  13102. };
  13103. function unrollBufferMaterial ( globject ) {
  13104. var object = globject.object,
  13105. buffer = globject.buffer,
  13106. material, materialIndex, meshMaterial;
  13107. meshMaterial = object.material;
  13108. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13109. materialIndex = buffer.materialIndex;
  13110. material = meshMaterial.materials[ materialIndex ];
  13111. if ( material.transparent ) {
  13112. globject.transparent = material;
  13113. globject.opaque = null;
  13114. } else {
  13115. globject.opaque = material;
  13116. globject.transparent = null;
  13117. }
  13118. } else {
  13119. material = meshMaterial;
  13120. if ( material ) {
  13121. if ( material.transparent ) {
  13122. globject.transparent = material;
  13123. globject.opaque = null;
  13124. } else {
  13125. globject.opaque = material;
  13126. globject.transparent = null;
  13127. }
  13128. }
  13129. }
  13130. };
  13131. // Geometry splitting
  13132. function sortFacesByMaterial ( geometry, material ) {
  13133. var f, fl, face, materialIndex, vertices,
  13134. groupHash, hash_map = {};
  13135. var numMorphTargets = geometry.morphTargets.length;
  13136. var numMorphNormals = geometry.morphNormals.length;
  13137. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13138. geometry.geometryGroups = {};
  13139. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13140. face = geometry.faces[ f ];
  13141. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13142. if ( hash_map[ materialIndex ] === undefined ) {
  13143. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13144. }
  13145. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13146. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13147. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13148. }
  13149. vertices = face instanceof THREE.Face3 ? 3 : 4;
  13150. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13151. hash_map[ materialIndex ].counter += 1;
  13152. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13153. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13154. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13155. }
  13156. }
  13157. if ( face instanceof THREE.Face3 ) {
  13158. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13159. } else {
  13160. geometry.geometryGroups[ groupHash ].faces4.push( f );
  13161. }
  13162. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13163. }
  13164. geometry.geometryGroupsList = [];
  13165. for ( var g in geometry.geometryGroups ) {
  13166. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13167. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13168. }
  13169. };
  13170. // Objects refresh
  13171. this.initWebGLObjects = function ( scene ) {
  13172. if ( !scene.__webglObjects ) {
  13173. scene.__webglObjects = [];
  13174. scene.__webglObjectsImmediate = [];
  13175. scene.__webglSprites = [];
  13176. scene.__webglFlares = [];
  13177. }
  13178. while ( scene.__objectsAdded.length ) {
  13179. addObject( scene.__objectsAdded[ 0 ], scene );
  13180. scene.__objectsAdded.splice( 0, 1 );
  13181. }
  13182. while ( scene.__objectsRemoved.length ) {
  13183. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13184. scene.__objectsRemoved.splice( 0, 1 );
  13185. }
  13186. // update must be called after objects adding / removal
  13187. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13188. updateObject( scene.__webglObjects[ o ].object );
  13189. }
  13190. };
  13191. // Objects adding
  13192. function addObject ( object, scene ) {
  13193. var g, geometry, material, geometryGroup;
  13194. if ( ! object.__webglInit ) {
  13195. object.__webglInit = true;
  13196. object._modelViewMatrix = new THREE.Matrix4();
  13197. object._normalMatrix = new THREE.Matrix3();
  13198. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13199. object.geometry.__webglInit = true;
  13200. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13201. }
  13202. if ( object instanceof THREE.Mesh ) {
  13203. geometry = object.geometry;
  13204. material = object.material;
  13205. if ( geometry instanceof THREE.Geometry ) {
  13206. if ( geometry.geometryGroups === undefined ) {
  13207. sortFacesByMaterial( geometry, material );
  13208. }
  13209. // create separate VBOs per geometry chunk
  13210. for ( g in geometry.geometryGroups ) {
  13211. geometryGroup = geometry.geometryGroups[ g ];
  13212. // initialise VBO on the first access
  13213. if ( ! geometryGroup.__webglVertexBuffer ) {
  13214. createMeshBuffers( geometryGroup );
  13215. initMeshBuffers( geometryGroup, object );
  13216. geometry.verticesNeedUpdate = true;
  13217. geometry.morphTargetsNeedUpdate = true;
  13218. geometry.elementsNeedUpdate = true;
  13219. geometry.uvsNeedUpdate = true;
  13220. geometry.normalsNeedUpdate = true;
  13221. geometry.tangentsNeedUpdate = true;
  13222. geometry.colorsNeedUpdate = true;
  13223. }
  13224. }
  13225. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13226. initDirectBuffers( geometry );
  13227. }
  13228. } else if ( object instanceof THREE.Ribbon ) {
  13229. geometry = object.geometry;
  13230. if ( ! geometry.__webglVertexBuffer ) {
  13231. createRibbonBuffers( geometry );
  13232. initRibbonBuffers( geometry, object );
  13233. geometry.verticesNeedUpdate = true;
  13234. geometry.colorsNeedUpdate = true;
  13235. geometry.normalsNeedUpdate = true;
  13236. }
  13237. } else if ( object instanceof THREE.Line ) {
  13238. geometry = object.geometry;
  13239. if ( ! geometry.__webglVertexBuffer ) {
  13240. createLineBuffers( geometry );
  13241. initLineBuffers( geometry, object );
  13242. geometry.verticesNeedUpdate = true;
  13243. geometry.colorsNeedUpdate = true;
  13244. geometry.lineDistancesNeedUpdate = true;
  13245. }
  13246. } else if ( object instanceof THREE.ParticleSystem ) {
  13247. geometry = object.geometry;
  13248. if ( ! geometry.__webglVertexBuffer ) {
  13249. if ( geometry instanceof THREE.Geometry ) {
  13250. createParticleBuffers( geometry );
  13251. initParticleBuffers( geometry, object );
  13252. geometry.verticesNeedUpdate = true;
  13253. geometry.colorsNeedUpdate = true;
  13254. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13255. initDirectBuffers( geometry );
  13256. }
  13257. }
  13258. }
  13259. }
  13260. if ( ! object.__webglActive ) {
  13261. if ( object instanceof THREE.Mesh ) {
  13262. geometry = object.geometry;
  13263. if ( geometry instanceof THREE.BufferGeometry ) {
  13264. addBuffer( scene.__webglObjects, geometry, object );
  13265. } else if ( geometry instanceof THREE.Geometry ) {
  13266. for ( g in geometry.geometryGroups ) {
  13267. geometryGroup = geometry.geometryGroups[ g ];
  13268. addBuffer( scene.__webglObjects, geometryGroup, object );
  13269. }
  13270. }
  13271. } else if ( object instanceof THREE.Ribbon ||
  13272. object instanceof THREE.Line ||
  13273. object instanceof THREE.ParticleSystem ) {
  13274. geometry = object.geometry;
  13275. addBuffer( scene.__webglObjects, geometry, object );
  13276. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13277. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13278. } else if ( object instanceof THREE.Sprite ) {
  13279. scene.__webglSprites.push( object );
  13280. } else if ( object instanceof THREE.LensFlare ) {
  13281. scene.__webglFlares.push( object );
  13282. }
  13283. object.__webglActive = true;
  13284. }
  13285. };
  13286. function addBuffer ( objlist, buffer, object ) {
  13287. objlist.push(
  13288. {
  13289. buffer: buffer,
  13290. object: object,
  13291. opaque: null,
  13292. transparent: null
  13293. }
  13294. );
  13295. };
  13296. function addBufferImmediate ( objlist, object ) {
  13297. objlist.push(
  13298. {
  13299. object: object,
  13300. opaque: null,
  13301. transparent: null
  13302. }
  13303. );
  13304. };
  13305. // Objects updates
  13306. function updateObject ( object ) {
  13307. var geometry = object.geometry,
  13308. geometryGroup, customAttributesDirty, material;
  13309. if ( object instanceof THREE.Mesh ) {
  13310. if ( geometry instanceof THREE.BufferGeometry ) {
  13311. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  13312. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13313. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  13314. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13315. }
  13316. geometry.verticesNeedUpdate = false;
  13317. geometry.elementsNeedUpdate = false;
  13318. geometry.uvsNeedUpdate = false;
  13319. geometry.normalsNeedUpdate = false;
  13320. geometry.colorsNeedUpdate = false;
  13321. geometry.tangentsNeedUpdate = false;
  13322. } else {
  13323. // check all geometry groups
  13324. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13325. geometryGroup = geometry.geometryGroupsList[ i ];
  13326. material = getBufferMaterial( object, geometryGroup );
  13327. if ( geometry.buffersNeedUpdate ) {
  13328. initMeshBuffers( geometryGroup, object );
  13329. }
  13330. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13331. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13332. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13333. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13334. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13335. }
  13336. }
  13337. geometry.verticesNeedUpdate = false;
  13338. geometry.morphTargetsNeedUpdate = false;
  13339. geometry.elementsNeedUpdate = false;
  13340. geometry.uvsNeedUpdate = false;
  13341. geometry.normalsNeedUpdate = false;
  13342. geometry.colorsNeedUpdate = false;
  13343. geometry.tangentsNeedUpdate = false;
  13344. geometry.buffersNeedUpdate = false;
  13345. material.attributes && clearCustomAttributes( material );
  13346. }
  13347. } else if ( object instanceof THREE.Ribbon ) {
  13348. material = getBufferMaterial( object, geometry );
  13349. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13350. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  13351. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  13352. }
  13353. geometry.verticesNeedUpdate = false;
  13354. geometry.colorsNeedUpdate = false;
  13355. geometry.normalsNeedUpdate = false;
  13356. material.attributes && clearCustomAttributes( material );
  13357. } else if ( object instanceof THREE.Line ) {
  13358. material = getBufferMaterial( object, geometry );
  13359. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13360. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13361. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13362. }
  13363. geometry.verticesNeedUpdate = false;
  13364. geometry.colorsNeedUpdate = false;
  13365. geometry.lineDistancesNeedUpdate = false;
  13366. material.attributes && clearCustomAttributes( material );
  13367. } else if ( object instanceof THREE.ParticleSystem ) {
  13368. if ( geometry instanceof THREE.BufferGeometry ) {
  13369. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  13370. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13371. }
  13372. geometry.verticesNeedUpdate = false;
  13373. geometry.colorsNeedUpdate = false;
  13374. } else {
  13375. material = getBufferMaterial( object, geometry );
  13376. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13377. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13378. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13379. }
  13380. geometry.verticesNeedUpdate = false;
  13381. geometry.colorsNeedUpdate = false;
  13382. material.attributes && clearCustomAttributes( material );
  13383. }
  13384. }
  13385. };
  13386. // Objects updates - custom attributes check
  13387. function areCustomAttributesDirty ( material ) {
  13388. for ( var a in material.attributes ) {
  13389. if ( material.attributes[ a ].needsUpdate ) return true;
  13390. }
  13391. return false;
  13392. };
  13393. function clearCustomAttributes ( material ) {
  13394. for ( var a in material.attributes ) {
  13395. material.attributes[ a ].needsUpdate = false;
  13396. }
  13397. };
  13398. // Objects removal
  13399. function removeObject ( object, scene ) {
  13400. if ( object instanceof THREE.Mesh ||
  13401. object instanceof THREE.ParticleSystem ||
  13402. object instanceof THREE.Ribbon ||
  13403. object instanceof THREE.Line ) {
  13404. removeInstances( scene.__webglObjects, object );
  13405. } else if ( object instanceof THREE.Sprite ) {
  13406. removeInstancesDirect( scene.__webglSprites, object );
  13407. } else if ( object instanceof THREE.LensFlare ) {
  13408. removeInstancesDirect( scene.__webglFlares, object );
  13409. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13410. removeInstances( scene.__webglObjectsImmediate, object );
  13411. }
  13412. object.__webglActive = false;
  13413. };
  13414. function removeInstances ( objlist, object ) {
  13415. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13416. if ( objlist[ o ].object === object ) {
  13417. objlist.splice( o, 1 );
  13418. }
  13419. }
  13420. };
  13421. function removeInstancesDirect ( objlist, object ) {
  13422. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13423. if ( objlist[ o ] === object ) {
  13424. objlist.splice( o, 1 );
  13425. }
  13426. }
  13427. };
  13428. // Materials
  13429. this.initMaterial = function ( material, lights, fog, object ) {
  13430. material.addEventListener( 'dispose', onMaterialDispose );
  13431. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13432. if ( material instanceof THREE.MeshDepthMaterial ) {
  13433. shaderID = 'depth';
  13434. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13435. shaderID = 'normal';
  13436. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13437. shaderID = 'basic';
  13438. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13439. shaderID = 'lambert';
  13440. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13441. shaderID = 'phong';
  13442. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13443. shaderID = 'basic';
  13444. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13445. shaderID = 'dashed';
  13446. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13447. shaderID = 'particle_basic';
  13448. }
  13449. if ( shaderID ) {
  13450. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13451. }
  13452. // heuristics to create shader parameters according to lights in the scene
  13453. // (not to blow over maxLights budget)
  13454. maxLightCount = allocateLights( lights );
  13455. maxShadows = allocateShadows( lights );
  13456. maxBones = allocateBones( object );
  13457. parameters = {
  13458. map: !!material.map,
  13459. envMap: !!material.envMap,
  13460. lightMap: !!material.lightMap,
  13461. bumpMap: !!material.bumpMap,
  13462. normalMap: !!material.normalMap,
  13463. specularMap: !!material.specularMap,
  13464. vertexColors: material.vertexColors,
  13465. fog: fog,
  13466. useFog: material.fog,
  13467. fogExp: fog instanceof THREE.FogExp2,
  13468. sizeAttenuation: material.sizeAttenuation,
  13469. skinning: material.skinning,
  13470. maxBones: maxBones,
  13471. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13472. boneTextureWidth: object && object.boneTextureWidth,
  13473. boneTextureHeight: object && object.boneTextureHeight,
  13474. morphTargets: material.morphTargets,
  13475. morphNormals: material.morphNormals,
  13476. maxMorphTargets: this.maxMorphTargets,
  13477. maxMorphNormals: this.maxMorphNormals,
  13478. maxDirLights: maxLightCount.directional,
  13479. maxPointLights: maxLightCount.point,
  13480. maxSpotLights: maxLightCount.spot,
  13481. maxHemiLights: maxLightCount.hemi,
  13482. maxShadows: maxShadows,
  13483. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13484. shadowMapType: this.shadowMapType,
  13485. shadowMapDebug: this.shadowMapDebug,
  13486. shadowMapCascade: this.shadowMapCascade,
  13487. alphaTest: material.alphaTest,
  13488. metal: material.metal,
  13489. perPixel: material.perPixel,
  13490. wrapAround: material.wrapAround,
  13491. doubleSided: material.side === THREE.DoubleSide,
  13492. flipSided: material.side === THREE.BackSide
  13493. };
  13494. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13495. var attributes = material.program.attributes;
  13496. if ( material.morphTargets ) {
  13497. material.numSupportedMorphTargets = 0;
  13498. var id, base = "morphTarget";
  13499. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13500. id = base + i;
  13501. if ( attributes[ id ] >= 0 ) {
  13502. material.numSupportedMorphTargets ++;
  13503. }
  13504. }
  13505. }
  13506. if ( material.morphNormals ) {
  13507. material.numSupportedMorphNormals = 0;
  13508. var id, base = "morphNormal";
  13509. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13510. id = base + i;
  13511. if ( attributes[ id ] >= 0 ) {
  13512. material.numSupportedMorphNormals ++;
  13513. }
  13514. }
  13515. }
  13516. material.uniformsList = [];
  13517. for ( u in material.uniforms ) {
  13518. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13519. }
  13520. };
  13521. function setMaterialShaders( material, shaders ) {
  13522. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13523. material.vertexShader = shaders.vertexShader;
  13524. material.fragmentShader = shaders.fragmentShader;
  13525. };
  13526. function setProgram( camera, lights, fog, material, object ) {
  13527. _usedTextureUnits = 0;
  13528. if ( material.needsUpdate ) {
  13529. if ( material.program ) deallocateMaterial( material );
  13530. _this.initMaterial( material, lights, fog, object );
  13531. material.needsUpdate = false;
  13532. }
  13533. if ( material.morphTargets ) {
  13534. if ( ! object.__webglMorphTargetInfluences ) {
  13535. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13536. }
  13537. }
  13538. var refreshMaterial = false;
  13539. var program = material.program,
  13540. p_uniforms = program.uniforms,
  13541. m_uniforms = material.uniforms;
  13542. if ( program !== _currentProgram ) {
  13543. _gl.useProgram( program );
  13544. _currentProgram = program;
  13545. refreshMaterial = true;
  13546. }
  13547. if ( material.id !== _currentMaterialId ) {
  13548. _currentMaterialId = material.id;
  13549. refreshMaterial = true;
  13550. }
  13551. if ( refreshMaterial || camera !== _currentCamera ) {
  13552. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13553. if ( camera !== _currentCamera ) _currentCamera = camera;
  13554. }
  13555. // skinning uniforms must be set even if material didn't change
  13556. // auto-setting of texture unit for bone texture must go before other textures
  13557. // not sure why, but otherwise weird things happen
  13558. if ( material.skinning ) {
  13559. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13560. if ( p_uniforms.boneTexture !== null ) {
  13561. var textureUnit = getTextureUnit();
  13562. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13563. _this.setTexture( object.boneTexture, textureUnit );
  13564. }
  13565. } else {
  13566. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13567. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  13568. }
  13569. }
  13570. }
  13571. if ( refreshMaterial ) {
  13572. // refresh uniforms common to several materials
  13573. if ( fog && material.fog ) {
  13574. refreshUniformsFog( m_uniforms, fog );
  13575. }
  13576. if ( material instanceof THREE.MeshPhongMaterial ||
  13577. material instanceof THREE.MeshLambertMaterial ||
  13578. material.lights ) {
  13579. if ( _lightsNeedUpdate ) {
  13580. setupLights( program, lights );
  13581. _lightsNeedUpdate = false;
  13582. }
  13583. refreshUniformsLights( m_uniforms, _lights );
  13584. }
  13585. if ( material instanceof THREE.MeshBasicMaterial ||
  13586. material instanceof THREE.MeshLambertMaterial ||
  13587. material instanceof THREE.MeshPhongMaterial ) {
  13588. refreshUniformsCommon( m_uniforms, material );
  13589. }
  13590. // refresh single material specific uniforms
  13591. if ( material instanceof THREE.LineBasicMaterial ) {
  13592. refreshUniformsLine( m_uniforms, material );
  13593. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13594. refreshUniformsLine( m_uniforms, material );
  13595. refreshUniformsDash( m_uniforms, material );
  13596. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13597. refreshUniformsParticle( m_uniforms, material );
  13598. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13599. refreshUniformsPhong( m_uniforms, material );
  13600. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13601. refreshUniformsLambert( m_uniforms, material );
  13602. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13603. m_uniforms.mNear.value = camera.near;
  13604. m_uniforms.mFar.value = camera.far;
  13605. m_uniforms.opacity.value = material.opacity;
  13606. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13607. m_uniforms.opacity.value = material.opacity;
  13608. }
  13609. if ( object.receiveShadow && ! material._shadowPass ) {
  13610. refreshUniformsShadow( m_uniforms, lights );
  13611. }
  13612. // load common uniforms
  13613. loadUniformsGeneric( program, material.uniformsList );
  13614. // load material specific uniforms
  13615. // (shader material also gets them for the sake of genericity)
  13616. if ( material instanceof THREE.ShaderMaterial ||
  13617. material instanceof THREE.MeshPhongMaterial ||
  13618. material.envMap ) {
  13619. if ( p_uniforms.cameraPosition !== null ) {
  13620. var position = camera.matrixWorld.getPosition();
  13621. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  13622. }
  13623. }
  13624. if ( material instanceof THREE.MeshPhongMaterial ||
  13625. material instanceof THREE.MeshLambertMaterial ||
  13626. material instanceof THREE.ShaderMaterial ||
  13627. material.skinning ) {
  13628. if ( p_uniforms.viewMatrix !== null ) {
  13629. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13630. }
  13631. }
  13632. }
  13633. loadUniformsMatrices( p_uniforms, object );
  13634. if ( p_uniforms.modelMatrix !== null ) {
  13635. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13636. }
  13637. return program;
  13638. };
  13639. // Uniforms (refresh uniforms objects)
  13640. function refreshUniformsCommon ( uniforms, material ) {
  13641. uniforms.opacity.value = material.opacity;
  13642. if ( _this.gammaInput ) {
  13643. uniforms.diffuse.value.copyGammaToLinear( material.color );
  13644. } else {
  13645. uniforms.diffuse.value = material.color;
  13646. }
  13647. uniforms.map.value = material.map;
  13648. uniforms.lightMap.value = material.lightMap;
  13649. uniforms.specularMap.value = material.specularMap;
  13650. if ( material.bumpMap ) {
  13651. uniforms.bumpMap.value = material.bumpMap;
  13652. uniforms.bumpScale.value = material.bumpScale;
  13653. }
  13654. if ( material.normalMap ) {
  13655. uniforms.normalMap.value = material.normalMap;
  13656. uniforms.normalScale.value.copy( material.normalScale );
  13657. }
  13658. // uv repeat and offset setting priorities
  13659. // 1. color map
  13660. // 2. specular map
  13661. // 3. normal map
  13662. // 4. bump map
  13663. var uvScaleMap;
  13664. if ( material.map ) {
  13665. uvScaleMap = material.map;
  13666. } else if ( material.specularMap ) {
  13667. uvScaleMap = material.specularMap;
  13668. } else if ( material.normalMap ) {
  13669. uvScaleMap = material.normalMap;
  13670. } else if ( material.bumpMap ) {
  13671. uvScaleMap = material.bumpMap;
  13672. }
  13673. if ( uvScaleMap !== undefined ) {
  13674. var offset = uvScaleMap.offset;
  13675. var repeat = uvScaleMap.repeat;
  13676. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13677. }
  13678. uniforms.envMap.value = material.envMap;
  13679. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  13680. if ( _this.gammaInput ) {
  13681. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  13682. uniforms.reflectivity.value = material.reflectivity;
  13683. } else {
  13684. uniforms.reflectivity.value = material.reflectivity;
  13685. }
  13686. uniforms.refractionRatio.value = material.refractionRatio;
  13687. uniforms.combine.value = material.combine;
  13688. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  13689. };
  13690. function refreshUniformsLine ( uniforms, material ) {
  13691. uniforms.diffuse.value = material.color;
  13692. uniforms.opacity.value = material.opacity;
  13693. };
  13694. function refreshUniformsDash ( uniforms, material ) {
  13695. uniforms.dashSize.value = material.dashSize;
  13696. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13697. uniforms.scale.value = material.scale;
  13698. };
  13699. function refreshUniformsParticle ( uniforms, material ) {
  13700. uniforms.psColor.value = material.color;
  13701. uniforms.opacity.value = material.opacity;
  13702. uniforms.size.value = material.size;
  13703. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13704. uniforms.map.value = material.map;
  13705. };
  13706. function refreshUniformsFog ( uniforms, fog ) {
  13707. uniforms.fogColor.value = fog.color;
  13708. if ( fog instanceof THREE.Fog ) {
  13709. uniforms.fogNear.value = fog.near;
  13710. uniforms.fogFar.value = fog.far;
  13711. } else if ( fog instanceof THREE.FogExp2 ) {
  13712. uniforms.fogDensity.value = fog.density;
  13713. }
  13714. };
  13715. function refreshUniformsPhong ( uniforms, material ) {
  13716. uniforms.shininess.value = material.shininess;
  13717. if ( _this.gammaInput ) {
  13718. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13719. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13720. uniforms.specular.value.copyGammaToLinear( material.specular );
  13721. } else {
  13722. uniforms.ambient.value = material.ambient;
  13723. uniforms.emissive.value = material.emissive;
  13724. uniforms.specular.value = material.specular;
  13725. }
  13726. if ( material.wrapAround ) {
  13727. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13728. }
  13729. };
  13730. function refreshUniformsLambert ( uniforms, material ) {
  13731. if ( _this.gammaInput ) {
  13732. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13733. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13734. } else {
  13735. uniforms.ambient.value = material.ambient;
  13736. uniforms.emissive.value = material.emissive;
  13737. }
  13738. if ( material.wrapAround ) {
  13739. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13740. }
  13741. };
  13742. function refreshUniformsLights ( uniforms, lights ) {
  13743. uniforms.ambientLightColor.value = lights.ambient;
  13744. uniforms.directionalLightColor.value = lights.directional.colors;
  13745. uniforms.directionalLightDirection.value = lights.directional.positions;
  13746. uniforms.pointLightColor.value = lights.point.colors;
  13747. uniforms.pointLightPosition.value = lights.point.positions;
  13748. uniforms.pointLightDistance.value = lights.point.distances;
  13749. uniforms.spotLightColor.value = lights.spot.colors;
  13750. uniforms.spotLightPosition.value = lights.spot.positions;
  13751. uniforms.spotLightDistance.value = lights.spot.distances;
  13752. uniforms.spotLightDirection.value = lights.spot.directions;
  13753. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13754. uniforms.spotLightExponent.value = lights.spot.exponents;
  13755. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13756. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13757. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13758. };
  13759. function refreshUniformsShadow ( uniforms, lights ) {
  13760. if ( uniforms.shadowMatrix ) {
  13761. var j = 0;
  13762. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13763. var light = lights[ i ];
  13764. if ( ! light.castShadow ) continue;
  13765. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13766. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13767. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13768. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13769. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13770. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13771. j ++;
  13772. }
  13773. }
  13774. }
  13775. };
  13776. // Uniforms (load to GPU)
  13777. function loadUniformsMatrices ( uniforms, object ) {
  13778. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13779. if ( uniforms.normalMatrix ) {
  13780. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13781. }
  13782. };
  13783. function getTextureUnit() {
  13784. var textureUnit = _usedTextureUnits;
  13785. if ( textureUnit >= _maxTextures ) {
  13786. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  13787. }
  13788. _usedTextureUnits += 1;
  13789. return textureUnit;
  13790. };
  13791. function loadUniformsGeneric ( program, uniforms ) {
  13792. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  13793. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13794. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  13795. if ( !location ) continue;
  13796. uniform = uniforms[ j ][ 0 ];
  13797. type = uniform.type;
  13798. value = uniform.value;
  13799. if ( type === "i" ) { // single integer
  13800. _gl.uniform1i( location, value );
  13801. } else if ( type === "f" ) { // single float
  13802. _gl.uniform1f( location, value );
  13803. } else if ( type === "v2" ) { // single THREE.Vector2
  13804. _gl.uniform2f( location, value.x, value.y );
  13805. } else if ( type === "v3" ) { // single THREE.Vector3
  13806. _gl.uniform3f( location, value.x, value.y, value.z );
  13807. } else if ( type === "v4" ) { // single THREE.Vector4
  13808. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13809. } else if ( type === "c" ) { // single THREE.Color
  13810. _gl.uniform3f( location, value.r, value.g, value.b );
  13811. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  13812. _gl.uniform1iv( location, value );
  13813. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  13814. _gl.uniform3iv( location, value );
  13815. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  13816. _gl.uniform1fv( location, value );
  13817. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  13818. _gl.uniform3fv( location, value );
  13819. } else if ( type === "v2v" ) { // array of THREE.Vector2
  13820. if ( uniform._array === undefined ) {
  13821. uniform._array = new Float32Array( 2 * value.length );
  13822. }
  13823. for ( i = 0, il = value.length; i < il; i ++ ) {
  13824. offset = i * 2;
  13825. uniform._array[ offset ] = value[ i ].x;
  13826. uniform._array[ offset + 1 ] = value[ i ].y;
  13827. }
  13828. _gl.uniform2fv( location, uniform._array );
  13829. } else if ( type === "v3v" ) { // array of THREE.Vector3
  13830. if ( uniform._array === undefined ) {
  13831. uniform._array = new Float32Array( 3 * value.length );
  13832. }
  13833. for ( i = 0, il = value.length; i < il; i ++ ) {
  13834. offset = i * 3;
  13835. uniform._array[ offset ] = value[ i ].x;
  13836. uniform._array[ offset + 1 ] = value[ i ].y;
  13837. uniform._array[ offset + 2 ] = value[ i ].z;
  13838. }
  13839. _gl.uniform3fv( location, uniform._array );
  13840. } else if ( type === "v4v" ) { // array of THREE.Vector4
  13841. if ( uniform._array === undefined ) {
  13842. uniform._array = new Float32Array( 4 * value.length );
  13843. }
  13844. for ( i = 0, il = value.length; i < il; i ++ ) {
  13845. offset = i * 4;
  13846. uniform._array[ offset ] = value[ i ].x;
  13847. uniform._array[ offset + 1 ] = value[ i ].y;
  13848. uniform._array[ offset + 2 ] = value[ i ].z;
  13849. uniform._array[ offset + 3 ] = value[ i ].w;
  13850. }
  13851. _gl.uniform4fv( location, uniform._array );
  13852. } else if ( type === "m4") { // single THREE.Matrix4
  13853. if ( uniform._array === undefined ) {
  13854. uniform._array = new Float32Array( 16 );
  13855. }
  13856. value.flattenToArray( uniform._array );
  13857. _gl.uniformMatrix4fv( location, false, uniform._array );
  13858. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  13859. if ( uniform._array === undefined ) {
  13860. uniform._array = new Float32Array( 16 * value.length );
  13861. }
  13862. for ( i = 0, il = value.length; i < il; i ++ ) {
  13863. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  13864. }
  13865. _gl.uniformMatrix4fv( location, false, uniform._array );
  13866. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  13867. texture = value;
  13868. textureUnit = getTextureUnit();
  13869. _gl.uniform1i( location, textureUnit );
  13870. if ( !texture ) continue;
  13871. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  13872. setCubeTexture( texture, textureUnit );
  13873. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  13874. setCubeTextureDynamic( texture, textureUnit );
  13875. } else {
  13876. _this.setTexture( texture, textureUnit );
  13877. }
  13878. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  13879. if ( uniform._array === undefined ) {
  13880. uniform._array = [];
  13881. }
  13882. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13883. uniform._array[ i ] = getTextureUnit();
  13884. }
  13885. _gl.uniform1iv( location, uniform._array );
  13886. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13887. texture = uniform.value[ i ];
  13888. textureUnit = uniform._array[ i ];
  13889. if ( !texture ) continue;
  13890. _this.setTexture( texture, textureUnit );
  13891. }
  13892. }
  13893. }
  13894. };
  13895. function setupMatrices ( object, camera ) {
  13896. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  13897. object._normalMatrix.getInverse( object._modelViewMatrix );
  13898. object._normalMatrix.transpose();
  13899. };
  13900. //
  13901. function setColorGamma( array, offset, color, intensitySq ) {
  13902. array[ offset ] = color.r * color.r * intensitySq;
  13903. array[ offset + 1 ] = color.g * color.g * intensitySq;
  13904. array[ offset + 2 ] = color.b * color.b * intensitySq;
  13905. };
  13906. function setColorLinear( array, offset, color, intensity ) {
  13907. array[ offset ] = color.r * intensity;
  13908. array[ offset + 1 ] = color.g * intensity;
  13909. array[ offset + 2 ] = color.b * intensity;
  13910. };
  13911. function setupLights ( program, lights ) {
  13912. var l, ll, light, n,
  13913. r = 0, g = 0, b = 0,
  13914. color, skyColor, groundColor,
  13915. intensity, intensitySq,
  13916. position,
  13917. distance,
  13918. zlights = _lights,
  13919. dirColors = zlights.directional.colors,
  13920. dirPositions = zlights.directional.positions,
  13921. pointColors = zlights.point.colors,
  13922. pointPositions = zlights.point.positions,
  13923. pointDistances = zlights.point.distances,
  13924. spotColors = zlights.spot.colors,
  13925. spotPositions = zlights.spot.positions,
  13926. spotDistances = zlights.spot.distances,
  13927. spotDirections = zlights.spot.directions,
  13928. spotAnglesCos = zlights.spot.anglesCos,
  13929. spotExponents = zlights.spot.exponents,
  13930. hemiSkyColors = zlights.hemi.skyColors,
  13931. hemiGroundColors = zlights.hemi.groundColors,
  13932. hemiPositions = zlights.hemi.positions,
  13933. dirLength = 0,
  13934. pointLength = 0,
  13935. spotLength = 0,
  13936. hemiLength = 0,
  13937. dirCount = 0,
  13938. pointCount = 0,
  13939. spotCount = 0,
  13940. hemiCount = 0,
  13941. dirOffset = 0,
  13942. pointOffset = 0,
  13943. spotOffset = 0,
  13944. hemiOffset = 0;
  13945. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13946. light = lights[ l ];
  13947. if ( light.onlyShadow ) continue;
  13948. color = light.color;
  13949. intensity = light.intensity;
  13950. distance = light.distance;
  13951. if ( light instanceof THREE.AmbientLight ) {
  13952. if ( ! light.visible ) continue;
  13953. if ( _this.gammaInput ) {
  13954. r += color.r * color.r;
  13955. g += color.g * color.g;
  13956. b += color.b * color.b;
  13957. } else {
  13958. r += color.r;
  13959. g += color.g;
  13960. b += color.b;
  13961. }
  13962. } else if ( light instanceof THREE.DirectionalLight ) {
  13963. dirCount += 1;
  13964. if ( ! light.visible ) continue;
  13965. _direction.copy( light.matrixWorld.getPosition() );
  13966. _direction.sub( light.target.matrixWorld.getPosition() );
  13967. _direction.normalize();
  13968. // skip lights with undefined direction
  13969. // these create troubles in OpenGL (making pixel black)
  13970. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13971. dirOffset = dirLength * 3;
  13972. dirPositions[ dirOffset ] = _direction.x;
  13973. dirPositions[ dirOffset + 1 ] = _direction.y;
  13974. dirPositions[ dirOffset + 2 ] = _direction.z;
  13975. if ( _this.gammaInput ) {
  13976. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  13977. } else {
  13978. setColorLinear( dirColors, dirOffset, color, intensity );
  13979. }
  13980. dirLength += 1;
  13981. } else if ( light instanceof THREE.PointLight ) {
  13982. pointCount += 1;
  13983. if ( ! light.visible ) continue;
  13984. pointOffset = pointLength * 3;
  13985. if ( _this.gammaInput ) {
  13986. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  13987. } else {
  13988. setColorLinear( pointColors, pointOffset, color, intensity );
  13989. }
  13990. position = light.matrixWorld.getPosition();
  13991. pointPositions[ pointOffset ] = position.x;
  13992. pointPositions[ pointOffset + 1 ] = position.y;
  13993. pointPositions[ pointOffset + 2 ] = position.z;
  13994. pointDistances[ pointLength ] = distance;
  13995. pointLength += 1;
  13996. } else if ( light instanceof THREE.SpotLight ) {
  13997. spotCount += 1;
  13998. if ( ! light.visible ) continue;
  13999. spotOffset = spotLength * 3;
  14000. if ( _this.gammaInput ) {
  14001. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14002. } else {
  14003. setColorLinear( spotColors, spotOffset, color, intensity );
  14004. }
  14005. position = light.matrixWorld.getPosition();
  14006. spotPositions[ spotOffset ] = position.x;
  14007. spotPositions[ spotOffset + 1 ] = position.y;
  14008. spotPositions[ spotOffset + 2 ] = position.z;
  14009. spotDistances[ spotLength ] = distance;
  14010. _direction.copy( position );
  14011. _direction.sub( light.target.matrixWorld.getPosition() );
  14012. _direction.normalize();
  14013. spotDirections[ spotOffset ] = _direction.x;
  14014. spotDirections[ spotOffset + 1 ] = _direction.y;
  14015. spotDirections[ spotOffset + 2 ] = _direction.z;
  14016. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14017. spotExponents[ spotLength ] = light.exponent;
  14018. spotLength += 1;
  14019. } else if ( light instanceof THREE.HemisphereLight ) {
  14020. hemiCount += 1;
  14021. if ( ! light.visible ) continue;
  14022. _direction.copy( light.matrixWorld.getPosition() );
  14023. _direction.normalize();
  14024. // skip lights with undefined direction
  14025. // these create troubles in OpenGL (making pixel black)
  14026. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14027. hemiOffset = hemiLength * 3;
  14028. hemiPositions[ hemiOffset ] = _direction.x;
  14029. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14030. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14031. skyColor = light.color;
  14032. groundColor = light.groundColor;
  14033. if ( _this.gammaInput ) {
  14034. intensitySq = intensity * intensity;
  14035. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14036. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14037. } else {
  14038. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14039. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14040. }
  14041. hemiLength += 1;
  14042. }
  14043. }
  14044. // null eventual remains from removed lights
  14045. // (this is to avoid if in shader)
  14046. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14047. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14048. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14049. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14050. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14051. zlights.directional.length = dirLength;
  14052. zlights.point.length = pointLength;
  14053. zlights.spot.length = spotLength;
  14054. zlights.hemi.length = hemiLength;
  14055. zlights.ambient[ 0 ] = r;
  14056. zlights.ambient[ 1 ] = g;
  14057. zlights.ambient[ 2 ] = b;
  14058. };
  14059. // GL state setting
  14060. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14061. if ( cullFace === THREE.CullFaceNone ) {
  14062. _gl.disable( _gl.CULL_FACE );
  14063. } else {
  14064. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14065. _gl.frontFace( _gl.CW );
  14066. } else {
  14067. _gl.frontFace( _gl.CCW );
  14068. }
  14069. if ( cullFace === THREE.CullFaceBack ) {
  14070. _gl.cullFace( _gl.BACK );
  14071. } else if ( cullFace === THREE.CullFaceFront ) {
  14072. _gl.cullFace( _gl.FRONT );
  14073. } else {
  14074. _gl.cullFace( _gl.FRONT_AND_BACK );
  14075. }
  14076. _gl.enable( _gl.CULL_FACE );
  14077. }
  14078. };
  14079. this.setMaterialFaces = function ( material ) {
  14080. var doubleSided = material.side === THREE.DoubleSide;
  14081. var flipSided = material.side === THREE.BackSide;
  14082. if ( _oldDoubleSided !== doubleSided ) {
  14083. if ( doubleSided ) {
  14084. _gl.disable( _gl.CULL_FACE );
  14085. } else {
  14086. _gl.enable( _gl.CULL_FACE );
  14087. }
  14088. _oldDoubleSided = doubleSided;
  14089. }
  14090. if ( _oldFlipSided !== flipSided ) {
  14091. if ( flipSided ) {
  14092. _gl.frontFace( _gl.CW );
  14093. } else {
  14094. _gl.frontFace( _gl.CCW );
  14095. }
  14096. _oldFlipSided = flipSided;
  14097. }
  14098. };
  14099. this.setDepthTest = function ( depthTest ) {
  14100. if ( _oldDepthTest !== depthTest ) {
  14101. if ( depthTest ) {
  14102. _gl.enable( _gl.DEPTH_TEST );
  14103. } else {
  14104. _gl.disable( _gl.DEPTH_TEST );
  14105. }
  14106. _oldDepthTest = depthTest;
  14107. }
  14108. };
  14109. this.setDepthWrite = function ( depthWrite ) {
  14110. if ( _oldDepthWrite !== depthWrite ) {
  14111. _gl.depthMask( depthWrite );
  14112. _oldDepthWrite = depthWrite;
  14113. }
  14114. };
  14115. function setLineWidth ( width ) {
  14116. if ( width !== _oldLineWidth ) {
  14117. _gl.lineWidth( width );
  14118. _oldLineWidth = width;
  14119. }
  14120. };
  14121. function setPolygonOffset ( polygonoffset, factor, units ) {
  14122. if ( _oldPolygonOffset !== polygonoffset ) {
  14123. if ( polygonoffset ) {
  14124. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14125. } else {
  14126. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14127. }
  14128. _oldPolygonOffset = polygonoffset;
  14129. }
  14130. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14131. _gl.polygonOffset( factor, units );
  14132. _oldPolygonOffsetFactor = factor;
  14133. _oldPolygonOffsetUnits = units;
  14134. }
  14135. };
  14136. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14137. if ( blending !== _oldBlending ) {
  14138. if ( blending === THREE.NoBlending ) {
  14139. _gl.disable( _gl.BLEND );
  14140. } else if ( blending === THREE.AdditiveBlending ) {
  14141. _gl.enable( _gl.BLEND );
  14142. _gl.blendEquation( _gl.FUNC_ADD );
  14143. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14144. } else if ( blending === THREE.SubtractiveBlending ) {
  14145. // TODO: Find blendFuncSeparate() combination
  14146. _gl.enable( _gl.BLEND );
  14147. _gl.blendEquation( _gl.FUNC_ADD );
  14148. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14149. } else if ( blending === THREE.MultiplyBlending ) {
  14150. // TODO: Find blendFuncSeparate() combination
  14151. _gl.enable( _gl.BLEND );
  14152. _gl.blendEquation( _gl.FUNC_ADD );
  14153. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14154. } else if ( blending === THREE.CustomBlending ) {
  14155. _gl.enable( _gl.BLEND );
  14156. } else {
  14157. _gl.enable( _gl.BLEND );
  14158. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14159. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14160. }
  14161. _oldBlending = blending;
  14162. }
  14163. if ( blending === THREE.CustomBlending ) {
  14164. if ( blendEquation !== _oldBlendEquation ) {
  14165. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14166. _oldBlendEquation = blendEquation;
  14167. }
  14168. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14169. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14170. _oldBlendSrc = blendSrc;
  14171. _oldBlendDst = blendDst;
  14172. }
  14173. } else {
  14174. _oldBlendEquation = null;
  14175. _oldBlendSrc = null;
  14176. _oldBlendDst = null;
  14177. }
  14178. };
  14179. // Defines
  14180. function generateDefines ( defines ) {
  14181. var value, chunk, chunks = [];
  14182. for ( var d in defines ) {
  14183. value = defines[ d ];
  14184. if ( value === false ) continue;
  14185. chunk = "#define " + d + " " + value;
  14186. chunks.push( chunk );
  14187. }
  14188. return chunks.join( "\n" );
  14189. };
  14190. // Shaders
  14191. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  14192. var p, pl, d, program, code;
  14193. var chunks = [];
  14194. // Generate code
  14195. if ( shaderID ) {
  14196. chunks.push( shaderID );
  14197. } else {
  14198. chunks.push( fragmentShader );
  14199. chunks.push( vertexShader );
  14200. }
  14201. for ( d in defines ) {
  14202. chunks.push( d );
  14203. chunks.push( defines[ d ] );
  14204. }
  14205. for ( p in parameters ) {
  14206. chunks.push( p );
  14207. chunks.push( parameters[ p ] );
  14208. }
  14209. code = chunks.join();
  14210. // Check if code has been already compiled
  14211. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14212. var programInfo = _programs[ p ];
  14213. if ( programInfo.code === code ) {
  14214. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  14215. programInfo.usedTimes ++;
  14216. return programInfo.program;
  14217. }
  14218. }
  14219. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14220. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14221. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14222. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14223. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14224. }
  14225. //console.log( "building new program " );
  14226. //
  14227. var customDefines = generateDefines( defines );
  14228. //
  14229. program = _gl.createProgram();
  14230. var prefix_vertex = [
  14231. "precision " + _precision + " float;",
  14232. customDefines,
  14233. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14234. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14235. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14236. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14237. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14238. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14239. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14240. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14241. "#define MAX_SHADOWS " + parameters.maxShadows,
  14242. "#define MAX_BONES " + parameters.maxBones,
  14243. parameters.map ? "#define USE_MAP" : "",
  14244. parameters.envMap ? "#define USE_ENVMAP" : "",
  14245. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14246. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14247. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14248. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14249. parameters.vertexColors ? "#define USE_COLOR" : "",
  14250. parameters.skinning ? "#define USE_SKINNING" : "",
  14251. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14252. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  14253. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  14254. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14255. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14256. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14257. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14258. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14259. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14260. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14261. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14262. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14263. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14264. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14265. "uniform mat4 modelMatrix;",
  14266. "uniform mat4 modelViewMatrix;",
  14267. "uniform mat4 projectionMatrix;",
  14268. "uniform mat4 viewMatrix;",
  14269. "uniform mat3 normalMatrix;",
  14270. "uniform vec3 cameraPosition;",
  14271. "attribute vec3 position;",
  14272. "attribute vec3 normal;",
  14273. "attribute vec2 uv;",
  14274. "attribute vec2 uv2;",
  14275. "#ifdef USE_COLOR",
  14276. "attribute vec3 color;",
  14277. "#endif",
  14278. "#ifdef USE_MORPHTARGETS",
  14279. "attribute vec3 morphTarget0;",
  14280. "attribute vec3 morphTarget1;",
  14281. "attribute vec3 morphTarget2;",
  14282. "attribute vec3 morphTarget3;",
  14283. "#ifdef USE_MORPHNORMALS",
  14284. "attribute vec3 morphNormal0;",
  14285. "attribute vec3 morphNormal1;",
  14286. "attribute vec3 morphNormal2;",
  14287. "attribute vec3 morphNormal3;",
  14288. "#else",
  14289. "attribute vec3 morphTarget4;",
  14290. "attribute vec3 morphTarget5;",
  14291. "attribute vec3 morphTarget6;",
  14292. "attribute vec3 morphTarget7;",
  14293. "#endif",
  14294. "#endif",
  14295. "#ifdef USE_SKINNING",
  14296. "attribute vec4 skinIndex;",
  14297. "attribute vec4 skinWeight;",
  14298. "#endif",
  14299. ""
  14300. ].join("\n");
  14301. var prefix_fragment = [
  14302. "precision " + _precision + " float;",
  14303. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14304. customDefines,
  14305. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14306. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14307. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14308. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14309. "#define MAX_SHADOWS " + parameters.maxShadows,
  14310. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14311. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14312. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14313. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14314. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14315. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14316. parameters.map ? "#define USE_MAP" : "",
  14317. parameters.envMap ? "#define USE_ENVMAP" : "",
  14318. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14319. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14320. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14321. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14322. parameters.vertexColors ? "#define USE_COLOR" : "",
  14323. parameters.metal ? "#define METAL" : "",
  14324. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14325. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14326. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14327. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14328. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14329. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14330. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14331. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14332. "uniform mat4 viewMatrix;",
  14333. "uniform vec3 cameraPosition;",
  14334. ""
  14335. ].join("\n");
  14336. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14337. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14338. _gl.attachShader( program, glVertexShader );
  14339. _gl.attachShader( program, glFragmentShader );
  14340. _gl.linkProgram( program );
  14341. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14342. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14343. }
  14344. // clean up
  14345. _gl.deleteShader( glFragmentShader );
  14346. _gl.deleteShader( glVertexShader );
  14347. //console.log( prefix_fragment + fragmentShader );
  14348. //console.log( prefix_vertex + vertexShader );
  14349. program.uniforms = {};
  14350. program.attributes = {};
  14351. var identifiers, u, a, i;
  14352. // cache uniform locations
  14353. identifiers = [
  14354. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14355. 'morphTargetInfluences'
  14356. ];
  14357. if ( parameters.useVertexTexture ) {
  14358. identifiers.push( 'boneTexture' );
  14359. } else {
  14360. identifiers.push( 'boneGlobalMatrices' );
  14361. }
  14362. for ( u in uniforms ) {
  14363. identifiers.push( u );
  14364. }
  14365. cacheUniformLocations( program, identifiers );
  14366. // cache attributes locations
  14367. identifiers = [
  14368. "position", "normal", "uv", "uv2", "tangent", "color",
  14369. "skinIndex", "skinWeight", "lineDistance"
  14370. ];
  14371. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14372. identifiers.push( "morphTarget" + i );
  14373. }
  14374. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14375. identifiers.push( "morphNormal" + i );
  14376. }
  14377. for ( a in attributes ) {
  14378. identifiers.push( a );
  14379. }
  14380. cacheAttributeLocations( program, identifiers );
  14381. program.id = _programs_counter ++;
  14382. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14383. _this.info.memory.programs = _programs.length;
  14384. return program;
  14385. };
  14386. // Shader parameters cache
  14387. function cacheUniformLocations ( program, identifiers ) {
  14388. var i, l, id;
  14389. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14390. id = identifiers[ i ];
  14391. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14392. }
  14393. };
  14394. function cacheAttributeLocations ( program, identifiers ) {
  14395. var i, l, id;
  14396. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14397. id = identifiers[ i ];
  14398. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14399. }
  14400. };
  14401. function addLineNumbers ( string ) {
  14402. var chunks = string.split( "\n" );
  14403. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14404. // Chrome reports shader errors on lines
  14405. // starting counting from 1
  14406. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14407. }
  14408. return chunks.join( "\n" );
  14409. };
  14410. function getShader ( type, string ) {
  14411. var shader;
  14412. if ( type === "fragment" ) {
  14413. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14414. } else if ( type === "vertex" ) {
  14415. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14416. }
  14417. _gl.shaderSource( shader, string );
  14418. _gl.compileShader( shader );
  14419. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14420. console.error( _gl.getShaderInfoLog( shader ) );
  14421. console.error( addLineNumbers( string ) );
  14422. return null;
  14423. }
  14424. return shader;
  14425. };
  14426. // Textures
  14427. function isPowerOfTwo ( value ) {
  14428. return ( value & ( value - 1 ) ) === 0;
  14429. };
  14430. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14431. if ( isImagePowerOfTwo ) {
  14432. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14433. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14434. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14435. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14436. } else {
  14437. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14438. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14439. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14440. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14441. }
  14442. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14443. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14444. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14445. texture.__oldAnisotropy = texture.anisotropy;
  14446. }
  14447. }
  14448. };
  14449. this.setTexture = function ( texture, slot ) {
  14450. if ( texture.needsUpdate ) {
  14451. if ( ! texture.__webglInit ) {
  14452. texture.__webglInit = true;
  14453. texture.addEventListener( 'dispose', onTextureDispose );
  14454. texture.__webglTexture = _gl.createTexture();
  14455. _this.info.memory.textures ++;
  14456. }
  14457. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14458. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14459. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14460. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14461. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14462. var image = texture.image,
  14463. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14464. glFormat = paramThreeToGL( texture.format ),
  14465. glType = paramThreeToGL( texture.type );
  14466. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14467. var mipmap, mipmaps = texture.mipmaps;
  14468. if ( texture instanceof THREE.DataTexture ) {
  14469. // use manually created mipmaps if available
  14470. // if there are no manual mipmaps
  14471. // set 0 level mipmap and then use GL to generate other mipmap levels
  14472. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14473. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14474. mipmap = mipmaps[ i ];
  14475. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14476. }
  14477. texture.generateMipmaps = false;
  14478. } else {
  14479. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14480. }
  14481. } else if ( texture instanceof THREE.CompressedTexture ) {
  14482. // compressed textures can only use manually created mipmaps
  14483. // WebGL can't generate mipmaps for DDS textures
  14484. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14485. mipmap = mipmaps[ i ];
  14486. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14487. }
  14488. } else { // regular Texture (image, video, canvas)
  14489. // use manually created mipmaps if available
  14490. // if there are no manual mipmaps
  14491. // set 0 level mipmap and then use GL to generate other mipmap levels
  14492. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14493. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14494. mipmap = mipmaps[ i ];
  14495. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14496. }
  14497. texture.generateMipmaps = false;
  14498. } else {
  14499. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14500. }
  14501. }
  14502. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14503. texture.needsUpdate = false;
  14504. if ( texture.onUpdate ) texture.onUpdate();
  14505. } else {
  14506. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14507. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14508. }
  14509. };
  14510. function clampToMaxSize ( image, maxSize ) {
  14511. if ( image.width <= maxSize && image.height <= maxSize ) {
  14512. return image;
  14513. }
  14514. // Warning: Scaling through the canvas will only work with images that use
  14515. // premultiplied alpha.
  14516. var maxDimension = Math.max( image.width, image.height );
  14517. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14518. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14519. var canvas = document.createElement( 'canvas' );
  14520. canvas.width = newWidth;
  14521. canvas.height = newHeight;
  14522. var ctx = canvas.getContext( "2d" );
  14523. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14524. return canvas;
  14525. }
  14526. function setCubeTexture ( texture, slot ) {
  14527. if ( texture.image.length === 6 ) {
  14528. if ( texture.needsUpdate ) {
  14529. if ( ! texture.image.__webglTextureCube ) {
  14530. texture.image.__webglTextureCube = _gl.createTexture();
  14531. _this.info.memory.textures ++;
  14532. }
  14533. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14534. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14535. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14536. var isCompressed = texture instanceof THREE.CompressedTexture;
  14537. var cubeImage = [];
  14538. for ( var i = 0; i < 6; i ++ ) {
  14539. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14540. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14541. } else {
  14542. cubeImage[ i ] = texture.image[ i ];
  14543. }
  14544. }
  14545. var image = cubeImage[ 0 ],
  14546. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14547. glFormat = paramThreeToGL( texture.format ),
  14548. glType = paramThreeToGL( texture.type );
  14549. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14550. for ( var i = 0; i < 6; i ++ ) {
  14551. if ( isCompressed ) {
  14552. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14553. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14554. mipmap = mipmaps[ j ];
  14555. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14556. }
  14557. } else {
  14558. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14559. }
  14560. }
  14561. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14562. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14563. }
  14564. texture.needsUpdate = false;
  14565. if ( texture.onUpdate ) texture.onUpdate();
  14566. } else {
  14567. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14568. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14569. }
  14570. }
  14571. };
  14572. function setCubeTextureDynamic ( texture, slot ) {
  14573. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14574. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14575. };
  14576. // Render targets
  14577. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14578. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14579. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14580. };
  14581. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14582. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14583. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14584. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14585. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14586. /* For some reason this is not working. Defaulting to RGBA4.
  14587. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14588. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14589. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14590. */
  14591. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14592. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14593. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14594. } else {
  14595. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14596. }
  14597. };
  14598. this.setRenderTarget = function ( renderTarget ) {
  14599. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14600. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14601. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14602. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14603. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14604. renderTarget.__webglTexture = _gl.createTexture();
  14605. _this.info.memory.textures ++;
  14606. // Setup texture, create render and frame buffers
  14607. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  14608. glFormat = paramThreeToGL( renderTarget.format ),
  14609. glType = paramThreeToGL( renderTarget.type );
  14610. if ( isCube ) {
  14611. renderTarget.__webglFramebuffer = [];
  14612. renderTarget.__webglRenderbuffer = [];
  14613. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14614. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14615. for ( var i = 0; i < 6; i ++ ) {
  14616. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14617. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14618. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14619. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14620. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14621. }
  14622. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14623. } else {
  14624. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14625. if ( renderTarget.shareDepthFrom ) {
  14626. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14627. } else {
  14628. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14629. }
  14630. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14631. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14632. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14633. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14634. if ( renderTarget.shareDepthFrom ) {
  14635. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14636. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14637. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14638. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14639. }
  14640. } else {
  14641. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14642. }
  14643. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14644. }
  14645. // Release everything
  14646. if ( isCube ) {
  14647. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14648. } else {
  14649. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14650. }
  14651. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14652. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14653. }
  14654. var framebuffer, width, height, vx, vy;
  14655. if ( renderTarget ) {
  14656. if ( isCube ) {
  14657. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14658. } else {
  14659. framebuffer = renderTarget.__webglFramebuffer;
  14660. }
  14661. width = renderTarget.width;
  14662. height = renderTarget.height;
  14663. vx = 0;
  14664. vy = 0;
  14665. } else {
  14666. framebuffer = null;
  14667. width = _viewportWidth;
  14668. height = _viewportHeight;
  14669. vx = _viewportX;
  14670. vy = _viewportY;
  14671. }
  14672. if ( framebuffer !== _currentFramebuffer ) {
  14673. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14674. _gl.viewport( vx, vy, width, height );
  14675. _currentFramebuffer = framebuffer;
  14676. }
  14677. _currentWidth = width;
  14678. _currentHeight = height;
  14679. };
  14680. function updateRenderTargetMipmap ( renderTarget ) {
  14681. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14682. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14683. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14684. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14685. } else {
  14686. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14687. _gl.generateMipmap( _gl.TEXTURE_2D );
  14688. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14689. }
  14690. };
  14691. // Fallback filters for non-power-of-2 textures
  14692. function filterFallback ( f ) {
  14693. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14694. return _gl.NEAREST;
  14695. }
  14696. return _gl.LINEAR;
  14697. };
  14698. // Map three.js constants to WebGL constants
  14699. function paramThreeToGL ( p ) {
  14700. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14701. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14702. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14703. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14704. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14705. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14706. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14707. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14708. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14709. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14710. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14711. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14712. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14713. if ( p === THREE.ByteType ) return _gl.BYTE;
  14714. if ( p === THREE.ShortType ) return _gl.SHORT;
  14715. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14716. if ( p === THREE.IntType ) return _gl.INT;
  14717. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14718. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14719. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14720. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14721. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14722. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14723. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14724. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14725. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14726. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14727. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14728. if ( p === THREE.OneFactor ) return _gl.ONE;
  14729. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14730. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14731. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14732. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14733. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14734. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14735. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14736. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14737. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14738. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  14739. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14740. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14741. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14742. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14743. }
  14744. return 0;
  14745. };
  14746. // Allocations
  14747. function allocateBones ( object ) {
  14748. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  14749. return 1024;
  14750. } else {
  14751. // default for when object is not specified
  14752. // ( for example when prebuilding shader
  14753. // to be used with multiple objects )
  14754. //
  14755. // - leave some extra space for other uniforms
  14756. // - limit here is ANGLE's 254 max uniform vectors
  14757. // (up to 54 should be safe)
  14758. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14759. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14760. var maxBones = nVertexMatrices;
  14761. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14762. maxBones = Math.min( object.bones.length, maxBones );
  14763. if ( maxBones < object.bones.length ) {
  14764. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  14765. }
  14766. }
  14767. return maxBones;
  14768. }
  14769. };
  14770. function allocateLights ( lights ) {
  14771. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  14772. dirLights = pointLights = spotLights = hemiLights = 0;
  14773. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14774. light = lights[ l ];
  14775. if ( light.onlyShadow ) continue;
  14776. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14777. if ( light instanceof THREE.PointLight ) pointLights ++;
  14778. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14779. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14780. }
  14781. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14782. };
  14783. function allocateShadows ( lights ) {
  14784. var l, ll, light, maxShadows = 0;
  14785. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  14786. light = lights[ l ];
  14787. if ( ! light.castShadow ) continue;
  14788. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14789. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14790. }
  14791. return maxShadows;
  14792. };
  14793. // Initialization
  14794. function initGL () {
  14795. try {
  14796. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  14797. throw 'Error creating WebGL context.';
  14798. }
  14799. } catch ( error ) {
  14800. console.error( error );
  14801. }
  14802. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  14803. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  14804. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  14805. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  14806. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14807. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  14808. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  14809. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14810. if ( ! _glExtensionTextureFloat ) {
  14811. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  14812. }
  14813. if ( ! _glExtensionStandardDerivatives ) {
  14814. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  14815. }
  14816. if ( ! _glExtensionTextureFilterAnisotropic ) {
  14817. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  14818. }
  14819. if ( ! _glExtensionCompressedTextureS3TC ) {
  14820. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  14821. }
  14822. };
  14823. function setDefaultGLState () {
  14824. _gl.clearColor( 0, 0, 0, 1 );
  14825. _gl.clearDepth( 1 );
  14826. _gl.clearStencil( 0 );
  14827. _gl.enable( _gl.DEPTH_TEST );
  14828. _gl.depthFunc( _gl.LEQUAL );
  14829. _gl.frontFace( _gl.CCW );
  14830. _gl.cullFace( _gl.BACK );
  14831. _gl.enable( _gl.CULL_FACE );
  14832. _gl.enable( _gl.BLEND );
  14833. _gl.blendEquation( _gl.FUNC_ADD );
  14834. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  14835. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14836. };
  14837. // default plugins (order is important)
  14838. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  14839. this.addPrePlugin( this.shadowMapPlugin );
  14840. this.addPostPlugin( new THREE.SpritePlugin() );
  14841. this.addPostPlugin( new THREE.LensFlarePlugin() );
  14842. };
  14843. /**
  14844. * @author szimek / https://github.com/szimek/
  14845. * @author alteredq / http://alteredqualia.com/
  14846. */
  14847. THREE.WebGLRenderTarget = function ( width, height, options ) {
  14848. THREE.EventDispatcher.call( this );
  14849. this.width = width;
  14850. this.height = height;
  14851. options = options || {};
  14852. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  14853. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  14854. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  14855. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  14856. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  14857. this.offset = new THREE.Vector2( 0, 0 );
  14858. this.repeat = new THREE.Vector2( 1, 1 );
  14859. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  14860. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  14861. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  14862. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  14863. this.generateMipmaps = true;
  14864. this.shareDepthFrom = null;
  14865. };
  14866. THREE.WebGLRenderTarget.prototype.clone = function() {
  14867. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  14868. tmp.wrapS = this.wrapS;
  14869. tmp.wrapT = this.wrapT;
  14870. tmp.magFilter = this.magFilter;
  14871. tmp.minFilter = this.minFilter;
  14872. tmp.anisotropy = this.anisotropy;
  14873. tmp.offset.copy( this.offset );
  14874. tmp.repeat.copy( this.repeat );
  14875. tmp.format = this.format;
  14876. tmp.type = this.type;
  14877. tmp.depthBuffer = this.depthBuffer;
  14878. tmp.stencilBuffer = this.stencilBuffer;
  14879. tmp.generateMipmaps = this.generateMipmaps;
  14880. tmp.shareDepthFrom = this.shareDepthFrom;
  14881. return tmp;
  14882. };
  14883. THREE.WebGLRenderTarget.prototype.dispose = function () {
  14884. this.dispatchEvent( { type: 'dispose' } );
  14885. };
  14886. /**
  14887. * @author alteredq / http://alteredqualia.com
  14888. */
  14889. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  14890. THREE.WebGLRenderTarget.call( this, width, height, options );
  14891. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  14892. };
  14893. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  14894. /**
  14895. * @author mrdoob / http://mrdoob.com/
  14896. */
  14897. THREE.RenderableVertex = function () {
  14898. this.positionWorld = new THREE.Vector3();
  14899. this.positionScreen = new THREE.Vector4();
  14900. this.visible = true;
  14901. };
  14902. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  14903. this.positionWorld.copy( vertex.positionWorld );
  14904. this.positionScreen.copy( vertex.positionScreen );
  14905. };
  14906. /**
  14907. * @author mrdoob / http://mrdoob.com/
  14908. */
  14909. THREE.RenderableFace3 = function () {
  14910. this.v1 = new THREE.RenderableVertex();
  14911. this.v2 = new THREE.RenderableVertex();
  14912. this.v3 = new THREE.RenderableVertex();
  14913. this.centroidModel = new THREE.Vector3();
  14914. this.normalModel = new THREE.Vector3();
  14915. this.normalModelView = new THREE.Vector3();
  14916. this.vertexNormalsLength = 0;
  14917. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14918. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14919. this.color = null;
  14920. this.material = null;
  14921. this.uvs = [[]];
  14922. this.z = null;
  14923. };
  14924. /**
  14925. * @author mrdoob / http://mrdoob.com/
  14926. */
  14927. THREE.RenderableFace4 = function () {
  14928. this.v1 = new THREE.RenderableVertex();
  14929. this.v2 = new THREE.RenderableVertex();
  14930. this.v3 = new THREE.RenderableVertex();
  14931. this.v4 = new THREE.RenderableVertex();
  14932. this.centroidModel = new THREE.Vector3();
  14933. this.normalModel = new THREE.Vector3();
  14934. this.normalModelView = new THREE.Vector3();
  14935. this.vertexNormalsLength = 0;
  14936. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14937. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14938. this.color = null;
  14939. this.material = null;
  14940. this.uvs = [[]];
  14941. this.z = null;
  14942. };
  14943. /**
  14944. * @author mrdoob / http://mrdoob.com/
  14945. */
  14946. THREE.RenderableObject = function () {
  14947. this.object = null;
  14948. this.z = null;
  14949. };
  14950. /**
  14951. * @author mrdoob / http://mrdoob.com/
  14952. */
  14953. THREE.RenderableParticle = function () {
  14954. this.object = null;
  14955. this.x = null;
  14956. this.y = null;
  14957. this.z = null;
  14958. this.rotation = null;
  14959. this.scale = new THREE.Vector2();
  14960. this.material = null;
  14961. };
  14962. /**
  14963. * @author mrdoob / http://mrdoob.com/
  14964. */
  14965. THREE.RenderableLine = function () {
  14966. this.z = null;
  14967. this.v1 = new THREE.RenderableVertex();
  14968. this.v2 = new THREE.RenderableVertex();
  14969. this.material = null;
  14970. };
  14971. /**
  14972. * @author alteredq / http://alteredqualia.com/
  14973. */
  14974. THREE.ColorUtils = {
  14975. adjustHSV : function ( color, h, s, v ) {
  14976. var hsv = THREE.ColorUtils.__hsv;
  14977. color.getHSV( hsv );
  14978. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  14979. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  14980. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  14981. color.setHSV( hsv.h, hsv.s, hsv.v );
  14982. }
  14983. };
  14984. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  14985. * @author mrdoob / http://mrdoob.com/
  14986. * @author alteredq / http://alteredqualia.com/
  14987. */
  14988. THREE.GeometryUtils = {
  14989. // Merge two geometries or geometry and geometry from object (using object's transform)
  14990. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  14991. var matrix, normalMatrix,
  14992. vertexOffset = geometry1.vertices.length,
  14993. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  14994. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  14995. vertices1 = geometry1.vertices,
  14996. vertices2 = geometry2.vertices,
  14997. faces1 = geometry1.faces,
  14998. faces2 = geometry2.faces,
  14999. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15000. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15001. if ( object2 instanceof THREE.Mesh ) {
  15002. object2.matrixAutoUpdate && object2.updateMatrix();
  15003. matrix = object2.matrix;
  15004. normalMatrix = new THREE.Matrix3();
  15005. normalMatrix.getInverse( matrix );
  15006. normalMatrix.transpose();
  15007. }
  15008. // vertices
  15009. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15010. var vertex = vertices2[ i ];
  15011. var vertexCopy = vertex.clone();
  15012. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15013. vertices1.push( vertexCopy );
  15014. }
  15015. // faces
  15016. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15017. var face = faces2[ i ], faceCopy, normal, color,
  15018. faceVertexNormals = face.vertexNormals,
  15019. faceVertexColors = face.vertexColors;
  15020. if ( face instanceof THREE.Face3 ) {
  15021. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15022. } else if ( face instanceof THREE.Face4 ) {
  15023. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15024. }
  15025. faceCopy.normal.copy( face.normal );
  15026. if ( normalMatrix ) {
  15027. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15028. }
  15029. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15030. normal = faceVertexNormals[ j ].clone();
  15031. if ( normalMatrix ) {
  15032. normal.applyMatrix3( normalMatrix ).normalize();
  15033. }
  15034. faceCopy.vertexNormals.push( normal );
  15035. }
  15036. faceCopy.color.copy( face.color );
  15037. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15038. color = faceVertexColors[ j ];
  15039. faceCopy.vertexColors.push( color.clone() );
  15040. }
  15041. faceCopy.materialIndex = face.materialIndex;
  15042. faceCopy.centroid.copy( face.centroid );
  15043. if ( matrix ) {
  15044. faceCopy.centroid.applyMatrix4( matrix );
  15045. }
  15046. faces1.push( faceCopy );
  15047. }
  15048. // uvs
  15049. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15050. var uv = uvs2[ i ], uvCopy = [];
  15051. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15052. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15053. }
  15054. uvs1.push( uvCopy );
  15055. }
  15056. },
  15057. removeMaterials: function ( geometry, materialIndexArray ) {
  15058. var materialIndexMap = {};
  15059. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15060. materialIndexMap[ materialIndexArray[i] ] = true;
  15061. }
  15062. var face, newFaces = [];
  15063. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15064. face = geometry.faces[ i ];
  15065. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15066. }
  15067. geometry.faces = newFaces;
  15068. },
  15069. // Get random point in triangle (via barycentric coordinates)
  15070. // (uniform distribution)
  15071. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15072. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15073. var a, b, c,
  15074. point = new THREE.Vector3(),
  15075. tmp = THREE.GeometryUtils.__v1;
  15076. a = THREE.GeometryUtils.random();
  15077. b = THREE.GeometryUtils.random();
  15078. if ( ( a + b ) > 1 ) {
  15079. a = 1 - a;
  15080. b = 1 - b;
  15081. }
  15082. c = 1 - a - b;
  15083. point.copy( vectorA );
  15084. point.multiplyScalar( a );
  15085. tmp.copy( vectorB );
  15086. tmp.multiplyScalar( b );
  15087. point.add( tmp );
  15088. tmp.copy( vectorC );
  15089. tmp.multiplyScalar( c );
  15090. point.add( tmp );
  15091. return point;
  15092. },
  15093. // Get random point in face (triangle / quad)
  15094. // (uniform distribution)
  15095. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15096. var vA, vB, vC, vD;
  15097. if ( face instanceof THREE.Face3 ) {
  15098. vA = geometry.vertices[ face.a ];
  15099. vB = geometry.vertices[ face.b ];
  15100. vC = geometry.vertices[ face.c ];
  15101. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15102. } else if ( face instanceof THREE.Face4 ) {
  15103. vA = geometry.vertices[ face.a ];
  15104. vB = geometry.vertices[ face.b ];
  15105. vC = geometry.vertices[ face.c ];
  15106. vD = geometry.vertices[ face.d ];
  15107. var area1, area2;
  15108. if ( useCachedAreas ) {
  15109. if ( face._area1 && face._area2 ) {
  15110. area1 = face._area1;
  15111. area2 = face._area2;
  15112. } else {
  15113. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15114. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15115. face._area1 = area1;
  15116. face._area2 = area2;
  15117. }
  15118. } else {
  15119. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15120. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15121. }
  15122. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15123. if ( r < area1 ) {
  15124. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  15125. } else {
  15126. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  15127. }
  15128. }
  15129. },
  15130. // Get uniformly distributed random points in mesh
  15131. // - create array with cumulative sums of face areas
  15132. // - pick random number from 0 to total area
  15133. // - find corresponding place in area array by binary search
  15134. // - get random point in face
  15135. randomPointsInGeometry: function ( geometry, n ) {
  15136. var face, i,
  15137. faces = geometry.faces,
  15138. vertices = geometry.vertices,
  15139. il = faces.length,
  15140. totalArea = 0,
  15141. cumulativeAreas = [],
  15142. vA, vB, vC, vD;
  15143. // precompute face areas
  15144. for ( i = 0; i < il; i ++ ) {
  15145. face = faces[ i ];
  15146. if ( face instanceof THREE.Face3 ) {
  15147. vA = vertices[ face.a ];
  15148. vB = vertices[ face.b ];
  15149. vC = vertices[ face.c ];
  15150. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15151. } else if ( face instanceof THREE.Face4 ) {
  15152. vA = vertices[ face.a ];
  15153. vB = vertices[ face.b ];
  15154. vC = vertices[ face.c ];
  15155. vD = vertices[ face.d ];
  15156. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15157. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15158. face._area = face._area1 + face._area2;
  15159. }
  15160. totalArea += face._area;
  15161. cumulativeAreas[ i ] = totalArea;
  15162. }
  15163. // binary search cumulative areas array
  15164. function binarySearchIndices( value ) {
  15165. function binarySearch( start, end ) {
  15166. // return closest larger index
  15167. // if exact number is not found
  15168. if ( end < start )
  15169. return start;
  15170. var mid = start + Math.floor( ( end - start ) / 2 );
  15171. if ( cumulativeAreas[ mid ] > value ) {
  15172. return binarySearch( start, mid - 1 );
  15173. } else if ( cumulativeAreas[ mid ] < value ) {
  15174. return binarySearch( mid + 1, end );
  15175. } else {
  15176. return mid;
  15177. }
  15178. }
  15179. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15180. return result;
  15181. }
  15182. // pick random face weighted by face area
  15183. var r, index,
  15184. result = [];
  15185. var stats = {};
  15186. for ( i = 0; i < n; i ++ ) {
  15187. r = THREE.GeometryUtils.random() * totalArea;
  15188. index = binarySearchIndices( r );
  15189. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15190. if ( ! stats[ index ] ) {
  15191. stats[ index ] = 1;
  15192. } else {
  15193. stats[ index ] += 1;
  15194. }
  15195. }
  15196. return result;
  15197. },
  15198. // Get triangle area (half of parallelogram)
  15199. // http://mathworld.wolfram.com/TriangleArea.html
  15200. triangleArea: function ( vectorA, vectorB, vectorC ) {
  15201. var tmp1 = THREE.GeometryUtils.__v1,
  15202. tmp2 = THREE.GeometryUtils.__v2;
  15203. tmp1.subVectors( vectorB, vectorA );
  15204. tmp2.subVectors( vectorC, vectorA );
  15205. tmp1.cross( tmp2 );
  15206. return 0.5 * tmp1.length();
  15207. },
  15208. // Center geometry so that 0,0,0 is in center of bounding box
  15209. center: function ( geometry ) {
  15210. geometry.computeBoundingBox();
  15211. var bb = geometry.boundingBox;
  15212. var offset = new THREE.Vector3();
  15213. offset.addVectors( bb.min, bb.max );
  15214. offset.multiplyScalar( -0.5 );
  15215. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset ) );
  15216. geometry.computeBoundingBox();
  15217. return offset;
  15218. },
  15219. // Normalize UVs to be from <0,1>
  15220. // (for now just the first set of UVs)
  15221. normalizeUVs: function ( geometry ) {
  15222. var uvSet = geometry.faceVertexUvs[ 0 ];
  15223. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  15224. var uvs = uvSet[ i ];
  15225. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  15226. // texture repeat
  15227. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  15228. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  15229. }
  15230. }
  15231. },
  15232. triangulateQuads: function ( geometry ) {
  15233. var i, il, j, jl;
  15234. var faces = [];
  15235. var faceUvs = [];
  15236. var faceVertexUvs = [];
  15237. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  15238. faceUvs[ i ] = [];
  15239. }
  15240. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15241. faceVertexUvs[ i ] = [];
  15242. }
  15243. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15244. var face = geometry.faces[ i ];
  15245. if ( face instanceof THREE.Face4 ) {
  15246. var a = face.a;
  15247. var b = face.b;
  15248. var c = face.c;
  15249. var d = face.d;
  15250. var triA = new THREE.Face3();
  15251. var triB = new THREE.Face3();
  15252. triA.color.copy( face.color );
  15253. triB.color.copy( face.color );
  15254. triA.materialIndex = face.materialIndex;
  15255. triB.materialIndex = face.materialIndex;
  15256. triA.a = a;
  15257. triA.b = b;
  15258. triA.c = d;
  15259. triB.a = b;
  15260. triB.b = c;
  15261. triB.c = d;
  15262. if ( face.vertexColors.length === 4 ) {
  15263. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  15264. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  15265. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15266. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  15267. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  15268. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15269. }
  15270. faces.push( triA, triB );
  15271. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15272. if ( geometry.faceVertexUvs[ j ].length ) {
  15273. var uvs = geometry.faceVertexUvs[ j ][ i ];
  15274. var uvA = uvs[ 0 ];
  15275. var uvB = uvs[ 1 ];
  15276. var uvC = uvs[ 2 ];
  15277. var uvD = uvs[ 3 ];
  15278. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  15279. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  15280. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15281. }
  15282. }
  15283. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15284. if ( geometry.faceUvs[ j ].length ) {
  15285. var faceUv = geometry.faceUvs[ j ][ i ];
  15286. faceUvs[ j ].push( faceUv, faceUv );
  15287. }
  15288. }
  15289. } else {
  15290. faces.push( face );
  15291. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15292. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  15293. }
  15294. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15295. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15296. }
  15297. }
  15298. }
  15299. geometry.faces = faces;
  15300. geometry.faceUvs = faceUvs;
  15301. geometry.faceVertexUvs = faceVertexUvs;
  15302. geometry.computeCentroids();
  15303. geometry.computeFaceNormals();
  15304. geometry.computeVertexNormals();
  15305. if ( geometry.hasTangents ) geometry.computeTangents();
  15306. },
  15307. // Make all faces use unique vertices
  15308. // so that each face can be separated from others
  15309. explode: function( geometry ) {
  15310. var vertices = [];
  15311. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15312. var n = vertices.length;
  15313. var face = geometry.faces[ i ];
  15314. if ( face instanceof THREE.Face4 ) {
  15315. var a = face.a;
  15316. var b = face.b;
  15317. var c = face.c;
  15318. var d = face.d;
  15319. var va = geometry.vertices[ a ];
  15320. var vb = geometry.vertices[ b ];
  15321. var vc = geometry.vertices[ c ];
  15322. var vd = geometry.vertices[ d ];
  15323. vertices.push( va.clone() );
  15324. vertices.push( vb.clone() );
  15325. vertices.push( vc.clone() );
  15326. vertices.push( vd.clone() );
  15327. face.a = n;
  15328. face.b = n + 1;
  15329. face.c = n + 2;
  15330. face.d = n + 3;
  15331. } else {
  15332. var a = face.a;
  15333. var b = face.b;
  15334. var c = face.c;
  15335. var va = geometry.vertices[ a ];
  15336. var vb = geometry.vertices[ b ];
  15337. var vc = geometry.vertices[ c ];
  15338. vertices.push( va.clone() );
  15339. vertices.push( vb.clone() );
  15340. vertices.push( vc.clone() );
  15341. face.a = n;
  15342. face.b = n + 1;
  15343. face.c = n + 2;
  15344. }
  15345. }
  15346. geometry.vertices = vertices;
  15347. delete geometry.__tmpVertices;
  15348. },
  15349. // Break faces with edges longer than maxEdgeLength
  15350. // - not recursive
  15351. tessellate: function ( geometry, maxEdgeLength ) {
  15352. var i, il, face,
  15353. a, b, c, d,
  15354. va, vb, vc, vd,
  15355. dab, dbc, dac, dcd, dad,
  15356. m, m1, m2,
  15357. vm, vm1, vm2,
  15358. vnm, vnm1, vnm2,
  15359. vcm, vcm1, vcm2,
  15360. triA, triB,
  15361. quadA, quadB,
  15362. edge;
  15363. var faces = [];
  15364. var faceVertexUvs = [];
  15365. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15366. faceVertexUvs[ i ] = [];
  15367. }
  15368. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15369. face = geometry.faces[ i ];
  15370. if ( face instanceof THREE.Face3 ) {
  15371. a = face.a;
  15372. b = face.b;
  15373. c = face.c;
  15374. va = geometry.vertices[ a ];
  15375. vb = geometry.vertices[ b ];
  15376. vc = geometry.vertices[ c ];
  15377. dab = va.distanceTo( vb );
  15378. dbc = vb.distanceTo( vc );
  15379. dac = va.distanceTo( vc );
  15380. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  15381. m = geometry.vertices.length;
  15382. triA = face.clone();
  15383. triB = face.clone();
  15384. if ( dab >= dbc && dab >= dac ) {
  15385. vm = va.clone();
  15386. vm.lerp( vb, 0.5 );
  15387. triA.a = a;
  15388. triA.b = m;
  15389. triA.c = c;
  15390. triB.a = m;
  15391. triB.b = b;
  15392. triB.c = c;
  15393. if ( face.vertexNormals.length === 3 ) {
  15394. vnm = face.vertexNormals[ 0 ].clone();
  15395. vnm.lerp( face.vertexNormals[ 1 ], 0.5 );
  15396. triA.vertexNormals[ 1 ].copy( vnm );
  15397. triB.vertexNormals[ 0 ].copy( vnm );
  15398. }
  15399. if ( face.vertexColors.length === 3 ) {
  15400. vcm = face.vertexColors[ 0 ].clone();
  15401. vcm.lerp( face.vertexColors[ 1 ], 0.5 );
  15402. triA.vertexColors[ 1 ].copy( vcm );
  15403. triB.vertexColors[ 0 ].copy( vcm );
  15404. }
  15405. edge = 0;
  15406. } else if ( dbc >= dab && dbc >= dac ) {
  15407. vm = vb.clone();
  15408. vm.lerp( vc, 0.5 );
  15409. triA.a = a;
  15410. triA.b = b;
  15411. triA.c = m;
  15412. triB.a = m;
  15413. triB.b = c;
  15414. triB.c = a;
  15415. if ( face.vertexNormals.length === 3 ) {
  15416. vnm = face.vertexNormals[ 1 ].clone();
  15417. vnm.lerp( face.vertexNormals[ 2 ], 0.5 );
  15418. triA.vertexNormals[ 2 ].copy( vnm );
  15419. triB.vertexNormals[ 0 ].copy( vnm );
  15420. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  15421. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  15422. }
  15423. if ( face.vertexColors.length === 3 ) {
  15424. vcm = face.vertexColors[ 1 ].clone();
  15425. vcm.lerp( face.vertexColors[ 2 ], 0.5 );
  15426. triA.vertexColors[ 2 ].copy( vcm );
  15427. triB.vertexColors[ 0 ].copy( vcm );
  15428. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  15429. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  15430. }
  15431. edge = 1;
  15432. } else {
  15433. vm = va.clone();
  15434. vm.lerp( vc, 0.5 );
  15435. triA.a = a;
  15436. triA.b = b;
  15437. triA.c = m;
  15438. triB.a = m;
  15439. triB.b = b;
  15440. triB.c = c;
  15441. if ( face.vertexNormals.length === 3 ) {
  15442. vnm = face.vertexNormals[ 0 ].clone();
  15443. vnm.lerp( face.vertexNormals[ 2 ], 0.5 );
  15444. triA.vertexNormals[ 2 ].copy( vnm );
  15445. triB.vertexNormals[ 0 ].copy( vnm );
  15446. }
  15447. if ( face.vertexColors.length === 3 ) {
  15448. vcm = face.vertexColors[ 0 ].clone();
  15449. vcm.lerp( face.vertexColors[ 2 ], 0.5 );
  15450. triA.vertexColors[ 2 ].copy( vcm );
  15451. triB.vertexColors[ 0 ].copy( vcm );
  15452. }
  15453. edge = 2;
  15454. }
  15455. faces.push( triA, triB );
  15456. geometry.vertices.push( vm );
  15457. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  15458. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15459. if ( geometry.faceVertexUvs[ j ].length ) {
  15460. uvs = geometry.faceVertexUvs[ j ][ i ];
  15461. uvA = uvs[ 0 ];
  15462. uvB = uvs[ 1 ];
  15463. uvC = uvs[ 2 ];
  15464. // AB
  15465. if ( edge === 0 ) {
  15466. uvM = uvA.clone();
  15467. uvM.lerp( uvB, 0.5 );
  15468. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  15469. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  15470. // BC
  15471. } else if ( edge === 1 ) {
  15472. uvM = uvB.clone();
  15473. uvM.lerp( uvC, 0.5 );
  15474. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  15475. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  15476. // AC
  15477. } else {
  15478. uvM = uvA.clone();
  15479. uvM.lerp( uvC, 0.5 );
  15480. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  15481. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  15482. }
  15483. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15484. }
  15485. }
  15486. } else {
  15487. faces.push( face );
  15488. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15489. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15490. }
  15491. }
  15492. } else {
  15493. a = face.a;
  15494. b = face.b;
  15495. c = face.c;
  15496. d = face.d;
  15497. va = geometry.vertices[ a ];
  15498. vb = geometry.vertices[ b ];
  15499. vc = geometry.vertices[ c ];
  15500. vd = geometry.vertices[ d ];
  15501. dab = va.distanceTo( vb );
  15502. dbc = vb.distanceTo( vc );
  15503. dcd = vc.distanceTo( vd );
  15504. dad = va.distanceTo( vd );
  15505. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  15506. m1 = geometry.vertices.length;
  15507. m2 = geometry.vertices.length + 1;
  15508. quadA = face.clone();
  15509. quadB = face.clone();
  15510. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  15511. vm1 = va.clone();
  15512. vm1.lerp( vb, 0.5 );
  15513. vm2 = vc.clone();
  15514. vm2.lerp( vd, 0.5 );
  15515. quadA.a = a;
  15516. quadA.b = m1;
  15517. quadA.c = m2;
  15518. quadA.d = d;
  15519. quadB.a = m1;
  15520. quadB.b = b;
  15521. quadB.c = c;
  15522. quadB.d = m2;
  15523. if ( face.vertexNormals.length === 4 ) {
  15524. vnm1 = face.vertexNormals[ 0 ].clone();
  15525. vnm1.lerp( face.vertexNormals[ 1 ], 0.5 );
  15526. vnm2 = face.vertexNormals[ 2 ].clone();
  15527. vnm2.lerp( face.vertexNormals[ 3 ], 0.5 );
  15528. quadA.vertexNormals[ 1 ].copy( vnm1 );
  15529. quadA.vertexNormals[ 2 ].copy( vnm2 );
  15530. quadB.vertexNormals[ 0 ].copy( vnm1 );
  15531. quadB.vertexNormals[ 3 ].copy( vnm2 );
  15532. }
  15533. if ( face.vertexColors.length === 4 ) {
  15534. vcm1 = face.vertexColors[ 0 ].clone();
  15535. vcm1.lerp( face.vertexColors[ 1 ], 0.5 );
  15536. vcm2 = face.vertexColors[ 2 ].clone();
  15537. vcm2.lerp( face.vertexColors[ 3 ], 0.5 );
  15538. quadA.vertexColors[ 1 ].copy( vcm1 );
  15539. quadA.vertexColors[ 2 ].copy( vcm2 );
  15540. quadB.vertexColors[ 0 ].copy( vcm1 );
  15541. quadB.vertexColors[ 3 ].copy( vcm2 );
  15542. }
  15543. edge = 0;
  15544. } else {
  15545. vm1 = vb.clone();
  15546. vm1.lerp( vc, 0.5 );
  15547. vm2 = vd.clone();
  15548. vm2.lerp( va, 0.5 );
  15549. quadA.a = a;
  15550. quadA.b = b;
  15551. quadA.c = m1;
  15552. quadA.d = m2;
  15553. quadB.a = m2;
  15554. quadB.b = m1;
  15555. quadB.c = c;
  15556. quadB.d = d;
  15557. if ( face.vertexNormals.length === 4 ) {
  15558. vnm1 = face.vertexNormals[ 1 ].clone();
  15559. vnm1.lerp( face.vertexNormals[ 2 ], 0.5 );
  15560. vnm2 = face.vertexNormals[ 3 ].clone();
  15561. vnm2.lerp( face.vertexNormals[ 0 ], 0.5 );
  15562. quadA.vertexNormals[ 2 ].copy( vnm1 );
  15563. quadA.vertexNormals[ 3 ].copy( vnm2 );
  15564. quadB.vertexNormals[ 0 ].copy( vnm2 );
  15565. quadB.vertexNormals[ 1 ].copy( vnm1 );
  15566. }
  15567. if ( face.vertexColors.length === 4 ) {
  15568. vcm1 = face.vertexColors[ 1 ].clone();
  15569. vcm1.lerp( face.vertexColors[ 2 ], 0.5 );
  15570. vcm2 = face.vertexColors[ 3 ].clone();
  15571. vcm2.lerp( face.vertexColors[ 0 ], 0.5 );
  15572. quadA.vertexColors[ 2 ].copy( vcm1 );
  15573. quadA.vertexColors[ 3 ].copy( vcm2 );
  15574. quadB.vertexColors[ 0 ].copy( vcm2 );
  15575. quadB.vertexColors[ 1 ].copy( vcm1 );
  15576. }
  15577. edge = 1;
  15578. }
  15579. faces.push( quadA, quadB );
  15580. geometry.vertices.push( vm1, vm2 );
  15581. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  15582. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15583. if ( geometry.faceVertexUvs[ j ].length ) {
  15584. uvs = geometry.faceVertexUvs[ j ][ i ];
  15585. uvA = uvs[ 0 ];
  15586. uvB = uvs[ 1 ];
  15587. uvC = uvs[ 2 ];
  15588. uvD = uvs[ 3 ];
  15589. // AB + CD
  15590. if ( edge === 0 ) {
  15591. uvM1 = uvA.clone();
  15592. uvM1.lerp( uvB, 0.5 );
  15593. uvM2 = uvC.clone();
  15594. uvM2.lerp( uvD, 0.5 );
  15595. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  15596. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  15597. // BC + AD
  15598. } else {
  15599. uvM1 = uvB.clone();
  15600. uvM1.lerp( uvC, 0.5 );
  15601. uvM2 = uvD.clone();
  15602. uvM2.lerp( uvA, 0.5 );
  15603. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  15604. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  15605. }
  15606. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  15607. }
  15608. }
  15609. } else {
  15610. faces.push( face );
  15611. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15612. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15613. }
  15614. }
  15615. }
  15616. }
  15617. geometry.faces = faces;
  15618. geometry.faceVertexUvs = faceVertexUvs;
  15619. },
  15620. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  15621. var faces = geometry.faces;
  15622. var start = startFace || 0;
  15623. var end = endFace || faces.length - 1;
  15624. for ( var i = start; i <= end; i ++ ) {
  15625. faces[i].materialIndex = index;
  15626. }
  15627. }
  15628. };
  15629. THREE.GeometryUtils.random = THREE.Math.random16;
  15630. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15631. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15632. /**
  15633. * @author alteredq / http://alteredqualia.com/
  15634. * @author mrdoob / http://mrdoob.com/
  15635. */
  15636. THREE.ImageUtils = {
  15637. crossOrigin: 'anonymous',
  15638. loadTexture: function ( url, mapping, onLoad, onError ) {
  15639. var image = new Image();
  15640. var texture = new THREE.Texture( image, mapping );
  15641. var loader = new THREE.ImageLoader();
  15642. loader.addEventListener( 'load', function ( event ) {
  15643. texture.image = event.content;
  15644. texture.needsUpdate = true;
  15645. if ( onLoad ) onLoad( texture );
  15646. } );
  15647. loader.addEventListener( 'error', function ( event ) {
  15648. if ( onError ) onError( event.message );
  15649. } );
  15650. loader.crossOrigin = this.crossOrigin;
  15651. loader.load( url, image );
  15652. texture.sourceFile = url;
  15653. return texture;
  15654. },
  15655. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15656. var texture = new THREE.CompressedTexture();
  15657. texture.mapping = mapping;
  15658. var request = new XMLHttpRequest();
  15659. request.onload = function () {
  15660. var buffer = request.response;
  15661. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15662. texture.format = dds.format;
  15663. texture.mipmaps = dds.mipmaps;
  15664. texture.image.width = dds.width;
  15665. texture.image.height = dds.height;
  15666. // gl.generateMipmap fails for compressed textures
  15667. // mipmaps must be embedded in the DDS file
  15668. // or texture filters must not use mipmapping
  15669. texture.generateMipmaps = false;
  15670. texture.needsUpdate = true;
  15671. if ( onLoad ) onLoad( texture );
  15672. }
  15673. request.onerror = onError;
  15674. request.open( 'GET', url, true );
  15675. request.responseType = "arraybuffer";
  15676. request.send( null );
  15677. return texture;
  15678. },
  15679. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15680. var images = [];
  15681. images.loadCount = 0;
  15682. var texture = new THREE.Texture();
  15683. texture.image = images;
  15684. if ( mapping !== undefined ) texture.mapping = mapping;
  15685. // no flipping needed for cube textures
  15686. texture.flipY = false;
  15687. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15688. var cubeImage = new Image();
  15689. images[ i ] = cubeImage;
  15690. cubeImage.onload = function () {
  15691. images.loadCount += 1;
  15692. if ( images.loadCount === 6 ) {
  15693. texture.needsUpdate = true;
  15694. if ( onLoad ) onLoad( texture );
  15695. }
  15696. };
  15697. cubeImage.onerror = onError;
  15698. cubeImage.crossOrigin = this.crossOrigin;
  15699. cubeImage.src = array[ i ];
  15700. }
  15701. return texture;
  15702. },
  15703. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15704. var images = [];
  15705. images.loadCount = 0;
  15706. var texture = new THREE.CompressedTexture();
  15707. texture.image = images;
  15708. if ( mapping !== undefined ) texture.mapping = mapping;
  15709. // no flipping for cube textures
  15710. // (also flipping doesn't work for compressed textures )
  15711. texture.flipY = false;
  15712. // can't generate mipmaps for compressed textures
  15713. // mips must be embedded in DDS files
  15714. texture.generateMipmaps = false;
  15715. var generateCubeFaceCallback = function ( rq, img ) {
  15716. return function () {
  15717. var buffer = rq.response;
  15718. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15719. img.format = dds.format;
  15720. img.mipmaps = dds.mipmaps;
  15721. img.width = dds.width;
  15722. img.height = dds.height;
  15723. images.loadCount += 1;
  15724. if ( images.loadCount === 6 ) {
  15725. texture.format = dds.format;
  15726. texture.needsUpdate = true;
  15727. if ( onLoad ) onLoad( texture );
  15728. }
  15729. }
  15730. }
  15731. // compressed cubemap textures as 6 separate DDS files
  15732. if ( array instanceof Array ) {
  15733. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15734. var cubeImage = {};
  15735. images[ i ] = cubeImage;
  15736. var request = new XMLHttpRequest();
  15737. request.onload = generateCubeFaceCallback( request, cubeImage );
  15738. request.onerror = onError;
  15739. var url = array[ i ];
  15740. request.open( 'GET', url, true );
  15741. request.responseType = "arraybuffer";
  15742. request.send( null );
  15743. }
  15744. // compressed cubemap texture stored in a single DDS file
  15745. } else {
  15746. var url = array;
  15747. var request = new XMLHttpRequest();
  15748. request.onload = function( ) {
  15749. var buffer = request.response;
  15750. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15751. if ( dds.isCubemap ) {
  15752. var faces = dds.mipmaps.length / dds.mipmapCount;
  15753. for ( var f = 0; f < faces; f ++ ) {
  15754. images[ f ] = { mipmaps : [] };
  15755. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15756. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15757. images[ f ].format = dds.format;
  15758. images[ f ].width = dds.width;
  15759. images[ f ].height = dds.height;
  15760. }
  15761. }
  15762. texture.format = dds.format;
  15763. texture.needsUpdate = true;
  15764. if ( onLoad ) onLoad( texture );
  15765. }
  15766. }
  15767. request.onerror = onError;
  15768. request.open( 'GET', url, true );
  15769. request.responseType = "arraybuffer";
  15770. request.send( null );
  15771. }
  15772. return texture;
  15773. },
  15774. parseDDS: function ( buffer, loadMipmaps ) {
  15775. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15776. // Adapted from @toji's DDS utils
  15777. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15778. // All values and structures referenced from:
  15779. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15780. var DDS_MAGIC = 0x20534444;
  15781. var DDSD_CAPS = 0x1,
  15782. DDSD_HEIGHT = 0x2,
  15783. DDSD_WIDTH = 0x4,
  15784. DDSD_PITCH = 0x8,
  15785. DDSD_PIXELFORMAT = 0x1000,
  15786. DDSD_MIPMAPCOUNT = 0x20000,
  15787. DDSD_LINEARSIZE = 0x80000,
  15788. DDSD_DEPTH = 0x800000;
  15789. var DDSCAPS_COMPLEX = 0x8,
  15790. DDSCAPS_MIPMAP = 0x400000,
  15791. DDSCAPS_TEXTURE = 0x1000;
  15792. var DDSCAPS2_CUBEMAP = 0x200,
  15793. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15794. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15795. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15796. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15797. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15798. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15799. DDSCAPS2_VOLUME = 0x200000;
  15800. var DDPF_ALPHAPIXELS = 0x1,
  15801. DDPF_ALPHA = 0x2,
  15802. DDPF_FOURCC = 0x4,
  15803. DDPF_RGB = 0x40,
  15804. DDPF_YUV = 0x200,
  15805. DDPF_LUMINANCE = 0x20000;
  15806. function fourCCToInt32( value ) {
  15807. return value.charCodeAt(0) +
  15808. (value.charCodeAt(1) << 8) +
  15809. (value.charCodeAt(2) << 16) +
  15810. (value.charCodeAt(3) << 24);
  15811. }
  15812. function int32ToFourCC( value ) {
  15813. return String.fromCharCode(
  15814. value & 0xff,
  15815. (value >> 8) & 0xff,
  15816. (value >> 16) & 0xff,
  15817. (value >> 24) & 0xff
  15818. );
  15819. }
  15820. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15821. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15822. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15823. var headerLengthInt = 31; // The header length in 32 bit ints
  15824. // Offsets into the header array
  15825. var off_magic = 0;
  15826. var off_size = 1;
  15827. var off_flags = 2;
  15828. var off_height = 3;
  15829. var off_width = 4;
  15830. var off_mipmapCount = 7;
  15831. var off_pfFlags = 20;
  15832. var off_pfFourCC = 21;
  15833. var off_caps = 27;
  15834. var off_caps2 = 28;
  15835. var off_caps3 = 29;
  15836. var off_caps4 = 30;
  15837. // Parse header
  15838. var header = new Int32Array( buffer, 0, headerLengthInt );
  15839. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15840. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15841. return dds;
  15842. }
  15843. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15844. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15845. return dds;
  15846. }
  15847. var blockBytes;
  15848. var fourCC = header[ off_pfFourCC ];
  15849. switch ( fourCC ) {
  15850. case FOURCC_DXT1:
  15851. blockBytes = 8;
  15852. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15853. break;
  15854. case FOURCC_DXT3:
  15855. blockBytes = 16;
  15856. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15857. break;
  15858. case FOURCC_DXT5:
  15859. blockBytes = 16;
  15860. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15861. break;
  15862. default:
  15863. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15864. return dds;
  15865. }
  15866. dds.mipmapCount = 1;
  15867. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15868. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15869. }
  15870. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15871. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15872. dds.width = header[ off_width ];
  15873. dds.height = header[ off_height ];
  15874. var dataOffset = header[ off_size ] + 4;
  15875. // Extract mipmaps buffers
  15876. var width = dds.width;
  15877. var height = dds.height;
  15878. var faces = dds.isCubemap ? 6 : 1;
  15879. for ( var face = 0; face < faces; face ++ ) {
  15880. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15881. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15882. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15883. var mipmap = { "data": byteArray, "width": width, "height": height };
  15884. dds.mipmaps.push( mipmap );
  15885. dataOffset += dataLength;
  15886. width = Math.max( width * 0.5, 1 );
  15887. height = Math.max( height * 0.5, 1 );
  15888. }
  15889. width = dds.width;
  15890. height = dds.height;
  15891. }
  15892. return dds;
  15893. },
  15894. getNormalMap: function ( image, depth ) {
  15895. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15896. var cross = function ( a, b ) {
  15897. 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 ] ];
  15898. }
  15899. var subtract = function ( a, b ) {
  15900. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15901. }
  15902. var normalize = function ( a ) {
  15903. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15904. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15905. }
  15906. depth = depth | 1;
  15907. var width = image.width;
  15908. var height = image.height;
  15909. var canvas = document.createElement( 'canvas' );
  15910. canvas.width = width;
  15911. canvas.height = height;
  15912. var context = canvas.getContext( '2d' );
  15913. context.drawImage( image, 0, 0 );
  15914. var data = context.getImageData( 0, 0, width, height ).data;
  15915. var imageData = context.createImageData( width, height );
  15916. var output = imageData.data;
  15917. for ( var x = 0; x < width; x ++ ) {
  15918. for ( var y = 0; y < height; y ++ ) {
  15919. var ly = y - 1 < 0 ? 0 : y - 1;
  15920. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15921. var lx = x - 1 < 0 ? 0 : x - 1;
  15922. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15923. var points = [];
  15924. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15925. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15926. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15927. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15928. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15929. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15930. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15931. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15932. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15933. var normals = [];
  15934. var num_points = points.length;
  15935. for ( var i = 0; i < num_points; i ++ ) {
  15936. var v1 = points[ i ];
  15937. var v2 = points[ ( i + 1 ) % num_points ];
  15938. v1 = subtract( v1, origin );
  15939. v2 = subtract( v2, origin );
  15940. normals.push( normalize( cross( v1, v2 ) ) );
  15941. }
  15942. var normal = [ 0, 0, 0 ];
  15943. for ( var i = 0; i < normals.length; i ++ ) {
  15944. normal[ 0 ] += normals[ i ][ 0 ];
  15945. normal[ 1 ] += normals[ i ][ 1 ];
  15946. normal[ 2 ] += normals[ i ][ 2 ];
  15947. }
  15948. normal[ 0 ] /= normals.length;
  15949. normal[ 1 ] /= normals.length;
  15950. normal[ 2 ] /= normals.length;
  15951. var idx = ( y * width + x ) * 4;
  15952. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15953. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15954. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15955. output[ idx + 3 ] = 255;
  15956. }
  15957. }
  15958. context.putImageData( imageData, 0, 0 );
  15959. return canvas;
  15960. },
  15961. generateDataTexture: function ( width, height, color ) {
  15962. var size = width * height;
  15963. var data = new Uint8Array( 3 * size );
  15964. var r = Math.floor( color.r * 255 );
  15965. var g = Math.floor( color.g * 255 );
  15966. var b = Math.floor( color.b * 255 );
  15967. for ( var i = 0; i < size; i ++ ) {
  15968. data[ i * 3 ] = r;
  15969. data[ i * 3 + 1 ] = g;
  15970. data[ i * 3 + 2 ] = b;
  15971. }
  15972. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15973. texture.needsUpdate = true;
  15974. return texture;
  15975. }
  15976. };
  15977. /**
  15978. * @author alteredq / http://alteredqualia.com/
  15979. */
  15980. THREE.SceneUtils = {
  15981. createMultiMaterialObject: function ( geometry, materials ) {
  15982. var group = new THREE.Object3D();
  15983. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15984. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15985. }
  15986. return group;
  15987. },
  15988. detach : function ( child, parent, scene ) {
  15989. child.applyMatrix( parent.matrixWorld );
  15990. parent.remove( child );
  15991. scene.add( child );
  15992. },
  15993. attach: function ( child, scene, parent ) {
  15994. var matrixWorldInverse = new THREE.Matrix4();
  15995. matrixWorldInverse.getInverse( parent.matrixWorld );
  15996. child.applyMatrix( matrixWorldInverse );
  15997. scene.remove( child );
  15998. parent.add( child );
  15999. }
  16000. };
  16001. /**
  16002. * @author alteredq / http://alteredqualia.com/
  16003. * @author mrdoob / http://mrdoob.com/
  16004. *
  16005. * ShaderUtils currently contains:
  16006. *
  16007. * fresnel
  16008. * normal
  16009. * cube
  16010. *
  16011. */
  16012. THREE.ShaderUtils = {
  16013. lib: {
  16014. /* -------------------------------------------------------------------------
  16015. // Fresnel shader
  16016. // - based on Nvidia Cg tutorial
  16017. ------------------------------------------------------------------------- */
  16018. 'fresnel': {
  16019. uniforms: {
  16020. "mRefractionRatio": { type: "f", value: 1.02 },
  16021. "mFresnelBias": { type: "f", value: 0.1 },
  16022. "mFresnelPower": { type: "f", value: 2.0 },
  16023. "mFresnelScale": { type: "f", value: 1.0 },
  16024. "tCube": { type: "t", value: null }
  16025. },
  16026. fragmentShader: [
  16027. "uniform samplerCube tCube;",
  16028. "varying vec3 vReflect;",
  16029. "varying vec3 vRefract[3];",
  16030. "varying float vReflectionFactor;",
  16031. "void main() {",
  16032. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  16033. "vec4 refractedColor = vec4( 1.0 );",
  16034. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  16035. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  16036. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  16037. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  16038. "}"
  16039. ].join("\n"),
  16040. vertexShader: [
  16041. "uniform float mRefractionRatio;",
  16042. "uniform float mFresnelBias;",
  16043. "uniform float mFresnelScale;",
  16044. "uniform float mFresnelPower;",
  16045. "varying vec3 vReflect;",
  16046. "varying vec3 vRefract[3];",
  16047. "varying float vReflectionFactor;",
  16048. "void main() {",
  16049. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  16050. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  16051. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  16052. "vec3 I = worldPosition.xyz - cameraPosition;",
  16053. "vReflect = reflect( I, worldNormal );",
  16054. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  16055. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  16056. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  16057. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  16058. "gl_Position = projectionMatrix * mvPosition;",
  16059. "}"
  16060. ].join("\n")
  16061. },
  16062. /* -------------------------------------------------------------------------
  16063. // Normal map shader
  16064. // - Blinn-Phong
  16065. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  16066. // - point and directional lights (use with "lights: true" material option)
  16067. ------------------------------------------------------------------------- */
  16068. 'normal' : {
  16069. uniforms: THREE.UniformsUtils.merge( [
  16070. THREE.UniformsLib[ "fog" ],
  16071. THREE.UniformsLib[ "lights" ],
  16072. THREE.UniformsLib[ "shadowmap" ],
  16073. {
  16074. "enableAO" : { type: "i", value: 0 },
  16075. "enableDiffuse" : { type: "i", value: 0 },
  16076. "enableSpecular" : { type: "i", value: 0 },
  16077. "enableReflection": { type: "i", value: 0 },
  16078. "enableDisplacement": { type: "i", value: 0 },
  16079. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  16080. "tDiffuse" : { type: "t", value: null },
  16081. "tCube" : { type: "t", value: null },
  16082. "tNormal" : { type: "t", value: null },
  16083. "tSpecular" : { type: "t", value: null },
  16084. "tAO" : { type: "t", value: null },
  16085. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  16086. "uDisplacementBias": { type: "f", value: 0.0 },
  16087. "uDisplacementScale": { type: "f", value: 1.0 },
  16088. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  16089. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  16090. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  16091. "uShininess": { type: "f", value: 30 },
  16092. "uOpacity": { type: "f", value: 1 },
  16093. "useRefract": { type: "i", value: 0 },
  16094. "uRefractionRatio": { type: "f", value: 0.98 },
  16095. "uReflectivity": { type: "f", value: 0.5 },
  16096. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  16097. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  16098. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  16099. }
  16100. ] ),
  16101. fragmentShader: [
  16102. "uniform vec3 uAmbientColor;",
  16103. "uniform vec3 uDiffuseColor;",
  16104. "uniform vec3 uSpecularColor;",
  16105. "uniform float uShininess;",
  16106. "uniform float uOpacity;",
  16107. "uniform bool enableDiffuse;",
  16108. "uniform bool enableSpecular;",
  16109. "uniform bool enableAO;",
  16110. "uniform bool enableReflection;",
  16111. "uniform sampler2D tDiffuse;",
  16112. "uniform sampler2D tNormal;",
  16113. "uniform sampler2D tSpecular;",
  16114. "uniform sampler2D tAO;",
  16115. "uniform samplerCube tCube;",
  16116. "uniform vec2 uNormalScale;",
  16117. "uniform bool useRefract;",
  16118. "uniform float uRefractionRatio;",
  16119. "uniform float uReflectivity;",
  16120. "varying vec3 vTangent;",
  16121. "varying vec3 vBinormal;",
  16122. "varying vec3 vNormal;",
  16123. "varying vec2 vUv;",
  16124. "uniform vec3 ambientLightColor;",
  16125. "#if MAX_DIR_LIGHTS > 0",
  16126. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  16127. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  16128. "#endif",
  16129. "#if MAX_HEMI_LIGHTS > 0",
  16130. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  16131. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  16132. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  16133. "#endif",
  16134. "#if MAX_POINT_LIGHTS > 0",
  16135. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  16136. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  16137. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  16138. "#endif",
  16139. "#if MAX_SPOT_LIGHTS > 0",
  16140. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  16141. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  16142. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  16143. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  16144. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  16145. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  16146. "#endif",
  16147. "#ifdef WRAP_AROUND",
  16148. "uniform vec3 wrapRGB;",
  16149. "#endif",
  16150. "varying vec3 vWorldPosition;",
  16151. "varying vec3 vViewPosition;",
  16152. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  16153. THREE.ShaderChunk[ "fog_pars_fragment" ],
  16154. "void main() {",
  16155. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  16156. "vec3 specularTex = vec3( 1.0 );",
  16157. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  16158. "normalTex.xy *= uNormalScale;",
  16159. "normalTex = normalize( normalTex );",
  16160. "if( enableDiffuse ) {",
  16161. "#ifdef GAMMA_INPUT",
  16162. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  16163. "texelColor.xyz *= texelColor.xyz;",
  16164. "gl_FragColor = gl_FragColor * texelColor;",
  16165. "#else",
  16166. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  16167. "#endif",
  16168. "}",
  16169. "if( enableAO ) {",
  16170. "#ifdef GAMMA_INPUT",
  16171. "vec4 aoColor = texture2D( tAO, vUv );",
  16172. "aoColor.xyz *= aoColor.xyz;",
  16173. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  16174. "#else",
  16175. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  16176. "#endif",
  16177. "}",
  16178. "if( enableSpecular )",
  16179. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  16180. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  16181. "vec3 finalNormal = tsb * normalTex;",
  16182. "#ifdef FLIP_SIDED",
  16183. "finalNormal = -finalNormal;",
  16184. "#endif",
  16185. "vec3 normal = normalize( finalNormal );",
  16186. "vec3 viewPosition = normalize( vViewPosition );",
  16187. // point lights
  16188. "#if MAX_POINT_LIGHTS > 0",
  16189. "vec3 pointDiffuse = vec3( 0.0 );",
  16190. "vec3 pointSpecular = vec3( 0.0 );",
  16191. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  16192. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  16193. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  16194. "float pointDistance = 1.0;",
  16195. "if ( pointLightDistance[ i ] > 0.0 )",
  16196. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  16197. "pointVector = normalize( pointVector );",
  16198. // diffuse
  16199. "#ifdef WRAP_AROUND",
  16200. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  16201. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  16202. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  16203. "#else",
  16204. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  16205. "#endif",
  16206. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  16207. // specular
  16208. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  16209. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  16210. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  16211. "#ifdef PHYSICALLY_BASED_SHADING",
  16212. // 2.0 => 2.0001 is hack to work around ANGLE bug
  16213. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  16214. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  16215. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  16216. "#else",
  16217. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  16218. "#endif",
  16219. "}",
  16220. "#endif",
  16221. // spot lights
  16222. "#if MAX_SPOT_LIGHTS > 0",
  16223. "vec3 spotDiffuse = vec3( 0.0 );",
  16224. "vec3 spotSpecular = vec3( 0.0 );",
  16225. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  16226. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  16227. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  16228. "float spotDistance = 1.0;",
  16229. "if ( spotLightDistance[ i ] > 0.0 )",
  16230. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  16231. "spotVector = normalize( spotVector );",
  16232. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  16233. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  16234. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  16235. // diffuse
  16236. "#ifdef WRAP_AROUND",
  16237. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  16238. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  16239. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  16240. "#else",
  16241. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  16242. "#endif",
  16243. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  16244. // specular
  16245. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  16246. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  16247. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  16248. "#ifdef PHYSICALLY_BASED_SHADING",
  16249. // 2.0 => 2.0001 is hack to work around ANGLE bug
  16250. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  16251. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  16252. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  16253. "#else",
  16254. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  16255. "#endif",
  16256. "}",
  16257. "}",
  16258. "#endif",
  16259. // directional lights
  16260. "#if MAX_DIR_LIGHTS > 0",
  16261. "vec3 dirDiffuse = vec3( 0.0 );",
  16262. "vec3 dirSpecular = vec3( 0.0 );",
  16263. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  16264. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  16265. "vec3 dirVector = normalize( lDirection.xyz );",
  16266. // diffuse
  16267. "#ifdef WRAP_AROUND",
  16268. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  16269. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  16270. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  16271. "#else",
  16272. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  16273. "#endif",
  16274. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  16275. // specular
  16276. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  16277. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  16278. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  16279. "#ifdef PHYSICALLY_BASED_SHADING",
  16280. // 2.0 => 2.0001 is hack to work around ANGLE bug
  16281. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  16282. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  16283. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  16284. "#else",
  16285. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  16286. "#endif",
  16287. "}",
  16288. "#endif",
  16289. // hemisphere lights
  16290. "#if MAX_HEMI_LIGHTS > 0",
  16291. "vec3 hemiDiffuse = vec3( 0.0 );",
  16292. "vec3 hemiSpecular = vec3( 0.0 );" ,
  16293. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  16294. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  16295. "vec3 lVector = normalize( lDirection.xyz );",
  16296. // diffuse
  16297. "float dotProduct = dot( normal, lVector );",
  16298. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  16299. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  16300. "hemiDiffuse += uDiffuseColor * hemiColor;",
  16301. // specular (sky light)
  16302. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  16303. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  16304. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  16305. // specular (ground light)
  16306. "vec3 lVectorGround = -lVector;",
  16307. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  16308. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  16309. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  16310. "#ifdef PHYSICALLY_BASED_SHADING",
  16311. "float dotProductGround = dot( normal, lVectorGround );",
  16312. // 2.0 => 2.0001 is hack to work around ANGLE bug
  16313. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  16314. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  16315. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  16316. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  16317. "#else",
  16318. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  16319. "#endif",
  16320. "}",
  16321. "#endif",
  16322. // all lights contribution summation
  16323. "vec3 totalDiffuse = vec3( 0.0 );",
  16324. "vec3 totalSpecular = vec3( 0.0 );",
  16325. "#if MAX_DIR_LIGHTS > 0",
  16326. "totalDiffuse += dirDiffuse;",
  16327. "totalSpecular += dirSpecular;",
  16328. "#endif",
  16329. "#if MAX_HEMI_LIGHTS > 0",
  16330. "totalDiffuse += hemiDiffuse;",
  16331. "totalSpecular += hemiSpecular;",
  16332. "#endif",
  16333. "#if MAX_POINT_LIGHTS > 0",
  16334. "totalDiffuse += pointDiffuse;",
  16335. "totalSpecular += pointSpecular;",
  16336. "#endif",
  16337. "#if MAX_SPOT_LIGHTS > 0",
  16338. "totalDiffuse += spotDiffuse;",
  16339. "totalSpecular += spotSpecular;",
  16340. "#endif",
  16341. "#ifdef METAL",
  16342. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  16343. "#else",
  16344. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  16345. "#endif",
  16346. "if ( enableReflection ) {",
  16347. "vec3 vReflect;",
  16348. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  16349. "if ( useRefract ) {",
  16350. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  16351. "} else {",
  16352. "vReflect = reflect( cameraToVertex, normal );",
  16353. "}",
  16354. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  16355. "#ifdef GAMMA_INPUT",
  16356. "cubeColor.xyz *= cubeColor.xyz;",
  16357. "#endif",
  16358. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  16359. "}",
  16360. THREE.ShaderChunk[ "shadowmap_fragment" ],
  16361. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  16362. THREE.ShaderChunk[ "fog_fragment" ],
  16363. "}"
  16364. ].join("\n"),
  16365. vertexShader: [
  16366. "attribute vec4 tangent;",
  16367. "uniform vec2 uOffset;",
  16368. "uniform vec2 uRepeat;",
  16369. "uniform bool enableDisplacement;",
  16370. "#ifdef VERTEX_TEXTURES",
  16371. "uniform sampler2D tDisplacement;",
  16372. "uniform float uDisplacementScale;",
  16373. "uniform float uDisplacementBias;",
  16374. "#endif",
  16375. "varying vec3 vTangent;",
  16376. "varying vec3 vBinormal;",
  16377. "varying vec3 vNormal;",
  16378. "varying vec2 vUv;",
  16379. "varying vec3 vWorldPosition;",
  16380. "varying vec3 vViewPosition;",
  16381. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  16382. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  16383. "void main() {",
  16384. THREE.ShaderChunk[ "skinbase_vertex" ],
  16385. THREE.ShaderChunk[ "skinnormal_vertex" ],
  16386. // normal, tangent and binormal vectors
  16387. "#ifdef USE_SKINNING",
  16388. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  16389. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  16390. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  16391. "#else",
  16392. "vNormal = normalize( normalMatrix * normal );",
  16393. "vTangent = normalize( normalMatrix * tangent.xyz );",
  16394. "#endif",
  16395. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  16396. "vUv = uv * uRepeat + uOffset;",
  16397. // displacement mapping
  16398. "vec3 displacedPosition;",
  16399. "#ifdef VERTEX_TEXTURES",
  16400. "if ( enableDisplacement ) {",
  16401. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  16402. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  16403. "displacedPosition = position + normalize( normal ) * df;",
  16404. "} else {",
  16405. "#ifdef USE_SKINNING",
  16406. "vec4 skinVertex = vec4( position, 1.0 );",
  16407. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  16408. "skinned += boneMatY * skinVertex * skinWeight.y;",
  16409. "displacedPosition = skinned.xyz;",
  16410. "#else",
  16411. "displacedPosition = position;",
  16412. "#endif",
  16413. "}",
  16414. "#else",
  16415. "#ifdef USE_SKINNING",
  16416. "vec4 skinVertex = vec4( position, 1.0 );",
  16417. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  16418. "skinned += boneMatY * skinVertex * skinWeight.y;",
  16419. "displacedPosition = skinned.xyz;",
  16420. "#else",
  16421. "displacedPosition = position;",
  16422. "#endif",
  16423. "#endif",
  16424. //
  16425. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  16426. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  16427. "gl_Position = projectionMatrix * mvPosition;",
  16428. //
  16429. "vWorldPosition = worldPosition.xyz;",
  16430. "vViewPosition = -mvPosition.xyz;",
  16431. // shadows
  16432. "#ifdef USE_SHADOWMAP",
  16433. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  16434. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  16435. "}",
  16436. "#endif",
  16437. "}"
  16438. ].join("\n")
  16439. },
  16440. /* -------------------------------------------------------------------------
  16441. // Cube map shader
  16442. ------------------------------------------------------------------------- */
  16443. 'cube': {
  16444. uniforms: { "tCube": { type: "t", value: null },
  16445. "tFlip": { type: "f", value: -1 } },
  16446. vertexShader: [
  16447. "varying vec3 vWorldPosition;",
  16448. "void main() {",
  16449. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  16450. "vWorldPosition = worldPosition.xyz;",
  16451. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  16452. "}"
  16453. ].join("\n"),
  16454. fragmentShader: [
  16455. "uniform samplerCube tCube;",
  16456. "uniform float tFlip;",
  16457. "varying vec3 vWorldPosition;",
  16458. "void main() {",
  16459. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  16460. "}"
  16461. ].join("\n")
  16462. }
  16463. }
  16464. };
  16465. /**
  16466. * @author zz85 / http://www.lab4games.net/zz85/blog
  16467. * @author alteredq / http://alteredqualia.com/
  16468. *
  16469. * For Text operations in three.js (See TextGeometry)
  16470. *
  16471. * It uses techniques used in:
  16472. *
  16473. * typeface.js and canvastext
  16474. * For converting fonts and rendering with javascript
  16475. * http://typeface.neocracy.org
  16476. *
  16477. * Triangulation ported from AS3
  16478. * Simple Polygon Triangulation
  16479. * http://actionsnippet.com/?p=1462
  16480. *
  16481. * A Method to triangulate shapes with holes
  16482. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16483. *
  16484. */
  16485. THREE.FontUtils = {
  16486. faces : {},
  16487. // Just for now. face[weight][style]
  16488. face : "helvetiker",
  16489. weight: "normal",
  16490. style : "normal",
  16491. size : 150,
  16492. divisions : 10,
  16493. getFace : function() {
  16494. return this.faces[ this.face ][ this.weight ][ this.style ];
  16495. },
  16496. loadFace : function( data ) {
  16497. var family = data.familyName.toLowerCase();
  16498. var ThreeFont = this;
  16499. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16500. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16501. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16502. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16503. return data;
  16504. },
  16505. drawText : function( text ) {
  16506. var characterPts = [], allPts = [];
  16507. // RenderText
  16508. var i, p,
  16509. face = this.getFace(),
  16510. scale = this.size / face.resolution,
  16511. offset = 0,
  16512. chars = String( text ).split( '' ),
  16513. length = chars.length;
  16514. var fontPaths = [];
  16515. for ( i = 0; i < length; i ++ ) {
  16516. var path = new THREE.Path();
  16517. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16518. offset += ret.offset;
  16519. fontPaths.push( ret.path );
  16520. }
  16521. // get the width
  16522. var width = offset / 2;
  16523. //
  16524. // for ( p = 0; p < allPts.length; p++ ) {
  16525. //
  16526. // allPts[ p ].x -= width;
  16527. //
  16528. // }
  16529. //var extract = this.extractPoints( allPts, characterPts );
  16530. //extract.contour = allPts;
  16531. //extract.paths = fontPaths;
  16532. //extract.offset = width;
  16533. return { paths : fontPaths, offset : width };
  16534. },
  16535. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16536. var pts = [];
  16537. var i, i2, divisions,
  16538. outline, action, length,
  16539. scaleX, scaleY,
  16540. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16541. laste,
  16542. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16543. if ( !glyph ) return;
  16544. if ( glyph.o ) {
  16545. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16546. length = outline.length;
  16547. scaleX = scale;
  16548. scaleY = scale;
  16549. for ( i = 0; i < length; ) {
  16550. action = outline[ i ++ ];
  16551. //console.log( action );
  16552. switch( action ) {
  16553. case 'm':
  16554. // Move To
  16555. x = outline[ i++ ] * scaleX + offset;
  16556. y = outline[ i++ ] * scaleY;
  16557. path.moveTo( x, y );
  16558. break;
  16559. case 'l':
  16560. // Line To
  16561. x = outline[ i++ ] * scaleX + offset;
  16562. y = outline[ i++ ] * scaleY;
  16563. path.lineTo(x,y);
  16564. break;
  16565. case 'q':
  16566. // QuadraticCurveTo
  16567. cpx = outline[ i++ ] * scaleX + offset;
  16568. cpy = outline[ i++ ] * scaleY;
  16569. cpx1 = outline[ i++ ] * scaleX + offset;
  16570. cpy1 = outline[ i++ ] * scaleY;
  16571. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16572. laste = pts[ pts.length - 1 ];
  16573. if ( laste ) {
  16574. cpx0 = laste.x;
  16575. cpy0 = laste.y;
  16576. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16577. var t = i2 / divisions;
  16578. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16579. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16580. }
  16581. }
  16582. break;
  16583. case 'b':
  16584. // Cubic Bezier Curve
  16585. cpx = outline[ i++ ] * scaleX + offset;
  16586. cpy = outline[ i++ ] * scaleY;
  16587. cpx1 = outline[ i++ ] * scaleX + offset;
  16588. cpy1 = outline[ i++ ] * -scaleY;
  16589. cpx2 = outline[ i++ ] * scaleX + offset;
  16590. cpy2 = outline[ i++ ] * -scaleY;
  16591. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16592. laste = pts[ pts.length - 1 ];
  16593. if ( laste ) {
  16594. cpx0 = laste.x;
  16595. cpy0 = laste.y;
  16596. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16597. var t = i2 / divisions;
  16598. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16599. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16600. }
  16601. }
  16602. break;
  16603. }
  16604. }
  16605. }
  16606. return { offset: glyph.ha*scale, path:path};
  16607. }
  16608. };
  16609. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16610. // Parameters
  16611. parameters = parameters || {};
  16612. var size = parameters.size !== undefined ? parameters.size : 100;
  16613. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16614. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16615. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16616. var style = parameters.style !== undefined ? parameters.style : "normal";
  16617. THREE.FontUtils.size = size;
  16618. THREE.FontUtils.divisions = curveSegments;
  16619. THREE.FontUtils.face = font;
  16620. THREE.FontUtils.weight = weight;
  16621. THREE.FontUtils.style = style;
  16622. // Get a Font data json object
  16623. var data = THREE.FontUtils.drawText( text );
  16624. var paths = data.paths;
  16625. var shapes = [];
  16626. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16627. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16628. }
  16629. return shapes;
  16630. };
  16631. /**
  16632. * This code is a quick port of code written in C++ which was submitted to
  16633. * flipcode.com by John W. Ratcliff // July 22, 2000
  16634. * See original code and more information here:
  16635. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16636. *
  16637. * ported to actionscript by Zevan Rosser
  16638. * www.actionsnippet.com
  16639. *
  16640. * ported to javascript by Joshua Koo
  16641. * http://www.lab4games.net/zz85/blog
  16642. *
  16643. */
  16644. ( function( namespace ) {
  16645. var EPSILON = 0.0000000001;
  16646. // takes in an contour array and returns
  16647. var process = function( contour, indices ) {
  16648. var n = contour.length;
  16649. if ( n < 3 ) return null;
  16650. var result = [],
  16651. verts = [],
  16652. vertIndices = [];
  16653. /* we want a counter-clockwise polygon in verts */
  16654. var u, v, w;
  16655. if ( area( contour ) > 0.0 ) {
  16656. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16657. } else {
  16658. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16659. }
  16660. var nv = n;
  16661. /* remove nv - 2 vertices, creating 1 triangle every time */
  16662. var count = 2 * nv; /* error detection */
  16663. for( v = nv - 1; nv > 2; ) {
  16664. /* if we loop, it is probably a non-simple polygon */
  16665. if ( ( count-- ) <= 0 ) {
  16666. //** Triangulate: ERROR - probable bad polygon!
  16667. //throw ( "Warning, unable to triangulate polygon!" );
  16668. //return null;
  16669. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16670. console.log( "Warning, unable to triangulate polygon!" );
  16671. if ( indices ) return vertIndices;
  16672. return result;
  16673. }
  16674. /* three consecutive vertices in current polygon, <u,v,w> */
  16675. u = v; if ( nv <= u ) u = 0; /* previous */
  16676. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16677. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16678. if ( snip( contour, u, v, w, nv, verts ) ) {
  16679. var a, b, c, s, t;
  16680. /* true names of the vertices */
  16681. a = verts[ u ];
  16682. b = verts[ v ];
  16683. c = verts[ w ];
  16684. /* output Triangle */
  16685. result.push( [ contour[ a ],
  16686. contour[ b ],
  16687. contour[ c ] ] );
  16688. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16689. /* remove v from the remaining polygon */
  16690. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16691. verts[ s ] = verts[ t ];
  16692. }
  16693. nv--;
  16694. /* reset error detection counter */
  16695. count = 2 * nv;
  16696. }
  16697. }
  16698. if ( indices ) return vertIndices;
  16699. return result;
  16700. };
  16701. // calculate area of the contour polygon
  16702. var area = function ( contour ) {
  16703. var n = contour.length;
  16704. var a = 0.0;
  16705. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16706. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16707. }
  16708. return a * 0.5;
  16709. };
  16710. var snip = function ( contour, u, v, w, n, verts ) {
  16711. var p;
  16712. var ax, ay, bx, by;
  16713. var cx, cy, px, py;
  16714. ax = contour[ verts[ u ] ].x;
  16715. ay = contour[ verts[ u ] ].y;
  16716. bx = contour[ verts[ v ] ].x;
  16717. by = contour[ verts[ v ] ].y;
  16718. cx = contour[ verts[ w ] ].x;
  16719. cy = contour[ verts[ w ] ].y;
  16720. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16721. var aX, aY, bX, bY, cX, cY;
  16722. var apx, apy, bpx, bpy, cpx, cpy;
  16723. var cCROSSap, bCROSScp, aCROSSbp;
  16724. aX = cx - bx; aY = cy - by;
  16725. bX = ax - cx; bY = ay - cy;
  16726. cX = bx - ax; cY = by - ay;
  16727. for ( p = 0; p < n; p++ ) {
  16728. if( (p === u) || (p === v) || (p === w) ) continue;
  16729. px = contour[ verts[ p ] ].x
  16730. py = contour[ verts[ p ] ].y
  16731. apx = px - ax; apy = py - ay;
  16732. bpx = px - bx; bpy = py - by;
  16733. cpx = px - cx; cpy = py - cy;
  16734. // see if p is inside triangle abc
  16735. aCROSSbp = aX*bpy - aY*bpx;
  16736. cCROSSap = cX*apy - cY*apx;
  16737. bCROSScp = bX*cpy - bY*cpx;
  16738. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16739. }
  16740. return true;
  16741. };
  16742. namespace.Triangulate = process;
  16743. namespace.Triangulate.area = area;
  16744. return namespace;
  16745. })(THREE.FontUtils);
  16746. // To use the typeface.js face files, hook up the API
  16747. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16748. * @author zz85 / http://www.lab4games.net/zz85/blog
  16749. * Extensible curve object
  16750. *
  16751. * Some common of Curve methods
  16752. * .getPoint(t), getTangent(t)
  16753. * .getPointAt(u), getTagentAt(u)
  16754. * .getPoints(), .getSpacedPoints()
  16755. * .getLength()
  16756. * .updateArcLengths()
  16757. *
  16758. * This file contains following classes:
  16759. *
  16760. * -- 2d classes --
  16761. * THREE.Curve
  16762. * THREE.LineCurve
  16763. * THREE.QuadraticBezierCurve
  16764. * THREE.CubicBezierCurve
  16765. * THREE.SplineCurve
  16766. * THREE.ArcCurve
  16767. * THREE.EllipseCurve
  16768. *
  16769. * -- 3d classes --
  16770. * THREE.LineCurve3
  16771. * THREE.QuadraticBezierCurve3
  16772. * THREE.CubicBezierCurve3
  16773. * THREE.SplineCurve3
  16774. * THREE.ClosedSplineCurve3
  16775. *
  16776. * A series of curves can be represented as a THREE.CurvePath
  16777. *
  16778. **/
  16779. /**************************************************************
  16780. * Abstract Curve base class
  16781. **************************************************************/
  16782. THREE.Curve = function () {
  16783. };
  16784. // Virtual base class method to overwrite and implement in subclasses
  16785. // - t [0 .. 1]
  16786. THREE.Curve.prototype.getPoint = function ( t ) {
  16787. console.log( "Warning, getPoint() not implemented!" );
  16788. return null;
  16789. };
  16790. // Get point at relative position in curve according to arc length
  16791. // - u [0 .. 1]
  16792. THREE.Curve.prototype.getPointAt = function ( u ) {
  16793. var t = this.getUtoTmapping( u );
  16794. return this.getPoint( t );
  16795. };
  16796. // Get sequence of points using getPoint( t )
  16797. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16798. if ( !divisions ) divisions = 5;
  16799. var d, pts = [];
  16800. for ( d = 0; d <= divisions; d ++ ) {
  16801. pts.push( this.getPoint( d / divisions ) );
  16802. }
  16803. return pts;
  16804. };
  16805. // Get sequence of points using getPointAt( u )
  16806. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16807. if ( !divisions ) divisions = 5;
  16808. var d, pts = [];
  16809. for ( d = 0; d <= divisions; d ++ ) {
  16810. pts.push( this.getPointAt( d / divisions ) );
  16811. }
  16812. return pts;
  16813. };
  16814. // Get total curve arc length
  16815. THREE.Curve.prototype.getLength = function () {
  16816. var lengths = this.getLengths();
  16817. return lengths[ lengths.length - 1 ];
  16818. };
  16819. // Get list of cumulative segment lengths
  16820. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16821. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16822. if ( this.cacheArcLengths
  16823. && ( this.cacheArcLengths.length == divisions + 1 )
  16824. && !this.needsUpdate) {
  16825. //console.log( "cached", this.cacheArcLengths );
  16826. return this.cacheArcLengths;
  16827. }
  16828. this.needsUpdate = false;
  16829. var cache = [];
  16830. var current, last = this.getPoint( 0 );
  16831. var p, sum = 0;
  16832. cache.push( 0 );
  16833. for ( p = 1; p <= divisions; p ++ ) {
  16834. current = this.getPoint ( p / divisions );
  16835. sum += current.distanceTo( last );
  16836. cache.push( sum );
  16837. last = current;
  16838. }
  16839. this.cacheArcLengths = cache;
  16840. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16841. };
  16842. THREE.Curve.prototype.updateArcLengths = function() {
  16843. this.needsUpdate = true;
  16844. this.getLengths();
  16845. };
  16846. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16847. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16848. var arcLengths = this.getLengths();
  16849. var i = 0, il = arcLengths.length;
  16850. var targetArcLength; // The targeted u distance value to get
  16851. if ( distance ) {
  16852. targetArcLength = distance;
  16853. } else {
  16854. targetArcLength = u * arcLengths[ il - 1 ];
  16855. }
  16856. //var time = Date.now();
  16857. // binary search for the index with largest value smaller than target u distance
  16858. var low = 0, high = il - 1, comparison;
  16859. while ( low <= high ) {
  16860. 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
  16861. comparison = arcLengths[ i ] - targetArcLength;
  16862. if ( comparison < 0 ) {
  16863. low = i + 1;
  16864. continue;
  16865. } else if ( comparison > 0 ) {
  16866. high = i - 1;
  16867. continue;
  16868. } else {
  16869. high = i;
  16870. break;
  16871. // DONE
  16872. }
  16873. }
  16874. i = high;
  16875. //console.log('b' , i, low, high, Date.now()- time);
  16876. if ( arcLengths[ i ] == targetArcLength ) {
  16877. var t = i / ( il - 1 );
  16878. return t;
  16879. }
  16880. // we could get finer grain at lengths, or use simple interpolatation between two points
  16881. var lengthBefore = arcLengths[ i ];
  16882. var lengthAfter = arcLengths[ i + 1 ];
  16883. var segmentLength = lengthAfter - lengthBefore;
  16884. // determine where we are between the 'before' and 'after' points
  16885. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16886. // add that fractional amount to t
  16887. var t = ( i + segmentFraction ) / ( il -1 );
  16888. return t;
  16889. };
  16890. // Returns a unit vector tangent at t
  16891. // In case any sub curve does not implement its tangent derivation,
  16892. // 2 points a small delta apart will be used to find its gradient
  16893. // which seems to give a reasonable approximation
  16894. THREE.Curve.prototype.getTangent = function( t ) {
  16895. var delta = 0.0001;
  16896. var t1 = t - delta;
  16897. var t2 = t + delta;
  16898. // Capping in case of danger
  16899. if ( t1 < 0 ) t1 = 0;
  16900. if ( t2 > 1 ) t2 = 1;
  16901. var pt1 = this.getPoint( t1 );
  16902. var pt2 = this.getPoint( t2 );
  16903. var vec = pt2.clone().sub(pt1);
  16904. return vec.normalize();
  16905. };
  16906. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16907. var t = this.getUtoTmapping( u );
  16908. return this.getTangent( t );
  16909. };
  16910. /**************************************************************
  16911. * Line
  16912. **************************************************************/
  16913. THREE.LineCurve = function ( v1, v2 ) {
  16914. this.v1 = v1;
  16915. this.v2 = v2;
  16916. };
  16917. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16918. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16919. var point = this.v2.clone().sub(this.v1);
  16920. point.multiplyScalar( t ).add( this.v1 );
  16921. return point;
  16922. };
  16923. // Line curve is linear, so we can overwrite default getPointAt
  16924. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16925. return this.getPoint( u );
  16926. };
  16927. THREE.LineCurve.prototype.getTangent = function( t ) {
  16928. var tangent = this.v2.clone().sub(this.v1);
  16929. return tangent.normalize();
  16930. };
  16931. /**************************************************************
  16932. * Quadratic Bezier curve
  16933. **************************************************************/
  16934. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16935. this.v0 = v0;
  16936. this.v1 = v1;
  16937. this.v2 = v2;
  16938. };
  16939. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16940. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16941. var tx, ty;
  16942. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16943. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16944. return new THREE.Vector2( tx, ty );
  16945. };
  16946. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16947. var tx, ty;
  16948. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16949. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16950. // returns unit vector
  16951. var tangent = new THREE.Vector2( tx, ty );
  16952. tangent.normalize();
  16953. return tangent;
  16954. };
  16955. /**************************************************************
  16956. * Cubic Bezier curve
  16957. **************************************************************/
  16958. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16959. this.v0 = v0;
  16960. this.v1 = v1;
  16961. this.v2 = v2;
  16962. this.v3 = v3;
  16963. };
  16964. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16965. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16966. var tx, ty;
  16967. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16968. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16969. return new THREE.Vector2( tx, ty );
  16970. };
  16971. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16972. var tx, ty;
  16973. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16974. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16975. var tangent = new THREE.Vector2( tx, ty );
  16976. tangent.normalize();
  16977. return tangent;
  16978. };
  16979. /**************************************************************
  16980. * Spline curve
  16981. **************************************************************/
  16982. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16983. this.points = (points == undefined) ? [] : points;
  16984. };
  16985. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16986. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16987. var v = new THREE.Vector2();
  16988. var c = [];
  16989. var points = this.points, point, intPoint, weight;
  16990. point = ( points.length - 1 ) * t;
  16991. intPoint = Math.floor( point );
  16992. weight = point - intPoint;
  16993. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16994. c[ 1 ] = intPoint;
  16995. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16996. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16997. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16998. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16999. return v;
  17000. };
  17001. /**************************************************************
  17002. * Ellipse curve
  17003. **************************************************************/
  17004. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  17005. aStartAngle, aEndAngle,
  17006. aClockwise ) {
  17007. this.aX = aX;
  17008. this.aY = aY;
  17009. this.xRadius = xRadius;
  17010. this.yRadius = yRadius;
  17011. this.aStartAngle = aStartAngle;
  17012. this.aEndAngle = aEndAngle;
  17013. this.aClockwise = aClockwise;
  17014. };
  17015. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17016. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17017. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17018. if ( !this.aClockwise ) {
  17019. t = 1 - t;
  17020. }
  17021. var angle = this.aStartAngle + t * deltaAngle;
  17022. var tx = this.aX + this.xRadius * Math.cos( angle );
  17023. var ty = this.aY + this.yRadius * Math.sin( angle );
  17024. return new THREE.Vector2( tx, ty );
  17025. };
  17026. /**************************************************************
  17027. * Arc curve
  17028. **************************************************************/
  17029. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17030. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17031. };
  17032. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17033. /**************************************************************
  17034. * Utils
  17035. **************************************************************/
  17036. THREE.Curve.Utils = {
  17037. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17038. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17039. },
  17040. // Puay Bing, thanks for helping with this derivative!
  17041. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  17042. return -3 * p0 * (1 - t) * (1 - t) +
  17043. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  17044. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  17045. 3 * t * t * p3;
  17046. },
  17047. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17048. // To check if my formulas are correct
  17049. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17050. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17051. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  17052. var h11 = 3 * t * t - 2 * t; // t3 − t2
  17053. return h00 + h10 + h01 + h11;
  17054. },
  17055. // Catmull-Rom
  17056. interpolate: function( p0, p1, p2, p3, t ) {
  17057. var v0 = ( p2 - p0 ) * 0.5;
  17058. var v1 = ( p3 - p1 ) * 0.5;
  17059. var t2 = t * t;
  17060. var t3 = t * t2;
  17061. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17062. }
  17063. };
  17064. // TODO: Transformation for Curves?
  17065. /**************************************************************
  17066. * 3D Curves
  17067. **************************************************************/
  17068. // A Factory method for creating new curve subclasses
  17069. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17070. constructor.prototype = Object.create( THREE.Curve.prototype );
  17071. constructor.prototype.getPoint = getPointFunc;
  17072. return constructor;
  17073. };
  17074. /**************************************************************
  17075. * Line3D
  17076. **************************************************************/
  17077. THREE.LineCurve3 = THREE.Curve.create(
  17078. function ( v1, v2 ) {
  17079. this.v1 = v1;
  17080. this.v2 = v2;
  17081. },
  17082. function ( t ) {
  17083. var r = new THREE.Vector3();
  17084. r.sub( this.v2, this.v1 ); // diff
  17085. r.multiplyScalar( t );
  17086. r.add( this.v1 );
  17087. return r;
  17088. }
  17089. );
  17090. /**************************************************************
  17091. * Quadratic Bezier 3D curve
  17092. **************************************************************/
  17093. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17094. function ( v0, v1, v2 ) {
  17095. this.v0 = v0;
  17096. this.v1 = v1;
  17097. this.v2 = v2;
  17098. },
  17099. function ( t ) {
  17100. var tx, ty, tz;
  17101. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17102. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17103. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17104. return new THREE.Vector3( tx, ty, tz );
  17105. }
  17106. );
  17107. /**************************************************************
  17108. * Cubic Bezier 3D curve
  17109. **************************************************************/
  17110. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17111. function ( v0, v1, v2, v3 ) {
  17112. this.v0 = v0;
  17113. this.v1 = v1;
  17114. this.v2 = v2;
  17115. this.v3 = v3;
  17116. },
  17117. function ( t ) {
  17118. var tx, ty, tz;
  17119. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17120. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17121. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17122. return new THREE.Vector3( tx, ty, tz );
  17123. }
  17124. );
  17125. /**************************************************************
  17126. * Spline 3D curve
  17127. **************************************************************/
  17128. THREE.SplineCurve3 = THREE.Curve.create(
  17129. function ( points /* array of Vector3 */) {
  17130. this.points = (points == undefined) ? [] : points;
  17131. },
  17132. function ( t ) {
  17133. var v = new THREE.Vector3();
  17134. var c = [];
  17135. var points = this.points, point, intPoint, weight;
  17136. point = ( points.length - 1 ) * t;
  17137. intPoint = Math.floor( point );
  17138. weight = point - intPoint;
  17139. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17140. c[ 1 ] = intPoint;
  17141. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17142. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17143. var pt0 = points[ c[0] ],
  17144. pt1 = points[ c[1] ],
  17145. pt2 = points[ c[2] ],
  17146. pt3 = points[ c[3] ];
  17147. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17148. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17149. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17150. return v;
  17151. }
  17152. );
  17153. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  17154. // var v = new THREE.Vector3();
  17155. // var c = [];
  17156. // var points = this.points, point, intPoint, weight;
  17157. // point = ( points.length - 1 ) * t;
  17158. // intPoint = Math.floor( point );
  17159. // weight = point - intPoint;
  17160. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17161. // c[ 1 ] = intPoint;
  17162. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17163. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17164. // var pt0 = points[ c[0] ],
  17165. // pt1 = points[ c[1] ],
  17166. // pt2 = points[ c[2] ],
  17167. // pt3 = points[ c[3] ];
  17168. // // t = weight;
  17169. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  17170. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  17171. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  17172. // return v;
  17173. // }
  17174. /**************************************************************
  17175. * Closed Spline 3D curve
  17176. **************************************************************/
  17177. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17178. function ( points /* array of Vector3 */) {
  17179. this.points = (points == undefined) ? [] : points;
  17180. },
  17181. function ( t ) {
  17182. var v = new THREE.Vector3();
  17183. var c = [];
  17184. var points = this.points, point, intPoint, weight;
  17185. point = ( points.length - 0 ) * t;
  17186. // This needs to be from 0-length +1
  17187. intPoint = Math.floor( point );
  17188. weight = point - intPoint;
  17189. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17190. c[ 0 ] = ( intPoint - 1 ) % points.length;
  17191. c[ 1 ] = ( intPoint ) % points.length;
  17192. c[ 2 ] = ( intPoint + 1 ) % points.length;
  17193. c[ 3 ] = ( intPoint + 2 ) % points.length;
  17194. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17195. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17196. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  17197. return v;
  17198. }
  17199. );
  17200. /**
  17201. * @author zz85 / http://www.lab4games.net/zz85/blog
  17202. *
  17203. **/
  17204. /**************************************************************
  17205. * Curved Path - a curve path is simply a array of connected
  17206. * curves, but retains the api of a curve
  17207. **************************************************************/
  17208. THREE.CurvePath = function () {
  17209. this.curves = [];
  17210. this.bends = [];
  17211. this.autoClose = false; // Automatically closes the path
  17212. };
  17213. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17214. THREE.CurvePath.prototype.add = function ( curve ) {
  17215. this.curves.push( curve );
  17216. };
  17217. THREE.CurvePath.prototype.checkConnection = function() {
  17218. // TODO
  17219. // If the ending of curve is not connected to the starting
  17220. // or the next curve, then, this is not a real path
  17221. };
  17222. THREE.CurvePath.prototype.closePath = function() {
  17223. // TODO Test
  17224. // and verify for vector3 (needs to implement equals)
  17225. // Add a line curve if start and end of lines are not connected
  17226. var startPoint = this.curves[0].getPoint(0);
  17227. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17228. if (!startPoint.equals(endPoint)) {
  17229. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17230. }
  17231. };
  17232. // To get accurate point with reference to
  17233. // entire path distance at time t,
  17234. // following has to be done:
  17235. // 1. Length of each sub path have to be known
  17236. // 2. Locate and identify type of curve
  17237. // 3. Get t for the curve
  17238. // 4. Return curve.getPointAt(t')
  17239. THREE.CurvePath.prototype.getPoint = function( t ) {
  17240. var d = t * this.getLength();
  17241. var curveLengths = this.getCurveLengths();
  17242. var i = 0, diff, curve;
  17243. // To think about boundaries points.
  17244. while ( i < curveLengths.length ) {
  17245. if ( curveLengths[ i ] >= d ) {
  17246. diff = curveLengths[ i ] - d;
  17247. curve = this.curves[ i ];
  17248. var u = 1 - diff / curve.getLength();
  17249. return curve.getPointAt( u );
  17250. break;
  17251. }
  17252. i ++;
  17253. }
  17254. return null;
  17255. // loop where sum != 0, sum > d , sum+1 <d
  17256. };
  17257. /*
  17258. THREE.CurvePath.prototype.getTangent = function( t ) {
  17259. };*/
  17260. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17261. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17262. // getPoint() depends on getLength
  17263. THREE.CurvePath.prototype.getLength = function() {
  17264. var lens = this.getCurveLengths();
  17265. return lens[ lens.length - 1 ];
  17266. };
  17267. // Compute lengths and cache them
  17268. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17269. THREE.CurvePath.prototype.getCurveLengths = function() {
  17270. // We use cache values if curves and cache array are same length
  17271. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17272. return this.cacheLengths;
  17273. };
  17274. // Get length of subsurve
  17275. // Push sums into cached array
  17276. var lengths = [], sums = 0;
  17277. var i, il = this.curves.length;
  17278. for ( i = 0; i < il; i ++ ) {
  17279. sums += this.curves[ i ].getLength();
  17280. lengths.push( sums );
  17281. }
  17282. this.cacheLengths = lengths;
  17283. return lengths;
  17284. };
  17285. // Returns min and max coordinates, as well as centroid
  17286. THREE.CurvePath.prototype.getBoundingBox = function () {
  17287. var points = this.getPoints();
  17288. var maxX, maxY, maxZ;
  17289. var minX, minY, minZ;
  17290. maxX = maxY = Number.NEGATIVE_INFINITY;
  17291. minX = minY = Number.POSITIVE_INFINITY;
  17292. var p, i, il, sum;
  17293. var v3 = points[0] instanceof THREE.Vector3;
  17294. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17295. for ( i = 0, il = points.length; i < il; i ++ ) {
  17296. p = points[ i ];
  17297. if ( p.x > maxX ) maxX = p.x;
  17298. else if ( p.x < minX ) minX = p.x;
  17299. if ( p.y > maxY ) maxY = p.y;
  17300. else if ( p.y < minY ) minY = p.y;
  17301. if ( v3 ) {
  17302. if ( p.z > maxZ ) maxZ = p.z;
  17303. else if ( p.z < minZ ) minZ = p.z;
  17304. }
  17305. sum.add( p );
  17306. }
  17307. var ret = {
  17308. minX: minX,
  17309. minY: minY,
  17310. maxX: maxX,
  17311. maxY: maxY,
  17312. centroid: sum.divideScalar( il )
  17313. };
  17314. if ( v3 ) {
  17315. ret.maxZ = maxZ;
  17316. ret.minZ = minZ;
  17317. }
  17318. return ret;
  17319. };
  17320. /**************************************************************
  17321. * Create Geometries Helpers
  17322. **************************************************************/
  17323. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17324. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17325. var pts = this.getPoints( divisions, true );
  17326. return this.createGeometry( pts );
  17327. };
  17328. // Generate geometry from equidistance sampling along the path
  17329. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17330. var pts = this.getSpacedPoints( divisions, true );
  17331. return this.createGeometry( pts );
  17332. };
  17333. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17334. var geometry = new THREE.Geometry();
  17335. for ( var i = 0; i < points.length; i ++ ) {
  17336. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17337. }
  17338. return geometry;
  17339. };
  17340. /**************************************************************
  17341. * Bend / Wrap Helper Methods
  17342. **************************************************************/
  17343. // Wrap path / Bend modifiers?
  17344. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17345. this.bends.push( bendpath );
  17346. };
  17347. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17348. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17349. var i, il;
  17350. if ( !bends ) {
  17351. bends = this.bends;
  17352. }
  17353. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17354. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17355. }
  17356. return oldPts;
  17357. };
  17358. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17359. var oldPts = this.getSpacedPoints( segments );
  17360. var i, il;
  17361. if ( !bends ) {
  17362. bends = this.bends;
  17363. }
  17364. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17365. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17366. }
  17367. return oldPts;
  17368. };
  17369. // This returns getPoints() bend/wrapped around the contour of a path.
  17370. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17371. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17372. var bounds = this.getBoundingBox();
  17373. var i, il, p, oldX, oldY, xNorm;
  17374. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17375. p = oldPts[ i ];
  17376. oldX = p.x;
  17377. oldY = p.y;
  17378. xNorm = oldX / bounds.maxX;
  17379. // If using actual distance, for length > path, requires line extrusions
  17380. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17381. xNorm = path.getUtoTmapping( xNorm, oldX );
  17382. // check for out of bounds?
  17383. var pathPt = path.getPoint( xNorm );
  17384. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  17385. p.x = pathPt.x + normal.x;
  17386. p.y = pathPt.y + normal.y;
  17387. }
  17388. return oldPts;
  17389. };
  17390. /**
  17391. * @author alteredq / http://alteredqualia.com/
  17392. */
  17393. THREE.Gyroscope = function () {
  17394. THREE.Object3D.call( this );
  17395. };
  17396. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17397. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17398. this.matrixAutoUpdate && this.updateMatrix();
  17399. // update matrixWorld
  17400. if ( this.matrixWorldNeedsUpdate || force ) {
  17401. if ( this.parent ) {
  17402. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17403. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  17404. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  17405. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  17406. } else {
  17407. this.matrixWorld.copy( this.matrix );
  17408. }
  17409. this.matrixWorldNeedsUpdate = false;
  17410. force = true;
  17411. }
  17412. // update children
  17413. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17414. this.children[ i ].updateMatrixWorld( force );
  17415. }
  17416. };
  17417. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17418. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17419. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  17420. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  17421. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17422. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17423. /**
  17424. * @author zz85 / http://www.lab4games.net/zz85/blog
  17425. * Creates free form 2d path using series of points, lines or curves.
  17426. *
  17427. **/
  17428. THREE.Path = function ( points ) {
  17429. THREE.CurvePath.call(this);
  17430. this.actions = [];
  17431. if ( points ) {
  17432. this.fromPoints( points );
  17433. }
  17434. };
  17435. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17436. THREE.PathActions = {
  17437. MOVE_TO: 'moveTo',
  17438. LINE_TO: 'lineTo',
  17439. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17440. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17441. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17442. ARC: 'arc', // Circle
  17443. ELLIPSE: 'ellipse'
  17444. };
  17445. // TODO Clean up PATH API
  17446. // Create path using straight lines to connect all points
  17447. // - vectors: array of Vector2
  17448. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17449. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17450. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17451. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17452. };
  17453. };
  17454. // startPath() endPath()?
  17455. THREE.Path.prototype.moveTo = function ( x, y ) {
  17456. var args = Array.prototype.slice.call( arguments );
  17457. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17458. };
  17459. THREE.Path.prototype.lineTo = function ( x, y ) {
  17460. var args = Array.prototype.slice.call( arguments );
  17461. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17462. var x0 = lastargs[ lastargs.length - 2 ];
  17463. var y0 = lastargs[ lastargs.length - 1 ];
  17464. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17465. this.curves.push( curve );
  17466. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17467. };
  17468. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17469. var args = Array.prototype.slice.call( arguments );
  17470. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17471. var x0 = lastargs[ lastargs.length - 2 ];
  17472. var y0 = lastargs[ lastargs.length - 1 ];
  17473. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17474. new THREE.Vector2( aCPx, aCPy ),
  17475. new THREE.Vector2( aX, aY ) );
  17476. this.curves.push( curve );
  17477. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17478. };
  17479. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17480. aCP2x, aCP2y,
  17481. aX, aY ) {
  17482. var args = Array.prototype.slice.call( arguments );
  17483. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17484. var x0 = lastargs[ lastargs.length - 2 ];
  17485. var y0 = lastargs[ lastargs.length - 1 ];
  17486. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17487. new THREE.Vector2( aCP1x, aCP1y ),
  17488. new THREE.Vector2( aCP2x, aCP2y ),
  17489. new THREE.Vector2( aX, aY ) );
  17490. this.curves.push( curve );
  17491. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17492. };
  17493. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17494. var args = Array.prototype.slice.call( arguments );
  17495. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17496. var x0 = lastargs[ lastargs.length - 2 ];
  17497. var y0 = lastargs[ lastargs.length - 1 ];
  17498. //---
  17499. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17500. Array.prototype.push.apply( npts, pts );
  17501. var curve = new THREE.SplineCurve( npts );
  17502. this.curves.push( curve );
  17503. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17504. };
  17505. // FUTURE: Change the API or follow canvas API?
  17506. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17507. aStartAngle, aEndAngle, aClockwise ) {
  17508. var lastargs = this.actions[ this.actions.length - 1].args;
  17509. var x0 = lastargs[ lastargs.length - 2 ];
  17510. var y0 = lastargs[ lastargs.length - 1 ];
  17511. this.absarc(aX + x0, aY + y0, aRadius,
  17512. aStartAngle, aEndAngle, aClockwise );
  17513. };
  17514. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17515. aStartAngle, aEndAngle, aClockwise ) {
  17516. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17517. };
  17518. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17519. aStartAngle, aEndAngle, aClockwise ) {
  17520. var lastargs = this.actions[ this.actions.length - 1].args;
  17521. var x0 = lastargs[ lastargs.length - 2 ];
  17522. var y0 = lastargs[ lastargs.length - 1 ];
  17523. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17524. aStartAngle, aEndAngle, aClockwise );
  17525. };
  17526. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17527. aStartAngle, aEndAngle, aClockwise ) {
  17528. var args = Array.prototype.slice.call( arguments );
  17529. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17530. aStartAngle, aEndAngle, aClockwise );
  17531. this.curves.push( curve );
  17532. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17533. args.push(lastPoint.x);
  17534. args.push(lastPoint.y);
  17535. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17536. };
  17537. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17538. if ( ! divisions ) divisions = 40;
  17539. var points = [];
  17540. for ( var i = 0; i < divisions; i ++ ) {
  17541. points.push( this.getPoint( i / divisions ) );
  17542. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17543. }
  17544. // if ( closedPath ) {
  17545. //
  17546. // points.push( points[ 0 ] );
  17547. //
  17548. // }
  17549. return points;
  17550. };
  17551. /* Return an array of vectors based on contour of the path */
  17552. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17553. if (this.useSpacedPoints) {
  17554. console.log('tata');
  17555. return this.getSpacedPoints( divisions, closedPath );
  17556. }
  17557. divisions = divisions || 12;
  17558. var points = [];
  17559. var i, il, item, action, args;
  17560. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17561. laste, j,
  17562. t, tx, ty;
  17563. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17564. item = this.actions[ i ];
  17565. action = item.action;
  17566. args = item.args;
  17567. switch( action ) {
  17568. case THREE.PathActions.MOVE_TO:
  17569. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17570. break;
  17571. case THREE.PathActions.LINE_TO:
  17572. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17573. break;
  17574. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17575. cpx = args[ 2 ];
  17576. cpy = args[ 3 ];
  17577. cpx1 = args[ 0 ];
  17578. cpy1 = args[ 1 ];
  17579. if ( points.length > 0 ) {
  17580. laste = points[ points.length - 1 ];
  17581. cpx0 = laste.x;
  17582. cpy0 = laste.y;
  17583. } else {
  17584. laste = this.actions[ i - 1 ].args;
  17585. cpx0 = laste[ laste.length - 2 ];
  17586. cpy0 = laste[ laste.length - 1 ];
  17587. }
  17588. for ( j = 1; j <= divisions; j ++ ) {
  17589. t = j / divisions;
  17590. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17591. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17592. points.push( new THREE.Vector2( tx, ty ) );
  17593. }
  17594. break;
  17595. case THREE.PathActions.BEZIER_CURVE_TO:
  17596. cpx = args[ 4 ];
  17597. cpy = args[ 5 ];
  17598. cpx1 = args[ 0 ];
  17599. cpy1 = args[ 1 ];
  17600. cpx2 = args[ 2 ];
  17601. cpy2 = args[ 3 ];
  17602. if ( points.length > 0 ) {
  17603. laste = points[ points.length - 1 ];
  17604. cpx0 = laste.x;
  17605. cpy0 = laste.y;
  17606. } else {
  17607. laste = this.actions[ i - 1 ].args;
  17608. cpx0 = laste[ laste.length - 2 ];
  17609. cpy0 = laste[ laste.length - 1 ];
  17610. }
  17611. for ( j = 1; j <= divisions; j ++ ) {
  17612. t = j / divisions;
  17613. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17614. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17615. points.push( new THREE.Vector2( tx, ty ) );
  17616. }
  17617. break;
  17618. case THREE.PathActions.CSPLINE_THRU:
  17619. laste = this.actions[ i - 1 ].args;
  17620. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17621. var spts = [ last ];
  17622. var n = divisions * args[ 0 ].length;
  17623. spts = spts.concat( args[ 0 ] );
  17624. var spline = new THREE.SplineCurve( spts );
  17625. for ( j = 1; j <= n; j ++ ) {
  17626. points.push( spline.getPointAt( j / n ) ) ;
  17627. }
  17628. break;
  17629. case THREE.PathActions.ARC:
  17630. var aX = args[ 0 ], aY = args[ 1 ],
  17631. aRadius = args[ 2 ],
  17632. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17633. aClockwise = !!args[ 5 ];
  17634. var deltaAngle = aEndAngle - aStartAngle;
  17635. var angle;
  17636. var tdivisions = divisions * 2;
  17637. for ( j = 1; j <= tdivisions; j ++ ) {
  17638. t = j / tdivisions;
  17639. if ( ! aClockwise ) {
  17640. t = 1 - t;
  17641. }
  17642. angle = aStartAngle + t * deltaAngle;
  17643. tx = aX + aRadius * Math.cos( angle );
  17644. ty = aY + aRadius * Math.sin( angle );
  17645. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17646. points.push( new THREE.Vector2( tx, ty ) );
  17647. }
  17648. //console.log(points);
  17649. break;
  17650. case THREE.PathActions.ELLIPSE:
  17651. var aX = args[ 0 ], aY = args[ 1 ],
  17652. xRadius = args[ 2 ],
  17653. yRadius = args[ 3 ],
  17654. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17655. aClockwise = !!args[ 6 ];
  17656. var deltaAngle = aEndAngle - aStartAngle;
  17657. var angle;
  17658. var tdivisions = divisions * 2;
  17659. for ( j = 1; j <= tdivisions; j ++ ) {
  17660. t = j / tdivisions;
  17661. if ( ! aClockwise ) {
  17662. t = 1 - t;
  17663. }
  17664. angle = aStartAngle + t * deltaAngle;
  17665. tx = aX + xRadius * Math.cos( angle );
  17666. ty = aY + yRadius * Math.sin( angle );
  17667. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17668. points.push( new THREE.Vector2( tx, ty ) );
  17669. }
  17670. //console.log(points);
  17671. break;
  17672. } // end switch
  17673. }
  17674. // Normalize to remove the closing point by default.
  17675. var lastPoint = points[ points.length - 1];
  17676. var EPSILON = 0.0000000001;
  17677. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17678. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17679. points.splice( points.length - 1, 1);
  17680. if ( closedPath ) {
  17681. points.push( points[ 0 ] );
  17682. }
  17683. return points;
  17684. };
  17685. // Breaks path into shapes
  17686. THREE.Path.prototype.toShapes = function() {
  17687. var i, il, item, action, args;
  17688. var subPaths = [], lastPath = new THREE.Path();
  17689. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17690. item = this.actions[ i ];
  17691. args = item.args;
  17692. action = item.action;
  17693. if ( action == THREE.PathActions.MOVE_TO ) {
  17694. if ( lastPath.actions.length != 0 ) {
  17695. subPaths.push( lastPath );
  17696. lastPath = new THREE.Path();
  17697. }
  17698. }
  17699. lastPath[ action ].apply( lastPath, args );
  17700. }
  17701. if ( lastPath.actions.length != 0 ) {
  17702. subPaths.push( lastPath );
  17703. }
  17704. // console.log(subPaths);
  17705. if ( subPaths.length == 0 ) return [];
  17706. var tmpPath, tmpShape, shapes = [];
  17707. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17708. // console.log("Holes first", holesFirst);
  17709. if ( subPaths.length == 1) {
  17710. tmpPath = subPaths[0];
  17711. tmpShape = new THREE.Shape();
  17712. tmpShape.actions = tmpPath.actions;
  17713. tmpShape.curves = tmpPath.curves;
  17714. shapes.push( tmpShape );
  17715. return shapes;
  17716. };
  17717. if ( holesFirst ) {
  17718. tmpShape = new THREE.Shape();
  17719. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17720. tmpPath = subPaths[ i ];
  17721. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17722. tmpShape.actions = tmpPath.actions;
  17723. tmpShape.curves = tmpPath.curves;
  17724. shapes.push( tmpShape );
  17725. tmpShape = new THREE.Shape();
  17726. //console.log('cw', i);
  17727. } else {
  17728. tmpShape.holes.push( tmpPath );
  17729. //console.log('ccw', i);
  17730. }
  17731. }
  17732. } else {
  17733. // Shapes first
  17734. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17735. tmpPath = subPaths[ i ];
  17736. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17737. if ( tmpShape ) shapes.push( tmpShape );
  17738. tmpShape = new THREE.Shape();
  17739. tmpShape.actions = tmpPath.actions;
  17740. tmpShape.curves = tmpPath.curves;
  17741. } else {
  17742. tmpShape.holes.push( tmpPath );
  17743. }
  17744. }
  17745. shapes.push( tmpShape );
  17746. }
  17747. //console.log("shape", shapes);
  17748. return shapes;
  17749. };
  17750. /**
  17751. * @author zz85 / http://www.lab4games.net/zz85/blog
  17752. * Defines a 2d shape plane using paths.
  17753. **/
  17754. // STEP 1 Create a path.
  17755. // STEP 2 Turn path into shape.
  17756. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17757. // STEP 3a - Extract points from each shape, turn to vertices
  17758. // STEP 3b - Triangulate each shape, add faces.
  17759. THREE.Shape = function ( ) {
  17760. THREE.Path.apply( this, arguments );
  17761. this.holes = [];
  17762. };
  17763. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17764. // Convenience method to return ExtrudeGeometry
  17765. THREE.Shape.prototype.extrude = function ( options ) {
  17766. var extruded = new THREE.ExtrudeGeometry( this, options );
  17767. return extruded;
  17768. };
  17769. // Convenience method to return ShapeGeometry
  17770. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17771. var geometry = new THREE.ShapeGeometry( this, options );
  17772. return geometry;
  17773. };
  17774. // Get points of holes
  17775. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17776. var i, il = this.holes.length, holesPts = [];
  17777. for ( i = 0; i < il; i ++ ) {
  17778. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17779. }
  17780. return holesPts;
  17781. };
  17782. // Get points of holes (spaced by regular distance)
  17783. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17784. var i, il = this.holes.length, holesPts = [];
  17785. for ( i = 0; i < il; i ++ ) {
  17786. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17787. }
  17788. return holesPts;
  17789. };
  17790. // Get points of shape and holes (keypoints based on segments parameter)
  17791. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17792. return {
  17793. shape: this.getTransformedPoints( divisions ),
  17794. holes: this.getPointsHoles( divisions )
  17795. };
  17796. };
  17797. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17798. if (this.useSpacedPoints) {
  17799. return this.extractAllSpacedPoints(divisions);
  17800. }
  17801. return this.extractAllPoints(divisions);
  17802. };
  17803. //
  17804. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17805. //
  17806. // return {
  17807. //
  17808. // shape: this.transform( bend, divisions ),
  17809. // holes: this.getPointsHoles( divisions, bend )
  17810. //
  17811. // };
  17812. //
  17813. // };
  17814. // Get points of shape and holes (spaced by regular distance)
  17815. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17816. return {
  17817. shape: this.getTransformedSpacedPoints( divisions ),
  17818. holes: this.getSpacedPointsHoles( divisions )
  17819. };
  17820. };
  17821. /**************************************************************
  17822. * Utils
  17823. **************************************************************/
  17824. THREE.Shape.Utils = {
  17825. /*
  17826. contour - array of vector2 for contour
  17827. holes - array of array of vector2
  17828. */
  17829. removeHoles: function ( contour, holes ) {
  17830. var shape = contour.concat(); // work on this shape
  17831. var allpoints = shape.concat();
  17832. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17833. var prevShapeVert, nextShapeVert,
  17834. prevHoleVert, nextHoleVert,
  17835. holeIndex, shapeIndex,
  17836. shapeId, shapeGroup,
  17837. h, h2,
  17838. hole, shortest, d,
  17839. p, pts1, pts2,
  17840. tmpShape1, tmpShape2,
  17841. tmpHole1, tmpHole2,
  17842. verts = [];
  17843. for ( h = 0; h < holes.length; h ++ ) {
  17844. hole = holes[ h ];
  17845. /*
  17846. shapeholes[ h ].concat(); // preserves original
  17847. holes.push( hole );
  17848. */
  17849. Array.prototype.push.apply( allpoints, hole );
  17850. shortest = Number.POSITIVE_INFINITY;
  17851. // Find the shortest pair of pts between shape and hole
  17852. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17853. // Using distanceToSquared() intead of distanceTo() should speed a little
  17854. // since running square roots operations are reduced.
  17855. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17856. pts1 = hole[ h2 ];
  17857. var dist = [];
  17858. for ( p = 0; p < shape.length; p++ ) {
  17859. pts2 = shape[ p ];
  17860. d = pts1.distanceToSquared( pts2 );
  17861. dist.push( d );
  17862. if ( d < shortest ) {
  17863. shortest = d;
  17864. holeIndex = h2;
  17865. shapeIndex = p;
  17866. }
  17867. }
  17868. }
  17869. //console.log("shortest", shortest, dist);
  17870. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17871. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17872. var areaapts = [
  17873. hole[ holeIndex ],
  17874. shape[ shapeIndex ],
  17875. shape[ prevShapeVert ]
  17876. ];
  17877. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17878. var areabpts = [
  17879. hole[ holeIndex ],
  17880. hole[ prevHoleVert ],
  17881. shape[ shapeIndex ]
  17882. ];
  17883. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17884. var shapeOffset = 1;
  17885. var holeOffset = -1;
  17886. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17887. shapeIndex += shapeOffset;
  17888. holeIndex += holeOffset;
  17889. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17890. shapeIndex %= shape.length;
  17891. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17892. holeIndex %= hole.length;
  17893. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17894. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17895. areaapts = [
  17896. hole[ holeIndex ],
  17897. shape[ shapeIndex ],
  17898. shape[ prevShapeVert ]
  17899. ];
  17900. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17901. areabpts = [
  17902. hole[ holeIndex ],
  17903. hole[ prevHoleVert ],
  17904. shape[ shapeIndex ]
  17905. ];
  17906. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17907. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17908. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17909. // In case areas are not correct.
  17910. //console.log("USE THIS");
  17911. shapeIndex = oldShapeIndex;
  17912. holeIndex = oldHoleIndex ;
  17913. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17914. shapeIndex %= shape.length;
  17915. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17916. holeIndex %= hole.length;
  17917. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17918. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17919. } else {
  17920. //console.log("USE THAT ")
  17921. }
  17922. tmpShape1 = shape.slice( 0, shapeIndex );
  17923. tmpShape2 = shape.slice( shapeIndex );
  17924. tmpHole1 = hole.slice( holeIndex );
  17925. tmpHole2 = hole.slice( 0, holeIndex );
  17926. // Should check orders here again?
  17927. var trianglea = [
  17928. hole[ holeIndex ],
  17929. shape[ shapeIndex ],
  17930. shape[ prevShapeVert ]
  17931. ];
  17932. var triangleb = [
  17933. hole[ holeIndex ] ,
  17934. hole[ prevHoleVert ],
  17935. shape[ shapeIndex ]
  17936. ];
  17937. verts.push( trianglea );
  17938. verts.push( triangleb );
  17939. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17940. }
  17941. return {
  17942. shape:shape, /* shape with no holes */
  17943. isolatedPts: verts, /* isolated faces */
  17944. allpoints: allpoints
  17945. }
  17946. },
  17947. triangulateShape: function ( contour, holes ) {
  17948. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17949. var shape = shapeWithoutHoles.shape,
  17950. allpoints = shapeWithoutHoles.allpoints,
  17951. isolatedPts = shapeWithoutHoles.isolatedPts;
  17952. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17953. // 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.
  17954. //console.log( "triangles",triangles, triangles.length );
  17955. //console.log( "allpoints",allpoints, allpoints.length );
  17956. var i, il, f, face,
  17957. key, index,
  17958. allPointsMap = {},
  17959. isolatedPointsMap = {};
  17960. // prepare all points map
  17961. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17962. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17963. if ( allPointsMap[ key ] !== undefined ) {
  17964. console.log( "Duplicate point", key );
  17965. }
  17966. allPointsMap[ key ] = i;
  17967. }
  17968. // check all face vertices against all points map
  17969. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17970. face = triangles[ i ];
  17971. for ( f = 0; f < 3; f ++ ) {
  17972. key = face[ f ].x + ":" + face[ f ].y;
  17973. index = allPointsMap[ key ];
  17974. if ( index !== undefined ) {
  17975. face[ f ] = index;
  17976. }
  17977. }
  17978. }
  17979. // check isolated points vertices against all points map
  17980. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17981. face = isolatedPts[ i ];
  17982. for ( f = 0; f < 3; f ++ ) {
  17983. key = face[ f ].x + ":" + face[ f ].y;
  17984. index = allPointsMap[ key ];
  17985. if ( index !== undefined ) {
  17986. face[ f ] = index;
  17987. }
  17988. }
  17989. }
  17990. return triangles.concat( isolatedPts );
  17991. }, // end triangulate shapes
  17992. /*
  17993. triangulate2 : function( pts, holes ) {
  17994. // For use with Poly2Tri.js
  17995. var allpts = pts.concat();
  17996. var shape = [];
  17997. for (var p in pts) {
  17998. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17999. }
  18000. var swctx = new js.poly2tri.SweepContext(shape);
  18001. for (var h in holes) {
  18002. var aHole = holes[h];
  18003. var newHole = []
  18004. for (i in aHole) {
  18005. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  18006. allpts.push(aHole[i]);
  18007. }
  18008. swctx.AddHole(newHole);
  18009. }
  18010. var find;
  18011. var findIndexForPt = function (pt) {
  18012. find = new THREE.Vector2(pt.x, pt.y);
  18013. var p;
  18014. for (p=0, pl = allpts.length; p<pl; p++) {
  18015. if (allpts[p].equals(find)) return p;
  18016. }
  18017. return -1;
  18018. };
  18019. // triangulate
  18020. js.poly2tri.sweep.Triangulate(swctx);
  18021. var triangles = swctx.GetTriangles();
  18022. var tr ;
  18023. var facesPts = [];
  18024. for (var t in triangles) {
  18025. tr = triangles[t];
  18026. facesPts.push([
  18027. findIndexForPt(tr.GetPoint(0)),
  18028. findIndexForPt(tr.GetPoint(1)),
  18029. findIndexForPt(tr.GetPoint(2))
  18030. ]);
  18031. }
  18032. // console.log(facesPts);
  18033. // console.log("triangles", triangles.length, triangles);
  18034. // Returns array of faces with 3 element each
  18035. return facesPts;
  18036. },
  18037. */
  18038. isClockWise: function ( pts ) {
  18039. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  18040. },
  18041. // Bezier Curves formulas obtained from
  18042. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18043. // Quad Bezier Functions
  18044. b2p0: function ( t, p ) {
  18045. var k = 1 - t;
  18046. return k * k * p;
  18047. },
  18048. b2p1: function ( t, p ) {
  18049. return 2 * ( 1 - t ) * t * p;
  18050. },
  18051. b2p2: function ( t, p ) {
  18052. return t * t * p;
  18053. },
  18054. b2: function ( t, p0, p1, p2 ) {
  18055. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  18056. },
  18057. // Cubic Bezier Functions
  18058. b3p0: function ( t, p ) {
  18059. var k = 1 - t;
  18060. return k * k * k * p;
  18061. },
  18062. b3p1: function ( t, p ) {
  18063. var k = 1 - t;
  18064. return 3 * k * k * t * p;
  18065. },
  18066. b3p2: function ( t, p ) {
  18067. var k = 1 - t;
  18068. return 3 * k * t * t * p;
  18069. },
  18070. b3p3: function ( t, p ) {
  18071. return t * t * t * p;
  18072. },
  18073. b3: function ( t, p0, p1, p2, p3 ) {
  18074. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  18075. }
  18076. };
  18077. /**
  18078. * @author mikael emtinger / http://gomo.se/
  18079. */
  18080. THREE.AnimationHandler = (function() {
  18081. var playing = [];
  18082. var library = {};
  18083. var that = {};
  18084. //--- update ---
  18085. that.update = function( deltaTimeMS ) {
  18086. for( var i = 0; i < playing.length; i ++ )
  18087. playing[ i ].update( deltaTimeMS );
  18088. };
  18089. //--- add ---
  18090. that.addToUpdate = function( animation ) {
  18091. if ( playing.indexOf( animation ) === -1 )
  18092. playing.push( animation );
  18093. };
  18094. //--- remove ---
  18095. that.removeFromUpdate = function( animation ) {
  18096. var index = playing.indexOf( animation );
  18097. if( index !== -1 )
  18098. playing.splice( index, 1 );
  18099. };
  18100. //--- add ---
  18101. that.add = function( data ) {
  18102. if ( library[ data.name ] !== undefined )
  18103. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18104. library[ data.name ] = data;
  18105. initData( data );
  18106. };
  18107. //--- get ---
  18108. that.get = function( name ) {
  18109. if ( typeof name === "string" ) {
  18110. if ( library[ name ] ) {
  18111. return library[ name ];
  18112. } else {
  18113. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18114. return null;
  18115. }
  18116. } else {
  18117. // todo: add simple tween library
  18118. }
  18119. };
  18120. //--- parse ---
  18121. that.parse = function( root ) {
  18122. // setup hierarchy
  18123. var hierarchy = [];
  18124. if ( root instanceof THREE.SkinnedMesh ) {
  18125. for( var b = 0; b < root.bones.length; b++ ) {
  18126. hierarchy.push( root.bones[ b ] );
  18127. }
  18128. } else {
  18129. parseRecurseHierarchy( root, hierarchy );
  18130. }
  18131. return hierarchy;
  18132. };
  18133. var parseRecurseHierarchy = function( root, hierarchy ) {
  18134. hierarchy.push( root );
  18135. for( var c = 0; c < root.children.length; c++ )
  18136. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18137. }
  18138. //--- init data ---
  18139. var initData = function( data ) {
  18140. if( data.initialized === true )
  18141. return;
  18142. // loop through all keys
  18143. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18144. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18145. // remove minus times
  18146. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18147. data.hierarchy[ h ].keys[ k ].time = 0;
  18148. // create quaternions
  18149. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18150. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18151. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18152. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18153. }
  18154. }
  18155. // prepare morph target keys
  18156. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18157. // get all used
  18158. var usedMorphTargets = {};
  18159. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18160. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18161. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18162. usedMorphTargets[ morphTargetName ] = -1;
  18163. }
  18164. }
  18165. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18166. // set all used on all frames
  18167. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18168. var influences = {};
  18169. for ( var morphTargetName in usedMorphTargets ) {
  18170. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18171. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18172. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18173. break;
  18174. }
  18175. }
  18176. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18177. influences[ morphTargetName ] = 0;
  18178. }
  18179. }
  18180. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18181. }
  18182. }
  18183. // remove all keys that are on the same time
  18184. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18185. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18186. data.hierarchy[ h ].keys.splice( k, 1 );
  18187. k --;
  18188. }
  18189. }
  18190. // set index
  18191. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18192. data.hierarchy[ h ].keys[ k ].index = k;
  18193. }
  18194. }
  18195. // JIT
  18196. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  18197. data.JIT = {};
  18198. data.JIT.hierarchy = [];
  18199. for( var h = 0; h < data.hierarchy.length; h ++ )
  18200. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  18201. // done
  18202. data.initialized = true;
  18203. };
  18204. // interpolation types
  18205. that.LINEAR = 0;
  18206. that.CATMULLROM = 1;
  18207. that.CATMULLROM_FORWARD = 2;
  18208. return that;
  18209. }());
  18210. /**
  18211. * @author mikael emtinger / http://gomo.se/
  18212. * @author mrdoob / http://mrdoob.com/
  18213. * @author alteredq / http://alteredqualia.com/
  18214. */
  18215. THREE.Animation = function ( root, name, interpolationType ) {
  18216. this.root = root;
  18217. this.data = THREE.AnimationHandler.get( name );
  18218. this.hierarchy = THREE.AnimationHandler.parse( root );
  18219. this.currentTime = 0;
  18220. this.timeScale = 1;
  18221. this.isPlaying = false;
  18222. this.isPaused = true;
  18223. this.loop = true;
  18224. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  18225. this.points = [];
  18226. this.target = new THREE.Vector3();
  18227. };
  18228. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  18229. if ( this.isPlaying === false ) {
  18230. this.isPlaying = true;
  18231. this.loop = loop !== undefined ? loop : true;
  18232. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18233. // reset key cache
  18234. var h, hl = this.hierarchy.length,
  18235. object;
  18236. for ( h = 0; h < hl; h ++ ) {
  18237. object = this.hierarchy[ h ];
  18238. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18239. object.useQuaternion = true;
  18240. }
  18241. object.matrixAutoUpdate = true;
  18242. if ( object.animationCache === undefined ) {
  18243. object.animationCache = {};
  18244. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18245. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18246. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18247. }
  18248. var prevKey = object.animationCache.prevKey;
  18249. var nextKey = object.animationCache.nextKey;
  18250. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18251. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18252. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18253. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18254. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18255. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18256. }
  18257. this.update( 0 );
  18258. }
  18259. this.isPaused = false;
  18260. THREE.AnimationHandler.addToUpdate( this );
  18261. };
  18262. THREE.Animation.prototype.pause = function() {
  18263. if ( this.isPaused === true ) {
  18264. THREE.AnimationHandler.addToUpdate( this );
  18265. } else {
  18266. THREE.AnimationHandler.removeFromUpdate( this );
  18267. }
  18268. this.isPaused = !this.isPaused;
  18269. };
  18270. THREE.Animation.prototype.stop = function() {
  18271. this.isPlaying = false;
  18272. this.isPaused = false;
  18273. THREE.AnimationHandler.removeFromUpdate( this );
  18274. };
  18275. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  18276. // early out
  18277. if ( this.isPlaying === false ) return;
  18278. // vars
  18279. var types = [ "pos", "rot", "scl" ];
  18280. var type;
  18281. var scale;
  18282. var vector;
  18283. var prevXYZ, nextXYZ;
  18284. var prevKey, nextKey;
  18285. var object;
  18286. var animationCache;
  18287. var frame;
  18288. var JIThierarchy = this.data.JIT.hierarchy;
  18289. var currentTime, unloopedCurrentTime;
  18290. var currentPoint, forwardPoint, angle;
  18291. this.currentTime += deltaTimeMS * this.timeScale;
  18292. unloopedCurrentTime = this.currentTime;
  18293. currentTime = this.currentTime = this.currentTime % this.data.length;
  18294. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18295. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18296. object = this.hierarchy[ h ];
  18297. animationCache = object.animationCache;
  18298. // loop through pos/rot/scl
  18299. for ( var t = 0; t < 3; t ++ ) {
  18300. // get keys
  18301. type = types[ t ];
  18302. prevKey = animationCache.prevKey[ type ];
  18303. nextKey = animationCache.nextKey[ type ];
  18304. // switch keys?
  18305. if ( nextKey.time <= unloopedCurrentTime ) {
  18306. // did we loop?
  18307. if ( currentTime < unloopedCurrentTime ) {
  18308. if ( this.loop ) {
  18309. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18310. nextKey = this.getNextKeyWith( type, h, 1 );
  18311. while( nextKey.time < currentTime ) {
  18312. prevKey = nextKey;
  18313. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18314. }
  18315. } else {
  18316. this.stop();
  18317. return;
  18318. }
  18319. } else {
  18320. do {
  18321. prevKey = nextKey;
  18322. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18323. } while( nextKey.time < currentTime )
  18324. }
  18325. animationCache.prevKey[ type ] = prevKey;
  18326. animationCache.nextKey[ type ] = nextKey;
  18327. }
  18328. object.matrixAutoUpdate = true;
  18329. object.matrixWorldNeedsUpdate = true;
  18330. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18331. prevXYZ = prevKey[ type ];
  18332. nextXYZ = nextKey[ type ];
  18333. // check scale error
  18334. if ( scale < 0 || scale > 1 ) {
  18335. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18336. scale = scale < 0 ? 0 : 1;
  18337. }
  18338. // interpolate
  18339. if ( type === "pos" ) {
  18340. vector = object.position;
  18341. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18342. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18343. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18344. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18345. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18346. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18347. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18348. this.points[ 1 ] = prevXYZ;
  18349. this.points[ 2 ] = nextXYZ;
  18350. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18351. scale = scale * 0.33 + 0.33;
  18352. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18353. vector.x = currentPoint[ 0 ];
  18354. vector.y = currentPoint[ 1 ];
  18355. vector.z = currentPoint[ 2 ];
  18356. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18357. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18358. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18359. this.target.sub( vector );
  18360. this.target.y = 0;
  18361. this.target.normalize();
  18362. angle = Math.atan2( this.target.x, this.target.z );
  18363. object.rotation.set( 0, angle, 0 );
  18364. }
  18365. }
  18366. } else if ( type === "rot" ) {
  18367. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18368. } else if ( type === "scl" ) {
  18369. vector = object.scale;
  18370. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18371. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18372. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18373. }
  18374. }
  18375. }
  18376. };
  18377. // Catmull-Rom spline
  18378. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18379. var c = [], v3 = [],
  18380. point, intPoint, weight, w2, w3,
  18381. pa, pb, pc, pd;
  18382. point = ( points.length - 1 ) * scale;
  18383. intPoint = Math.floor( point );
  18384. weight = point - intPoint;
  18385. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18386. c[ 1 ] = intPoint;
  18387. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18388. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18389. pa = points[ c[ 0 ] ];
  18390. pb = points[ c[ 1 ] ];
  18391. pc = points[ c[ 2 ] ];
  18392. pd = points[ c[ 3 ] ];
  18393. w2 = weight * weight;
  18394. w3 = weight * w2;
  18395. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18396. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18397. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18398. return v3;
  18399. };
  18400. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18401. var v0 = ( p2 - p0 ) * 0.5,
  18402. v1 = ( p3 - p1 ) * 0.5;
  18403. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18404. };
  18405. // Get next key with
  18406. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18407. var keys = this.data.hierarchy[ h ].keys;
  18408. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18409. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18410. key = key < keys.length - 1 ? key : keys.length - 1;
  18411. } else {
  18412. key = key % keys.length;
  18413. }
  18414. for ( ; key < keys.length; key++ ) {
  18415. if ( keys[ key ][ type ] !== undefined ) {
  18416. return keys[ key ];
  18417. }
  18418. }
  18419. return this.data.hierarchy[ h ].keys[ 0 ];
  18420. };
  18421. // Get previous key with
  18422. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18423. var keys = this.data.hierarchy[ h ].keys;
  18424. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18425. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18426. key = key > 0 ? key : 0;
  18427. } else {
  18428. key = key >= 0 ? key : key + keys.length;
  18429. }
  18430. for ( ; key >= 0; key -- ) {
  18431. if ( keys[ key ][ type ] !== undefined ) {
  18432. return keys[ key ];
  18433. }
  18434. }
  18435. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18436. };
  18437. /**
  18438. * @author mikael emtinger / http://gomo.se/
  18439. * @author mrdoob / http://mrdoob.com/
  18440. * @author alteredq / http://alteredqualia.com/
  18441. * @author khang duong
  18442. * @author erik kitson
  18443. */
  18444. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18445. this.root = root;
  18446. this.data = THREE.AnimationHandler.get( data );
  18447. this.hierarchy = THREE.AnimationHandler.parse( root );
  18448. this.currentTime = 0;
  18449. this.timeScale = 0.001;
  18450. this.isPlaying = false;
  18451. this.isPaused = true;
  18452. this.loop = true;
  18453. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18454. // initialize to first keyframes
  18455. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18456. var keys = this.data.hierarchy[h].keys,
  18457. sids = this.data.hierarchy[h].sids,
  18458. obj = this.hierarchy[h];
  18459. if ( keys.length && sids ) {
  18460. for ( var s = 0; s < sids.length; s++ ) {
  18461. var sid = sids[ s ],
  18462. next = this.getNextKeyWith( sid, h, 0 );
  18463. if ( next ) {
  18464. next.apply( sid );
  18465. }
  18466. }
  18467. obj.matrixAutoUpdate = false;
  18468. this.data.hierarchy[h].node.updateMatrix();
  18469. obj.matrixWorldNeedsUpdate = true;
  18470. }
  18471. }
  18472. };
  18473. // Play
  18474. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18475. if( !this.isPlaying ) {
  18476. this.isPlaying = true;
  18477. this.loop = loop !== undefined ? loop : true;
  18478. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18479. this.startTimeMs = startTimeMS;
  18480. this.startTime = 10000000;
  18481. this.endTime = -this.startTime;
  18482. // reset key cache
  18483. var h, hl = this.hierarchy.length,
  18484. object,
  18485. node;
  18486. for ( h = 0; h < hl; h++ ) {
  18487. object = this.hierarchy[ h ];
  18488. node = this.data.hierarchy[ h ];
  18489. object.useQuaternion = true;
  18490. if ( node.animationCache === undefined ) {
  18491. node.animationCache = {};
  18492. node.animationCache.prevKey = null;
  18493. node.animationCache.nextKey = null;
  18494. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18495. }
  18496. var keys = this.data.hierarchy[h].keys;
  18497. if (keys.length) {
  18498. node.animationCache.prevKey = keys[ 0 ];
  18499. node.animationCache.nextKey = keys[ 1 ];
  18500. this.startTime = Math.min( keys[0].time, this.startTime );
  18501. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18502. }
  18503. }
  18504. this.update( 0 );
  18505. }
  18506. this.isPaused = false;
  18507. THREE.AnimationHandler.addToUpdate( this );
  18508. };
  18509. // Pause
  18510. THREE.KeyFrameAnimation.prototype.pause = function() {
  18511. if( this.isPaused ) {
  18512. THREE.AnimationHandler.addToUpdate( this );
  18513. } else {
  18514. THREE.AnimationHandler.removeFromUpdate( this );
  18515. }
  18516. this.isPaused = !this.isPaused;
  18517. };
  18518. // Stop
  18519. THREE.KeyFrameAnimation.prototype.stop = function() {
  18520. this.isPlaying = false;
  18521. this.isPaused = false;
  18522. THREE.AnimationHandler.removeFromUpdate( this );
  18523. // reset JIT matrix and remove cache
  18524. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18525. var obj = this.hierarchy[ h ];
  18526. var node = this.data.hierarchy[ h ];
  18527. if ( node.animationCache !== undefined ) {
  18528. var original = node.animationCache.originalMatrix;
  18529. if( obj instanceof THREE.Bone ) {
  18530. original.copy( obj.skinMatrix );
  18531. obj.skinMatrix = original;
  18532. } else {
  18533. original.copy( obj.matrix );
  18534. obj.matrix = original;
  18535. }
  18536. delete node.animationCache;
  18537. }
  18538. }
  18539. };
  18540. // Update
  18541. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18542. // early out
  18543. if( !this.isPlaying ) return;
  18544. // vars
  18545. var prevKey, nextKey;
  18546. var object;
  18547. var node;
  18548. var frame;
  18549. var JIThierarchy = this.data.JIT.hierarchy;
  18550. var currentTime, unloopedCurrentTime;
  18551. var looped;
  18552. // update
  18553. this.currentTime += deltaTimeMS * this.timeScale;
  18554. unloopedCurrentTime = this.currentTime;
  18555. currentTime = this.currentTime = this.currentTime % this.data.length;
  18556. // if looped around, the current time should be based on the startTime
  18557. if ( currentTime < this.startTimeMs ) {
  18558. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18559. }
  18560. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18561. looped = currentTime < unloopedCurrentTime;
  18562. if ( looped && !this.loop ) {
  18563. // Set the animation to the last keyframes and stop
  18564. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18565. var keys = this.data.hierarchy[h].keys,
  18566. sids = this.data.hierarchy[h].sids,
  18567. end = keys.length-1,
  18568. obj = this.hierarchy[h];
  18569. if ( keys.length ) {
  18570. for ( var s = 0; s < sids.length; s++ ) {
  18571. var sid = sids[ s ],
  18572. prev = this.getPrevKeyWith( sid, h, end );
  18573. if ( prev ) {
  18574. prev.apply( sid );
  18575. }
  18576. }
  18577. this.data.hierarchy[h].node.updateMatrix();
  18578. obj.matrixWorldNeedsUpdate = true;
  18579. }
  18580. }
  18581. this.stop();
  18582. return;
  18583. }
  18584. // check pre-infinity
  18585. if ( currentTime < this.startTime ) {
  18586. return;
  18587. }
  18588. // update
  18589. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18590. object = this.hierarchy[ h ];
  18591. node = this.data.hierarchy[ h ];
  18592. var keys = node.keys,
  18593. animationCache = node.animationCache;
  18594. // use JIT?
  18595. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18596. if( object instanceof THREE.Bone ) {
  18597. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18598. object.matrixWorldNeedsUpdate = false;
  18599. } else {
  18600. object.matrix = JIThierarchy[ h ][ frame ];
  18601. object.matrixWorldNeedsUpdate = true;
  18602. }
  18603. // use interpolation
  18604. } else if ( keys.length ) {
  18605. // make sure so original matrix and not JIT matrix is set
  18606. if ( this.JITCompile && animationCache ) {
  18607. if( object instanceof THREE.Bone ) {
  18608. object.skinMatrix = animationCache.originalMatrix;
  18609. } else {
  18610. object.matrix = animationCache.originalMatrix;
  18611. }
  18612. }
  18613. prevKey = animationCache.prevKey;
  18614. nextKey = animationCache.nextKey;
  18615. if ( prevKey && nextKey ) {
  18616. // switch keys?
  18617. if ( nextKey.time <= unloopedCurrentTime ) {
  18618. // did we loop?
  18619. if ( looped && this.loop ) {
  18620. prevKey = keys[ 0 ];
  18621. nextKey = keys[ 1 ];
  18622. while ( nextKey.time < currentTime ) {
  18623. prevKey = nextKey;
  18624. nextKey = keys[ prevKey.index + 1 ];
  18625. }
  18626. } else if ( !looped ) {
  18627. var lastIndex = keys.length - 1;
  18628. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18629. prevKey = nextKey;
  18630. nextKey = keys[ prevKey.index + 1 ];
  18631. }
  18632. }
  18633. animationCache.prevKey = prevKey;
  18634. animationCache.nextKey = nextKey;
  18635. }
  18636. if(nextKey.time >= currentTime)
  18637. prevKey.interpolate( nextKey, currentTime );
  18638. else
  18639. prevKey.interpolate( nextKey, nextKey.time);
  18640. }
  18641. this.data.hierarchy[h].node.updateMatrix();
  18642. object.matrixWorldNeedsUpdate = true;
  18643. }
  18644. }
  18645. // update JIT?
  18646. if ( this.JITCompile ) {
  18647. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18648. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18649. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18650. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18651. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18652. } else {
  18653. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18654. }
  18655. }
  18656. }
  18657. }
  18658. };
  18659. // Get next key with
  18660. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18661. var keys = this.data.hierarchy[ h ].keys;
  18662. key = key % keys.length;
  18663. for ( ; key < keys.length; key++ ) {
  18664. if ( keys[ key ].hasTarget( sid ) ) {
  18665. return keys[ key ];
  18666. }
  18667. }
  18668. return keys[ 0 ];
  18669. };
  18670. // Get previous key with
  18671. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18672. var keys = this.data.hierarchy[ h ].keys;
  18673. key = key >= 0 ? key : key + keys.length;
  18674. for ( ; key >= 0; key-- ) {
  18675. if ( keys[ key ].hasTarget( sid ) ) {
  18676. return keys[ key ];
  18677. }
  18678. }
  18679. return keys[ keys.length - 1 ];
  18680. };
  18681. /**
  18682. * Camera for rendering cube maps
  18683. * - renders scene into axis-aligned cube
  18684. *
  18685. * @author alteredq / http://alteredqualia.com/
  18686. */
  18687. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18688. THREE.Object3D.call( this );
  18689. var fov = 90, aspect = 1;
  18690. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18691. cameraPX.up.set( 0, -1, 0 );
  18692. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18693. this.add( cameraPX );
  18694. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18695. cameraNX.up.set( 0, -1, 0 );
  18696. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18697. this.add( cameraNX );
  18698. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18699. cameraPY.up.set( 0, 0, 1 );
  18700. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18701. this.add( cameraPY );
  18702. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18703. cameraNY.up.set( 0, 0, -1 );
  18704. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18705. this.add( cameraNY );
  18706. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18707. cameraPZ.up.set( 0, -1, 0 );
  18708. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18709. this.add( cameraPZ );
  18710. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18711. cameraNZ.up.set( 0, -1, 0 );
  18712. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18713. this.add( cameraNZ );
  18714. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18715. this.updateCubeMap = function ( renderer, scene ) {
  18716. var renderTarget = this.renderTarget;
  18717. var generateMipmaps = renderTarget.generateMipmaps;
  18718. renderTarget.generateMipmaps = false;
  18719. renderTarget.activeCubeFace = 0;
  18720. renderer.render( scene, cameraPX, renderTarget );
  18721. renderTarget.activeCubeFace = 1;
  18722. renderer.render( scene, cameraNX, renderTarget );
  18723. renderTarget.activeCubeFace = 2;
  18724. renderer.render( scene, cameraPY, renderTarget );
  18725. renderTarget.activeCubeFace = 3;
  18726. renderer.render( scene, cameraNY, renderTarget );
  18727. renderTarget.activeCubeFace = 4;
  18728. renderer.render( scene, cameraPZ, renderTarget );
  18729. renderTarget.generateMipmaps = generateMipmaps;
  18730. renderTarget.activeCubeFace = 5;
  18731. renderer.render( scene, cameraNZ, renderTarget );
  18732. };
  18733. };
  18734. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18735. /*
  18736. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18737. *
  18738. * A general perpose camera, for setting FOV, Lens Focal Length,
  18739. * and switching between perspective and orthographic views easily.
  18740. * Use this only if you do not wish to manage
  18741. * both a Orthographic and Perspective Camera
  18742. *
  18743. */
  18744. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18745. THREE.Camera.call( this );
  18746. this.fov = fov;
  18747. this.left = -width / 2;
  18748. this.right = width / 2
  18749. this.top = height / 2;
  18750. this.bottom = -height / 2;
  18751. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18752. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18753. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18754. this.zoom = 1;
  18755. this.toPerspective();
  18756. var aspect = width/height;
  18757. };
  18758. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18759. THREE.CombinedCamera.prototype.toPerspective = function () {
  18760. // Switches to the Perspective Camera
  18761. this.near = this.cameraP.near;
  18762. this.far = this.cameraP.far;
  18763. this.cameraP.fov = this.fov / this.zoom ;
  18764. this.cameraP.updateProjectionMatrix();
  18765. this.projectionMatrix = this.cameraP.projectionMatrix;
  18766. this.inPerspectiveMode = true;
  18767. this.inOrthographicMode = false;
  18768. };
  18769. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18770. // Switches to the Orthographic camera estimating viewport from Perspective
  18771. var fov = this.fov;
  18772. var aspect = this.cameraP.aspect;
  18773. var near = this.cameraP.near;
  18774. var far = this.cameraP.far;
  18775. // The size that we set is the mid plane of the viewing frustum
  18776. var hyperfocus = ( near + far ) / 2;
  18777. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18778. var planeHeight = 2 * halfHeight;
  18779. var planeWidth = planeHeight * aspect;
  18780. var halfWidth = planeWidth / 2;
  18781. halfHeight /= this.zoom;
  18782. halfWidth /= this.zoom;
  18783. this.cameraO.left = -halfWidth;
  18784. this.cameraO.right = halfWidth;
  18785. this.cameraO.top = halfHeight;
  18786. this.cameraO.bottom = -halfHeight;
  18787. // this.cameraO.left = -farHalfWidth;
  18788. // this.cameraO.right = farHalfWidth;
  18789. // this.cameraO.top = farHalfHeight;
  18790. // this.cameraO.bottom = -farHalfHeight;
  18791. // this.cameraO.left = this.left / this.zoom;
  18792. // this.cameraO.right = this.right / this.zoom;
  18793. // this.cameraO.top = this.top / this.zoom;
  18794. // this.cameraO.bottom = this.bottom / this.zoom;
  18795. this.cameraO.updateProjectionMatrix();
  18796. this.near = this.cameraO.near;
  18797. this.far = this.cameraO.far;
  18798. this.projectionMatrix = this.cameraO.projectionMatrix;
  18799. this.inPerspectiveMode = false;
  18800. this.inOrthographicMode = true;
  18801. };
  18802. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18803. this.cameraP.aspect = width / height;
  18804. this.left = -width / 2;
  18805. this.right = width / 2
  18806. this.top = height / 2;
  18807. this.bottom = -height / 2;
  18808. };
  18809. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18810. this.fov = fov;
  18811. if ( this.inPerspectiveMode ) {
  18812. this.toPerspective();
  18813. } else {
  18814. this.toOrthographic();
  18815. }
  18816. };
  18817. // For mantaining similar API with PerspectiveCamera
  18818. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18819. if ( this.inPerspectiveMode ) {
  18820. this.toPerspective();
  18821. } else {
  18822. this.toPerspective();
  18823. this.toOrthographic();
  18824. }
  18825. };
  18826. /*
  18827. * Uses Focal Length (in mm) to estimate and set FOV
  18828. * 35mm (fullframe) camera is used if frame size is not specified;
  18829. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18830. */
  18831. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18832. if ( frameHeight === undefined ) frameHeight = 24;
  18833. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18834. this.setFov( fov );
  18835. return fov;
  18836. };
  18837. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18838. this.zoom = zoom;
  18839. if ( this.inPerspectiveMode ) {
  18840. this.toPerspective();
  18841. } else {
  18842. this.toOrthographic();
  18843. }
  18844. };
  18845. THREE.CombinedCamera.prototype.toFrontView = function() {
  18846. this.rotation.x = 0;
  18847. this.rotation.y = 0;
  18848. this.rotation.z = 0;
  18849. // should we be modifing the matrix instead?
  18850. this.rotationAutoUpdate = false;
  18851. };
  18852. THREE.CombinedCamera.prototype.toBackView = function() {
  18853. this.rotation.x = 0;
  18854. this.rotation.y = Math.PI;
  18855. this.rotation.z = 0;
  18856. this.rotationAutoUpdate = false;
  18857. };
  18858. THREE.CombinedCamera.prototype.toLeftView = function() {
  18859. this.rotation.x = 0;
  18860. this.rotation.y = - Math.PI / 2;
  18861. this.rotation.z = 0;
  18862. this.rotationAutoUpdate = false;
  18863. };
  18864. THREE.CombinedCamera.prototype.toRightView = function() {
  18865. this.rotation.x = 0;
  18866. this.rotation.y = Math.PI / 2;
  18867. this.rotation.z = 0;
  18868. this.rotationAutoUpdate = false;
  18869. };
  18870. THREE.CombinedCamera.prototype.toTopView = function() {
  18871. this.rotation.x = - Math.PI / 2;
  18872. this.rotation.y = 0;
  18873. this.rotation.z = 0;
  18874. this.rotationAutoUpdate = false;
  18875. };
  18876. THREE.CombinedCamera.prototype.toBottomView = function() {
  18877. this.rotation.x = Math.PI / 2;
  18878. this.rotation.y = 0;
  18879. this.rotation.z = 0;
  18880. this.rotationAutoUpdate = false;
  18881. };
  18882. /**
  18883. * @author alteredq / http://alteredqualia.com/
  18884. *
  18885. * - 3d asterisk shape (for line pieces THREE.Line)
  18886. */
  18887. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  18888. THREE.Geometry.call( this );
  18889. var sd = innerRadius;
  18890. var ed = outerRadius;
  18891. var sd2 = 0.707 * sd;
  18892. var ed2 = 0.707 * ed;
  18893. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  18894. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  18895. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  18896. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  18897. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  18898. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  18899. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  18900. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  18901. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  18902. ];
  18903. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  18904. var x = rays[ i ][ 0 ];
  18905. var y = rays[ i ][ 1 ];
  18906. var z = rays[ i ][ 2 ];
  18907. this.vertices.push( new THREE.Vector3( x, y, z ) );
  18908. }
  18909. };
  18910. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  18911. * @author hughes
  18912. */
  18913. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18914. THREE.Geometry.call( this );
  18915. radius = radius || 50;
  18916. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18917. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18918. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18919. var i, uvs = [],
  18920. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18921. this.vertices.push(center);
  18922. uvs.push( centerUV );
  18923. for ( i = 0; i <= segments; i ++ ) {
  18924. var vertex = new THREE.Vector3();
  18925. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  18926. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  18927. this.vertices.push( vertex );
  18928. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18929. }
  18930. var n = new THREE.Vector3( 0, 0, -1 );
  18931. for ( i = 1; i <= segments; i ++ ) {
  18932. var v1 = i;
  18933. var v2 = i + 1 ;
  18934. var v3 = 0;
  18935. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18936. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18937. }
  18938. this.computeCentroids();
  18939. this.computeFaceNormals();
  18940. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18941. };
  18942. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18943. /**
  18944. * @author mrdoob / http://mrdoob.com/
  18945. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18946. */
  18947. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18948. THREE.Geometry.call( this );
  18949. var scope = this;
  18950. this.width = width;
  18951. this.height = height;
  18952. this.depth = depth;
  18953. this.widthSegments = widthSegments || 1;
  18954. this.heightSegments = heightSegments || 1;
  18955. this.depthSegments = depthSegments || 1;
  18956. var width_half = this.width / 2;
  18957. var height_half = this.height / 2;
  18958. var depth_half = this.depth / 2;
  18959. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18960. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18961. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18962. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18963. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18964. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18965. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18966. var w, ix, iy,
  18967. gridX = scope.widthSegments,
  18968. gridY = scope.heightSegments,
  18969. width_half = width / 2,
  18970. height_half = height / 2,
  18971. offset = scope.vertices.length;
  18972. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18973. w = 'z';
  18974. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18975. w = 'y';
  18976. gridY = scope.depthSegments;
  18977. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18978. w = 'x';
  18979. gridX = scope.depthSegments;
  18980. }
  18981. var gridX1 = gridX + 1,
  18982. gridY1 = gridY + 1,
  18983. segment_width = width / gridX,
  18984. segment_height = height / gridY,
  18985. normal = new THREE.Vector3();
  18986. normal[ w ] = depth > 0 ? 1 : - 1;
  18987. for ( iy = 0; iy < gridY1; iy ++ ) {
  18988. for ( ix = 0; ix < gridX1; ix ++ ) {
  18989. var vector = new THREE.Vector3();
  18990. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18991. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18992. vector[ w ] = depth;
  18993. scope.vertices.push( vector );
  18994. }
  18995. }
  18996. for ( iy = 0; iy < gridY; iy++ ) {
  18997. for ( ix = 0; ix < gridX; ix++ ) {
  18998. var a = ix + gridX1 * iy;
  18999. var b = ix + gridX1 * ( iy + 1 );
  19000. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19001. var d = ( ix + 1 ) + gridX1 * iy;
  19002. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  19003. face.normal.copy( normal );
  19004. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19005. face.materialIndex = materialIndex;
  19006. scope.faces.push( face );
  19007. scope.faceVertexUvs[ 0 ].push( [
  19008. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  19009. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  19010. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  19011. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  19012. ] );
  19013. }
  19014. }
  19015. }
  19016. this.computeCentroids();
  19017. this.mergeVertices();
  19018. };
  19019. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19020. /**
  19021. * @author mrdoob / http://mrdoob.com/
  19022. */
  19023. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  19024. THREE.Geometry.call( this );
  19025. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19026. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19027. height = height !== undefined ? height : 100;
  19028. var heightHalf = height / 2;
  19029. var segmentsX = radiusSegments || 8;
  19030. var segmentsY = heightSegments || 1;
  19031. var x, y, vertices = [], uvs = [];
  19032. for ( y = 0; y <= segmentsY; y ++ ) {
  19033. var verticesRow = [];
  19034. var uvsRow = [];
  19035. var v = y / segmentsY;
  19036. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19037. for ( x = 0; x <= segmentsX; x ++ ) {
  19038. var u = x / segmentsX;
  19039. var vertex = new THREE.Vector3();
  19040. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19041. vertex.y = - v * height + heightHalf;
  19042. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19043. this.vertices.push( vertex );
  19044. verticesRow.push( this.vertices.length - 1 );
  19045. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19046. }
  19047. vertices.push( verticesRow );
  19048. uvs.push( uvsRow );
  19049. }
  19050. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19051. var na, nb;
  19052. for ( x = 0; x < segmentsX; x ++ ) {
  19053. if ( radiusTop !== 0 ) {
  19054. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19055. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19056. } else {
  19057. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19058. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19059. }
  19060. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19061. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19062. for ( y = 0; y < segmentsY; y ++ ) {
  19063. var v1 = vertices[ y ][ x ];
  19064. var v2 = vertices[ y + 1 ][ x ];
  19065. var v3 = vertices[ y + 1 ][ x + 1 ];
  19066. var v4 = vertices[ y ][ x + 1 ];
  19067. var n1 = na.clone();
  19068. var n2 = na.clone();
  19069. var n3 = nb.clone();
  19070. var n4 = nb.clone();
  19071. var uv1 = uvs[ y ][ x ].clone();
  19072. var uv2 = uvs[ y + 1 ][ x ].clone();
  19073. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19074. var uv4 = uvs[ y ][ x + 1 ].clone();
  19075. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19076. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19077. }
  19078. }
  19079. // top cap
  19080. if ( !openEnded && radiusTop > 0 ) {
  19081. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19082. for ( x = 0; x < segmentsX; x ++ ) {
  19083. var v1 = vertices[ 0 ][ x ];
  19084. var v2 = vertices[ 0 ][ x + 1 ];
  19085. var v3 = this.vertices.length - 1;
  19086. var n1 = new THREE.Vector3( 0, 1, 0 );
  19087. var n2 = new THREE.Vector3( 0, 1, 0 );
  19088. var n3 = new THREE.Vector3( 0, 1, 0 );
  19089. var uv1 = uvs[ 0 ][ x ].clone();
  19090. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19091. var uv3 = new THREE.Vector2( uv2.u, 0 );
  19092. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19093. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19094. }
  19095. }
  19096. // bottom cap
  19097. if ( !openEnded && radiusBottom > 0 ) {
  19098. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19099. for ( x = 0; x < segmentsX; x ++ ) {
  19100. var v1 = vertices[ y ][ x + 1 ];
  19101. var v2 = vertices[ y ][ x ];
  19102. var v3 = this.vertices.length - 1;
  19103. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19104. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19105. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19106. var uv1 = uvs[ y ][ x + 1 ].clone();
  19107. var uv2 = uvs[ y ][ x ].clone();
  19108. var uv3 = new THREE.Vector2( uv2.u, 1 );
  19109. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19110. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19111. }
  19112. }
  19113. this.computeCentroids();
  19114. this.computeFaceNormals();
  19115. }
  19116. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19117. /**
  19118. * @author zz85 / http://www.lab4games.net/zz85/blog
  19119. *
  19120. * Creates extruded geometry from a path shape.
  19121. *
  19122. * parameters = {
  19123. *
  19124. * size: <float>, // size of the text
  19125. * height: <float>, // thickness to extrude text
  19126. * curveSegments: <int>, // number of points on the curves
  19127. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19128. * amount: <int>, // Amount
  19129. *
  19130. * bevelEnabled: <bool>, // turn on bevel
  19131. * bevelThickness: <float>, // how deep into text bevel goes
  19132. * bevelSize: <float>, // how far from text outline is bevel
  19133. * bevelSegments: <int>, // number of bevel layers
  19134. *
  19135. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19136. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19137. *
  19138. * material: <int> // material index for front and back faces
  19139. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19140. * uvGenerator: <Object> // object that provides UV generator functions
  19141. *
  19142. * }
  19143. **/
  19144. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19145. if ( typeof( shapes ) === "undefined" ) {
  19146. shapes = [];
  19147. return;
  19148. }
  19149. THREE.Geometry.call( this );
  19150. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19151. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19152. this.addShapeList( shapes, options );
  19153. this.computeCentroids();
  19154. this.computeFaceNormals();
  19155. // can't really use automatic vertex normals
  19156. // as then front and back sides get smoothed too
  19157. // should do separate smoothing just for sides
  19158. //this.computeVertexNormals();
  19159. //console.log( "took", ( Date.now() - startTime ) );
  19160. };
  19161. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19162. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19163. var sl = shapes.length;
  19164. for ( var s = 0; s < sl; s ++ ) {
  19165. var shape = shapes[ s ];
  19166. this.addShape( shape, options );
  19167. }
  19168. };
  19169. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19170. var amount = options.amount !== undefined ? options.amount : 100;
  19171. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19172. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19173. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19174. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19175. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19176. var steps = options.steps !== undefined ? options.steps : 1;
  19177. var extrudePath = options.extrudePath;
  19178. var extrudePts, extrudeByPath = false;
  19179. var material = options.material;
  19180. var extrudeMaterial = options.extrudeMaterial;
  19181. // Use default WorldUVGenerator if no UV generators are specified.
  19182. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19183. var shapebb = this.shapebb;
  19184. //shapebb = shape.getBoundingBox();
  19185. var splineTube, binormal, normal, position2;
  19186. if ( extrudePath ) {
  19187. extrudePts = extrudePath.getSpacedPoints( steps );
  19188. extrudeByPath = true;
  19189. bevelEnabled = false; // bevels not supported for path extrusion
  19190. // SETUP TNB variables
  19191. // Reuse TNB from TubeGeomtry for now.
  19192. // TODO1 - have a .isClosed in spline?
  19193. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19194. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19195. binormal = new THREE.Vector3();
  19196. normal = new THREE.Vector3();
  19197. position2 = new THREE.Vector3();
  19198. }
  19199. // Safeguards if bevels are not enabled
  19200. if ( ! bevelEnabled ) {
  19201. bevelSegments = 0;
  19202. bevelThickness = 0;
  19203. bevelSize = 0;
  19204. }
  19205. // Variables initalization
  19206. var ahole, h, hl; // looping of holes
  19207. var scope = this;
  19208. var bevelPoints = [];
  19209. var shapesOffset = this.vertices.length;
  19210. var shapePoints = shape.extractPoints( curveSegments );
  19211. var vertices = shapePoints.shape;
  19212. var holes = shapePoints.holes;
  19213. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19214. if ( reverse ) {
  19215. vertices = vertices.reverse();
  19216. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19217. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19218. ahole = holes[ h ];
  19219. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19220. holes[ h ] = ahole.reverse();
  19221. }
  19222. }
  19223. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19224. }
  19225. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19226. /* Vertices */
  19227. var contour = vertices; // vertices has all points but contour has only points of circumference
  19228. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19229. ahole = holes[ h ];
  19230. vertices = vertices.concat( ahole );
  19231. }
  19232. function scalePt2 ( pt, vec, size ) {
  19233. if ( !vec ) console.log( "die" );
  19234. return vec.clone().multiplyScalar( size ).add( pt );
  19235. }
  19236. var b, bs, t, z,
  19237. vert, vlen = vertices.length,
  19238. face, flen = faces.length,
  19239. cont, clen = contour.length;
  19240. // Find directions for point movement
  19241. var RAD_TO_DEGREES = 180 / Math.PI;
  19242. function getBevelVec( pt_i, pt_j, pt_k ) {
  19243. // Algorithm 2
  19244. return getBevelVec2( pt_i, pt_j, pt_k );
  19245. }
  19246. function getBevelVec1( pt_i, pt_j, pt_k ) {
  19247. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  19248. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  19249. if ( anglea > angleb ) {
  19250. angleb += Math.PI * 2;
  19251. }
  19252. var anglec = ( anglea + angleb ) / 2;
  19253. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  19254. var x = - Math.cos( anglec );
  19255. var y = - Math.sin( anglec );
  19256. var vec = new THREE.Vector2( x, y ); //.normalize();
  19257. return vec;
  19258. }
  19259. function getBevelVec2( pt_i, pt_j, pt_k ) {
  19260. var a = THREE.ExtrudeGeometry.__v1,
  19261. b = THREE.ExtrudeGeometry.__v2,
  19262. v_hat = THREE.ExtrudeGeometry.__v3,
  19263. w_hat = THREE.ExtrudeGeometry.__v4,
  19264. p = THREE.ExtrudeGeometry.__v5,
  19265. q = THREE.ExtrudeGeometry.__v6,
  19266. v, w,
  19267. v_dot_w_hat, q_sub_p_dot_w_hat,
  19268. s, intersection;
  19269. // good reading for line-line intersection
  19270. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  19271. // define a as vector j->i
  19272. // define b as vectot k->i
  19273. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  19274. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  19275. // get unit vectors
  19276. v = a.normalize();
  19277. w = b.normalize();
  19278. // normals from pt i
  19279. v_hat.set( -v.y, v.x );
  19280. w_hat.set( w.y, -w.x );
  19281. // pts from i
  19282. p.copy( pt_i ).add( v_hat );
  19283. q.copy( pt_i ).add( w_hat );
  19284. if ( p.equals( q ) ) {
  19285. //console.log("Warning: lines are straight");
  19286. return w_hat.clone();
  19287. }
  19288. // Points from j, k. helps prevents points cross overover most of the time
  19289. p.copy( pt_j ).add( v_hat );
  19290. q.copy( pt_k ).add( w_hat );
  19291. v_dot_w_hat = v.dot( w_hat );
  19292. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  19293. // We should not reach these conditions
  19294. if ( v_dot_w_hat === 0 ) {
  19295. console.log( "Either infinite or no solutions!" );
  19296. if ( q_sub_p_dot_w_hat === 0 ) {
  19297. console.log( "Its finite solutions." );
  19298. } else {
  19299. console.log( "Too bad, no solutions." );
  19300. }
  19301. }
  19302. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  19303. if ( s < 0 ) {
  19304. // in case of emergecy, revert to algorithm 1.
  19305. return getBevelVec1( pt_i, pt_j, pt_k );
  19306. }
  19307. intersection = v.multiplyScalar( s ).add( p );
  19308. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19309. }
  19310. var contourMovements = [];
  19311. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19312. if ( j === il ) j = 0;
  19313. if ( k === il ) k = 0;
  19314. // (j)---(i)---(k)
  19315. // console.log('i,j,k', i, j , k)
  19316. var pt_i = contour[ i ];
  19317. var pt_j = contour[ j ];
  19318. var pt_k = contour[ k ];
  19319. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19320. }
  19321. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19322. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19323. ahole = holes[ h ];
  19324. oneHoleMovements = [];
  19325. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19326. if ( j === il ) j = 0;
  19327. if ( k === il ) k = 0;
  19328. // (j)---(i)---(k)
  19329. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19330. }
  19331. holesMovements.push( oneHoleMovements );
  19332. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19333. }
  19334. // Loop bevelSegments, 1 for the front, 1 for the back
  19335. for ( b = 0; b < bevelSegments; b ++ ) {
  19336. //for ( b = bevelSegments; b > 0; b -- ) {
  19337. t = b / bevelSegments;
  19338. z = bevelThickness * ( 1 - t );
  19339. //z = bevelThickness * t;
  19340. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19341. //bs = bevelSize * t ; // linear
  19342. // contract shape
  19343. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19344. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19345. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19346. v( vert.x, vert.y, - z );
  19347. }
  19348. // expand holes
  19349. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19350. ahole = holes[ h ];
  19351. oneHoleMovements = holesMovements[ h ];
  19352. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19353. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19354. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19355. v( vert.x, vert.y, -z );
  19356. }
  19357. }
  19358. }
  19359. bs = bevelSize;
  19360. // Back facing vertices
  19361. for ( i = 0; i < vlen; i ++ ) {
  19362. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19363. if ( !extrudeByPath ) {
  19364. v( vert.x, vert.y, 0 );
  19365. } else {
  19366. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19367. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19368. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19369. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19370. v( position2.x, position2.y, position2.z );
  19371. }
  19372. }
  19373. // Add stepped vertices...
  19374. // Including front facing vertices
  19375. var s;
  19376. for ( s = 1; s <= steps; s ++ ) {
  19377. for ( i = 0; i < vlen; i ++ ) {
  19378. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19379. if ( !extrudeByPath ) {
  19380. v( vert.x, vert.y, amount / steps * s );
  19381. } else {
  19382. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19383. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19384. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19385. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19386. v( position2.x, position2.y, position2.z );
  19387. }
  19388. }
  19389. }
  19390. // Add bevel segments planes
  19391. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19392. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19393. t = b / bevelSegments;
  19394. z = bevelThickness * ( 1 - t );
  19395. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19396. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19397. // contract shape
  19398. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19399. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19400. v( vert.x, vert.y, amount + z );
  19401. }
  19402. // expand holes
  19403. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19404. ahole = holes[ h ];
  19405. oneHoleMovements = holesMovements[ h ];
  19406. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19407. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19408. if ( !extrudeByPath ) {
  19409. v( vert.x, vert.y, amount + z );
  19410. } else {
  19411. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19412. }
  19413. }
  19414. }
  19415. }
  19416. /* Faces */
  19417. // Top and bottom faces
  19418. buildLidFaces();
  19419. // Sides faces
  19420. buildSideFaces();
  19421. ///// Internal functions
  19422. function buildLidFaces() {
  19423. if ( bevelEnabled ) {
  19424. var layer = 0 ; // steps + 1
  19425. var offset = vlen * layer;
  19426. // Bottom faces
  19427. for ( i = 0; i < flen; i ++ ) {
  19428. face = faces[ i ];
  19429. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19430. }
  19431. layer = steps + bevelSegments * 2;
  19432. offset = vlen * layer;
  19433. // Top faces
  19434. for ( i = 0; i < flen; i ++ ) {
  19435. face = faces[ i ];
  19436. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19437. }
  19438. } else {
  19439. // Bottom faces
  19440. for ( i = 0; i < flen; i++ ) {
  19441. face = faces[ i ];
  19442. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19443. }
  19444. // Top faces
  19445. for ( i = 0; i < flen; i ++ ) {
  19446. face = faces[ i ];
  19447. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19448. }
  19449. }
  19450. }
  19451. // Create faces for the z-sides of the shape
  19452. function buildSideFaces() {
  19453. var layeroffset = 0;
  19454. sidewalls( contour, layeroffset );
  19455. layeroffset += contour.length;
  19456. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19457. ahole = holes[ h ];
  19458. sidewalls( ahole, layeroffset );
  19459. //, true
  19460. layeroffset += ahole.length;
  19461. }
  19462. }
  19463. function sidewalls( contour, layeroffset ) {
  19464. var j, k;
  19465. i = contour.length;
  19466. while ( --i >= 0 ) {
  19467. j = i;
  19468. k = i - 1;
  19469. if ( k < 0 ) k = contour.length - 1;
  19470. //console.log('b', i,j, i-1, k,vertices.length);
  19471. var s = 0, sl = steps + bevelSegments * 2;
  19472. for ( s = 0; s < sl; s ++ ) {
  19473. var slen1 = vlen * s;
  19474. var slen2 = vlen * ( s + 1 );
  19475. var a = layeroffset + j + slen1,
  19476. b = layeroffset + k + slen1,
  19477. c = layeroffset + k + slen2,
  19478. d = layeroffset + j + slen2;
  19479. f4( a, b, c, d, contour, s, sl, j, k );
  19480. }
  19481. }
  19482. }
  19483. function v( x, y, z ) {
  19484. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19485. }
  19486. function f3( a, b, c, isBottom ) {
  19487. a += shapesOffset;
  19488. b += shapesOffset;
  19489. c += shapesOffset;
  19490. // normal, color, material
  19491. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19492. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19493. scope.faceVertexUvs[ 0 ].push( uvs );
  19494. }
  19495. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19496. a += shapesOffset;
  19497. b += shapesOffset;
  19498. c += shapesOffset;
  19499. d += shapesOffset;
  19500. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19501. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19502. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19503. scope.faceVertexUvs[ 0 ].push( uvs );
  19504. }
  19505. };
  19506. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19507. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19508. var ax = geometry.vertices[ indexA ].x,
  19509. ay = geometry.vertices[ indexA ].y,
  19510. bx = geometry.vertices[ indexB ].x,
  19511. by = geometry.vertices[ indexB ].y,
  19512. cx = geometry.vertices[ indexC ].x,
  19513. cy = geometry.vertices[ indexC ].y;
  19514. return [
  19515. new THREE.Vector2( ax, ay ),
  19516. new THREE.Vector2( bx, by ),
  19517. new THREE.Vector2( cx, cy )
  19518. ];
  19519. },
  19520. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19521. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19522. },
  19523. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19524. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19525. contourIndex1, contourIndex2 ) {
  19526. var ax = geometry.vertices[ indexA ].x,
  19527. ay = geometry.vertices[ indexA ].y,
  19528. az = geometry.vertices[ indexA ].z,
  19529. bx = geometry.vertices[ indexB ].x,
  19530. by = geometry.vertices[ indexB ].y,
  19531. bz = geometry.vertices[ indexB ].z,
  19532. cx = geometry.vertices[ indexC ].x,
  19533. cy = geometry.vertices[ indexC ].y,
  19534. cz = geometry.vertices[ indexC ].z,
  19535. dx = geometry.vertices[ indexD ].x,
  19536. dy = geometry.vertices[ indexD ].y,
  19537. dz = geometry.vertices[ indexD ].z;
  19538. if ( Math.abs( ay - by ) < 0.01 ) {
  19539. return [
  19540. new THREE.Vector2( ax, 1 - az ),
  19541. new THREE.Vector2( bx, 1 - bz ),
  19542. new THREE.Vector2( cx, 1 - cz ),
  19543. new THREE.Vector2( dx, 1 - dz )
  19544. ];
  19545. } else {
  19546. return [
  19547. new THREE.Vector2( ay, 1 - az ),
  19548. new THREE.Vector2( by, 1 - bz ),
  19549. new THREE.Vector2( cy, 1 - cz ),
  19550. new THREE.Vector2( dy, 1 - dz )
  19551. ];
  19552. }
  19553. }
  19554. };
  19555. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19556. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19557. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19558. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19559. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19560. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19561. /**
  19562. * @author jonobr1 / http://jonobr1.com
  19563. *
  19564. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19565. * ExtrudeGeometry.
  19566. *
  19567. * parameters = {
  19568. *
  19569. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19570. *
  19571. * material: <int> // material index for front and back faces
  19572. * uvGenerator: <Object> // object that provides UV generator functions
  19573. *
  19574. * }
  19575. **/
  19576. THREE.ShapeGeometry = function ( shapes, options ) {
  19577. THREE.Geometry.call( this );
  19578. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19579. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19580. this.addShapeList( shapes, options );
  19581. this.computeCentroids();
  19582. this.computeFaceNormals();
  19583. };
  19584. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19585. /**
  19586. * Add an array of shapes to THREE.ShapeGeometry.
  19587. */
  19588. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19589. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19590. this.addShape( shapes[ i ], options );
  19591. }
  19592. return this;
  19593. };
  19594. /**
  19595. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19596. */
  19597. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19598. if ( options === undefined ) options = {};
  19599. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19600. var material = options.material;
  19601. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19602. var shapebb = this.shapebb;
  19603. //
  19604. var i, l, hole, s;
  19605. var shapesOffset = this.vertices.length;
  19606. var shapePoints = shape.extractPoints( curveSegments );
  19607. var vertices = shapePoints.shape;
  19608. var holes = shapePoints.holes;
  19609. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19610. if ( reverse ) {
  19611. vertices = vertices.reverse();
  19612. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19613. for ( i = 0, l = holes.length; i < l; i++ ) {
  19614. hole = holes[ i ];
  19615. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19616. holes[ i ] = hole.reverse();
  19617. }
  19618. }
  19619. reverse = false;
  19620. }
  19621. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19622. // Vertices
  19623. var contour = vertices;
  19624. for ( i = 0, l = holes.length; i < l; i++ ) {
  19625. hole = holes[ i ];
  19626. vertices = vertices.concat( hole );
  19627. }
  19628. //
  19629. var vert, vlen = vertices.length;
  19630. var face, flen = faces.length;
  19631. var cont, clen = contour.length;
  19632. for ( i = 0; i < vlen; i++ ) {
  19633. vert = vertices[ i ];
  19634. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19635. }
  19636. for ( i = 0; i < flen; i++ ) {
  19637. face = faces[ i ];
  19638. var a = face[ 0 ] + shapesOffset;
  19639. var b = face[ 1 ] + shapesOffset;
  19640. var c = face[ 2 ] + shapesOffset;
  19641. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19642. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19643. }
  19644. };
  19645. /**
  19646. * @author astrodud / http://astrodud.isgreat.org/
  19647. * @author zz85 / https://github.com/zz85
  19648. */
  19649. THREE.LatheGeometry = function ( points, steps, angle ) {
  19650. THREE.Geometry.call( this );
  19651. var _steps = steps || 12;
  19652. var _angle = angle || 2 * Math.PI;
  19653. var _newV = [];
  19654. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  19655. for ( var j = 0; j < points.length; j ++ ) {
  19656. _newV[ j ] = points[ j ].clone();
  19657. this.vertices.push( _newV[ j ] );
  19658. }
  19659. var i, il = _steps + 1;
  19660. for ( i = 0; i < il; i ++ ) {
  19661. for ( var j = 0; j < _newV.length; j ++ ) {
  19662. _newV[ j ] = _newV[ j ].clone().applyMatrix4( _matrix );
  19663. this.vertices.push( _newV[ j ] );
  19664. }
  19665. }
  19666. for ( i = 0; i < _steps; i ++ ) {
  19667. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  19668. var a = i * kl + k;
  19669. var b = ( ( i + 1 ) % il ) * kl + k;
  19670. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  19671. var d = i * kl + ( k + 1 ) % kl;
  19672. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19673. this.faceVertexUvs[ 0 ].push( [
  19674. new THREE.Vector2( 1 - i / _steps, k / kl ),
  19675. new THREE.Vector2( 1 - ( i + 1 ) / _steps, k / kl ),
  19676. new THREE.Vector2( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  19677. new THREE.Vector2( 1 - i / _steps, ( k + 1 ) / kl )
  19678. ] );
  19679. }
  19680. }
  19681. this.computeCentroids();
  19682. this.computeFaceNormals();
  19683. this.computeVertexNormals();
  19684. };
  19685. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19686. /**
  19687. * @author mrdoob / http://mrdoob.com/
  19688. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19689. */
  19690. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19691. THREE.Geometry.call( this );
  19692. this.width = width;
  19693. this.height = height;
  19694. this.widthSegments = widthSegments || 1;
  19695. this.heightSegments = heightSegments || 1;
  19696. var ix, iz;
  19697. var width_half = width / 2;
  19698. var height_half = height / 2;
  19699. var gridX = this.widthSegments;
  19700. var gridZ = this.heightSegments;
  19701. var gridX1 = gridX + 1;
  19702. var gridZ1 = gridZ + 1;
  19703. var segment_width = this.width / gridX;
  19704. var segment_height = this.height / gridZ;
  19705. var normal = new THREE.Vector3( 0, 0, 1 );
  19706. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19707. for ( ix = 0; ix < gridX1; ix ++ ) {
  19708. var x = ix * segment_width - width_half;
  19709. var y = iz * segment_height - height_half;
  19710. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19711. }
  19712. }
  19713. for ( iz = 0; iz < gridZ; iz ++ ) {
  19714. for ( ix = 0; ix < gridX; ix ++ ) {
  19715. var a = ix + gridX1 * iz;
  19716. var b = ix + gridX1 * ( iz + 1 );
  19717. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19718. var d = ( ix + 1 ) + gridX1 * iz;
  19719. var face = new THREE.Face4( a, b, c, d );
  19720. face.normal.copy( normal );
  19721. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19722. this.faces.push( face );
  19723. this.faceVertexUvs[ 0 ].push( [
  19724. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19725. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19726. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19727. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19728. ] );
  19729. }
  19730. }
  19731. this.computeCentroids();
  19732. };
  19733. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19734. /**
  19735. * @author mrdoob / http://mrdoob.com/
  19736. */
  19737. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19738. THREE.Geometry.call( this );
  19739. this.radius = radius || 50;
  19740. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19741. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19742. phiStart = phiStart !== undefined ? phiStart : 0;
  19743. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19744. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19745. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19746. var x, y, vertices = [], uvs = [];
  19747. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19748. var verticesRow = [];
  19749. var uvsRow = [];
  19750. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19751. var u = x / this.widthSegments;
  19752. var v = y / this.heightSegments;
  19753. var vertex = new THREE.Vector3();
  19754. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19755. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19756. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19757. this.vertices.push( vertex );
  19758. verticesRow.push( this.vertices.length - 1 );
  19759. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19760. }
  19761. vertices.push( verticesRow );
  19762. uvs.push( uvsRow );
  19763. }
  19764. for ( y = 0; y < this.heightSegments; y ++ ) {
  19765. for ( x = 0; x < this.widthSegments; x ++ ) {
  19766. var v1 = vertices[ y ][ x + 1 ];
  19767. var v2 = vertices[ y ][ x ];
  19768. var v3 = vertices[ y + 1 ][ x ];
  19769. var v4 = vertices[ y + 1 ][ x + 1 ];
  19770. var n1 = this.vertices[ v1 ].clone().normalize();
  19771. var n2 = this.vertices[ v2 ].clone().normalize();
  19772. var n3 = this.vertices[ v3 ].clone().normalize();
  19773. var n4 = this.vertices[ v4 ].clone().normalize();
  19774. var uv1 = uvs[ y ][ x + 1 ].clone();
  19775. var uv2 = uvs[ y ][ x ].clone();
  19776. var uv3 = uvs[ y + 1 ][ x ].clone();
  19777. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19778. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19779. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19780. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19781. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19782. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19783. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19784. } else {
  19785. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19786. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19787. }
  19788. }
  19789. }
  19790. this.computeCentroids();
  19791. this.computeFaceNormals();
  19792. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19793. };
  19794. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19795. /**
  19796. * @author zz85 / http://www.lab4games.net/zz85/blog
  19797. * @author alteredq / http://alteredqualia.com/
  19798. *
  19799. * For creating 3D text geometry in three.js
  19800. *
  19801. * Text = 3D Text
  19802. *
  19803. * parameters = {
  19804. * size: <float>, // size of the text
  19805. * height: <float>, // thickness to extrude text
  19806. * curveSegments: <int>, // number of points on the curves
  19807. *
  19808. * font: <string>, // font name
  19809. * weight: <string>, // font weight (normal, bold)
  19810. * style: <string>, // font style (normal, italics)
  19811. *
  19812. * bevelEnabled: <bool>, // turn on bevel
  19813. * bevelThickness: <float>, // how deep into text bevel goes
  19814. * bevelSize: <float>, // how far from text outline is bevel
  19815. * }
  19816. *
  19817. */
  19818. /* Usage Examples
  19819. // TextGeometry wrapper
  19820. var text3d = new TextGeometry( text, options );
  19821. // Complete manner
  19822. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19823. var text3d = new ExtrudeGeometry( textShapes, options );
  19824. */
  19825. THREE.TextGeometry = function ( text, parameters ) {
  19826. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19827. // translate parameters to ExtrudeGeometry API
  19828. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19829. // defaults
  19830. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19831. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19832. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19833. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19834. };
  19835. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19836. /**
  19837. * @author oosmoxiecode
  19838. * @author mrdoob / http://mrdoob.com/
  19839. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19840. */
  19841. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19842. THREE.Geometry.call( this );
  19843. var scope = this;
  19844. this.radius = radius || 100;
  19845. this.tube = tube || 40;
  19846. this.radialSegments = radialSegments || 8;
  19847. this.tubularSegments = tubularSegments || 6;
  19848. this.arc = arc || Math.PI * 2;
  19849. var center = new THREE.Vector3(), uvs = [], normals = [];
  19850. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19851. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19852. var u = i / this.tubularSegments * this.arc;
  19853. var v = j / this.radialSegments * Math.PI * 2;
  19854. center.x = this.radius * Math.cos( u );
  19855. center.y = this.radius * Math.sin( u );
  19856. var vertex = new THREE.Vector3();
  19857. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19858. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19859. vertex.z = this.tube * Math.sin( v );
  19860. this.vertices.push( vertex );
  19861. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19862. normals.push( vertex.clone().sub( center ).normalize() );
  19863. }
  19864. }
  19865. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19866. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19867. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19868. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19869. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19870. var d = ( this.tubularSegments + 1 ) * j + i;
  19871. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19872. face.normal.add( normals[ a ] );
  19873. face.normal.add( normals[ b ] );
  19874. face.normal.add( normals[ c ] );
  19875. face.normal.add( normals[ d ] );
  19876. face.normal.normalize();
  19877. this.faces.push( face );
  19878. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19879. }
  19880. }
  19881. this.computeCentroids();
  19882. };
  19883. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19884. /**
  19885. * @author oosmoxiecode
  19886. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19887. */
  19888. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19889. THREE.Geometry.call( this );
  19890. var scope = this;
  19891. this.radius = radius || 100;
  19892. this.tube = tube || 40;
  19893. this.radialSegments = radialSegments || 64;
  19894. this.tubularSegments = tubularSegments || 8;
  19895. this.p = p || 2;
  19896. this.q = q || 3;
  19897. this.heightScale = heightScale || 1;
  19898. this.grid = new Array( this.radialSegments );
  19899. var tang = new THREE.Vector3();
  19900. var n = new THREE.Vector3();
  19901. var bitan = new THREE.Vector3();
  19902. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19903. this.grid[ i ] = new Array( this.tubularSegments );
  19904. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19905. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19906. var v = j / this.tubularSegments * 2 * Math.PI;
  19907. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19908. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19909. var cx, cy;
  19910. tang.subVectors( p2, p1 );
  19911. n.addVectors( p2, p1 );
  19912. bitan.crossVectors( tang, n );
  19913. n.crossVectors( bitan, tang );
  19914. bitan.normalize();
  19915. n.normalize();
  19916. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19917. cy = this.tube * Math.sin( v );
  19918. p1.x += cx * n.x + cy * bitan.x;
  19919. p1.y += cx * n.y + cy * bitan.y;
  19920. p1.z += cx * n.z + cy * bitan.z;
  19921. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19922. }
  19923. }
  19924. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19925. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19926. var ip = ( i + 1 ) % this.radialSegments;
  19927. var jp = ( j + 1 ) % this.tubularSegments;
  19928. var a = this.grid[ i ][ j ];
  19929. var b = this.grid[ ip ][ j ];
  19930. var c = this.grid[ ip ][ jp ];
  19931. var d = this.grid[ i ][ jp ];
  19932. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19933. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19934. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19935. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19936. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19937. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19938. }
  19939. }
  19940. this.computeCentroids();
  19941. this.computeFaceNormals();
  19942. this.computeVertexNormals();
  19943. function vert( x, y, z ) {
  19944. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19945. }
  19946. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19947. var cu = Math.cos( u );
  19948. var cv = Math.cos( v );
  19949. var su = Math.sin( u );
  19950. var quOverP = in_q / in_p * u;
  19951. var cs = Math.cos( quOverP );
  19952. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19953. var ty = radius * ( 2 + cs ) * su * 0.5;
  19954. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19955. return new THREE.Vector3( tx, ty, tz );
  19956. }
  19957. };
  19958. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19959. /**
  19960. * @author WestLangley / https://github.com/WestLangley
  19961. * @author zz85 / https://github.com/zz85
  19962. * @author miningold / https://github.com/miningold
  19963. *
  19964. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19965. *
  19966. * Creates a tube which extrudes along a 3d spline
  19967. *
  19968. * Uses parallel transport frames as described in
  19969. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19970. */
  19971. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19972. THREE.Geometry.call( this );
  19973. this.path = path;
  19974. this.segments = segments || 64;
  19975. this.radius = radius || 1;
  19976. this.radiusSegments = radiusSegments || 8;
  19977. this.closed = closed || false;
  19978. if ( debug ) this.debug = new THREE.Object3D();
  19979. this.grid = [];
  19980. var scope = this,
  19981. tangent,
  19982. normal,
  19983. binormal,
  19984. numpoints = this.segments + 1,
  19985. x, y, z,
  19986. tx, ty, tz,
  19987. u, v,
  19988. cx, cy,
  19989. pos, pos2 = new THREE.Vector3(),
  19990. i, j,
  19991. ip, jp,
  19992. a, b, c, d,
  19993. uva, uvb, uvc, uvd;
  19994. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19995. tangents = frames.tangents,
  19996. normals = frames.normals,
  19997. binormals = frames.binormals;
  19998. // proxy internals
  19999. this.tangents = tangents;
  20000. this.normals = normals;
  20001. this.binormals = binormals;
  20002. function vert( x, y, z ) {
  20003. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20004. }
  20005. // consruct the grid
  20006. for ( i = 0; i < numpoints; i++ ) {
  20007. this.grid[ i ] = [];
  20008. u = i / ( numpoints - 1 );
  20009. pos = path.getPointAt( u );
  20010. tangent = tangents[ i ];
  20011. normal = normals[ i ];
  20012. binormal = binormals[ i ];
  20013. if ( this.debug ) {
  20014. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  20015. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  20016. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  20017. }
  20018. for ( j = 0; j < this.radiusSegments; j++ ) {
  20019. v = j / this.radiusSegments * 2 * Math.PI;
  20020. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20021. cy = this.radius * Math.sin( v );
  20022. pos2.copy( pos );
  20023. pos2.x += cx * normal.x + cy * binormal.x;
  20024. pos2.y += cx * normal.y + cy * binormal.y;
  20025. pos2.z += cx * normal.z + cy * binormal.z;
  20026. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20027. }
  20028. }
  20029. // construct the mesh
  20030. for ( i = 0; i < this.segments; i++ ) {
  20031. for ( j = 0; j < this.radiusSegments; j++ ) {
  20032. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  20033. jp = (j + 1) % this.radiusSegments;
  20034. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20035. b = this.grid[ ip ][ j ];
  20036. c = this.grid[ ip ][ jp ];
  20037. d = this.grid[ i ][ jp ];
  20038. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  20039. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  20040. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  20041. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  20042. this.faces.push( new THREE.Face4( a, b, c, d ) );
  20043. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  20044. }
  20045. }
  20046. this.computeCentroids();
  20047. this.computeFaceNormals();
  20048. this.computeVertexNormals();
  20049. };
  20050. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20051. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20052. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  20053. var tangent = new THREE.Vector3(),
  20054. normal = new THREE.Vector3(),
  20055. binormal = new THREE.Vector3(),
  20056. tangents = [],
  20057. normals = [],
  20058. binormals = [],
  20059. vec = new THREE.Vector3(),
  20060. mat = new THREE.Matrix4(),
  20061. numpoints = segments + 1,
  20062. theta,
  20063. epsilon = 0.0001,
  20064. smallest,
  20065. tx, ty, tz,
  20066. i, u, v;
  20067. // expose internals
  20068. this.tangents = tangents;
  20069. this.normals = normals;
  20070. this.binormals = binormals;
  20071. // compute the tangent vectors for each segment on the path
  20072. for ( i = 0; i < numpoints; i++ ) {
  20073. u = i / ( numpoints - 1 );
  20074. tangents[ i ] = path.getTangentAt( u );
  20075. tangents[ i ].normalize();
  20076. }
  20077. initialNormal3();
  20078. function initialNormal1(lastBinormal) {
  20079. // fixed start binormal. Has dangers of 0 vectors
  20080. normals[ 0 ] = new THREE.Vector3();
  20081. binormals[ 0 ] = new THREE.Vector3();
  20082. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20083. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20084. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20085. }
  20086. function initialNormal2() {
  20087. // This uses the Frenet-Serret formula for deriving binormal
  20088. var t2 = path.getTangentAt( epsilon );
  20089. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20090. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20091. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20092. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20093. }
  20094. function initialNormal3() {
  20095. // select an initial normal vector perpenicular to the first tangent vector,
  20096. // and in the direction of the smallest tangent xyz component
  20097. normals[ 0 ] = new THREE.Vector3();
  20098. binormals[ 0 ] = new THREE.Vector3();
  20099. smallest = Number.MAX_VALUE;
  20100. tx = Math.abs( tangents[ 0 ].x );
  20101. ty = Math.abs( tangents[ 0 ].y );
  20102. tz = Math.abs( tangents[ 0 ].z );
  20103. if ( tx <= smallest ) {
  20104. smallest = tx;
  20105. normal.set( 1, 0, 0 );
  20106. }
  20107. if ( ty <= smallest ) {
  20108. smallest = ty;
  20109. normal.set( 0, 1, 0 );
  20110. }
  20111. if ( tz <= smallest ) {
  20112. normal.set( 0, 0, 1 );
  20113. }
  20114. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20115. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20116. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20117. }
  20118. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20119. for ( i = 1; i < numpoints; i++ ) {
  20120. normals[ i ] = normals[ i-1 ].clone();
  20121. binormals[ i ] = binormals[ i-1 ].clone();
  20122. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20123. if ( vec.length() > epsilon ) {
  20124. vec.normalize();
  20125. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  20126. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20127. }
  20128. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20129. }
  20130. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20131. if ( closed ) {
  20132. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  20133. theta /= ( numpoints - 1 );
  20134. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20135. theta = -theta;
  20136. }
  20137. for ( i = 1; i < numpoints; i++ ) {
  20138. // twist a little...
  20139. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20140. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20141. }
  20142. }
  20143. };
  20144. /**
  20145. * @author clockworkgeek / https://github.com/clockworkgeek
  20146. * @author timothypratley / https://github.com/timothypratley
  20147. */
  20148. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20149. THREE.Geometry.call( this );
  20150. radius = radius || 1;
  20151. detail = detail || 0;
  20152. var that = this;
  20153. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20154. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20155. }
  20156. var midpoints = [], p = this.vertices;
  20157. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20158. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  20159. }
  20160. this.mergeVertices();
  20161. // Apply radius
  20162. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20163. this.vertices[ i ].multiplyScalar( radius );
  20164. }
  20165. // Project vector onto sphere's surface
  20166. function prepare( vector ) {
  20167. var vertex = vector.normalize().clone();
  20168. vertex.index = that.vertices.push( vertex ) - 1;
  20169. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20170. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20171. var v = inclination( vector ) / Math.PI + 0.5;
  20172. vertex.uv = new THREE.Vector2( u, 1 - v );
  20173. return vertex;
  20174. }
  20175. // Approximate a curved face with recursively sub-divided triangles.
  20176. function make( v1, v2, v3, detail ) {
  20177. if ( detail < 1 ) {
  20178. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20179. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20180. face.normal = face.centroid.clone().normalize();
  20181. that.faces.push( face );
  20182. var azi = azimuth( face.centroid );
  20183. that.faceVertexUvs[ 0 ].push( [
  20184. correctUV( v1.uv, v1, azi ),
  20185. correctUV( v2.uv, v2, azi ),
  20186. correctUV( v3.uv, v3, azi )
  20187. ] );
  20188. } else {
  20189. detail -= 1;
  20190. // split triangle into 4 smaller triangles
  20191. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  20192. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  20193. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  20194. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  20195. }
  20196. }
  20197. function midpoint( v1, v2 ) {
  20198. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  20199. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  20200. var mid = midpoints[ v1.index ][ v2.index ];
  20201. if ( mid === undefined ) {
  20202. // generate mean point and project to surface with prepare()
  20203. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  20204. new THREE.Vector3().addVectors( v1, v2 ).divideScalar( 2 )
  20205. );
  20206. }
  20207. return mid;
  20208. }
  20209. // Angle around the Y axis, counter-clockwise when looking from above.
  20210. function azimuth( vector ) {
  20211. return Math.atan2( vector.z, -vector.x );
  20212. }
  20213. // Angle above the XZ plane.
  20214. function inclination( vector ) {
  20215. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20216. }
  20217. // Texture fixing helper. Spheres have some odd behaviours.
  20218. function correctUV( uv, vector, azimuth ) {
  20219. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20220. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20221. return uv;
  20222. }
  20223. this.computeCentroids();
  20224. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20225. };
  20226. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20227. /**
  20228. * @author timothypratley / https://github.com/timothypratley
  20229. */
  20230. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20231. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20232. var vertices = [
  20233. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20234. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20235. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20236. ];
  20237. var faces = [
  20238. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20239. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20240. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20241. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20242. ];
  20243. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20244. };
  20245. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20246. /**
  20247. * @author timothypratley / https://github.com/timothypratley
  20248. */
  20249. THREE.OctahedronGeometry = function ( radius, detail ) {
  20250. var vertices = [
  20251. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20252. ];
  20253. var faces = [
  20254. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20255. ];
  20256. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20257. };
  20258. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20259. /**
  20260. * @author timothypratley / https://github.com/timothypratley
  20261. */
  20262. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20263. var vertices = [
  20264. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20265. ];
  20266. var faces = [
  20267. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20268. ];
  20269. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20270. };
  20271. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20272. /**
  20273. * @author zz85 / https://github.com/zz85
  20274. * Parametric Surfaces Geometry
  20275. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20276. *
  20277. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  20278. *
  20279. */
  20280. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  20281. THREE.Geometry.call( this );
  20282. var verts = this.vertices;
  20283. var faces = this.faces;
  20284. var uvs = this.faceVertexUvs[ 0 ];
  20285. useTris = (useTris === undefined) ? false : useTris;
  20286. var i, il, j, p;
  20287. var u, v;
  20288. var stackCount = stacks + 1;
  20289. var sliceCount = slices + 1;
  20290. for ( i = 0; i <= stacks; i ++ ) {
  20291. v = i / stacks;
  20292. for ( j = 0; j <= slices; j ++ ) {
  20293. u = j / slices;
  20294. p = func( u, v );
  20295. verts.push( p );
  20296. }
  20297. }
  20298. var a, b, c, d;
  20299. var uva, uvb, uvc, uvd;
  20300. for ( i = 0; i < stacks; i ++ ) {
  20301. for ( j = 0; j < slices; j ++ ) {
  20302. a = i * sliceCount + j;
  20303. b = i * sliceCount + j + 1;
  20304. c = (i + 1) * sliceCount + j;
  20305. d = (i + 1) * sliceCount + j + 1;
  20306. uva = new THREE.Vector2( j / slices, i / stacks );
  20307. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20308. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20309. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20310. if ( useTris ) {
  20311. faces.push( new THREE.Face3( a, b, c ) );
  20312. faces.push( new THREE.Face3( b, d, c ) );
  20313. uvs.push( [ uva, uvb, uvc ] );
  20314. uvs.push( [ uvb, uvd, uvc ] );
  20315. } else {
  20316. faces.push( new THREE.Face4( a, b, d, c ) );
  20317. uvs.push( [ uva, uvb, uvd, uvc ] );
  20318. }
  20319. }
  20320. }
  20321. // console.log(this);
  20322. // magic bullet
  20323. // var diff = this.mergeVertices();
  20324. // console.log('removed ', diff, ' vertices by merging');
  20325. this.computeCentroids();
  20326. this.computeFaceNormals();
  20327. this.computeVertexNormals();
  20328. };
  20329. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20330. /**
  20331. * @author qiao / https://github.com/qiao
  20332. * @fileoverview This is a convex hull generator using the incremental method.
  20333. * The complexity is O(n^2) where n is the number of vertices.
  20334. * O(nlogn) algorithms do exist, but they are much more complicated.
  20335. *
  20336. * Benchmark:
  20337. *
  20338. * Platform: CPU: P7350 @2.00GHz Engine: V8
  20339. *
  20340. * Num Vertices Time(ms)
  20341. *
  20342. * 10 1
  20343. * 20 3
  20344. * 30 19
  20345. * 40 48
  20346. * 50 107
  20347. */
  20348. THREE.ConvexGeometry = function( vertices ) {
  20349. THREE.Geometry.call( this );
  20350. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  20351. for ( var i = 3; i < vertices.length; i++ ) {
  20352. addPoint( i );
  20353. }
  20354. function addPoint( vertexId ) {
  20355. var vertex = vertices[ vertexId ].clone();
  20356. var mag = vertex.length();
  20357. vertex.x += mag * randomOffset();
  20358. vertex.y += mag * randomOffset();
  20359. vertex.z += mag * randomOffset();
  20360. var hole = [];
  20361. for ( var f = 0; f < faces.length; ) {
  20362. var face = faces[ f ];
  20363. // for each face, if the vertex can see it,
  20364. // then we try to add the face's edges into the hole.
  20365. if ( visible( face, vertex ) ) {
  20366. for ( var e = 0; e < 3; e++ ) {
  20367. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  20368. var boundary = true;
  20369. // remove duplicated edges.
  20370. for ( var h = 0; h < hole.length; h++ ) {
  20371. if ( equalEdge( hole[ h ], edge ) ) {
  20372. hole[ h ] = hole[ hole.length - 1 ];
  20373. hole.pop();
  20374. boundary = false;
  20375. break;
  20376. }
  20377. }
  20378. if ( boundary ) {
  20379. hole.push( edge );
  20380. }
  20381. }
  20382. // remove faces[ f ]
  20383. faces[ f ] = faces[ faces.length - 1 ];
  20384. faces.pop();
  20385. } else { // not visible
  20386. f++;
  20387. }
  20388. }
  20389. // construct the new faces formed by the edges of the hole and the vertex
  20390. for ( var h = 0; h < hole.length; h++ ) {
  20391. faces.push( [
  20392. hole[ h ][ 0 ],
  20393. hole[ h ][ 1 ],
  20394. vertexId
  20395. ] );
  20396. }
  20397. }
  20398. /**
  20399. * Whether the face is visible from the vertex
  20400. */
  20401. function visible( face, vertex ) {
  20402. var va = vertices[ face[ 0 ] ];
  20403. var vb = vertices[ face[ 1 ] ];
  20404. var vc = vertices[ face[ 2 ] ];
  20405. var n = normal( va, vb, vc );
  20406. // distance from face to origin
  20407. var dist = n.dot( va );
  20408. return n.dot( vertex ) >= dist;
  20409. }
  20410. /**
  20411. * Face normal
  20412. */
  20413. function normal( va, vb, vc ) {
  20414. var cb = new THREE.Vector3();
  20415. var ab = new THREE.Vector3();
  20416. cb.subVectors( vc, vb );
  20417. ab.subVectors( va, vb );
  20418. cb.cross( ab );
  20419. cb.normalize();
  20420. return cb;
  20421. }
  20422. /**
  20423. * Detect whether two edges are equal.
  20424. * Note that when constructing the convex hull, two same edges can only
  20425. * be of the negative direction.
  20426. */
  20427. function equalEdge( ea, eb ) {
  20428. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20429. }
  20430. /**
  20431. * Create a random offset between -1e-6 and 1e-6.
  20432. */
  20433. function randomOffset() {
  20434. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20435. }
  20436. /**
  20437. * XXX: Not sure if this is the correct approach. Need someone to review.
  20438. */
  20439. function vertexUv( vertex ) {
  20440. var mag = vertex.length();
  20441. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20442. }
  20443. // Push vertices into `this.vertices`, skipping those inside the hull
  20444. var id = 0;
  20445. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20446. for ( var i = 0; i < faces.length; i++ ) {
  20447. var face = faces[ i ];
  20448. for ( var j = 0; j < 3; j++ ) {
  20449. if ( newId[ face[ j ] ] === undefined ) {
  20450. newId[ face[ j ] ] = id++;
  20451. this.vertices.push( vertices[ face[ j ] ] );
  20452. }
  20453. face[ j ] = newId[ face[ j ] ];
  20454. }
  20455. }
  20456. // Convert faces into instances of THREE.Face3
  20457. for ( var i = 0; i < faces.length; i++ ) {
  20458. this.faces.push( new THREE.Face3(
  20459. faces[ i ][ 0 ],
  20460. faces[ i ][ 1 ],
  20461. faces[ i ][ 2 ]
  20462. ) );
  20463. }
  20464. // Compute UVs
  20465. for ( var i = 0; i < this.faces.length; i++ ) {
  20466. var face = this.faces[ i ];
  20467. this.faceVertexUvs[ 0 ].push( [
  20468. vertexUv( this.vertices[ face.a ] ),
  20469. vertexUv( this.vertices[ face.b ] ),
  20470. vertexUv( this.vertices[ face.c ])
  20471. ] );
  20472. }
  20473. this.computeCentroids();
  20474. this.computeFaceNormals();
  20475. this.computeVertexNormals();
  20476. };
  20477. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20478. /**
  20479. * @author sroucheray / http://sroucheray.org/
  20480. * @author mrdoob / http://mrdoob.com/
  20481. */
  20482. THREE.AxisHelper = function ( size ) {
  20483. var geometry = new THREE.Geometry();
  20484. geometry.vertices.push(
  20485. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  20486. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  20487. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  20488. );
  20489. geometry.colors.push(
  20490. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20491. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20492. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20493. );
  20494. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20495. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20496. };
  20497. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20498. /**
  20499. * @author WestLangley / http://github.com/WestLangley
  20500. * @author zz85 / https://github.com/zz85
  20501. * @author bhouston / https://exocortex.com
  20502. *
  20503. * Creates an arrow for visualizing directions
  20504. *
  20505. * Parameters:
  20506. * dir - Vector3
  20507. * origin - Vector3
  20508. * length - Number
  20509. * hex - color in hex value
  20510. */
  20511. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20512. THREE.Object3D.call( this );
  20513. if ( length === undefined ) length = 20;
  20514. if ( hex === undefined ) hex = 0xffff00;
  20515. var lineGeometry = new THREE.Geometry();
  20516. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20517. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20518. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20519. this.add( this.line );
  20520. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20521. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20522. this.cone.position.set( 0, 1, 0 );
  20523. this.add( this.cone );
  20524. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  20525. this.setDirection( dir );
  20526. this.setLength( length );
  20527. };
  20528. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20529. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  20530. var d = THREE.ArrowHelper.__v1.copy( dir ).normalize();
  20531. if ( d.y > 0.999 ) {
  20532. this.rotation.set( 0, 0, 0 );
  20533. } else if ( d.y < - 0.999 ) {
  20534. this.rotation.set( Math.PI, 0, 0 );
  20535. } else {
  20536. var axis = THREE.ArrowHelper.__v2.set( d.z, 0, - d.x ).normalize();
  20537. var radians = Math.acos( d.y );
  20538. var quaternion = THREE.ArrowHelper.__q1.setFromAxisAngle( axis, radians );
  20539. this.rotation.setEulerFromQuaternion( quaternion, this.eulerOrder );
  20540. }
  20541. };
  20542. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20543. this.scale.set( length, length, length );
  20544. };
  20545. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20546. this.line.material.color.setHex( hex );
  20547. this.cone.material.color.setHex( hex );
  20548. };
  20549. THREE.ArrowHelper.__v1 = new THREE.Vector3();
  20550. THREE.ArrowHelper.__v2 = new THREE.Vector3();
  20551. THREE.ArrowHelper.__q1 = new THREE.Quaternion();
  20552. /**
  20553. * @author alteredq / http://alteredqualia.com/
  20554. *
  20555. * - shows frustum, line of sight and up of the camera
  20556. * - suitable for fast updates
  20557. * - based on frustum visualization in lightgl.js shadowmap example
  20558. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20559. */
  20560. THREE.CameraHelper = function ( camera ) {
  20561. THREE.Line.call( this );
  20562. var scope = this;
  20563. this.geometry = new THREE.Geometry();
  20564. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20565. this.type = THREE.LinePieces;
  20566. this.matrixWorld = camera.matrixWorld;
  20567. this.matrixAutoUpdate = false;
  20568. this.pointMap = {};
  20569. // colors
  20570. var hexFrustum = 0xffaa00;
  20571. var hexCone = 0xff0000;
  20572. var hexUp = 0x00aaff;
  20573. var hexTarget = 0xffffff;
  20574. var hexCross = 0x333333;
  20575. // near
  20576. addLine( "n1", "n2", hexFrustum );
  20577. addLine( "n2", "n4", hexFrustum );
  20578. addLine( "n4", "n3", hexFrustum );
  20579. addLine( "n3", "n1", hexFrustum );
  20580. // far
  20581. addLine( "f1", "f2", hexFrustum );
  20582. addLine( "f2", "f4", hexFrustum );
  20583. addLine( "f4", "f3", hexFrustum );
  20584. addLine( "f3", "f1", hexFrustum );
  20585. // sides
  20586. addLine( "n1", "f1", hexFrustum );
  20587. addLine( "n2", "f2", hexFrustum );
  20588. addLine( "n3", "f3", hexFrustum );
  20589. addLine( "n4", "f4", hexFrustum );
  20590. // cone
  20591. addLine( "p", "n1", hexCone );
  20592. addLine( "p", "n2", hexCone );
  20593. addLine( "p", "n3", hexCone );
  20594. addLine( "p", "n4", hexCone );
  20595. // up
  20596. addLine( "u1", "u2", hexUp );
  20597. addLine( "u2", "u3", hexUp );
  20598. addLine( "u3", "u1", hexUp );
  20599. // target
  20600. addLine( "c", "t", hexTarget );
  20601. addLine( "p", "c", hexCross );
  20602. // cross
  20603. addLine( "cn1", "cn2", hexCross );
  20604. addLine( "cn3", "cn4", hexCross );
  20605. addLine( "cf1", "cf2", hexCross );
  20606. addLine( "cf3", "cf4", hexCross );
  20607. this.camera = camera;
  20608. function addLine( a, b, hex ) {
  20609. addPoint( a, hex );
  20610. addPoint( b, hex );
  20611. }
  20612. function addPoint( id, hex ) {
  20613. scope.geometry.vertices.push( new THREE.Vector3() );
  20614. scope.geometry.colors.push( new THREE.Color( hex ) );
  20615. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  20616. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  20617. }
  20618. this.update( camera );
  20619. };
  20620. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20621. THREE.CameraHelper.prototype.update = function () {
  20622. var scope = this;
  20623. var w = 1, h = 1;
  20624. // we need just camera projection matrix
  20625. // world matrix must be identity
  20626. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  20627. // center / target
  20628. setPoint( "c", 0, 0, -1 );
  20629. setPoint( "t", 0, 0, 1 );
  20630. // near
  20631. setPoint( "n1", -w, -h, -1 );
  20632. setPoint( "n2", w, -h, -1 );
  20633. setPoint( "n3", -w, h, -1 );
  20634. setPoint( "n4", w, h, -1 );
  20635. // far
  20636. setPoint( "f1", -w, -h, 1 );
  20637. setPoint( "f2", w, -h, 1 );
  20638. setPoint( "f3", -w, h, 1 );
  20639. setPoint( "f4", w, h, 1 );
  20640. // up
  20641. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20642. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20643. setPoint( "u3", 0, h * 2, -1 );
  20644. // cross
  20645. setPoint( "cf1", -w, 0, 1 );
  20646. setPoint( "cf2", w, 0, 1 );
  20647. setPoint( "cf3", 0, -h, 1 );
  20648. setPoint( "cf4", 0, h, 1 );
  20649. setPoint( "cn1", -w, 0, -1 );
  20650. setPoint( "cn2", w, 0, -1 );
  20651. setPoint( "cn3", 0, -h, -1 );
  20652. setPoint( "cn4", 0, h, -1 );
  20653. function setPoint( point, x, y, z ) {
  20654. THREE.CameraHelper.__v.set( x, y, z );
  20655. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  20656. var points = scope.pointMap[ point ];
  20657. if ( points !== undefined ) {
  20658. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20659. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  20660. }
  20661. }
  20662. }
  20663. this.geometry.verticesNeedUpdate = true;
  20664. };
  20665. THREE.CameraHelper.__projector = new THREE.Projector();
  20666. THREE.CameraHelper.__v = new THREE.Vector3();
  20667. THREE.CameraHelper.__c = new THREE.Camera();
  20668. /**
  20669. * @author alteredq / http://alteredqualia.com/
  20670. *
  20671. * - shows directional light color, intensity, position, orientation and target
  20672. */
  20673. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20674. THREE.Object3D.call( this );
  20675. this.light = light;
  20676. // position
  20677. this.position = light.position;
  20678. // direction
  20679. this.direction = new THREE.Vector3();
  20680. this.direction.subVectors( light.target.position, light.position );
  20681. // color
  20682. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20683. this.color = light.color.clone();
  20684. this.color.multiplyScalar( intensity );
  20685. var hexColor = this.color.getHex();
  20686. // light helper
  20687. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20688. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20689. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20690. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20691. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20692. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20693. this.add( this.lightSphere );
  20694. this.add( this.lightRays );
  20695. this.lightSphere.properties.isGizmo = true;
  20696. this.lightSphere.properties.gizmoSubject = light;
  20697. this.lightSphere.properties.gizmoRoot = this;
  20698. // light target helper
  20699. this.targetSphere = null;
  20700. if ( light.target.properties.targetInverse ) {
  20701. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20702. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20703. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20704. this.targetSphere.position = light.target.position;
  20705. this.targetSphere.properties.isGizmo = true;
  20706. this.targetSphere.properties.gizmoSubject = light.target;
  20707. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20708. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20709. var lineGeometry = new THREE.Geometry();
  20710. lineGeometry.vertices.push( this.position.clone() );
  20711. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20712. lineGeometry.computeLineDistances();
  20713. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20714. this.targetLine.properties.isGizmo = true;
  20715. }
  20716. //
  20717. this.properties.isGizmo = true;
  20718. }
  20719. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20720. THREE.DirectionalLightHelper.prototype.update = function () {
  20721. // update arrow orientation
  20722. // pointing from light to target
  20723. this.direction.subVectors( this.light.target.position, this.light.position );
  20724. // update arrow, spheres, rays and line colors to light color * light intensity
  20725. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20726. this.color.copy( this.light.color );
  20727. this.color.multiplyScalar( intensity );
  20728. this.lightSphere.material.color.copy( this.color );
  20729. this.lightRays.material.color.copy( this.color );
  20730. this.targetSphere.material.color.copy( this.color );
  20731. this.targetLine.material.color.copy( this.color );
  20732. // update target line vertices
  20733. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20734. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20735. this.targetLine.geometry.computeLineDistances();
  20736. this.targetLine.geometry.verticesNeedUpdate = true;
  20737. }
  20738. /**
  20739. * @author alteredq / http://alteredqualia.com/
  20740. *
  20741. * - shows hemisphere light intensity, sky and ground colors and directions
  20742. */
  20743. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20744. THREE.Object3D.call( this );
  20745. this.light = light;
  20746. // position
  20747. this.position = light.position;
  20748. //
  20749. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20750. // sky color
  20751. this.color = light.color.clone();
  20752. this.color.multiplyScalar( intensity );
  20753. var hexColor = this.color.getHex();
  20754. // ground color
  20755. this.groundColor = light.groundColor.clone();
  20756. this.groundColor.multiplyScalar( intensity );
  20757. var hexColorGround = this.groundColor.getHex();
  20758. // double colored light bulb
  20759. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20760. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20761. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20762. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20763. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20764. bulbGeometry.faces[ i ].materialIndex = 0;
  20765. }
  20766. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20767. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20768. }
  20769. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20770. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20771. // arrows for sky and ground light directions
  20772. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20773. this.lightArrow.rotation.x = Math.PI;
  20774. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20775. var joint = new THREE.Object3D();
  20776. joint.rotation.x = -Math.PI * 0.5;
  20777. joint.add( this.lightSphere );
  20778. joint.add( this.lightArrow );
  20779. joint.add( this.lightArrowGround );
  20780. this.add( joint );
  20781. //
  20782. this.lightSphere.properties.isGizmo = true;
  20783. this.lightSphere.properties.gizmoSubject = light;
  20784. this.lightSphere.properties.gizmoRoot = this;
  20785. //
  20786. this.properties.isGizmo = true;
  20787. //
  20788. this.target = new THREE.Vector3();
  20789. this.lookAt( this.target );
  20790. }
  20791. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20792. THREE.HemisphereLightHelper.prototype.update = function () {
  20793. // update sphere sky and ground colors to light color * light intensity
  20794. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20795. this.color.copy( this.light.color );
  20796. this.color.multiplyScalar( intensity );
  20797. this.groundColor.copy( this.light.groundColor );
  20798. this.groundColor.multiplyScalar( intensity );
  20799. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20800. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20801. this.lightArrow.setColor( this.color.getHex() );
  20802. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20803. this.lookAt( this.target );
  20804. }
  20805. /**
  20806. * @author alteredq / http://alteredqualia.com/
  20807. *
  20808. * - shows point light color, intensity, position and distance
  20809. */
  20810. THREE.PointLightHelper = function ( light, sphereSize ) {
  20811. THREE.Object3D.call( this );
  20812. this.light = light;
  20813. // position
  20814. this.position = light.position;
  20815. // color
  20816. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20817. this.color = light.color.clone();
  20818. this.color.multiplyScalar( intensity );
  20819. var hexColor = this.color.getHex();
  20820. // light helper
  20821. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20822. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20823. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20824. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20825. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20826. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20827. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20828. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20829. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20830. var d = light.distance;
  20831. if ( d === 0.0 ) {
  20832. this.lightDistance.visible = false;
  20833. } else {
  20834. this.lightDistance.scale.set( d, d, d );
  20835. }
  20836. this.add( this.lightSphere );
  20837. this.add( this.lightRays );
  20838. this.add( this.lightDistance );
  20839. //
  20840. this.lightSphere.properties.isGizmo = true;
  20841. this.lightSphere.properties.gizmoSubject = light;
  20842. this.lightSphere.properties.gizmoRoot = this;
  20843. //
  20844. this.properties.isGizmo = true;
  20845. }
  20846. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20847. THREE.PointLightHelper.prototype.update = function () {
  20848. // update sphere and rays colors to light color * light intensity
  20849. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20850. this.color.copy( this.light.color );
  20851. this.color.multiplyScalar( intensity );
  20852. this.lightSphere.material.color.copy( this.color );
  20853. this.lightRays.material.color.copy( this.color );
  20854. this.lightDistance.material.color.copy( this.color );
  20855. //
  20856. var d = this.light.distance;
  20857. if ( d === 0.0 ) {
  20858. this.lightDistance.visible = false;
  20859. } else {
  20860. this.lightDistance.visible = true;
  20861. this.lightDistance.scale.set( d, d, d );
  20862. }
  20863. }
  20864. /**
  20865. * @author alteredq / http://alteredqualia.com/
  20866. *
  20867. * - shows spot light color, intensity, position, orientation, light cone and target
  20868. */
  20869. THREE.SpotLightHelper = function ( light, sphereSize ) {
  20870. THREE.Object3D.call( this );
  20871. this.light = light;
  20872. // position
  20873. this.position = light.position;
  20874. // direction
  20875. this.direction = new THREE.Vector3();
  20876. this.direction.subVectors( light.target.position, light.position );
  20877. // color
  20878. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20879. this.color = light.color.clone();
  20880. this.color.multiplyScalar( intensity );
  20881. var hexColor = this.color.getHex();
  20882. // light helper
  20883. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20884. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20885. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20886. var coneMatrix = new THREE.Matrix4();
  20887. coneMatrix.rotateX( -Math.PI/2 );
  20888. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20889. coneGeometry.applyMatrix( coneMatrix );
  20890. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20891. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20892. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20893. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20894. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20895. var coneLength = light.distance ? light.distance : 10000;
  20896. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20897. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20898. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20899. this.gyroscope = new THREE.Gyroscope();
  20900. this.gyroscope.add( this.lightSphere );
  20901. this.gyroscope.add( this.lightRays );
  20902. this.add( this.gyroscope );
  20903. this.add( this.lightCone );
  20904. this.lookAt( light.target.position );
  20905. this.lightSphere.properties.isGizmo = true;
  20906. this.lightSphere.properties.gizmoSubject = light;
  20907. this.lightSphere.properties.gizmoRoot = this;
  20908. // light target helper
  20909. this.targetSphere = null;
  20910. if ( light.target.properties.targetInverse ) {
  20911. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20912. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20913. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20914. this.targetSphere.position = light.target.position;
  20915. this.targetSphere.properties.isGizmo = true;
  20916. this.targetSphere.properties.gizmoSubject = light.target;
  20917. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20918. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20919. var lineGeometry = new THREE.Geometry();
  20920. lineGeometry.vertices.push( this.position.clone() );
  20921. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20922. lineGeometry.computeLineDistances();
  20923. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20924. this.targetLine.properties.isGizmo = true;
  20925. }
  20926. //
  20927. this.properties.isGizmo = true;
  20928. }
  20929. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20930. THREE.SpotLightHelper.prototype.update = function () {
  20931. // update arrow orientation
  20932. // pointing from light to target
  20933. this.direction.subVectors( this.light.target.position, this.light.position );
  20934. // update light cone orientation and size
  20935. this.lookAt( this.light.target.position );
  20936. var coneLength = this.light.distance ? this.light.distance : 10000;
  20937. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20938. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20939. // update arrow, spheres, rays and line colors to light color * light intensity
  20940. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20941. this.color.copy( this.light.color );
  20942. this.color.multiplyScalar( intensity );
  20943. this.lightSphere.material.color.copy( this.color );
  20944. this.lightRays.material.color.copy( this.color );
  20945. this.lightCone.material.color.copy( this.color );
  20946. this.targetSphere.material.color.copy( this.color );
  20947. this.targetLine.material.color.copy( this.color );
  20948. // update target line vertices
  20949. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20950. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20951. this.targetLine.geometry.computeLineDistances();
  20952. this.targetLine.geometry.verticesNeedUpdate = true;
  20953. };
  20954. /**
  20955. * @author alteredq / http://alteredqualia.com/
  20956. */
  20957. THREE.ImmediateRenderObject = function ( ) {
  20958. THREE.Object3D.call( this );
  20959. this.render = function ( renderCallback ) { };
  20960. };
  20961. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20962. /**
  20963. * @author mikael emtinger / http://gomo.se/
  20964. * @author alteredq / http://alteredqualia.com/
  20965. */
  20966. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20967. THREE.Object3D.call( this );
  20968. this.lensFlares = [];
  20969. this.positionScreen = new THREE.Vector3();
  20970. this.customUpdateCallback = undefined;
  20971. if( texture !== undefined ) {
  20972. this.add( texture, size, distance, blending, color );
  20973. }
  20974. };
  20975. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20976. /*
  20977. * Add: adds another flare
  20978. */
  20979. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20980. if( size === undefined ) size = -1;
  20981. if( distance === undefined ) distance = 0;
  20982. if( opacity === undefined ) opacity = 1;
  20983. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20984. if( blending === undefined ) blending = THREE.NormalBlending;
  20985. distance = Math.min( distance, Math.max( 0, distance ) );
  20986. this.lensFlares.push( { texture: texture, // THREE.Texture
  20987. size: size, // size in pixels (-1 = use texture.width)
  20988. distance: distance, // distance (0-1) from light source (0=at light source)
  20989. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20990. scale: 1, // scale
  20991. rotation: 1, // rotation
  20992. opacity: opacity, // opacity
  20993. color: color, // color
  20994. blending: blending } ); // blending
  20995. };
  20996. /*
  20997. * Update lens flares update positions on all flares based on the screen position
  20998. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20999. */
  21000. THREE.LensFlare.prototype.updateLensFlares = function () {
  21001. var f, fl = this.lensFlares.length;
  21002. var flare;
  21003. var vecX = -this.positionScreen.x * 2;
  21004. var vecY = -this.positionScreen.y * 2;
  21005. for( f = 0; f < fl; f ++ ) {
  21006. flare = this.lensFlares[ f ];
  21007. flare.x = this.positionScreen.x + vecX * flare.distance;
  21008. flare.y = this.positionScreen.y + vecY * flare.distance;
  21009. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21010. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21011. }
  21012. };
  21013. /**
  21014. * @author alteredq / http://alteredqualia.com/
  21015. */
  21016. THREE.MorphBlendMesh = function( geometry, material ) {
  21017. THREE.Mesh.call( this, geometry, material );
  21018. this.animationsMap = {};
  21019. this.animationsList = [];
  21020. // prepare default animation
  21021. // (all frames played together in 1 second)
  21022. var numFrames = this.geometry.morphTargets.length;
  21023. var name = "__default";
  21024. var startFrame = 0;
  21025. var endFrame = numFrames - 1;
  21026. var fps = numFrames / 1;
  21027. this.createAnimation( name, startFrame, endFrame, fps );
  21028. this.setAnimationWeight( name, 1 );
  21029. };
  21030. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21031. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21032. var animation = {
  21033. startFrame: start,
  21034. endFrame: end,
  21035. length: end - start + 1,
  21036. fps: fps,
  21037. duration: ( end - start ) / fps,
  21038. lastFrame: 0,
  21039. currentFrame: 0,
  21040. active: false,
  21041. time: 0,
  21042. direction: 1,
  21043. weight: 1,
  21044. directionBackwards: false,
  21045. mirroredLoop: false
  21046. };
  21047. this.animationsMap[ name ] = animation;
  21048. this.animationsList.push( animation );
  21049. };
  21050. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21051. var pattern = /([a-z]+)(\d+)/;
  21052. var firstAnimation, frameRanges = {};
  21053. var geometry = this.geometry;
  21054. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21055. var morph = geometry.morphTargets[ i ];
  21056. var chunks = morph.name.match( pattern );
  21057. if ( chunks && chunks.length > 1 ) {
  21058. var name = chunks[ 1 ];
  21059. var num = chunks[ 2 ];
  21060. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21061. var range = frameRanges[ name ];
  21062. if ( i < range.start ) range.start = i;
  21063. if ( i > range.end ) range.end = i;
  21064. if ( ! firstAnimation ) firstAnimation = name;
  21065. }
  21066. }
  21067. for ( var name in frameRanges ) {
  21068. var range = frameRanges[ name ];
  21069. this.createAnimation( name, range.start, range.end, fps );
  21070. }
  21071. this.firstAnimation = firstAnimation;
  21072. };
  21073. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21074. var animation = this.animationsMap[ name ];
  21075. if ( animation ) {
  21076. animation.direction = 1;
  21077. animation.directionBackwards = false;
  21078. }
  21079. };
  21080. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21081. var animation = this.animationsMap[ name ];
  21082. if ( animation ) {
  21083. animation.direction = -1;
  21084. animation.directionBackwards = true;
  21085. }
  21086. };
  21087. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21088. var animation = this.animationsMap[ name ];
  21089. if ( animation ) {
  21090. animation.fps = fps;
  21091. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21092. }
  21093. };
  21094. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21095. var animation = this.animationsMap[ name ];
  21096. if ( animation ) {
  21097. animation.duration = duration;
  21098. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21099. }
  21100. };
  21101. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21102. var animation = this.animationsMap[ name ];
  21103. if ( animation ) {
  21104. animation.weight = weight;
  21105. }
  21106. };
  21107. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21108. var animation = this.animationsMap[ name ];
  21109. if ( animation ) {
  21110. animation.time = time;
  21111. }
  21112. };
  21113. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21114. var time = 0;
  21115. var animation = this.animationsMap[ name ];
  21116. if ( animation ) {
  21117. time = animation.time;
  21118. }
  21119. return time;
  21120. };
  21121. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21122. var duration = -1;
  21123. var animation = this.animationsMap[ name ];
  21124. if ( animation ) {
  21125. duration = animation.duration;
  21126. }
  21127. return duration;
  21128. };
  21129. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21130. var animation = this.animationsMap[ name ];
  21131. if ( animation ) {
  21132. animation.time = 0;
  21133. animation.active = true;
  21134. } else {
  21135. console.warn( "animation[" + name + "] undefined" );
  21136. }
  21137. };
  21138. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21139. var animation = this.animationsMap[ name ];
  21140. if ( animation ) {
  21141. animation.active = false;
  21142. }
  21143. };
  21144. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21145. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21146. var animation = this.animationsList[ i ];
  21147. if ( ! animation.active ) continue;
  21148. var frameTime = animation.duration / animation.length;
  21149. animation.time += animation.direction * delta;
  21150. if ( animation.mirroredLoop ) {
  21151. if ( animation.time > animation.duration || animation.time < 0 ) {
  21152. animation.direction *= -1;
  21153. if ( animation.time > animation.duration ) {
  21154. animation.time = animation.duration;
  21155. animation.directionBackwards = true;
  21156. }
  21157. if ( animation.time < 0 ) {
  21158. animation.time = 0;
  21159. animation.directionBackwards = false;
  21160. }
  21161. }
  21162. } else {
  21163. animation.time = animation.time % animation.duration;
  21164. if ( animation.time < 0 ) animation.time += animation.duration;
  21165. }
  21166. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21167. var weight = animation.weight;
  21168. if ( keyframe !== animation.currentFrame ) {
  21169. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21170. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21171. this.morphTargetInfluences[ keyframe ] = 0;
  21172. animation.lastFrame = animation.currentFrame;
  21173. animation.currentFrame = keyframe;
  21174. }
  21175. var mix = ( animation.time % frameTime ) / frameTime;
  21176. if ( animation.directionBackwards ) mix = 1 - mix;
  21177. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21178. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21179. }
  21180. };
  21181. /**
  21182. * @author mikael emtinger / http://gomo.se/
  21183. * @author alteredq / http://alteredqualia.com/
  21184. */
  21185. THREE.LensFlarePlugin = function ( ) {
  21186. var _gl, _renderer, _precision, _lensFlare = {};
  21187. this.init = function ( renderer ) {
  21188. _gl = renderer.context;
  21189. _renderer = renderer;
  21190. _precision = renderer.getPrecision();
  21191. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21192. _lensFlare.faces = new Uint16Array( 6 );
  21193. var i = 0;
  21194. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21195. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21196. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21197. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21198. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21199. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21200. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21201. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21202. i = 0;
  21203. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21204. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21205. // buffers
  21206. _lensFlare.vertexBuffer = _gl.createBuffer();
  21207. _lensFlare.elementBuffer = _gl.createBuffer();
  21208. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21209. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21210. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21211. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21212. // textures
  21213. _lensFlare.tempTexture = _gl.createTexture();
  21214. _lensFlare.occlusionTexture = _gl.createTexture();
  21215. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21216. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21217. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21218. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21219. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21220. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21221. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21222. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21223. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21224. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21225. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21226. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21227. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21228. _lensFlare.hasVertexTexture = false;
  21229. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21230. } else {
  21231. _lensFlare.hasVertexTexture = true;
  21232. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21233. }
  21234. _lensFlare.attributes = {};
  21235. _lensFlare.uniforms = {};
  21236. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21237. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21238. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21239. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21240. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21241. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21242. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21243. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21244. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21245. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21246. };
  21247. /*
  21248. * Render lens flares
  21249. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21250. * reads these back and calculates occlusion.
  21251. * Then _lensFlare.update_lensFlares() is called to re-position and
  21252. * update transparency of flares. Then they are rendered.
  21253. *
  21254. */
  21255. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21256. var flares = scene.__webglFlares,
  21257. nFlares = flares.length;
  21258. if ( ! nFlares ) return;
  21259. var tempPosition = new THREE.Vector3();
  21260. var invAspect = viewportHeight / viewportWidth,
  21261. halfViewportWidth = viewportWidth * 0.5,
  21262. halfViewportHeight = viewportHeight * 0.5;
  21263. var size = 16 / viewportHeight,
  21264. scale = new THREE.Vector2( size * invAspect, size );
  21265. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21266. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21267. var uniforms = _lensFlare.uniforms,
  21268. attributes = _lensFlare.attributes;
  21269. // set _lensFlare program and reset blending
  21270. _gl.useProgram( _lensFlare.program );
  21271. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21272. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21273. // loop through all lens flares to update their occlusion and positions
  21274. // setup gl and common used attribs/unforms
  21275. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21276. _gl.uniform1i( uniforms.map, 1 );
  21277. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21278. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21279. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21280. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21281. _gl.disable( _gl.CULL_FACE );
  21282. _gl.depthMask( false );
  21283. var i, j, jl, flare, sprite;
  21284. for ( i = 0; i < nFlares; i ++ ) {
  21285. size = 16 / viewportHeight;
  21286. scale.set( size * invAspect, size );
  21287. // calc object screen position
  21288. flare = flares[ i ];
  21289. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21290. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21291. tempPosition.applyMatrix4( camera.projectionMatrix );
  21292. // setup arrays for gl programs
  21293. screenPosition.copy( tempPosition )
  21294. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21295. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21296. // screen cull
  21297. if ( _lensFlare.hasVertexTexture || (
  21298. screenPositionPixels.x > 0 &&
  21299. screenPositionPixels.x < viewportWidth &&
  21300. screenPositionPixels.y > 0 &&
  21301. screenPositionPixels.y < viewportHeight ) ) {
  21302. // save current RGB to temp texture
  21303. _gl.activeTexture( _gl.TEXTURE1 );
  21304. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21305. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21306. // render pink quad
  21307. _gl.uniform1i( uniforms.renderType, 0 );
  21308. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21309. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21310. _gl.disable( _gl.BLEND );
  21311. _gl.enable( _gl.DEPTH_TEST );
  21312. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21313. // copy result to occlusionMap
  21314. _gl.activeTexture( _gl.TEXTURE0 );
  21315. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21316. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21317. // restore graphics
  21318. _gl.uniform1i( uniforms.renderType, 1 );
  21319. _gl.disable( _gl.DEPTH_TEST );
  21320. _gl.activeTexture( _gl.TEXTURE1 );
  21321. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21322. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21323. // update object positions
  21324. flare.positionScreen.copy( screenPosition )
  21325. if ( flare.customUpdateCallback ) {
  21326. flare.customUpdateCallback( flare );
  21327. } else {
  21328. flare.updateLensFlares();
  21329. }
  21330. // render flares
  21331. _gl.uniform1i( uniforms.renderType, 2 );
  21332. _gl.enable( _gl.BLEND );
  21333. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21334. sprite = flare.lensFlares[ j ];
  21335. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21336. screenPosition.x = sprite.x;
  21337. screenPosition.y = sprite.y;
  21338. screenPosition.z = sprite.z;
  21339. size = sprite.size * sprite.scale / viewportHeight;
  21340. scale.x = size * invAspect;
  21341. scale.y = size;
  21342. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21343. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21344. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21345. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21346. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21347. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21348. _renderer.setTexture( sprite.texture, 1 );
  21349. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21350. }
  21351. }
  21352. }
  21353. }
  21354. // restore gl
  21355. _gl.enable( _gl.CULL_FACE );
  21356. _gl.enable( _gl.DEPTH_TEST );
  21357. _gl.depthMask( true );
  21358. };
  21359. function createProgram ( shader, precision ) {
  21360. var program = _gl.createProgram();
  21361. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21362. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21363. var prefix = "precision " + precision + " float;\n";
  21364. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21365. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21366. _gl.compileShader( fragmentShader );
  21367. _gl.compileShader( vertexShader );
  21368. _gl.attachShader( program, fragmentShader );
  21369. _gl.attachShader( program, vertexShader );
  21370. _gl.linkProgram( program );
  21371. return program;
  21372. };
  21373. };
  21374. /**
  21375. * @author alteredq / http://alteredqualia.com/
  21376. */
  21377. THREE.ShadowMapPlugin = function ( ) {
  21378. var _gl,
  21379. _renderer,
  21380. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21381. _frustum = new THREE.Frustum(),
  21382. _projScreenMatrix = new THREE.Matrix4(),
  21383. _min = new THREE.Vector3(),
  21384. _max = new THREE.Vector3();
  21385. this.init = function ( renderer ) {
  21386. _gl = renderer.context;
  21387. _renderer = renderer;
  21388. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21389. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21390. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21391. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21392. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21393. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21394. _depthMaterial._shadowPass = true;
  21395. _depthMaterialMorph._shadowPass = true;
  21396. _depthMaterialSkin._shadowPass = true;
  21397. _depthMaterialMorphSkin._shadowPass = true;
  21398. };
  21399. this.render = function ( scene, camera ) {
  21400. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21401. this.update( scene, camera );
  21402. };
  21403. this.update = function ( scene, camera ) {
  21404. var i, il, j, jl, n,
  21405. shadowMap, shadowMatrix, shadowCamera,
  21406. program, buffer, material,
  21407. webglObject, object, light,
  21408. renderList,
  21409. lights = [],
  21410. k = 0,
  21411. fog = null;
  21412. // set GL state for depth map
  21413. _gl.clearColor( 1, 1, 1, 1 );
  21414. _gl.disable( _gl.BLEND );
  21415. _gl.enable( _gl.CULL_FACE );
  21416. _gl.frontFace( _gl.CCW );
  21417. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21418. _gl.cullFace( _gl.FRONT );
  21419. } else {
  21420. _gl.cullFace( _gl.BACK );
  21421. }
  21422. _renderer.setDepthTest( true );
  21423. // preprocess lights
  21424. // - skip lights that are not casting shadows
  21425. // - create virtual lights for cascaded shadow maps
  21426. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21427. light = scene.__lights[ i ];
  21428. if ( ! light.castShadow ) continue;
  21429. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21430. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21431. var virtualLight;
  21432. if ( ! light.shadowCascadeArray[ n ] ) {
  21433. virtualLight = createVirtualLight( light, n );
  21434. virtualLight.originalCamera = camera;
  21435. var gyro = new THREE.Gyroscope();
  21436. gyro.position = light.shadowCascadeOffset;
  21437. gyro.add( virtualLight );
  21438. gyro.add( virtualLight.target );
  21439. camera.add( gyro );
  21440. light.shadowCascadeArray[ n ] = virtualLight;
  21441. console.log( "Created virtualLight", virtualLight );
  21442. } else {
  21443. virtualLight = light.shadowCascadeArray[ n ];
  21444. }
  21445. updateVirtualLight( light, n );
  21446. lights[ k ] = virtualLight;
  21447. k ++;
  21448. }
  21449. } else {
  21450. lights[ k ] = light;
  21451. k ++;
  21452. }
  21453. }
  21454. // render depth map
  21455. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21456. light = lights[ i ];
  21457. if ( ! light.shadowMap ) {
  21458. var shadowFilter = THREE.LinearFilter;
  21459. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21460. shadowFilter = THREE.NearestFilter;
  21461. }
  21462. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21463. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21464. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21465. light.shadowMatrix = new THREE.Matrix4();
  21466. }
  21467. if ( ! light.shadowCamera ) {
  21468. if ( light instanceof THREE.SpotLight ) {
  21469. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21470. } else if ( light instanceof THREE.DirectionalLight ) {
  21471. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21472. } else {
  21473. console.error( "Unsupported light type for shadow" );
  21474. continue;
  21475. }
  21476. scene.add( light.shadowCamera );
  21477. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21478. }
  21479. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21480. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21481. light.shadowCamera.add( light.cameraHelper );
  21482. }
  21483. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21484. updateShadowCamera( camera, light );
  21485. }
  21486. shadowMap = light.shadowMap;
  21487. shadowMatrix = light.shadowMatrix;
  21488. shadowCamera = light.shadowCamera;
  21489. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  21490. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  21491. shadowCamera.updateMatrixWorld();
  21492. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21493. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21494. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21495. // compute shadow matrix
  21496. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21497. 0.0, 0.5, 0.0, 0.5,
  21498. 0.0, 0.0, 0.5, 0.5,
  21499. 0.0, 0.0, 0.0, 1.0 );
  21500. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21501. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21502. // update camera matrices and frustum
  21503. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21504. _frustum.setFromMatrix( _projScreenMatrix );
  21505. // render shadow map
  21506. _renderer.setRenderTarget( shadowMap );
  21507. _renderer.clear();
  21508. // set object matrices & frustum culling
  21509. renderList = scene.__webglObjects;
  21510. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21511. webglObject = renderList[ j ];
  21512. object = webglObject.object;
  21513. webglObject.render = false;
  21514. if ( object.visible && object.castShadow ) {
  21515. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21516. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21517. webglObject.render = true;
  21518. }
  21519. }
  21520. }
  21521. // render regular objects
  21522. var objectMaterial, useMorphing, useSkinning;
  21523. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21524. webglObject = renderList[ j ];
  21525. if ( webglObject.render ) {
  21526. object = webglObject.object;
  21527. buffer = webglObject.buffer;
  21528. // culling is overriden globally for all objects
  21529. // while rendering depth map
  21530. // need to deal with MeshFaceMaterial somehow
  21531. // in that case just use the first of material.materials for now
  21532. // (proper solution would require to break objects by materials
  21533. // similarly to regular rendering and then set corresponding
  21534. // depth materials per each chunk instead of just once per object)
  21535. objectMaterial = getObjectMaterial( object );
  21536. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21537. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21538. if ( object.customDepthMaterial ) {
  21539. material = object.customDepthMaterial;
  21540. } else if ( useSkinning ) {
  21541. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21542. } else if ( useMorphing ) {
  21543. material = _depthMaterialMorph;
  21544. } else {
  21545. material = _depthMaterial;
  21546. }
  21547. if ( buffer instanceof THREE.BufferGeometry ) {
  21548. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21549. } else {
  21550. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21551. }
  21552. }
  21553. }
  21554. // set matrices and render immediate objects
  21555. renderList = scene.__webglObjectsImmediate;
  21556. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21557. webglObject = renderList[ j ];
  21558. object = webglObject.object;
  21559. if ( object.visible && object.castShadow ) {
  21560. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21561. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21562. }
  21563. }
  21564. }
  21565. // restore GL state
  21566. var clearColor = _renderer.getClearColor(),
  21567. clearAlpha = _renderer.getClearAlpha();
  21568. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21569. _gl.enable( _gl.BLEND );
  21570. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21571. _gl.cullFace( _gl.BACK );
  21572. }
  21573. };
  21574. function createVirtualLight( light, cascade ) {
  21575. var virtualLight = new THREE.DirectionalLight();
  21576. virtualLight.isVirtual = true;
  21577. virtualLight.onlyShadow = true;
  21578. virtualLight.castShadow = true;
  21579. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21580. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21581. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21582. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21583. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21584. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21585. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21586. virtualLight.shadowDarkness = light.shadowDarkness;
  21587. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21588. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21589. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21590. virtualLight.pointsWorld = [];
  21591. virtualLight.pointsFrustum = [];
  21592. var pointsWorld = virtualLight.pointsWorld,
  21593. pointsFrustum = virtualLight.pointsFrustum;
  21594. for ( var i = 0; i < 8; i ++ ) {
  21595. pointsWorld[ i ] = new THREE.Vector3();
  21596. pointsFrustum[ i ] = new THREE.Vector3();
  21597. }
  21598. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21599. var farZ = light.shadowCascadeFarZ[ cascade ];
  21600. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21601. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21602. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21603. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21604. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21605. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21606. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21607. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21608. return virtualLight;
  21609. }
  21610. // Synchronize virtual light with the original light
  21611. function updateVirtualLight( light, cascade ) {
  21612. var virtualLight = light.shadowCascadeArray[ cascade ];
  21613. virtualLight.position.copy( light.position );
  21614. virtualLight.target.position.copy( light.target.position );
  21615. virtualLight.lookAt( virtualLight.target );
  21616. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21617. virtualLight.shadowDarkness = light.shadowDarkness;
  21618. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21619. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21620. var farZ = light.shadowCascadeFarZ[ cascade ];
  21621. var pointsFrustum = virtualLight.pointsFrustum;
  21622. pointsFrustum[ 0 ].z = nearZ;
  21623. pointsFrustum[ 1 ].z = nearZ;
  21624. pointsFrustum[ 2 ].z = nearZ;
  21625. pointsFrustum[ 3 ].z = nearZ;
  21626. pointsFrustum[ 4 ].z = farZ;
  21627. pointsFrustum[ 5 ].z = farZ;
  21628. pointsFrustum[ 6 ].z = farZ;
  21629. pointsFrustum[ 7 ].z = farZ;
  21630. }
  21631. // Fit shadow camera's ortho frustum to camera frustum
  21632. function updateShadowCamera( camera, light ) {
  21633. var shadowCamera = light.shadowCamera,
  21634. pointsFrustum = light.pointsFrustum,
  21635. pointsWorld = light.pointsWorld;
  21636. _min.set( Infinity, Infinity, Infinity );
  21637. _max.set( -Infinity, -Infinity, -Infinity );
  21638. for ( var i = 0; i < 8; i ++ ) {
  21639. var p = pointsWorld[ i ];
  21640. p.copy( pointsFrustum[ i ] );
  21641. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21642. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21643. if ( p.x < _min.x ) _min.x = p.x;
  21644. if ( p.x > _max.x ) _max.x = p.x;
  21645. if ( p.y < _min.y ) _min.y = p.y;
  21646. if ( p.y > _max.y ) _max.y = p.y;
  21647. if ( p.z < _min.z ) _min.z = p.z;
  21648. if ( p.z > _max.z ) _max.z = p.z;
  21649. }
  21650. shadowCamera.left = _min.x;
  21651. shadowCamera.right = _max.x;
  21652. shadowCamera.top = _max.y;
  21653. shadowCamera.bottom = _min.y;
  21654. // can't really fit near/far
  21655. //shadowCamera.near = _min.z;
  21656. //shadowCamera.far = _max.z;
  21657. shadowCamera.updateProjectionMatrix();
  21658. }
  21659. // For the moment just ignore objects that have multiple materials with different animation methods
  21660. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21661. function getObjectMaterial( object ) {
  21662. return object.material instanceof THREE.MeshFaceMaterial
  21663. ? object.material.materials[ 0 ]
  21664. : object.material;
  21665. };
  21666. };
  21667. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21668. /**
  21669. * @author mikael emtinger / http://gomo.se/
  21670. * @author alteredq / http://alteredqualia.com/
  21671. */
  21672. THREE.SpritePlugin = function ( ) {
  21673. var _gl, _renderer, _precision, _sprite = {};
  21674. this.init = function ( renderer ) {
  21675. _gl = renderer.context;
  21676. _renderer = renderer;
  21677. _precision = renderer.getPrecision();
  21678. _sprite.vertices = new Float32Array( 8 + 8 );
  21679. _sprite.faces = new Uint16Array( 6 );
  21680. var i = 0;
  21681. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21682. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21683. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21684. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21685. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21686. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21687. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21688. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21689. i = 0;
  21690. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21691. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21692. _sprite.vertexBuffer = _gl.createBuffer();
  21693. _sprite.elementBuffer = _gl.createBuffer();
  21694. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21695. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21696. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21697. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21698. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21699. _sprite.attributes = {};
  21700. _sprite.uniforms = {};
  21701. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21702. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21703. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21704. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21705. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21706. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21707. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21708. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21709. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21710. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21711. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21712. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21713. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21714. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21715. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21716. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21717. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21718. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21719. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21720. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21721. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21722. };
  21723. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21724. var sprites = scene.__webglSprites,
  21725. nSprites = sprites.length;
  21726. if ( ! nSprites ) return;
  21727. var attributes = _sprite.attributes,
  21728. uniforms = _sprite.uniforms;
  21729. var invAspect = viewportHeight / viewportWidth;
  21730. var halfViewportWidth = viewportWidth * 0.5,
  21731. halfViewportHeight = viewportHeight * 0.5;
  21732. // setup gl
  21733. _gl.useProgram( _sprite.program );
  21734. _gl.enableVertexAttribArray( attributes.position );
  21735. _gl.enableVertexAttribArray( attributes.uv );
  21736. _gl.disable( _gl.CULL_FACE );
  21737. _gl.enable( _gl.BLEND );
  21738. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21739. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21740. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21741. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21742. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21743. _gl.activeTexture( _gl.TEXTURE0 );
  21744. _gl.uniform1i( uniforms.map, 0 );
  21745. var oldFogType = 0;
  21746. var sceneFogType = 0;
  21747. var fog = scene.fog;
  21748. if ( fog ) {
  21749. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21750. if ( fog instanceof THREE.Fog ) {
  21751. _gl.uniform1f( uniforms.fogNear, fog.near );
  21752. _gl.uniform1f( uniforms.fogFar, fog.far );
  21753. _gl.uniform1i( uniforms.fogType, 1 );
  21754. oldFogType = 1;
  21755. sceneFogType = 1;
  21756. } else if ( fog instanceof THREE.FogExp2 ) {
  21757. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21758. _gl.uniform1i( uniforms.fogType, 2 );
  21759. oldFogType = 2;
  21760. sceneFogType = 2;
  21761. }
  21762. } else {
  21763. _gl.uniform1i( uniforms.fogType, 0 );
  21764. oldFogType = 0;
  21765. sceneFogType = 0;
  21766. }
  21767. // update positions and sort
  21768. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21769. for( i = 0; i < nSprites; i ++ ) {
  21770. sprite = sprites[ i ];
  21771. material = sprite.material;
  21772. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21773. if ( ! material.useScreenCoordinates ) {
  21774. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21775. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21776. } else {
  21777. sprite.z = - sprite.position.z;
  21778. }
  21779. }
  21780. sprites.sort( painterSortStable );
  21781. // render all sprites
  21782. for( i = 0; i < nSprites; i ++ ) {
  21783. sprite = sprites[ i ];
  21784. material = sprite.material;
  21785. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21786. if ( material.map && material.map.image && material.map.image.width ) {
  21787. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21788. if ( material.useScreenCoordinates === true ) {
  21789. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21790. _gl.uniform3f(
  21791. uniforms.screenPosition,
  21792. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21793. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21794. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21795. );
  21796. scale[ 0 ] = _renderer.devicePixelRatio;
  21797. scale[ 1 ] = _renderer.devicePixelRatio;
  21798. } else {
  21799. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21800. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21801. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21802. scale[ 0 ] = 1;
  21803. scale[ 1 ] = 1;
  21804. }
  21805. if ( scene.fog && material.fog ) {
  21806. fogType = sceneFogType;
  21807. } else {
  21808. fogType = 0;
  21809. }
  21810. if ( oldFogType !== fogType ) {
  21811. _gl.uniform1i( uniforms.fogType, fogType );
  21812. oldFogType = fogType;
  21813. }
  21814. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21815. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21816. scale[ 1 ] *= size * sprite.scale.y;
  21817. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21818. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21819. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21820. _gl.uniform1f( uniforms.opacity, material.opacity );
  21821. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21822. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21823. _gl.uniform2fv( uniforms.scale, scale );
  21824. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21825. _renderer.setDepthTest( material.depthTest );
  21826. _renderer.setDepthWrite( material.depthWrite );
  21827. _renderer.setTexture( material.map, 0 );
  21828. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21829. }
  21830. }
  21831. // restore gl
  21832. _gl.enable( _gl.CULL_FACE );
  21833. };
  21834. function createProgram ( shader, precision ) {
  21835. var program = _gl.createProgram();
  21836. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21837. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21838. var prefix = "precision " + precision + " float;\n";
  21839. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21840. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21841. _gl.compileShader( fragmentShader );
  21842. _gl.compileShader( vertexShader );
  21843. _gl.attachShader( program, fragmentShader );
  21844. _gl.attachShader( program, vertexShader );
  21845. _gl.linkProgram( program );
  21846. return program;
  21847. };
  21848. function painterSortStable ( a, b ) {
  21849. if ( a.z !== b.z ) {
  21850. return b.z - a.z;
  21851. } else {
  21852. return b.id - a.id;
  21853. }
  21854. };
  21855. };
  21856. /**
  21857. * @author alteredq / http://alteredqualia.com/
  21858. */
  21859. THREE.DepthPassPlugin = function ( ) {
  21860. this.enabled = false;
  21861. this.renderTarget = null;
  21862. var _gl,
  21863. _renderer,
  21864. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21865. _frustum = new THREE.Frustum(),
  21866. _projScreenMatrix = new THREE.Matrix4();
  21867. this.init = function ( renderer ) {
  21868. _gl = renderer.context;
  21869. _renderer = renderer;
  21870. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21871. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21872. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21873. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21874. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21875. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21876. _depthMaterial._shadowPass = true;
  21877. _depthMaterialMorph._shadowPass = true;
  21878. _depthMaterialSkin._shadowPass = true;
  21879. _depthMaterialMorphSkin._shadowPass = true;
  21880. };
  21881. this.render = function ( scene, camera ) {
  21882. if ( ! this.enabled ) return;
  21883. this.update( scene, camera );
  21884. };
  21885. this.update = function ( scene, camera ) {
  21886. var i, il, j, jl, n,
  21887. program, buffer, material,
  21888. webglObject, object, light,
  21889. renderList,
  21890. fog = null;
  21891. // set GL state for depth map
  21892. _gl.clearColor( 1, 1, 1, 1 );
  21893. _gl.disable( _gl.BLEND );
  21894. _renderer.setDepthTest( true );
  21895. // update scene
  21896. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21897. // update camera matrices and frustum
  21898. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21899. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21900. _frustum.setFromMatrix( _projScreenMatrix );
  21901. // render depth map
  21902. _renderer.setRenderTarget( this.renderTarget );
  21903. _renderer.clear();
  21904. // set object matrices & frustum culling
  21905. renderList = scene.__webglObjects;
  21906. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21907. webglObject = renderList[ j ];
  21908. object = webglObject.object;
  21909. webglObject.render = false;
  21910. if ( object.visible ) {
  21911. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21912. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21913. webglObject.render = true;
  21914. }
  21915. }
  21916. }
  21917. // render regular objects
  21918. var objectMaterial, useMorphing, useSkinning;
  21919. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21920. webglObject = renderList[ j ];
  21921. if ( webglObject.render ) {
  21922. object = webglObject.object;
  21923. buffer = webglObject.buffer;
  21924. // todo: create proper depth material for particles
  21925. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21926. objectMaterial = getObjectMaterial( object );
  21927. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21928. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21929. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21930. if ( object.customDepthMaterial ) {
  21931. material = object.customDepthMaterial;
  21932. } else if ( useSkinning ) {
  21933. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21934. } else if ( useMorphing ) {
  21935. material = _depthMaterialMorph;
  21936. } else {
  21937. material = _depthMaterial;
  21938. }
  21939. if ( buffer instanceof THREE.BufferGeometry ) {
  21940. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21941. } else {
  21942. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21943. }
  21944. }
  21945. }
  21946. // set matrices and render immediate objects
  21947. renderList = scene.__webglObjectsImmediate;
  21948. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21949. webglObject = renderList[ j ];
  21950. object = webglObject.object;
  21951. if ( object.visible ) {
  21952. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21953. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21954. }
  21955. }
  21956. // restore GL state
  21957. var clearColor = _renderer.getClearColor(),
  21958. clearAlpha = _renderer.getClearAlpha();
  21959. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21960. _gl.enable( _gl.BLEND );
  21961. };
  21962. // For the moment just ignore objects that have multiple materials with different animation methods
  21963. // Only the first material will be taken into account for deciding which depth material to use
  21964. function getObjectMaterial( object ) {
  21965. return object.material instanceof THREE.MeshFaceMaterial
  21966. ? object.material.materials[ 0 ]
  21967. : object.material;
  21968. };
  21969. };
  21970. /**
  21971. * @author mikael emtinger / http://gomo.se/
  21972. *
  21973. */
  21974. THREE.ShaderFlares = {
  21975. 'lensFlareVertexTexture': {
  21976. vertexShader: [
  21977. "uniform lowp int renderType;",
  21978. "uniform vec3 screenPosition;",
  21979. "uniform vec2 scale;",
  21980. "uniform float rotation;",
  21981. "uniform sampler2D occlusionMap;",
  21982. "attribute vec2 position;",
  21983. "attribute vec2 uv;",
  21984. "varying vec2 vUV;",
  21985. "varying float vVisibility;",
  21986. "void main() {",
  21987. "vUV = uv;",
  21988. "vec2 pos = position;",
  21989. "if( renderType == 2 ) {",
  21990. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21991. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21992. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21993. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21994. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21995. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21996. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21997. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21998. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21999. "vVisibility = ( visibility.r / 9.0 ) *",
  22000. "( 1.0 - visibility.g / 9.0 ) *",
  22001. "( visibility.b / 9.0 ) *",
  22002. "( 1.0 - visibility.a / 9.0 );",
  22003. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22004. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22005. "}",
  22006. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22007. "}"
  22008. ].join( "\n" ),
  22009. fragmentShader: [
  22010. "uniform lowp int renderType;",
  22011. "uniform sampler2D map;",
  22012. "uniform float opacity;",
  22013. "uniform vec3 color;",
  22014. "varying vec2 vUV;",
  22015. "varying float vVisibility;",
  22016. "void main() {",
  22017. // pink square
  22018. "if( renderType == 0 ) {",
  22019. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22020. // restore
  22021. "} else if( renderType == 1 ) {",
  22022. "gl_FragColor = texture2D( map, vUV );",
  22023. // flare
  22024. "} else {",
  22025. "vec4 texture = texture2D( map, vUV );",
  22026. "texture.a *= opacity * vVisibility;",
  22027. "gl_FragColor = texture;",
  22028. "gl_FragColor.rgb *= color;",
  22029. "}",
  22030. "}"
  22031. ].join( "\n" )
  22032. },
  22033. 'lensFlare': {
  22034. vertexShader: [
  22035. "uniform lowp int renderType;",
  22036. "uniform vec3 screenPosition;",
  22037. "uniform vec2 scale;",
  22038. "uniform float rotation;",
  22039. "attribute vec2 position;",
  22040. "attribute vec2 uv;",
  22041. "varying vec2 vUV;",
  22042. "void main() {",
  22043. "vUV = uv;",
  22044. "vec2 pos = position;",
  22045. "if( renderType == 2 ) {",
  22046. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22047. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22048. "}",
  22049. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22050. "}"
  22051. ].join( "\n" ),
  22052. fragmentShader: [
  22053. "precision mediump float;",
  22054. "uniform lowp int renderType;",
  22055. "uniform sampler2D map;",
  22056. "uniform sampler2D occlusionMap;",
  22057. "uniform float opacity;",
  22058. "uniform vec3 color;",
  22059. "varying vec2 vUV;",
  22060. "void main() {",
  22061. // pink square
  22062. "if( renderType == 0 ) {",
  22063. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22064. // restore
  22065. "} else if( renderType == 1 ) {",
  22066. "gl_FragColor = texture2D( map, vUV );",
  22067. // flare
  22068. "} else {",
  22069. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  22070. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  22071. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  22072. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22073. "visibility = ( 1.0 - visibility / 4.0 );",
  22074. "vec4 texture = texture2D( map, vUV );",
  22075. "texture.a *= opacity * visibility;",
  22076. "gl_FragColor = texture;",
  22077. "gl_FragColor.rgb *= color;",
  22078. "}",
  22079. "}"
  22080. ].join( "\n" )
  22081. }
  22082. };
  22083. /**
  22084. * @author mikael emtinger / http://gomo.se/
  22085. * @author alteredq / http://alteredqualia.com/
  22086. *
  22087. */
  22088. THREE.ShaderSprite = {
  22089. 'sprite': {
  22090. vertexShader: [
  22091. "uniform int useScreenCoordinates;",
  22092. "uniform int sizeAttenuation;",
  22093. "uniform vec3 screenPosition;",
  22094. "uniform mat4 modelViewMatrix;",
  22095. "uniform mat4 projectionMatrix;",
  22096. "uniform float rotation;",
  22097. "uniform vec2 scale;",
  22098. "uniform vec2 alignment;",
  22099. "uniform vec2 uvOffset;",
  22100. "uniform vec2 uvScale;",
  22101. "attribute vec2 position;",
  22102. "attribute vec2 uv;",
  22103. "varying vec2 vUV;",
  22104. "void main() {",
  22105. "vUV = uvOffset + uv * uvScale;",
  22106. "vec2 alignedPosition = position + alignment;",
  22107. "vec2 rotatedPosition;",
  22108. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  22109. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  22110. "vec4 finalPosition;",
  22111. "if( useScreenCoordinates != 0 ) {",
  22112. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  22113. "} else {",
  22114. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  22115. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  22116. "}",
  22117. "gl_Position = finalPosition;",
  22118. "}"
  22119. ].join( "\n" ),
  22120. fragmentShader: [
  22121. "uniform vec3 color;",
  22122. "uniform sampler2D map;",
  22123. "uniform float opacity;",
  22124. "uniform int fogType;",
  22125. "uniform vec3 fogColor;",
  22126. "uniform float fogDensity;",
  22127. "uniform float fogNear;",
  22128. "uniform float fogFar;",
  22129. "uniform float alphaTest;",
  22130. "varying vec2 vUV;",
  22131. "void main() {",
  22132. "vec4 texture = texture2D( map, vUV );",
  22133. "if ( texture.a < alphaTest ) discard;",
  22134. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  22135. "if ( fogType > 0 ) {",
  22136. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  22137. "float fogFactor = 0.0;",
  22138. "if ( fogType == 1 ) {",
  22139. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  22140. "} else {",
  22141. "const float LOG2 = 1.442695;",
  22142. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  22143. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  22144. "}",
  22145. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  22146. "}",
  22147. "}"
  22148. ].join( "\n" )
  22149. }
  22150. };