three.js 806 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. var THREE = THREE || { REVISION: '51dev' };
  5. if ( self.console === undefined ) {
  6. self.console = {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. }
  14. if ( self.Int32Array === undefined ) {
  15. self.Int32Array = Array;
  16. self.Float32Array = Array;
  17. }
  18. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  19. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  20. // requestAnimationFrame polyfill by Erik Möller
  21. // fixes from Paul Irish and Tino Zijdel
  22. ( function () {
  23. var lastTime = 0;
  24. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  25. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  26. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  27. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  28. }
  29. if ( window.requestAnimationFrame === undefined ) {
  30. window.requestAnimationFrame = function ( callback, element ) {
  31. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  32. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  33. lastTime = currTime + timeToCall;
  34. return id;
  35. };
  36. }
  37. if ( window.cancelAnimationFrame === undefined ) {
  38. window.cancelAnimationFrame = function ( id ) { clearTimeout( id ); };
  39. }
  40. }() );
  41. // MATERIAL CONSTANTS
  42. // side
  43. THREE.FrontSide = 0;
  44. THREE.BackSide = 1;
  45. THREE.DoubleSide = 2;
  46. // shading
  47. THREE.NoShading = 0;
  48. THREE.FlatShading = 1;
  49. THREE.SmoothShading = 2;
  50. // colors
  51. THREE.NoColors = 0;
  52. THREE.FaceColors = 1;
  53. THREE.VertexColors = 2;
  54. // blending modes
  55. THREE.NoBlending = 0;
  56. THREE.NormalBlending = 1;
  57. THREE.AdditiveBlending = 2;
  58. THREE.SubtractiveBlending = 3;
  59. THREE.MultiplyBlending = 4;
  60. THREE.CustomBlending = 5;
  61. // custom blending equations
  62. // (numbers start from 100 not to clash with other
  63. // mappings to OpenGL constants defined in Texture.js)
  64. THREE.AddEquation = 100;
  65. THREE.SubtractEquation = 101;
  66. THREE.ReverseSubtractEquation = 102;
  67. // custom blending destination factors
  68. THREE.ZeroFactor = 200;
  69. THREE.OneFactor = 201;
  70. THREE.SrcColorFactor = 202;
  71. THREE.OneMinusSrcColorFactor = 203;
  72. THREE.SrcAlphaFactor = 204;
  73. THREE.OneMinusSrcAlphaFactor = 205;
  74. THREE.DstAlphaFactor = 206;
  75. THREE.OneMinusDstAlphaFactor = 207;
  76. // custom blending source factors
  77. //THREE.ZeroFactor = 200;
  78. //THREE.OneFactor = 201;
  79. //THREE.SrcAlphaFactor = 204;
  80. //THREE.OneMinusSrcAlphaFactor = 205;
  81. //THREE.DstAlphaFactor = 206;
  82. //THREE.OneMinusDstAlphaFactor = 207;
  83. THREE.DstColorFactor = 208;
  84. THREE.OneMinusDstColorFactor = 209;
  85. THREE.SrcAlphaSaturateFactor = 210;
  86. // TEXTURE CONSTANTS
  87. THREE.MultiplyOperation = 0;
  88. THREE.MixOperation = 1;
  89. // Mapping modes
  90. THREE.UVMapping = function () {};
  91. THREE.CubeReflectionMapping = function () {};
  92. THREE.CubeRefractionMapping = function () {};
  93. THREE.SphericalReflectionMapping = function () {};
  94. THREE.SphericalRefractionMapping = function () {};
  95. // Wrapping modes
  96. THREE.RepeatWrapping = 1000;
  97. THREE.ClampToEdgeWrapping = 1001;
  98. THREE.MirroredRepeatWrapping = 1002;
  99. // Filters
  100. THREE.NearestFilter = 1003;
  101. THREE.NearestMipMapNearestFilter = 1004;
  102. THREE.NearestMipMapLinearFilter = 1005;
  103. THREE.LinearFilter = 1006;
  104. THREE.LinearMipMapNearestFilter = 1007;
  105. THREE.LinearMipMapLinearFilter = 1008;
  106. // Data types
  107. THREE.UnsignedByteType = 1009;
  108. THREE.ByteType = 1010;
  109. THREE.ShortType = 1011;
  110. THREE.UnsignedShortType = 1012;
  111. THREE.IntType = 1013;
  112. THREE.UnsignedIntType = 1014;
  113. THREE.FloatType = 1015;
  114. // Pixel types
  115. //THREE.UnsignedByteType = 1009;
  116. THREE.UnsignedShort4444Type = 1016;
  117. THREE.UnsignedShort5551Type = 1017;
  118. THREE.UnsignedShort565Type = 1018;
  119. // Pixel formats
  120. THREE.AlphaFormat = 1019;
  121. THREE.RGBFormat = 1020;
  122. THREE.RGBAFormat = 1021;
  123. THREE.LuminanceFormat = 1022;
  124. THREE.LuminanceAlphaFormat = 1023;
  125. /**
  126. * @author alteredq / http://alteredqualia.com/
  127. */
  128. THREE.Clock = function ( autoStart ) {
  129. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  130. this.startTime = 0;
  131. this.oldTime = 0;
  132. this.elapsedTime = 0;
  133. this.running = false;
  134. };
  135. THREE.Clock.prototype.start = function () {
  136. this.startTime = Date.now();
  137. this.oldTime = this.startTime;
  138. this.running = true;
  139. };
  140. THREE.Clock.prototype.stop = function () {
  141. this.getElapsedTime();
  142. this.running = false;
  143. };
  144. THREE.Clock.prototype.getElapsedTime = function () {
  145. this.elapsedTime += this.getDelta();
  146. return this.elapsedTime;
  147. };
  148. THREE.Clock.prototype.getDelta = function () {
  149. var diff = 0;
  150. if ( this.autoStart && ! this.running ) {
  151. this.start();
  152. }
  153. if ( this.running ) {
  154. var newTime = Date.now();
  155. diff = 0.001 * ( newTime - this.oldTime );
  156. this.oldTime = newTime;
  157. this.elapsedTime += diff;
  158. }
  159. return diff;
  160. };/**
  161. * @author mrdoob / http://mrdoob.com/
  162. */
  163. THREE.Color = function ( hex ) {
  164. if ( hex !== undefined ) this.setHex( hex );
  165. return this;
  166. };
  167. THREE.Color.prototype = {
  168. constructor: THREE.Color,
  169. r: 1, g: 1, b: 1,
  170. copy: function ( color ) {
  171. this.r = color.r;
  172. this.g = color.g;
  173. this.b = color.b;
  174. return this;
  175. },
  176. copyGammaToLinear: function ( color ) {
  177. this.r = color.r * color.r;
  178. this.g = color.g * color.g;
  179. this.b = color.b * color.b;
  180. return this;
  181. },
  182. copyLinearToGamma: function ( color ) {
  183. this.r = Math.sqrt( color.r );
  184. this.g = Math.sqrt( color.g );
  185. this.b = Math.sqrt( color.b );
  186. return this;
  187. },
  188. convertGammaToLinear: function () {
  189. var r = this.r, g = this.g, b = this.b;
  190. this.r = r * r;
  191. this.g = g * g;
  192. this.b = b * b;
  193. return this;
  194. },
  195. convertLinearToGamma: function () {
  196. this.r = Math.sqrt( this.r );
  197. this.g = Math.sqrt( this.g );
  198. this.b = Math.sqrt( this.b );
  199. return this;
  200. },
  201. setRGB: function ( r, g, b ) {
  202. this.r = r;
  203. this.g = g;
  204. this.b = b;
  205. return this;
  206. },
  207. setHSV: function ( h, s, v ) {
  208. // based on MochiKit implementation by Bob Ippolito
  209. // h,s,v ranges are < 0.0 - 1.0 >
  210. var i, f, p, q, t;
  211. if ( v === 0 ) {
  212. this.r = this.g = this.b = 0;
  213. } else {
  214. i = Math.floor( h * 6 );
  215. f = ( h * 6 ) - i;
  216. p = v * ( 1 - s );
  217. q = v * ( 1 - ( s * f ) );
  218. t = v * ( 1 - ( s * ( 1 - f ) ) );
  219. if ( i === 0 ) {
  220. this.r = v;
  221. this.g = t;
  222. this.b = p;
  223. } else if ( i === 1 ) {
  224. this.r = q;
  225. this.g = v;
  226. this.b = p;
  227. } else if ( i === 2 ) {
  228. this.r = p;
  229. this.g = v;
  230. this.b = t;
  231. } else if ( i === 3 ) {
  232. this.r = p;
  233. this.g = q;
  234. this.b = v;
  235. } else if ( i === 4 ) {
  236. this.r = t;
  237. this.g = p;
  238. this.b = v;
  239. } else if ( i === 5 ) {
  240. this.r = v;
  241. this.g = p;
  242. this.b = q;
  243. }
  244. }
  245. return this;
  246. },
  247. setHex: function ( hex ) {
  248. hex = Math.floor( hex );
  249. this.r = ( hex >> 16 & 255 ) / 255;
  250. this.g = ( hex >> 8 & 255 ) / 255;
  251. this.b = ( hex & 255 ) / 255;
  252. return this;
  253. },
  254. lerpSelf: function ( color, alpha ) {
  255. this.r += ( color.r - this.r ) * alpha;
  256. this.g += ( color.g - this.g ) * alpha;
  257. this.b += ( color.b - this.b ) * alpha;
  258. return this;
  259. },
  260. getHex: function () {
  261. return Math.floor( this.r * 255 ) << 16 ^ Math.floor( this.g * 255 ) << 8 ^ Math.floor( this.b * 255 );
  262. },
  263. getContextStyle: function () {
  264. return 'rgb(' + Math.floor( this.r * 255 ) + ',' + Math.floor( this.g * 255 ) + ',' + Math.floor( this.b * 255 ) + ')';
  265. },
  266. clone: function () {
  267. return new THREE.Color().setRGB( this.r, this.g, this.b );
  268. }
  269. };
  270. /**
  271. * @author mrdoob / http://mrdoob.com/
  272. * @author philogb / http://blog.thejit.org/
  273. * @author egraether / http://egraether.com/
  274. * @author zz85 / http://www.lab4games.net/zz85/blog
  275. */
  276. THREE.Vector2 = function ( x, y ) {
  277. this.x = x || 0;
  278. this.y = y || 0;
  279. };
  280. THREE.Vector2.prototype = {
  281. constructor: THREE.Vector2,
  282. set: function ( x, y ) {
  283. this.x = x;
  284. this.y = y;
  285. return this;
  286. },
  287. copy: function ( v ) {
  288. this.x = v.x;
  289. this.y = v.y;
  290. return this;
  291. },
  292. add: function ( a, b ) {
  293. this.x = a.x + b.x;
  294. this.y = a.y + b.y;
  295. return this;
  296. },
  297. addSelf: function ( v ) {
  298. this.x += v.x;
  299. this.y += v.y;
  300. return this;
  301. },
  302. sub: function ( a, b ) {
  303. this.x = a.x - b.x;
  304. this.y = a.y - b.y;
  305. return this;
  306. },
  307. subSelf: function ( v ) {
  308. this.x -= v.x;
  309. this.y -= v.y;
  310. return this;
  311. },
  312. multiplyScalar: function ( s ) {
  313. this.x *= s;
  314. this.y *= s;
  315. return this;
  316. },
  317. divideScalar: function ( s ) {
  318. if ( s ) {
  319. this.x /= s;
  320. this.y /= s;
  321. } else {
  322. this.set( 0, 0 );
  323. }
  324. return this;
  325. },
  326. negate: function() {
  327. return this.multiplyScalar( - 1 );
  328. },
  329. dot: function ( v ) {
  330. return this.x * v.x + this.y * v.y;
  331. },
  332. lengthSq: function () {
  333. return this.x * this.x + this.y * this.y;
  334. },
  335. length: function () {
  336. return Math.sqrt( this.lengthSq() );
  337. },
  338. normalize: function () {
  339. return this.divideScalar( this.length() );
  340. },
  341. distanceTo: function ( v ) {
  342. return Math.sqrt( this.distanceToSquared( v ) );
  343. },
  344. distanceToSquared: function ( v ) {
  345. var dx = this.x - v.x, dy = this.y - v.y;
  346. return dx * dx + dy * dy;
  347. },
  348. setLength: function ( l ) {
  349. return this.normalize().multiplyScalar( l );
  350. },
  351. lerpSelf: function ( v, alpha ) {
  352. this.x += ( v.x - this.x ) * alpha;
  353. this.y += ( v.y - this.y ) * alpha;
  354. return this;
  355. },
  356. equals: function( v ) {
  357. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  358. },
  359. isZero: function () {
  360. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  361. },
  362. clone: function () {
  363. return new THREE.Vector2( this.x, this.y );
  364. }
  365. };
  366. /**
  367. * @author mrdoob / http://mrdoob.com/
  368. * @author kile / http://kile.stravaganza.org/
  369. * @author philogb / http://blog.thejit.org/
  370. * @author mikael emtinger / http://gomo.se/
  371. * @author egraether / http://egraether.com/
  372. * @author WestLangley / http://github.com/WestLangley
  373. */
  374. THREE.Vector3 = function ( x, y, z ) {
  375. this.x = x || 0;
  376. this.y = y || 0;
  377. this.z = z || 0;
  378. };
  379. THREE.Vector3.prototype = {
  380. constructor: THREE.Vector3,
  381. set: function ( x, y, z ) {
  382. this.x = x;
  383. this.y = y;
  384. this.z = z;
  385. return this;
  386. },
  387. setX: function ( x ) {
  388. this.x = x;
  389. return this;
  390. },
  391. setY: function ( y ) {
  392. this.y = y;
  393. return this;
  394. },
  395. setZ: function ( z ) {
  396. this.z = z;
  397. return this;
  398. },
  399. copy: function ( v ) {
  400. this.x = v.x;
  401. this.y = v.y;
  402. this.z = v.z;
  403. return this;
  404. },
  405. add: function ( a, b ) {
  406. this.x = a.x + b.x;
  407. this.y = a.y + b.y;
  408. this.z = a.z + b.z;
  409. return this;
  410. },
  411. addSelf: function ( v ) {
  412. this.x += v.x;
  413. this.y += v.y;
  414. this.z += v.z;
  415. return this;
  416. },
  417. addScalar: function ( s ) {
  418. this.x += s;
  419. this.y += s;
  420. this.z += s;
  421. return this;
  422. },
  423. sub: function ( a, b ) {
  424. this.x = a.x - b.x;
  425. this.y = a.y - b.y;
  426. this.z = a.z - b.z;
  427. return this;
  428. },
  429. subSelf: function ( v ) {
  430. this.x -= v.x;
  431. this.y -= v.y;
  432. this.z -= v.z;
  433. return this;
  434. },
  435. multiply: function ( a, b ) {
  436. this.x = a.x * b.x;
  437. this.y = a.y * b.y;
  438. this.z = a.z * b.z;
  439. return this;
  440. },
  441. multiplySelf: function ( v ) {
  442. this.x *= v.x;
  443. this.y *= v.y;
  444. this.z *= v.z;
  445. return this;
  446. },
  447. multiplyScalar: function ( s ) {
  448. this.x *= s;
  449. this.y *= s;
  450. this.z *= s;
  451. return this;
  452. },
  453. divideSelf: function ( v ) {
  454. this.x /= v.x;
  455. this.y /= v.y;
  456. this.z /= v.z;
  457. return this;
  458. },
  459. divideScalar: function ( s ) {
  460. if ( s ) {
  461. this.x /= s;
  462. this.y /= s;
  463. this.z /= s;
  464. } else {
  465. this.x = 0;
  466. this.y = 0;
  467. this.z = 0;
  468. }
  469. return this;
  470. },
  471. negate: function() {
  472. return this.multiplyScalar( - 1 );
  473. },
  474. dot: function ( v ) {
  475. return this.x * v.x + this.y * v.y + this.z * v.z;
  476. },
  477. lengthSq: function () {
  478. return this.x * this.x + this.y * this.y + this.z * this.z;
  479. },
  480. length: function () {
  481. return Math.sqrt( this.lengthSq() );
  482. },
  483. lengthManhattan: function () {
  484. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  485. },
  486. normalize: function () {
  487. return this.divideScalar( this.length() );
  488. },
  489. setLength: function ( l ) {
  490. return this.normalize().multiplyScalar( l );
  491. },
  492. lerpSelf: function ( v, alpha ) {
  493. this.x += ( v.x - this.x ) * alpha;
  494. this.y += ( v.y - this.y ) * alpha;
  495. this.z += ( v.z - this.z ) * alpha;
  496. return this;
  497. },
  498. cross: function ( a, b ) {
  499. this.x = a.y * b.z - a.z * b.y;
  500. this.y = a.z * b.x - a.x * b.z;
  501. this.z = a.x * b.y - a.y * b.x;
  502. return this;
  503. },
  504. crossSelf: function ( v ) {
  505. var x = this.x, y = this.y, z = this.z;
  506. this.x = y * v.z - z * v.y;
  507. this.y = z * v.x - x * v.z;
  508. this.z = x * v.y - y * v.x;
  509. return this;
  510. },
  511. distanceTo: function ( v ) {
  512. return Math.sqrt( this.distanceToSquared( v ) );
  513. },
  514. distanceToSquared: function ( v ) {
  515. return new THREE.Vector3().sub( this, v ).lengthSq();
  516. },
  517. getPositionFromMatrix: function ( m ) {
  518. this.x = m.elements[12];
  519. this.y = m.elements[13];
  520. this.z = m.elements[14];
  521. return this;
  522. },
  523. setEulerFromRotationMatrix: function ( m, order ) {
  524. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  525. // clamp, to handle numerical problems
  526. function clamp( x ) {
  527. return Math.min( Math.max( x, -1 ), 1 );
  528. }
  529. var te = m.elements;
  530. var m11 = te[0], m12 = te[4], m13 = te[8];
  531. var m21 = te[1], m22 = te[5], m23 = te[9];
  532. var m31 = te[2], m32 = te[6], m33 = te[10];
  533. if ( order === undefined || order === 'XYZ' ) {
  534. this.y = Math.asin( clamp( m13 ) );
  535. if ( Math.abs( m13 ) < 0.99999 ) {
  536. this.x = Math.atan2( - m23, m33 );
  537. this.z = Math.atan2( - m12, m11 );
  538. } else {
  539. this.x = Math.atan2( m21, m22 );
  540. this.z = 0;
  541. }
  542. } else if ( order === 'YXZ' ) {
  543. this.x = Math.asin( - clamp( m23 ) );
  544. if ( Math.abs( m23 ) < 0.99999 ) {
  545. this.y = Math.atan2( m13, m33 );
  546. this.z = Math.atan2( m21, m22 );
  547. } else {
  548. this.y = Math.atan2( - m31, m11 );
  549. this.z = 0;
  550. }
  551. } else if ( order === 'ZXY' ) {
  552. this.x = Math.asin( clamp( m32 ) );
  553. if ( Math.abs( m32 ) < 0.99999 ) {
  554. this.y = Math.atan2( - m31, m33 );
  555. this.z = Math.atan2( - m12, m22 );
  556. } else {
  557. this.y = 0;
  558. this.z = Math.atan2( m13, m11 );
  559. }
  560. } else if ( order === 'ZYX' ) {
  561. this.y = Math.asin( - clamp( m31 ) );
  562. if ( Math.abs( m31 ) < 0.99999 ) {
  563. this.x = Math.atan2( m32, m33 );
  564. this.z = Math.atan2( m21, m11 );
  565. } else {
  566. this.x = 0;
  567. this.z = Math.atan2( - m12, m22 );
  568. }
  569. } else if ( order === 'YZX' ) {
  570. this.z = Math.asin( clamp( m21 ) );
  571. if ( Math.abs( m21 ) < 0.99999 ) {
  572. this.x = Math.atan2( - m23, m22 );
  573. this.y = Math.atan2( - m31, m11 );
  574. } else {
  575. this.x = 0;
  576. this.y = Math.atan2( m31, m33 );
  577. }
  578. } else if ( order === 'XZY' ) {
  579. this.z = Math.asin( - clamp( m12 ) );
  580. if ( Math.abs( m12 ) < 0.99999 ) {
  581. this.x = Math.atan2( m32, m22 );
  582. this.y = Math.atan2( m13, m11 );
  583. } else {
  584. this.x = Math.atan2( - m13, m33 );
  585. this.y = 0;
  586. }
  587. }
  588. return this;
  589. },
  590. setEulerFromQuaternion: function ( q, order ) {
  591. // q is assumed to be normalized
  592. // clamp, to handle numerical problems
  593. function clamp( x ) {
  594. return Math.min( Math.max( x, -1 ), 1 );
  595. }
  596. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  597. var sqx = q.x * q.x;
  598. var sqy = q.y * q.y;
  599. var sqz = q.z * q.z;
  600. var sqw = q.w * q.w;
  601. if ( order === undefined || order === 'XYZ' ) {
  602. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  603. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  604. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  605. } else if ( order === 'YXZ' ) {
  606. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  607. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  608. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  609. } else if ( order === 'ZXY' ) {
  610. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  611. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  612. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  613. } else if ( order === 'ZYX' ) {
  614. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  615. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  616. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  617. } else if ( order === 'YZX' ) {
  618. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  619. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  620. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  621. } else if ( order === 'XZY' ) {
  622. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  623. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  624. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  625. }
  626. return this;
  627. },
  628. getScaleFromMatrix: function ( m ) {
  629. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  630. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  631. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  632. this.x = sx;
  633. this.y = sy;
  634. this.z = sz;
  635. return this;
  636. },
  637. equals: function ( v ) {
  638. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  639. },
  640. isZero: function () {
  641. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  642. },
  643. clone: function () {
  644. return new THREE.Vector3( this.x, this.y, this.z );
  645. }
  646. };
  647. /**
  648. * @author supereggbert / http://www.paulbrunt.co.uk/
  649. * @author philogb / http://blog.thejit.org/
  650. * @author mikael emtinger / http://gomo.se/
  651. * @author egraether / http://egraether.com/
  652. * @author WestLangley / http://github.com/WestLangley
  653. */
  654. THREE.Vector4 = function ( x, y, z, w ) {
  655. this.x = x || 0;
  656. this.y = y || 0;
  657. this.z = z || 0;
  658. this.w = ( w !== undefined ) ? w : 1;
  659. };
  660. THREE.Vector4.prototype = {
  661. constructor: THREE.Vector4,
  662. set: function ( x, y, z, w ) {
  663. this.x = x;
  664. this.y = y;
  665. this.z = z;
  666. this.w = w;
  667. return this;
  668. },
  669. copy: function ( v ) {
  670. this.x = v.x;
  671. this.y = v.y;
  672. this.z = v.z;
  673. this.w = ( v.w !== undefined ) ? v.w : 1;
  674. return this;
  675. },
  676. add: function ( a, b ) {
  677. this.x = a.x + b.x;
  678. this.y = a.y + b.y;
  679. this.z = a.z + b.z;
  680. this.w = a.w + b.w;
  681. return this;
  682. },
  683. addSelf: function ( v ) {
  684. this.x += v.x;
  685. this.y += v.y;
  686. this.z += v.z;
  687. this.w += v.w;
  688. return this;
  689. },
  690. sub: function ( a, b ) {
  691. this.x = a.x - b.x;
  692. this.y = a.y - b.y;
  693. this.z = a.z - b.z;
  694. this.w = a.w - b.w;
  695. return this;
  696. },
  697. subSelf: function ( v ) {
  698. this.x -= v.x;
  699. this.y -= v.y;
  700. this.z -= v.z;
  701. this.w -= v.w;
  702. return this;
  703. },
  704. multiplyScalar: function ( s ) {
  705. this.x *= s;
  706. this.y *= s;
  707. this.z *= s;
  708. this.w *= s;
  709. return this;
  710. },
  711. divideScalar: function ( s ) {
  712. if ( s ) {
  713. this.x /= s;
  714. this.y /= s;
  715. this.z /= s;
  716. this.w /= s;
  717. } else {
  718. this.x = 0;
  719. this.y = 0;
  720. this.z = 0;
  721. this.w = 1;
  722. }
  723. return this;
  724. },
  725. negate: function() {
  726. return this.multiplyScalar( -1 );
  727. },
  728. dot: function ( v ) {
  729. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  730. },
  731. lengthSq: function () {
  732. return this.dot( this );
  733. },
  734. length: function () {
  735. return Math.sqrt( this.lengthSq() );
  736. },
  737. lengthManhattan: function () {
  738. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  739. },
  740. normalize: function () {
  741. return this.divideScalar( this.length() );
  742. },
  743. setLength: function ( l ) {
  744. return this.normalize().multiplyScalar( l );
  745. },
  746. lerpSelf: function ( v, alpha ) {
  747. this.x += ( v.x - this.x ) * alpha;
  748. this.y += ( v.y - this.y ) * alpha;
  749. this.z += ( v.z - this.z ) * alpha;
  750. this.w += ( v.w - this.w ) * alpha;
  751. return this;
  752. },
  753. clone: function () {
  754. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  755. },
  756. setAxisAngleFromQuaternion: function ( q ) {
  757. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  758. // q is assumed to be normalized
  759. this.w = 2 * Math.acos( q.w );
  760. var s = Math.sqrt( 1 - q.w * q.w );
  761. if ( s < 0.0001 ) {
  762. this.x = 1;
  763. this.y = 0;
  764. this.z = 0;
  765. } else {
  766. this.x = q.x / s;
  767. this.y = q.y / s;
  768. this.z = q.z / s;
  769. }
  770. return this;
  771. },
  772. setAxisAngleFromRotationMatrix: function ( m ) {
  773. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  774. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  775. var angle, x, y, z, // variables for result
  776. epsilon = 0.01, // margin to allow for rounding errors
  777. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  778. te = m.elements,
  779. m11 = te[0], m12 = te[4], m13 = te[8],
  780. m21 = te[1], m22 = te[5], m23 = te[9],
  781. m31 = te[2], m32 = te[6], m33 = te[10];
  782. if ( ( Math.abs( m12 - m21 ) < epsilon )
  783. && ( Math.abs( m13 - m31 ) < epsilon )
  784. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  785. // singularity found
  786. // first check for identity matrix which must have +1 for all terms
  787. // in leading diagonal and zero in other terms
  788. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  789. && ( Math.abs( m13 + m31 ) < epsilon2 )
  790. && ( Math.abs( m23 + m32 ) < epsilon2 )
  791. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  792. // this singularity is identity matrix so angle = 0
  793. this.set( 1, 0, 0, 0 );
  794. return this; // zero angle, arbitrary axis
  795. }
  796. // otherwise this singularity is angle = 180
  797. angle = Math.PI;
  798. var xx = ( m11 + 1 ) / 2;
  799. var yy = ( m22 + 1 ) / 2;
  800. var zz = ( m33 + 1 ) / 2;
  801. var xy = ( m12 + m21 ) / 4;
  802. var xz = ( m13 + m31 ) / 4;
  803. var yz = ( m23 + m32 ) / 4;
  804. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  805. if ( xx < epsilon ) {
  806. x = 0;
  807. y = 0.707106781;
  808. z = 0.707106781;
  809. } else {
  810. x = Math.sqrt( xx );
  811. y = xy / x;
  812. z = xz / x;
  813. }
  814. } else if ( yy > zz ) { // m22 is the largest diagonal term
  815. if ( yy < epsilon ) {
  816. x = 0.707106781;
  817. y = 0;
  818. z = 0.707106781;
  819. } else {
  820. y = Math.sqrt( yy );
  821. x = xy / y;
  822. z = yz / y;
  823. }
  824. } else { // m33 is the largest diagonal term so base result on this
  825. if ( zz < epsilon ) {
  826. x = 0.707106781;
  827. y = 0.707106781;
  828. z = 0;
  829. } else {
  830. z = Math.sqrt( zz );
  831. x = xz / z;
  832. y = yz / z;
  833. }
  834. }
  835. this.set( x, y, z, angle );
  836. return this; // return 180 deg rotation
  837. }
  838. // as we have reached here there are no singularities so we can handle normally
  839. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  840. + ( m13 - m31 ) * ( m13 - m31 )
  841. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  842. if ( Math.abs( s ) < 0.001 ) s = 1;
  843. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  844. // caught by singularity test above, but I've left it in just in case
  845. this.x = ( m32 - m23 ) / s;
  846. this.y = ( m13 - m31 ) / s;
  847. this.z = ( m21 - m12 ) / s;
  848. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  849. return this;
  850. }
  851. };
  852. /**
  853. * https://github.com/mrdoob/eventtarget.js/
  854. */
  855. THREE.EventTarget = function () {
  856. var listeners = {};
  857. this.addEventListener = function ( type, listener ) {
  858. if ( listeners[ type ] === undefined ) {
  859. listeners[ type ] = [];
  860. }
  861. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  862. listeners[ type ].push( listener );
  863. }
  864. };
  865. this.dispatchEvent = function ( event ) {
  866. for ( var listener in listeners[ event.type ] ) {
  867. listeners[ event.type ][ listener ]( event );
  868. }
  869. };
  870. this.removeEventListener = function ( type, listener ) {
  871. var index = listeners[ type ].indexOf( listener );
  872. if ( index !== - 1 ) {
  873. listeners[ type ].splice( index, 1 );
  874. }
  875. };
  876. };
  877. /**
  878. * @author mrdoob / http://mrdoob.com/
  879. * @author alteredq / http://alteredqualia.com/
  880. */
  881. THREE.Frustum = function ( ) {
  882. this.planes = [
  883. new THREE.Vector4(),
  884. new THREE.Vector4(),
  885. new THREE.Vector4(),
  886. new THREE.Vector4(),
  887. new THREE.Vector4(),
  888. new THREE.Vector4()
  889. ];
  890. };
  891. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  892. var plane;
  893. var planes = this.planes;
  894. var me = m.elements;
  895. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  896. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  897. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  898. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  899. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  900. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  901. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  902. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  903. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  904. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  905. for ( var i = 0; i < 6; i ++ ) {
  906. plane = planes[ i ];
  907. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  908. }
  909. };
  910. THREE.Frustum.prototype.contains = function ( object ) {
  911. var distance = 0.0;
  912. var planes = this.planes;
  913. var matrix = object.matrixWorld;
  914. var me = matrix.elements;
  915. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  916. for ( var i = 0; i < 6; i ++ ) {
  917. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  918. if ( distance <= radius ) return false;
  919. }
  920. return true;
  921. };
  922. THREE.Frustum.__v1 = new THREE.Vector3();
  923. /**
  924. * @author mrdoob / http://mrdoob.com/
  925. */
  926. THREE.Ray = function ( origin, direction, near, far ) {
  927. this.origin = origin || new THREE.Vector3();
  928. this.direction = direction || new THREE.Vector3();
  929. this.near = near || 0;
  930. this.far = far || Infinity;
  931. //
  932. var a;// = new THREE.Vector3();
  933. var b;// = new THREE.Vector3();
  934. var c;// = new THREE.Vector3();
  935. var d;// = new THREE.Vector3();
  936. var originCopy = new THREE.Vector3();
  937. // var directionCopy = new THREE.Vector3();
  938. var localOriginCopy = new THREE.Vector3();
  939. var localDirectionCopy = new THREE.Vector3();
  940. var vector = new THREE.Vector3();
  941. var normal = new THREE.Vector3();
  942. var intersectPoint = new THREE.Vector3();
  943. var inverseMatrix = new THREE.Matrix4();
  944. var descSort = function ( a, b ) {
  945. return a.distance - b.distance;
  946. };
  947. //
  948. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  949. var dot, intersect, distance;
  950. var distanceFromIntersection = function ( origin, direction, position ) {
  951. v0.sub( position, origin );
  952. dot = v0.dot( direction );
  953. intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  954. distance = position.distanceTo( intersect );
  955. return distance;
  956. }
  957. // http://www.blackpawn.com/texts/pointinpoly/default.html
  958. var dot00, dot01, dot02, dot11, dot12, invDenom, u, v;
  959. var pointInFace3 = function ( p, a, b, c ) {
  960. v0.sub( c, a );
  961. v1.sub( b, a );
  962. v2.sub( p, a );
  963. dot00 = v0.dot( v0 );
  964. dot01 = v0.dot( v1 );
  965. dot02 = v0.dot( v2 );
  966. dot11 = v1.dot( v1 );
  967. dot12 = v1.dot( v2 );
  968. invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  969. u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  970. v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  971. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  972. }
  973. //
  974. var precision = 0.0001;
  975. this.setPrecision = function ( value ) {
  976. precision = value;
  977. };
  978. this.intersectObject = function ( object, recursive ) {
  979. var intersect, intersects = [];
  980. if ( recursive === true ) {
  981. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  982. Array.prototype.push.apply( intersects, this.intersectObject( object.children[ i ], recursive ) );
  983. }
  984. }
  985. if ( object instanceof THREE.Particle ) {
  986. distance = distanceFromIntersection( this.origin, this.direction, object.matrixWorld.getPosition() );
  987. if ( distance > object.scale.x ) {
  988. return [];
  989. }
  990. intersect = {
  991. distance: distance,
  992. point: object.position,
  993. face: null,
  994. object: object
  995. };
  996. intersects.push( intersect );
  997. } else if ( object instanceof THREE.Mesh ) {
  998. // Checking boundingSphere
  999. //var scale = THREE.Frustum.__v1.set( object.matrixWorld.getColumnX().length(), object.matrixWorld.getColumnY().length(), object.matrixWorld.getColumnZ().length() );
  1000. var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
  1001. // Checking distance to ray
  1002. distance = distanceFromIntersection( this.origin, this.direction, object.matrixWorld.getPosition() );
  1003. if ( distance > scaledRadius) {
  1004. return intersects;
  1005. }
  1006. // Checking faces
  1007. var f, fl, face, dot, scalar,
  1008. geometry = object.geometry,
  1009. vertices = geometry.vertices,
  1010. objMatrix, geometryMaterials,
  1011. isFaceMaterial, material, side;
  1012. geometryMaterials = object.geometry.materials;
  1013. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  1014. side = object.material.side;
  1015. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  1016. originCopy.copy( this.origin );
  1017. //directionCopy.copy( this.direction );
  1018. objMatrix = object.matrixWorld;
  1019. inverseMatrix.getInverse(objMatrix);
  1020. localOriginCopy.copy(originCopy);
  1021. inverseMatrix.multiplyVector3(localOriginCopy);
  1022. localDirectionCopy.copy(this.direction);
  1023. inverseMatrix.rotateAxis(localDirectionCopy).normalize();
  1024. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  1025. face = geometry.faces[ f ];
  1026. material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  1027. if ( material === undefined ) continue;
  1028. side = material.side;
  1029. vector.sub( face.centroid, localOriginCopy );
  1030. normal = face.normal;
  1031. dot = localDirectionCopy.dot( normal );
  1032. // bail if ray and plane are parallel
  1033. if ( Math.abs( dot ) < precision ) continue;
  1034. // calc distance to plane
  1035. scalar = normal.dot( vector ) / dot;
  1036. // if negative distance, then plane is behind ray
  1037. if ( scalar < 0 ) continue;
  1038. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  1039. intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
  1040. if ( face instanceof THREE.Face3 ) {
  1041. a = vertices[ face.a ];
  1042. b = vertices[ face.b ];
  1043. c = vertices[ face.c ];
  1044. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  1045. var point = object.matrixWorld.multiplyVector3(intersectPoint.clone());
  1046. distance = originCopy.distanceTo( point);
  1047. if ( distance < this.near ) continue;
  1048. if ( distance > this.far ) continue;
  1049. intersect = {
  1050. distance: distance,
  1051. point: point,
  1052. face: face,
  1053. faceIndex: f,
  1054. object: object
  1055. };
  1056. intersects.push( intersect );
  1057. }
  1058. } else if ( face instanceof THREE.Face4 ) {
  1059. a = vertices[ face.a ];
  1060. b = vertices[ face.b ];
  1061. c = vertices[ face.c ];
  1062. d = vertices[ face.d ];
  1063. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  1064. var point = object.matrixWorld.multiplyVector3(intersectPoint.clone());
  1065. distance = originCopy.distanceTo( point);
  1066. if ( distance < this.near ) continue;
  1067. if ( distance > this.far ) continue;
  1068. intersect = {
  1069. distance: distance,
  1070. point: point,
  1071. face: face,
  1072. faceIndex: f,
  1073. object: object
  1074. };
  1075. intersects.push( intersect );
  1076. }
  1077. }
  1078. }
  1079. }
  1080. }
  1081. intersects.sort( descSort );
  1082. return intersects;
  1083. };
  1084. this.intersectObjects = function ( objects, recursive ) {
  1085. var intersects = [];
  1086. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  1087. Array.prototype.push.apply( intersects, this.intersectObject( objects[ i ], recursive ) );
  1088. }
  1089. intersects.sort( descSort );
  1090. return intersects;
  1091. };
  1092. };
  1093. /**
  1094. * @author mrdoob / http://mrdoob.com/
  1095. */
  1096. THREE.Rectangle = function () {
  1097. var _left = 0;
  1098. var _top = 0;
  1099. var _right = 0;
  1100. var _bottom = 0;
  1101. var _width = 0;
  1102. var _height = 0;
  1103. var _isEmpty = true;
  1104. function resize() {
  1105. _width = _right - _left;
  1106. _height = _bottom - _top;
  1107. }
  1108. this.getX = function () {
  1109. return _left;
  1110. };
  1111. this.getY = function () {
  1112. return _top;
  1113. };
  1114. this.getWidth = function () {
  1115. return _width;
  1116. };
  1117. this.getHeight = function () {
  1118. return _height;
  1119. };
  1120. this.getLeft = function() {
  1121. return _left;
  1122. };
  1123. this.getTop = function() {
  1124. return _top;
  1125. };
  1126. this.getRight = function() {
  1127. return _right;
  1128. };
  1129. this.getBottom = function() {
  1130. return _bottom;
  1131. };
  1132. this.set = function ( left, top, right, bottom ) {
  1133. _isEmpty = false;
  1134. _left = left; _top = top;
  1135. _right = right; _bottom = bottom;
  1136. resize();
  1137. };
  1138. this.addPoint = function ( x, y ) {
  1139. if ( _isEmpty === true ) {
  1140. _isEmpty = false;
  1141. _left = x; _top = y;
  1142. _right = x; _bottom = y;
  1143. resize();
  1144. } else {
  1145. _left = _left < x ? _left : x; // Math.min( _left, x );
  1146. _top = _top < y ? _top : y; // Math.min( _top, y );
  1147. _right = _right > x ? _right : x; // Math.max( _right, x );
  1148. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  1149. resize();
  1150. }
  1151. };
  1152. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  1153. if ( _isEmpty === true ) {
  1154. _isEmpty = false;
  1155. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  1156. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  1157. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  1158. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  1159. resize();
  1160. } else {
  1161. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  1162. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  1163. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  1164. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  1165. resize();
  1166. };
  1167. };
  1168. this.addRectangle = function ( r ) {
  1169. if ( _isEmpty === true ) {
  1170. _isEmpty = false;
  1171. _left = r.getLeft(); _top = r.getTop();
  1172. _right = r.getRight(); _bottom = r.getBottom();
  1173. resize();
  1174. } else {
  1175. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  1176. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  1177. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  1178. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  1179. resize();
  1180. }
  1181. };
  1182. this.inflate = function ( v ) {
  1183. _left -= v; _top -= v;
  1184. _right += v; _bottom += v;
  1185. resize();
  1186. };
  1187. this.minSelf = function ( r ) {
  1188. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  1189. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  1190. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  1191. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  1192. resize();
  1193. };
  1194. this.intersects = function ( r ) {
  1195. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  1196. if ( _right < r.getLeft() ) return false;
  1197. if ( _left > r.getRight() ) return false;
  1198. if ( _bottom < r.getTop() ) return false;
  1199. if ( _top > r.getBottom() ) return false;
  1200. return true;
  1201. };
  1202. this.empty = function () {
  1203. _isEmpty = true;
  1204. _left = 0; _top = 0;
  1205. _right = 0; _bottom = 0;
  1206. resize();
  1207. };
  1208. this.isEmpty = function () {
  1209. return _isEmpty;
  1210. };
  1211. };
  1212. /**
  1213. * @author alteredq / http://alteredqualia.com/
  1214. */
  1215. THREE.Math = {
  1216. // Clamp value to range <a, b>
  1217. clamp: function ( x, a, b ) {
  1218. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  1219. },
  1220. // Clamp value to range <a, inf)
  1221. clampBottom: function ( x, a ) {
  1222. return x < a ? a : x;
  1223. },
  1224. // Linear mapping from range <a1, a2> to range <b1, b2>
  1225. mapLinear: function ( x, a1, a2, b1, b2 ) {
  1226. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1227. },
  1228. // Random float from <0, 1> with 16 bits of randomness
  1229. // (standard Math.random() creates repetitive patterns when applied over larger space)
  1230. random16: function () {
  1231. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  1232. },
  1233. // Random integer from <low, high> interval
  1234. randInt: function ( low, high ) {
  1235. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1236. },
  1237. // Random float from <low, high> interval
  1238. randFloat: function ( low, high ) {
  1239. return low + Math.random() * ( high - low );
  1240. },
  1241. // Random float from <-range/2, range/2> interval
  1242. randFloatSpread: function ( range ) {
  1243. return range * ( 0.5 - Math.random() );
  1244. },
  1245. sign: function ( x ) {
  1246. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  1247. }
  1248. };
  1249. /**
  1250. * @author alteredq / http://alteredqualia.com/
  1251. */
  1252. THREE.Matrix3 = function () {
  1253. this.elements = new Float32Array(9);
  1254. };
  1255. THREE.Matrix3.prototype = {
  1256. constructor: THREE.Matrix3,
  1257. getInverse: function ( matrix ) {
  1258. // input: THREE.Matrix4
  1259. // ( based on http://code.google.com/p/webgl-mjs/ )
  1260. var me = matrix.elements;
  1261. var a11 = me[10] * me[5] - me[6] * me[9];
  1262. var a21 = - me[10] * me[1] + me[2] * me[9];
  1263. var a31 = me[6] * me[1] - me[2] * me[5];
  1264. var a12 = - me[10] * me[4] + me[6] * me[8];
  1265. var a22 = me[10] * me[0] - me[2] * me[8];
  1266. var a32 = - me[6] * me[0] + me[2] * me[4];
  1267. var a13 = me[9] * me[4] - me[5] * me[8];
  1268. var a23 = - me[9] * me[0] + me[1] * me[8];
  1269. var a33 = me[5] * me[0] - me[1] * me[4];
  1270. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  1271. // no inverse
  1272. if ( det === 0 ) {
  1273. console.warn( "Matrix3.getInverse(): determinant == 0" );
  1274. }
  1275. var idet = 1.0 / det;
  1276. var m = this.elements;
  1277. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  1278. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  1279. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  1280. return this;
  1281. },
  1282. transpose: function () {
  1283. var tmp, m = this.elements;
  1284. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  1285. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  1286. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  1287. return this;
  1288. },
  1289. transposeIntoArray: function ( r ) {
  1290. var m = this.m;
  1291. r[ 0 ] = m[ 0 ];
  1292. r[ 1 ] = m[ 3 ];
  1293. r[ 2 ] = m[ 6 ];
  1294. r[ 3 ] = m[ 1 ];
  1295. r[ 4 ] = m[ 4 ];
  1296. r[ 5 ] = m[ 7 ];
  1297. r[ 6 ] = m[ 2 ];
  1298. r[ 7 ] = m[ 5 ];
  1299. r[ 8 ] = m[ 8 ];
  1300. return this;
  1301. }
  1302. };
  1303. /**
  1304. * @author mrdoob / http://mrdoob.com/
  1305. * @author supereggbert / http://www.paulbrunt.co.uk/
  1306. * @author philogb / http://blog.thejit.org/
  1307. * @author jordi_ros / http://plattsoft.com
  1308. * @author D1plo1d / http://github.com/D1plo1d
  1309. * @author alteredq / http://alteredqualia.com/
  1310. * @author mikael emtinger / http://gomo.se/
  1311. * @author timknip / http://www.floorplanner.com/
  1312. */
  1313. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1314. this.elements = new Float32Array( 16 );
  1315. this.set(
  1316. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1317. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1318. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1319. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1320. );
  1321. };
  1322. THREE.Matrix4.prototype = {
  1323. constructor: THREE.Matrix4,
  1324. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1325. var te = this.elements;
  1326. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1327. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1328. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1329. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1330. return this;
  1331. },
  1332. identity: function () {
  1333. this.set(
  1334. 1, 0, 0, 0,
  1335. 0, 1, 0, 0,
  1336. 0, 0, 1, 0,
  1337. 0, 0, 0, 1
  1338. );
  1339. return this;
  1340. },
  1341. copy: function ( m ) {
  1342. var me = m.elements;
  1343. this.set(
  1344. me[0], me[4], me[8], me[12],
  1345. me[1], me[5], me[9], me[13],
  1346. me[2], me[6], me[10], me[14],
  1347. me[3], me[7], me[11], me[15]
  1348. );
  1349. return this;
  1350. },
  1351. lookAt: function ( eye, target, up ) {
  1352. var te = this.elements;
  1353. var x = THREE.Matrix4.__v1;
  1354. var y = THREE.Matrix4.__v2;
  1355. var z = THREE.Matrix4.__v3;
  1356. z.sub( eye, target ).normalize();
  1357. if ( z.length() === 0 ) {
  1358. z.z = 1;
  1359. }
  1360. x.cross( up, z ).normalize();
  1361. if ( x.length() === 0 ) {
  1362. z.x += 0.0001;
  1363. x.cross( up, z ).normalize();
  1364. }
  1365. y.cross( z, x );
  1366. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1367. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1368. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1369. return this;
  1370. },
  1371. multiply: function ( a, b ) {
  1372. var ae = a.elements;
  1373. var be = b.elements;
  1374. var te = this.elements;
  1375. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1376. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1377. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1378. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1379. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1380. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1381. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1382. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1383. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1384. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1385. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1386. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1387. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1388. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1389. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1390. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1391. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1392. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1393. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1394. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1395. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1396. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1397. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1398. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1399. return this;
  1400. },
  1401. multiplySelf: function ( m ) {
  1402. return this.multiply( this, m );
  1403. },
  1404. multiplyToArray: function ( a, b, r ) {
  1405. var te = this.elements;
  1406. this.multiply( a, b );
  1407. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1408. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1409. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1410. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1411. return this;
  1412. },
  1413. multiplyScalar: function ( s ) {
  1414. var te = this.elements;
  1415. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1416. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1417. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1418. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1419. return this;
  1420. },
  1421. multiplyVector3: function ( v ) {
  1422. var te = this.elements;
  1423. var vx = v.x, vy = v.y, vz = v.z;
  1424. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1425. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1426. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1427. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1428. return v;
  1429. },
  1430. multiplyVector4: function ( v ) {
  1431. var te = this.elements;
  1432. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1433. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1434. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1435. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1436. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1437. return v;
  1438. },
  1439. multiplyVector3Array: function ( a ) {
  1440. var tmp = THREE.Matrix4.__v1;
  1441. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1442. tmp.x = a[ i ];
  1443. tmp.y = a[ i + 1 ];
  1444. tmp.z = a[ i + 2 ];
  1445. this.multiplyVector3( tmp );
  1446. a[ i ] = tmp.x;
  1447. a[ i + 1 ] = tmp.y;
  1448. a[ i + 2 ] = tmp.z;
  1449. }
  1450. return a;
  1451. },
  1452. rotateAxis: function ( v ) {
  1453. var te = this.elements;
  1454. var vx = v.x, vy = v.y, vz = v.z;
  1455. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1456. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1457. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1458. v.normalize();
  1459. return v;
  1460. },
  1461. crossVector: function ( a ) {
  1462. var te = this.elements;
  1463. var v = new THREE.Vector4();
  1464. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1465. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1466. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1467. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1468. return v;
  1469. },
  1470. determinant: function () {
  1471. var te = this.elements;
  1472. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1473. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1474. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1475. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1476. //TODO: make this more efficient
  1477. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1478. return (
  1479. n14 * n23 * n32 * n41-
  1480. n13 * n24 * n32 * n41-
  1481. n14 * n22 * n33 * n41+
  1482. n12 * n24 * n33 * n41+
  1483. n13 * n22 * n34 * n41-
  1484. n12 * n23 * n34 * n41-
  1485. n14 * n23 * n31 * n42+
  1486. n13 * n24 * n31 * n42+
  1487. n14 * n21 * n33 * n42-
  1488. n11 * n24 * n33 * n42-
  1489. n13 * n21 * n34 * n42+
  1490. n11 * n23 * n34 * n42+
  1491. n14 * n22 * n31 * n43-
  1492. n12 * n24 * n31 * n43-
  1493. n14 * n21 * n32 * n43+
  1494. n11 * n24 * n32 * n43+
  1495. n12 * n21 * n34 * n43-
  1496. n11 * n22 * n34 * n43-
  1497. n13 * n22 * n31 * n44+
  1498. n12 * n23 * n31 * n44+
  1499. n13 * n21 * n32 * n44-
  1500. n11 * n23 * n32 * n44-
  1501. n12 * n21 * n33 * n44+
  1502. n11 * n22 * n33 * n44
  1503. );
  1504. },
  1505. transpose: function () {
  1506. var te = this.elements;
  1507. var tmp;
  1508. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1509. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1510. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1511. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1512. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1513. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1514. return this;
  1515. },
  1516. flattenToArray: function ( flat ) {
  1517. var te = this.elements;
  1518. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1519. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1520. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1521. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1522. return flat;
  1523. },
  1524. flattenToArrayOffset: function( flat, offset ) {
  1525. var te = this.elements;
  1526. flat[ offset ] = te[0];
  1527. flat[ offset + 1 ] = te[1];
  1528. flat[ offset + 2 ] = te[2];
  1529. flat[ offset + 3 ] = te[3];
  1530. flat[ offset + 4 ] = te[4];
  1531. flat[ offset + 5 ] = te[5];
  1532. flat[ offset + 6 ] = te[6];
  1533. flat[ offset + 7 ] = te[7];
  1534. flat[ offset + 8 ] = te[8];
  1535. flat[ offset + 9 ] = te[9];
  1536. flat[ offset + 10 ] = te[10];
  1537. flat[ offset + 11 ] = te[11];
  1538. flat[ offset + 12 ] = te[12];
  1539. flat[ offset + 13 ] = te[13];
  1540. flat[ offset + 14 ] = te[14];
  1541. flat[ offset + 15 ] = te[15];
  1542. return flat;
  1543. },
  1544. getPosition: function () {
  1545. var te = this.elements;
  1546. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1547. },
  1548. setPosition: function ( v ) {
  1549. var te = this.elements;
  1550. te[12] = v.x;
  1551. te[13] = v.y;
  1552. te[14] = v.z;
  1553. return this;
  1554. },
  1555. getColumnX: function () {
  1556. var te = this.elements;
  1557. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1558. },
  1559. getColumnY: function () {
  1560. var te = this.elements;
  1561. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1562. },
  1563. getColumnZ: function() {
  1564. var te = this.elements;
  1565. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1566. },
  1567. getInverse: function ( m ) {
  1568. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1569. var te = this.elements;
  1570. var me = m.elements;
  1571. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1572. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1573. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1574. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1575. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1576. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1577. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1578. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1579. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1580. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1581. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1582. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1583. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1584. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1585. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1586. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1587. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1588. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1589. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1590. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1591. this.multiplyScalar( 1 / m.determinant() );
  1592. return this;
  1593. },
  1594. setRotationFromEuler: function ( v, order ) {
  1595. var te = this.elements;
  1596. var x = v.x, y = v.y, z = v.z;
  1597. var a = Math.cos( x ), b = Math.sin( x );
  1598. var c = Math.cos( y ), d = Math.sin( y );
  1599. var e = Math.cos( z ), f = Math.sin( z );
  1600. if ( order === undefined || order === 'XYZ' ) {
  1601. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1602. te[0] = c * e;
  1603. te[4] = - c * f;
  1604. te[8] = d;
  1605. te[1] = af + be * d;
  1606. te[5] = ae - bf * d;
  1607. te[9] = - b * c;
  1608. te[2] = bf - ae * d;
  1609. te[6] = be + af * d;
  1610. te[10] = a * c;
  1611. } else if ( order === 'YXZ' ) {
  1612. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1613. te[0] = ce + df * b;
  1614. te[4] = de * b - cf;
  1615. te[8] = a * d;
  1616. te[1] = a * f;
  1617. te[5] = a * e;
  1618. te[9] = - b;
  1619. te[2] = cf * b - de;
  1620. te[6] = df + ce * b;
  1621. te[10] = a * c;
  1622. } else if ( order === 'ZXY' ) {
  1623. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1624. te[0] = ce - df * b;
  1625. te[4] = - a * f;
  1626. te[8] = de + cf * b;
  1627. te[1] = cf + de * b;
  1628. te[5] = a * e;
  1629. te[9] = df - ce * b;
  1630. te[2] = - a * d;
  1631. te[6] = b;
  1632. te[10] = a * c;
  1633. } else if ( order === 'ZYX' ) {
  1634. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1635. te[0] = c * e;
  1636. te[4] = be * d - af;
  1637. te[8] = ae * d + bf;
  1638. te[1] = c * f;
  1639. te[5] = bf * d + ae;
  1640. te[9] = af * d - be;
  1641. te[2] = - d;
  1642. te[6] = b * c;
  1643. te[10] = a * c;
  1644. } else if ( order === 'YZX' ) {
  1645. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1646. te[0] = c * e;
  1647. te[4] = bd - ac * f;
  1648. te[8] = bc * f + ad;
  1649. te[1] = f;
  1650. te[5] = a * e;
  1651. te[9] = - b * e;
  1652. te[2] = - d * e;
  1653. te[6] = ad * f + bc;
  1654. te[10] = ac - bd * f;
  1655. } else if ( order === 'XZY' ) {
  1656. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1657. te[0] = c * e;
  1658. te[4] = - f;
  1659. te[8] = d * e;
  1660. te[1] = ac * f + bd;
  1661. te[5] = a * e;
  1662. te[9] = ad * f - bc;
  1663. te[2] = bc * f - ad;
  1664. te[6] = b * e;
  1665. te[10] = bd * f + ac;
  1666. }
  1667. return this;
  1668. },
  1669. setRotationFromQuaternion: function ( q ) {
  1670. var te = this.elements;
  1671. var x = q.x, y = q.y, z = q.z, w = q.w;
  1672. var x2 = x + x, y2 = y + y, z2 = z + z;
  1673. var xx = x * x2, xy = x * y2, xz = x * z2;
  1674. var yy = y * y2, yz = y * z2, zz = z * z2;
  1675. var wx = w * x2, wy = w * y2, wz = w * z2;
  1676. te[0] = 1 - ( yy + zz );
  1677. te[4] = xy - wz;
  1678. te[8] = xz + wy;
  1679. te[1] = xy + wz;
  1680. te[5] = 1 - ( xx + zz );
  1681. te[9] = yz - wx;
  1682. te[2] = xz - wy;
  1683. te[6] = yz + wx;
  1684. te[10] = 1 - ( xx + yy );
  1685. return this;
  1686. },
  1687. compose: function ( translation, rotation, scale ) {
  1688. var te = this.elements;
  1689. var mRotation = THREE.Matrix4.__m1;
  1690. var mScale = THREE.Matrix4.__m2;
  1691. mRotation.identity();
  1692. mRotation.setRotationFromQuaternion( rotation );
  1693. mScale.makeScale( scale.x, scale.y, scale.z );
  1694. this.multiply( mRotation, mScale );
  1695. te[12] = translation.x;
  1696. te[13] = translation.y;
  1697. te[14] = translation.z;
  1698. return this;
  1699. },
  1700. decompose: function ( translation, rotation, scale ) {
  1701. var te = this.elements;
  1702. // grab the axis vectors
  1703. var x = THREE.Matrix4.__v1;
  1704. var y = THREE.Matrix4.__v2;
  1705. var z = THREE.Matrix4.__v3;
  1706. x.set( te[0], te[1], te[2] );
  1707. y.set( te[4], te[5], te[6] );
  1708. z.set( te[8], te[9], te[10] );
  1709. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1710. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1711. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1712. scale.x = x.length();
  1713. scale.y = y.length();
  1714. scale.z = z.length();
  1715. translation.x = te[12];
  1716. translation.y = te[13];
  1717. translation.z = te[14];
  1718. // scale the rotation part
  1719. var matrix = THREE.Matrix4.__m1;
  1720. matrix.copy( this );
  1721. matrix.elements[0] /= scale.x;
  1722. matrix.elements[1] /= scale.x;
  1723. matrix.elements[2] /= scale.x;
  1724. matrix.elements[4] /= scale.y;
  1725. matrix.elements[5] /= scale.y;
  1726. matrix.elements[6] /= scale.y;
  1727. matrix.elements[8] /= scale.z;
  1728. matrix.elements[9] /= scale.z;
  1729. matrix.elements[10] /= scale.z;
  1730. rotation.setFromRotationMatrix( matrix );
  1731. return [ translation, rotation, scale ];
  1732. },
  1733. extractPosition: function ( m ) {
  1734. var te = this.elements;
  1735. var me = m.elements;
  1736. te[12] = me[12];
  1737. te[13] = me[13];
  1738. te[14] = me[14];
  1739. return this;
  1740. },
  1741. extractRotation: function ( m ) {
  1742. var te = this.elements;
  1743. var me = m.elements;
  1744. var vector = THREE.Matrix4.__v1;
  1745. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1746. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1747. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1748. te[0] = me[0] * scaleX;
  1749. te[1] = me[1] * scaleX;
  1750. te[2] = me[2] * scaleX;
  1751. te[4] = me[4] * scaleY;
  1752. te[5] = me[5] * scaleY;
  1753. te[6] = me[6] * scaleY;
  1754. te[8] = me[8] * scaleZ;
  1755. te[9] = me[9] * scaleZ;
  1756. te[10] = me[10] * scaleZ;
  1757. return this;
  1758. },
  1759. //
  1760. translate: function ( v ) {
  1761. var te = this.elements;
  1762. var x = v.x, y = v.y, z = v.z;
  1763. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1764. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1765. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1766. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1767. return this;
  1768. },
  1769. rotateX: function ( angle ) {
  1770. var te = this.elements;
  1771. var m12 = te[4];
  1772. var m22 = te[5];
  1773. var m32 = te[6];
  1774. var m42 = te[7];
  1775. var m13 = te[8];
  1776. var m23 = te[9];
  1777. var m33 = te[10];
  1778. var m43 = te[11];
  1779. var c = Math.cos( angle );
  1780. var s = Math.sin( angle );
  1781. te[4] = c * m12 + s * m13;
  1782. te[5] = c * m22 + s * m23;
  1783. te[6] = c * m32 + s * m33;
  1784. te[7] = c * m42 + s * m43;
  1785. te[8] = c * m13 - s * m12;
  1786. te[9] = c * m23 - s * m22;
  1787. te[10] = c * m33 - s * m32;
  1788. te[11] = c * m43 - s * m42;
  1789. return this;
  1790. },
  1791. rotateY: function ( angle ) {
  1792. var te = this.elements;
  1793. var m11 = te[0];
  1794. var m21 = te[1];
  1795. var m31 = te[2];
  1796. var m41 = te[3];
  1797. var m13 = te[8];
  1798. var m23 = te[9];
  1799. var m33 = te[10];
  1800. var m43 = te[11];
  1801. var c = Math.cos( angle );
  1802. var s = Math.sin( angle );
  1803. te[0] = c * m11 - s * m13;
  1804. te[1] = c * m21 - s * m23;
  1805. te[2] = c * m31 - s * m33;
  1806. te[3] = c * m41 - s * m43;
  1807. te[8] = c * m13 + s * m11;
  1808. te[9] = c * m23 + s * m21;
  1809. te[10] = c * m33 + s * m31;
  1810. te[11] = c * m43 + s * m41;
  1811. return this;
  1812. },
  1813. rotateZ: function ( angle ) {
  1814. var te = this.elements;
  1815. var m11 = te[0];
  1816. var m21 = te[1];
  1817. var m31 = te[2];
  1818. var m41 = te[3];
  1819. var m12 = te[4];
  1820. var m22 = te[5];
  1821. var m32 = te[6];
  1822. var m42 = te[7];
  1823. var c = Math.cos( angle );
  1824. var s = Math.sin( angle );
  1825. te[0] = c * m11 + s * m12;
  1826. te[1] = c * m21 + s * m22;
  1827. te[2] = c * m31 + s * m32;
  1828. te[3] = c * m41 + s * m42;
  1829. te[4] = c * m12 - s * m11;
  1830. te[5] = c * m22 - s * m21;
  1831. te[6] = c * m32 - s * m31;
  1832. te[7] = c * m42 - s * m41;
  1833. return this;
  1834. },
  1835. rotateByAxis: function ( axis, angle ) {
  1836. var te = this.elements;
  1837. // optimize by checking axis
  1838. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1839. return this.rotateX( angle );
  1840. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1841. return this.rotateY( angle );
  1842. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1843. return this.rotateZ( angle );
  1844. }
  1845. var x = axis.x, y = axis.y, z = axis.z;
  1846. var n = Math.sqrt(x * x + y * y + z * z);
  1847. x /= n;
  1848. y /= n;
  1849. z /= n;
  1850. var xx = x * x, yy = y * y, zz = z * z;
  1851. var c = Math.cos( angle );
  1852. var s = Math.sin( angle );
  1853. var oneMinusCosine = 1 - c;
  1854. var xy = x * y * oneMinusCosine;
  1855. var xz = x * z * oneMinusCosine;
  1856. var yz = y * z * oneMinusCosine;
  1857. var xs = x * s;
  1858. var ys = y * s;
  1859. var zs = z * s;
  1860. var r11 = xx + (1 - xx) * c;
  1861. var r21 = xy + zs;
  1862. var r31 = xz - ys;
  1863. var r12 = xy - zs;
  1864. var r22 = yy + (1 - yy) * c;
  1865. var r32 = yz + xs;
  1866. var r13 = xz + ys;
  1867. var r23 = yz - xs;
  1868. var r33 = zz + (1 - zz) * c;
  1869. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1870. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1871. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1872. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1873. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1874. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1875. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1876. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1877. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1878. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1879. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1880. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1881. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1882. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1883. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1884. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1885. return this;
  1886. },
  1887. scale: function ( v ) {
  1888. var te = this.elements;
  1889. var x = v.x, y = v.y, z = v.z;
  1890. te[0] *= x; te[4] *= y; te[8] *= z;
  1891. te[1] *= x; te[5] *= y; te[9] *= z;
  1892. te[2] *= x; te[6] *= y; te[10] *= z;
  1893. te[3] *= x; te[7] *= y; te[11] *= z;
  1894. return this;
  1895. },
  1896. getMaxScaleOnAxis: function () {
  1897. var te = this.elements;
  1898. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  1899. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  1900. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  1901. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  1902. },
  1903. //
  1904. makeTranslation: function ( x, y, z ) {
  1905. this.set(
  1906. 1, 0, 0, x,
  1907. 0, 1, 0, y,
  1908. 0, 0, 1, z,
  1909. 0, 0, 0, 1
  1910. );
  1911. return this;
  1912. },
  1913. makeRotationX: function ( theta ) {
  1914. var c = Math.cos( theta ), s = Math.sin( theta );
  1915. this.set(
  1916. 1, 0, 0, 0,
  1917. 0, c, -s, 0,
  1918. 0, s, c, 0,
  1919. 0, 0, 0, 1
  1920. );
  1921. return this;
  1922. },
  1923. makeRotationY: function ( theta ) {
  1924. var c = Math.cos( theta ), s = Math.sin( theta );
  1925. this.set(
  1926. c, 0, s, 0,
  1927. 0, 1, 0, 0,
  1928. -s, 0, c, 0,
  1929. 0, 0, 0, 1
  1930. );
  1931. return this;
  1932. },
  1933. makeRotationZ: function ( theta ) {
  1934. var c = Math.cos( theta ), s = Math.sin( theta );
  1935. this.set(
  1936. c, -s, 0, 0,
  1937. s, c, 0, 0,
  1938. 0, 0, 1, 0,
  1939. 0, 0, 0, 1
  1940. );
  1941. return this;
  1942. },
  1943. makeRotationAxis: function ( axis, angle ) {
  1944. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1945. var c = Math.cos( angle );
  1946. var s = Math.sin( angle );
  1947. var t = 1 - c;
  1948. var x = axis.x, y = axis.y, z = axis.z;
  1949. var tx = t * x, ty = t * y;
  1950. this.set(
  1951. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1952. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1953. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1954. 0, 0, 0, 1
  1955. );
  1956. return this;
  1957. },
  1958. makeScale: function ( x, y, z ) {
  1959. this.set(
  1960. x, 0, 0, 0,
  1961. 0, y, 0, 0,
  1962. 0, 0, z, 0,
  1963. 0, 0, 0, 1
  1964. );
  1965. return this;
  1966. },
  1967. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1968. var te = this.elements;
  1969. var x = 2 * near / ( right - left );
  1970. var y = 2 * near / ( top - bottom );
  1971. var a = ( right + left ) / ( right - left );
  1972. var b = ( top + bottom ) / ( top - bottom );
  1973. var c = - ( far + near ) / ( far - near );
  1974. var d = - 2 * far * near / ( far - near );
  1975. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1976. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1977. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1978. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1979. return this;
  1980. },
  1981. makePerspective: function ( fov, aspect, near, far ) {
  1982. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1983. var ymin = - ymax;
  1984. var xmin = ymin * aspect;
  1985. var xmax = ymax * aspect;
  1986. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1987. },
  1988. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1989. var te = this.elements;
  1990. var w = right - left;
  1991. var h = top - bottom;
  1992. var p = far - near;
  1993. var x = ( right + left ) / w;
  1994. var y = ( top + bottom ) / h;
  1995. var z = ( far + near ) / p;
  1996. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1997. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1998. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1999. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2000. return this;
  2001. },
  2002. clone: function () {
  2003. var te = this.elements;
  2004. return new THREE.Matrix4(
  2005. te[0], te[4], te[8], te[12],
  2006. te[1], te[5], te[9], te[13],
  2007. te[2], te[6], te[10], te[14],
  2008. te[3], te[7], te[11], te[15]
  2009. );
  2010. }
  2011. };
  2012. THREE.Matrix4.__v1 = new THREE.Vector3();
  2013. THREE.Matrix4.__v2 = new THREE.Vector3();
  2014. THREE.Matrix4.__v3 = new THREE.Vector3();
  2015. THREE.Matrix4.__m1 = new THREE.Matrix4();
  2016. THREE.Matrix4.__m2 = new THREE.Matrix4();
  2017. /**
  2018. * @author mrdoob / http://mrdoob.com/
  2019. * @author mikael emtinger / http://gomo.se/
  2020. * @author alteredq / http://alteredqualia.com/
  2021. */
  2022. THREE.Object3D = function () {
  2023. this.id = THREE.Object3DCount ++;
  2024. this.name = '';
  2025. this.properties = {};
  2026. this.parent = undefined;
  2027. this.children = [];
  2028. this.up = new THREE.Vector3( 0, 1, 0 );
  2029. this.position = new THREE.Vector3();
  2030. this.rotation = new THREE.Vector3();
  2031. this.eulerOrder = 'XYZ';
  2032. this.scale = new THREE.Vector3( 1, 1, 1 );
  2033. this.renderDepth = null;
  2034. this.rotationAutoUpdate = true;
  2035. this.matrix = new THREE.Matrix4();
  2036. this.matrixWorld = new THREE.Matrix4();
  2037. this.matrixRotationWorld = new THREE.Matrix4();
  2038. this.matrixAutoUpdate = true;
  2039. this.matrixWorldNeedsUpdate = true;
  2040. this.quaternion = new THREE.Quaternion();
  2041. this.useQuaternion = false;
  2042. this.boundRadius = 0.0;
  2043. this.boundRadiusScale = 1.0;
  2044. this.visible = true;
  2045. this.castShadow = false;
  2046. this.receiveShadow = false;
  2047. this.frustumCulled = true;
  2048. this._vector = new THREE.Vector3();
  2049. };
  2050. THREE.Object3D.prototype = {
  2051. constructor: THREE.Object3D,
  2052. applyMatrix: function ( matrix ) {
  2053. this.matrix.multiply( matrix, this.matrix );
  2054. this.scale.getScaleFromMatrix( this.matrix );
  2055. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2056. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2057. this.position.getPositionFromMatrix( this.matrix );
  2058. },
  2059. translate: function ( distance, axis ) {
  2060. this.matrix.rotateAxis( axis );
  2061. this.position.addSelf( axis.multiplyScalar( distance ) );
  2062. },
  2063. translateX: function ( distance ) {
  2064. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2065. },
  2066. translateY: function ( distance ) {
  2067. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2068. },
  2069. translateZ: function ( distance ) {
  2070. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2071. },
  2072. lookAt: function ( vector ) {
  2073. // TODO: Add hierarchy support.
  2074. this.matrix.lookAt( vector, this.position, this.up );
  2075. if ( this.rotationAutoUpdate ) {
  2076. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2077. }
  2078. },
  2079. add: function ( object ) {
  2080. if ( object === this ) {
  2081. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2082. return;
  2083. }
  2084. if ( object instanceof THREE.Object3D ) {
  2085. if ( object.parent !== undefined ) {
  2086. object.parent.remove( object );
  2087. }
  2088. object.parent = this;
  2089. this.children.push( object );
  2090. // add to scene
  2091. var scene = this;
  2092. while ( scene.parent !== undefined ) {
  2093. scene = scene.parent;
  2094. }
  2095. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2096. scene.__addObject( object );
  2097. }
  2098. }
  2099. },
  2100. remove: function ( object ) {
  2101. var index = this.children.indexOf( object );
  2102. if ( index !== - 1 ) {
  2103. object.parent = undefined;
  2104. this.children.splice( index, 1 );
  2105. // remove from scene
  2106. var scene = this;
  2107. while ( scene.parent !== undefined ) {
  2108. scene = scene.parent;
  2109. }
  2110. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2111. scene.__removeObject( object );
  2112. }
  2113. }
  2114. },
  2115. getChildByName: function ( name, recursive ) {
  2116. var c, cl, child;
  2117. for ( c = 0, cl = this.children.length; c < cl; c ++ ) {
  2118. child = this.children[ c ];
  2119. if ( child.name === name ) {
  2120. return child;
  2121. }
  2122. if ( recursive ) {
  2123. child = child.getChildByName( name, recursive );
  2124. if ( child !== undefined ) {
  2125. return child;
  2126. }
  2127. }
  2128. }
  2129. return undefined;
  2130. },
  2131. getDescendants: function ( array ) {
  2132. if ( array === undefined ) array = [];
  2133. Array.prototype.push.apply( array, this.children );
  2134. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2135. this.children[ i ].getDescendants( array );
  2136. };
  2137. return array;
  2138. },
  2139. updateMatrix: function () {
  2140. this.matrix.setPosition( this.position );
  2141. if ( this.useQuaternion === true ) {
  2142. this.matrix.setRotationFromQuaternion( this.quaternion );
  2143. } else {
  2144. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2145. }
  2146. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2147. this.matrix.scale( this.scale );
  2148. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2149. }
  2150. this.matrixWorldNeedsUpdate = true;
  2151. },
  2152. updateMatrixWorld: function ( force ) {
  2153. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2154. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2155. if ( this.parent !== undefined ) {
  2156. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2157. } else {
  2158. this.matrixWorld.copy( this.matrix );
  2159. }
  2160. this.matrixWorldNeedsUpdate = false;
  2161. force = true;
  2162. }
  2163. // update children
  2164. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2165. this.children[ i ].updateMatrixWorld( force );
  2166. }
  2167. },
  2168. worldToLocal: function ( vector ) {
  2169. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2170. },
  2171. localToWorld: function ( vector ) {
  2172. return this.matrixWorld.multiplyVector3( vector );
  2173. },
  2174. clone: function () {
  2175. // TODO
  2176. }
  2177. };
  2178. THREE.Object3D.__m1 = new THREE.Matrix4();
  2179. THREE.Object3DCount = 0;
  2180. /**
  2181. * @author mrdoob / http://mrdoob.com/
  2182. * @author supereggbert / http://www.paulbrunt.co.uk/
  2183. * @author julianwa / https://github.com/julianwa
  2184. */
  2185. THREE.Projector = function() {
  2186. var _object, _objectCount, _objectPool = [],
  2187. _vertex, _vertexCount, _vertexPool = [],
  2188. _face, _face3Count, _face3Pool = [], _face4Count, _face4Pool = [],
  2189. _line, _lineCount, _linePool = [],
  2190. _particle, _particleCount, _particlePool = [],
  2191. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  2192. _vector3 = new THREE.Vector3(),
  2193. _vector4 = new THREE.Vector4(),
  2194. _viewProjectionMatrix = new THREE.Matrix4(),
  2195. _modelViewProjectionMatrix = new THREE.Matrix4(),
  2196. _frustum = new THREE.Frustum(),
  2197. _clippedVertex1PositionScreen = new THREE.Vector4(),
  2198. _clippedVertex2PositionScreen = new THREE.Vector4(),
  2199. _face3VertexNormals;
  2200. this.projectVector = function ( vector, camera ) {
  2201. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2202. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2203. _viewProjectionMatrix.multiplyVector3( vector );
  2204. return vector;
  2205. };
  2206. this.unprojectVector = function ( vector, camera ) {
  2207. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  2208. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  2209. _viewProjectionMatrix.multiplyVector3( vector );
  2210. return vector;
  2211. };
  2212. this.pickingRay = function ( vector, camera ) {
  2213. var end, ray, t;
  2214. // set two vectors with opposing z values
  2215. vector.z = -1.0;
  2216. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  2217. this.unprojectVector( vector, camera );
  2218. this.unprojectVector( end, camera );
  2219. // find direction from vector to end
  2220. end.subSelf( vector ).normalize();
  2221. return new THREE.Ray( vector, end );
  2222. };
  2223. function projectGraph( root, sort ) {
  2224. _objectCount = 0;
  2225. _renderData.objects.length = 0;
  2226. _renderData.sprites.length = 0;
  2227. _renderData.lights.length = 0;
  2228. var projectObject = function ( object ) {
  2229. if ( object.visible === false ) return;
  2230. if ( ( object instanceof THREE.Mesh || object instanceof THREE.Line ) &&
  2231. ( object.frustumCulled === false || _frustum.contains( object ) === true ) ) {
  2232. _vector3.copy( object.matrixWorld.getPosition() );
  2233. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2234. _object = getNextObjectInPool();
  2235. _object.object = object;
  2236. _object.z = _vector3.z;
  2237. _renderData.objects.push( _object );
  2238. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  2239. _vector3.copy( object.matrixWorld.getPosition() );
  2240. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2241. _object = getNextObjectInPool();
  2242. _object.object = object;
  2243. _object.z = _vector3.z;
  2244. _renderData.sprites.push( _object );
  2245. } else if ( object instanceof THREE.Light ) {
  2246. _renderData.lights.push( object );
  2247. }
  2248. for ( var c = 0, cl = object.children.length; c < cl; c ++ ) {
  2249. projectObject( object.children[ c ] );
  2250. }
  2251. };
  2252. projectObject( root );
  2253. if ( sort === true ) _renderData.objects.sort( painterSort );
  2254. return _renderData;
  2255. };
  2256. this.projectScene = function ( scene, camera, sort ) {
  2257. var near = camera.near, far = camera.far, visible = false,
  2258. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  2259. modelMatrix, rotationMatrix,
  2260. geometry, geometryMaterials, vertices, vertex, vertexPositionScreen,
  2261. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  2262. v1, v2, v3, v4, isFaceMaterial, material, side;
  2263. _face3Count = 0;
  2264. _face4Count = 0;
  2265. _lineCount = 0;
  2266. _particleCount = 0;
  2267. _renderData.elements.length = 0;
  2268. scene.updateMatrixWorld();
  2269. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2270. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2271. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2272. _frustum.setFromMatrix( _viewProjectionMatrix );
  2273. _renderData = projectGraph( scene, false );
  2274. for ( o = 0, ol = _renderData.objects.length; o < ol; o++ ) {
  2275. object = _renderData.objects[ o ].object;
  2276. modelMatrix = object.matrixWorld;
  2277. _vertexCount = 0;
  2278. if ( object instanceof THREE.Mesh ) {
  2279. geometry = object.geometry;
  2280. geometryMaterials = object.geometry.materials;
  2281. vertices = geometry.vertices;
  2282. faces = geometry.faces;
  2283. faceVertexUvs = geometry.faceVertexUvs;
  2284. rotationMatrix = object.matrixRotationWorld.extractRotation( modelMatrix );
  2285. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2286. side = object.material.side;
  2287. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  2288. _vertex = getNextVertexInPool();
  2289. _vertex.positionWorld.copy( vertices[ v ] );
  2290. modelMatrix.multiplyVector3( _vertex.positionWorld );
  2291. _vertex.positionScreen.copy( _vertex.positionWorld );
  2292. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  2293. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  2294. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  2295. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  2296. }
  2297. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  2298. face = faces[ f ];
  2299. material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  2300. if ( material === undefined ) continue;
  2301. side = material.side;
  2302. if ( face instanceof THREE.Face3 ) {
  2303. v1 = _vertexPool[ face.a ];
  2304. v2 = _vertexPool[ face.b ];
  2305. v3 = _vertexPool[ face.c ];
  2306. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  2307. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2308. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  2309. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2310. _face = getNextFace3InPool();
  2311. _face.v1.copy( v1 );
  2312. _face.v2.copy( v2 );
  2313. _face.v3.copy( v3 );
  2314. } else {
  2315. continue;
  2316. }
  2317. } else {
  2318. continue;
  2319. }
  2320. } else if ( face instanceof THREE.Face4 ) {
  2321. v1 = _vertexPool[ face.a ];
  2322. v2 = _vertexPool[ face.b ];
  2323. v3 = _vertexPool[ face.c ];
  2324. v4 = _vertexPool[ face.d ];
  2325. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  2326. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2327. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  2328. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  2329. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  2330. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2331. _face = getNextFace4InPool();
  2332. _face.v1.copy( v1 );
  2333. _face.v2.copy( v2 );
  2334. _face.v3.copy( v3 );
  2335. _face.v4.copy( v4 );
  2336. } else {
  2337. continue;
  2338. }
  2339. } else {
  2340. continue;
  2341. }
  2342. }
  2343. _face.normalWorld.copy( face.normal );
  2344. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  2345. rotationMatrix.multiplyVector3( _face.normalWorld );
  2346. _face.centroidWorld.copy( face.centroid );
  2347. modelMatrix.multiplyVector3( _face.centroidWorld );
  2348. _face.centroidScreen.copy( _face.centroidWorld );
  2349. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  2350. faceVertexNormals = face.vertexNormals;
  2351. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  2352. normal = _face.vertexNormalsWorld[ n ];
  2353. normal.copy( faceVertexNormals[ n ] );
  2354. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  2355. rotationMatrix.multiplyVector3( normal );
  2356. }
  2357. _face.vertexNormalsLength = faceVertexNormals.length;
  2358. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  2359. uvs = faceVertexUvs[ c ][ f ];
  2360. if ( uvs === undefined ) continue;
  2361. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2362. _face.uvs[ c ][ u ] = uvs[ u ];
  2363. }
  2364. }
  2365. _face.material = material;
  2366. _face.z = _face.centroidScreen.z;
  2367. _renderData.elements.push( _face );
  2368. }
  2369. } else if ( object instanceof THREE.Line ) {
  2370. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  2371. vertices = object.geometry.vertices;
  2372. v1 = getNextVertexInPool();
  2373. v1.positionScreen.copy( vertices[ 0 ] );
  2374. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2375. // Handle LineStrip and LinePieces
  2376. var step = object.type === THREE.LinePieces ? 2 : 1;
  2377. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2378. v1 = getNextVertexInPool();
  2379. v1.positionScreen.copy( vertices[ v ] );
  2380. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2381. if ( ( v + 1 ) % step > 0 ) continue;
  2382. v2 = _vertexPool[ _vertexCount - 2 ];
  2383. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2384. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2385. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  2386. // Perform the perspective divide
  2387. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2388. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2389. _line = getNextLineInPool();
  2390. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2391. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2392. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2393. _line.material = object.material;
  2394. _renderData.elements.push( _line );
  2395. }
  2396. }
  2397. }
  2398. }
  2399. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2400. object = _renderData.sprites[ o ].object;
  2401. modelMatrix = object.matrixWorld;
  2402. if ( object instanceof THREE.Particle ) {
  2403. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  2404. _viewProjectionMatrix.multiplyVector4( _vector4 );
  2405. _vector4.z /= _vector4.w;
  2406. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2407. _particle = getNextParticleInPool();
  2408. _particle.object = object;
  2409. _particle.x = _vector4.x / _vector4.w;
  2410. _particle.y = _vector4.y / _vector4.w;
  2411. _particle.z = _vector4.z;
  2412. _particle.rotation = object.rotation.z;
  2413. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2414. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2415. _particle.material = object.material;
  2416. _renderData.elements.push( _particle );
  2417. }
  2418. }
  2419. }
  2420. sort && _renderData.elements.sort( painterSort );
  2421. return _renderData;
  2422. };
  2423. // Pools
  2424. function getNextObjectInPool() {
  2425. var object;
  2426. if ( _objectCount === _objectPool.length ) {
  2427. object = new THREE.RenderableObject();
  2428. _objectPool.push( object );
  2429. } else {
  2430. object = _objectPool[ _objectCount ];
  2431. }
  2432. _objectCount ++;
  2433. return object;
  2434. }
  2435. function getNextVertexInPool() {
  2436. var vertex;
  2437. if ( _vertexCount === _vertexPool.length ) {
  2438. vertex = new THREE.RenderableVertex();
  2439. _vertexPool.push( vertex );
  2440. } else {
  2441. vertex = _vertexPool[ _vertexCount ];
  2442. }
  2443. _vertexCount ++;
  2444. return vertex;
  2445. }
  2446. function getNextFace3InPool() {
  2447. var face;
  2448. if ( _face3Count === _face3Pool.length ) {
  2449. face = new THREE.RenderableFace3();
  2450. _face3Pool.push( face );
  2451. } else {
  2452. face = _face3Pool[ _face3Count ];
  2453. }
  2454. _face3Count ++;
  2455. return face;
  2456. }
  2457. function getNextFace4InPool() {
  2458. var face;
  2459. if ( _face4Count === _face4Pool.length ) {
  2460. face = new THREE.RenderableFace4();
  2461. _face4Pool.push( face );
  2462. } else {
  2463. face = _face4Pool[ _face4Count ];
  2464. }
  2465. _face4Count ++;
  2466. return face;
  2467. }
  2468. function getNextLineInPool() {
  2469. var line;
  2470. if ( _lineCount === _linePool.length ) {
  2471. line = new THREE.RenderableLine();
  2472. _linePool.push( line );
  2473. } else {
  2474. line = _linePool[ _lineCount ];
  2475. }
  2476. _lineCount ++;
  2477. return line;
  2478. }
  2479. function getNextParticleInPool() {
  2480. var particle;
  2481. if ( _particleCount === _particlePool.length ) {
  2482. particle = new THREE.RenderableParticle();
  2483. _particlePool.push( particle );
  2484. } else {
  2485. particle = _particlePool[ _particleCount ];
  2486. }
  2487. _particleCount ++;
  2488. return particle;
  2489. }
  2490. //
  2491. function painterSort( a, b ) {
  2492. return b.z - a.z;
  2493. }
  2494. function clipLine( s1, s2 ) {
  2495. var alpha1 = 0, alpha2 = 1,
  2496. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2497. // Z = -1 and Z = +1, respectively.
  2498. bc1near = s1.z + s1.w,
  2499. bc2near = s2.z + s2.w,
  2500. bc1far = - s1.z + s1.w,
  2501. bc2far = - s2.z + s2.w;
  2502. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2503. // Both vertices lie entirely within all clip planes.
  2504. return true;
  2505. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2506. // Both vertices lie entirely outside one of the clip planes.
  2507. return false;
  2508. } else {
  2509. // The line segment spans at least one clip plane.
  2510. if ( bc1near < 0 ) {
  2511. // v1 lies outside the near plane, v2 inside
  2512. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2513. } else if ( bc2near < 0 ) {
  2514. // v2 lies outside the near plane, v1 inside
  2515. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2516. }
  2517. if ( bc1far < 0 ) {
  2518. // v1 lies outside the far plane, v2 inside
  2519. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2520. } else if ( bc2far < 0 ) {
  2521. // v2 lies outside the far plane, v2 inside
  2522. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2523. }
  2524. if ( alpha2 < alpha1 ) {
  2525. // The line segment spans two boundaries, but is outside both of them.
  2526. // (This can't happen when we're only clipping against just near/far but good
  2527. // to leave the check here for future usage if other clip planes are added.)
  2528. return false;
  2529. } else {
  2530. // Update the s1 and s2 vertices to match the clipped line segment.
  2531. s1.lerpSelf( s2, alpha1 );
  2532. s2.lerpSelf( s1, 1 - alpha2 );
  2533. return true;
  2534. }
  2535. }
  2536. }
  2537. };
  2538. /**
  2539. * @author mikael emtinger / http://gomo.se/
  2540. * @author alteredq / http://alteredqualia.com/
  2541. * @author WestLangley / http://github.com/WestLangley
  2542. */
  2543. THREE.Quaternion = function( x, y, z, w ) {
  2544. this.x = x || 0;
  2545. this.y = y || 0;
  2546. this.z = z || 0;
  2547. this.w = ( w !== undefined ) ? w : 1;
  2548. };
  2549. THREE.Quaternion.prototype = {
  2550. constructor: THREE.Quaternion,
  2551. set: function ( x, y, z, w ) {
  2552. this.x = x;
  2553. this.y = y;
  2554. this.z = z;
  2555. this.w = w;
  2556. return this;
  2557. },
  2558. copy: function ( q ) {
  2559. this.x = q.x;
  2560. this.y = q.y;
  2561. this.z = q.z;
  2562. this.w = q.w;
  2563. return this;
  2564. },
  2565. setFromEuler: function ( v, order ) {
  2566. // http://www.mathworks.com/matlabcentral/fileexchange/
  2567. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2568. // content/SpinCalc.m
  2569. var c1 = Math.cos( v.x / 2 );
  2570. var c2 = Math.cos( v.y / 2 );
  2571. var c3 = Math.cos( v.z / 2 );
  2572. var s1 = Math.sin( v.x / 2 );
  2573. var s2 = Math.sin( v.y / 2 );
  2574. var s3 = Math.sin( v.z / 2 );
  2575. if ( order === undefined || order === 'XYZ' ) {
  2576. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2577. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2578. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2579. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2580. } else if ( order === 'YXZ' ) {
  2581. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2582. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2583. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2584. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2585. } else if ( order === 'ZXY' ) {
  2586. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2587. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2588. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2589. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2590. } else if ( order === 'ZYX' ) {
  2591. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2592. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2593. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2594. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2595. } else if ( order === 'YZX' ) {
  2596. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2597. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2598. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2599. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2600. } else if ( order === 'XZY' ) {
  2601. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2602. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2603. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2604. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2605. }
  2606. return this;
  2607. },
  2608. setFromAxisAngle: function ( axis, angle ) {
  2609. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2610. // axis have to be normalized
  2611. var halfAngle = angle / 2,
  2612. s = Math.sin( halfAngle );
  2613. this.x = axis.x * s;
  2614. this.y = axis.y * s;
  2615. this.z = axis.z * s;
  2616. this.w = Math.cos( halfAngle );
  2617. return this;
  2618. },
  2619. setFromRotationMatrix: function ( m ) {
  2620. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2621. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2622. var te = m.elements,
  2623. m11 = te[0], m12 = te[4], m13 = te[8],
  2624. m21 = te[1], m22 = te[5], m23 = te[9],
  2625. m31 = te[2], m32 = te[6], m33 = te[10],
  2626. trace = m11 + m22 + m33,
  2627. s;
  2628. if( trace > 0 ) {
  2629. s = 0.5 / Math.sqrt( trace + 1.0 );
  2630. this.w = 0.25 / s;
  2631. this.x = ( m32 - m23 ) * s;
  2632. this.y = ( m13 - m31 ) * s;
  2633. this.z = ( m21 - m12 ) * s;
  2634. } else if ( m11 > m22 && m11 > m33 ) {
  2635. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2636. this.w = (m32 - m23 ) / s;
  2637. this.x = 0.25 * s;
  2638. this.y = (m12 + m21 ) / s;
  2639. this.z = (m13 + m31 ) / s;
  2640. } else if (m22 > m33) {
  2641. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2642. this.w = (m13 - m31 ) / s;
  2643. this.x = (m12 + m21 ) / s;
  2644. this.y = 0.25 * s;
  2645. this.z = (m23 + m32 ) / s;
  2646. } else {
  2647. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2648. this.w = ( m21 - m12 ) / s;
  2649. this.x = ( m13 + m31 ) / s;
  2650. this.y = ( m23 + m32 ) / s;
  2651. this.z = 0.25 * s;
  2652. }
  2653. return this;
  2654. },
  2655. calculateW : function () {
  2656. this.w = - Math.sqrt( Math.abs( 1.0 - this.x * this.x - this.y * this.y - this.z * this.z ) );
  2657. return this;
  2658. },
  2659. inverse: function () {
  2660. this.x *= -1;
  2661. this.y *= -1;
  2662. this.z *= -1;
  2663. return this;
  2664. },
  2665. length: function () {
  2666. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2667. },
  2668. normalize: function () {
  2669. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2670. if ( l === 0 ) {
  2671. this.x = 0;
  2672. this.y = 0;
  2673. this.z = 0;
  2674. this.w = 0;
  2675. } else {
  2676. l = 1 / l;
  2677. this.x = this.x * l;
  2678. this.y = this.y * l;
  2679. this.z = this.z * l;
  2680. this.w = this.w * l;
  2681. }
  2682. return this;
  2683. },
  2684. multiply: function ( a, b ) {
  2685. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2686. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2687. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2688. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2689. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2690. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2691. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2692. return this;
  2693. },
  2694. multiplySelf: function ( b ) {
  2695. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2696. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2697. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2698. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2699. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2700. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2701. return this;
  2702. },
  2703. multiplyVector3: function ( vector, dest ) {
  2704. if ( !dest ) { dest = vector; }
  2705. var x = vector.x, y = vector.y, z = vector.z,
  2706. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2707. // calculate quat * vector
  2708. var ix = qw * x + qy * z - qz * y,
  2709. iy = qw * y + qz * x - qx * z,
  2710. iz = qw * z + qx * y - qy * x,
  2711. iw = -qx * x - qy * y - qz * z;
  2712. // calculate result * inverse quat
  2713. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2714. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2715. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2716. return dest;
  2717. },
  2718. slerpSelf: function ( qb, t ) {
  2719. var x = this.x, y = this.y, z = this.z, w = this.w;
  2720. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2721. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2722. if ( cosHalfTheta < 0 ) {
  2723. this.w = -qb.w;
  2724. this.x = -qb.x;
  2725. this.y = -qb.y;
  2726. this.z = -qb.z;
  2727. cosHalfTheta = -cosHalfTheta;
  2728. } else {
  2729. this.copy( qb );
  2730. }
  2731. if ( cosHalfTheta >= 1.0 ) {
  2732. this.w = w;
  2733. this.x = x;
  2734. this.y = y;
  2735. this.z = z;
  2736. return this;
  2737. }
  2738. var halfTheta = Math.acos( cosHalfTheta );
  2739. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2740. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2741. this.w = 0.5 * ( w + this.w );
  2742. this.x = 0.5 * ( x + this.x );
  2743. this.y = 0.5 * ( y + this.y );
  2744. this.z = 0.5 * ( z + this.z );
  2745. return this;
  2746. }
  2747. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2748. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2749. this.w = ( w * ratioA + this.w * ratioB );
  2750. this.x = ( x * ratioA + this.x * ratioB );
  2751. this.y = ( y * ratioA + this.y * ratioB );
  2752. this.z = ( z * ratioA + this.z * ratioB );
  2753. return this;
  2754. },
  2755. clone: function () {
  2756. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2757. }
  2758. }
  2759. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2760. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2761. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2762. if ( cosHalfTheta < 0 ) {
  2763. qm.w = -qb.w;
  2764. qm.x = -qb.x;
  2765. qm.y = -qb.y;
  2766. qm.z = -qb.z;
  2767. cosHalfTheta = -cosHalfTheta;
  2768. } else {
  2769. qm.copy( qb );
  2770. }
  2771. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2772. qm.w = qa.w;
  2773. qm.x = qa.x;
  2774. qm.y = qa.y;
  2775. qm.z = qa.z;
  2776. return qm;
  2777. }
  2778. var halfTheta = Math.acos( cosHalfTheta );
  2779. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2780. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2781. qm.w = 0.5 * ( qa.w + qm.w );
  2782. qm.x = 0.5 * ( qa.x + qm.x );
  2783. qm.y = 0.5 * ( qa.y + qm.y );
  2784. qm.z = 0.5 * ( qa.z + qm.z );
  2785. return qm;
  2786. }
  2787. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2788. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2789. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2790. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2791. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2792. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2793. return qm;
  2794. }
  2795. /**
  2796. * @author mrdoob / http://mrdoob.com/
  2797. */
  2798. THREE.Vertex = function ( v ) {
  2799. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  2800. return v;
  2801. };
  2802. /**
  2803. * @author mrdoob / http://mrdoob.com/
  2804. * @author alteredq / http://alteredqualia.com/
  2805. */
  2806. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2807. this.a = a;
  2808. this.b = b;
  2809. this.c = c;
  2810. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2811. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2812. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2813. this.vertexColors = color instanceof Array ? color : [];
  2814. this.vertexTangents = [];
  2815. this.materialIndex = materialIndex;
  2816. this.centroid = new THREE.Vector3();
  2817. };
  2818. THREE.Face3.prototype = {
  2819. constructor: THREE.Face3,
  2820. clone: function () {
  2821. var face = new THREE.Face3( this.a, this.b, this.c );
  2822. face.normal.copy( this.normal );
  2823. face.color.copy( this.color );
  2824. face.centroid.copy( this.centroid );
  2825. face.materialIndex = this.materialIndex;
  2826. var i, il;
  2827. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2828. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2829. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2830. return face;
  2831. }
  2832. };
  2833. /**
  2834. * @author mrdoob / http://mrdoob.com/
  2835. * @author alteredq / http://alteredqualia.com/
  2836. */
  2837. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2838. this.a = a;
  2839. this.b = b;
  2840. this.c = c;
  2841. this.d = d;
  2842. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2843. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2844. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2845. this.vertexColors = color instanceof Array ? color : [];
  2846. this.vertexTangents = [];
  2847. this.materialIndex = materialIndex;
  2848. this.centroid = new THREE.Vector3();
  2849. };
  2850. THREE.Face4.prototype = {
  2851. constructor: THREE.Face4,
  2852. clone: function () {
  2853. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  2854. face.normal.copy( this.normal );
  2855. face.color.copy( this.color );
  2856. face.centroid.copy( this.centroid );
  2857. face.materialIndex = this.materialIndex;
  2858. var i, il;
  2859. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2860. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2861. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2862. return face;
  2863. }
  2864. };
  2865. /**
  2866. * @author mrdoob / http://mrdoob.com/
  2867. */
  2868. THREE.UV = function ( u, v ) {
  2869. this.u = u || 0;
  2870. this.v = v || 0;
  2871. };
  2872. THREE.UV.prototype = {
  2873. constructor: THREE.UV,
  2874. set: function ( u, v ) {
  2875. this.u = u;
  2876. this.v = v;
  2877. return this;
  2878. },
  2879. copy: function ( uv ) {
  2880. this.u = uv.u;
  2881. this.v = uv.v;
  2882. return this;
  2883. },
  2884. lerpSelf: function ( uv, alpha ) {
  2885. this.u += ( uv.u - this.u ) * alpha;
  2886. this.v += ( uv.v - this.v ) * alpha;
  2887. return this;
  2888. },
  2889. clone: function () {
  2890. return new THREE.UV( this.u, this.v );
  2891. }
  2892. };
  2893. /**
  2894. * @author mrdoob / http://mrdoob.com/
  2895. * @author kile / http://kile.stravaganza.org/
  2896. * @author alteredq / http://alteredqualia.com/
  2897. * @author mikael emtinger / http://gomo.se/
  2898. * @author zz85 / http://www.lab4games.net/zz85/blog
  2899. */
  2900. THREE.Geometry = function () {
  2901. this.id = THREE.GeometryCount ++;
  2902. this.name = '';
  2903. this.vertices = [];
  2904. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  2905. this.materials = [];
  2906. this.faces = [];
  2907. this.faceUvs = [[]];
  2908. this.faceVertexUvs = [[]];
  2909. this.morphTargets = [];
  2910. this.morphColors = [];
  2911. this.morphNormals = [];
  2912. this.skinWeights = [];
  2913. this.skinIndices = [];
  2914. this.boundingBox = null;
  2915. this.boundingSphere = null;
  2916. this.hasTangents = false;
  2917. this.dynamic = true; // the intermediate typearrays will be deleted when set to false
  2918. };
  2919. THREE.Geometry.prototype = {
  2920. constructor : THREE.Geometry,
  2921. applyMatrix: function ( matrix ) {
  2922. var matrixRotation = new THREE.Matrix4();
  2923. matrixRotation.extractRotation( matrix );
  2924. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  2925. var vertex = this.vertices[ i ];
  2926. matrix.multiplyVector3( vertex );
  2927. }
  2928. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  2929. var face = this.faces[ i ];
  2930. matrixRotation.multiplyVector3( face.normal );
  2931. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  2932. matrixRotation.multiplyVector3( face.vertexNormals[ j ] );
  2933. }
  2934. matrix.multiplyVector3( face.centroid );
  2935. }
  2936. },
  2937. computeCentroids: function () {
  2938. var f, fl, face;
  2939. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2940. face = this.faces[ f ];
  2941. face.centroid.set( 0, 0, 0 );
  2942. if ( face instanceof THREE.Face3 ) {
  2943. face.centroid.addSelf( this.vertices[ face.a ] );
  2944. face.centroid.addSelf( this.vertices[ face.b ] );
  2945. face.centroid.addSelf( this.vertices[ face.c ] );
  2946. face.centroid.divideScalar( 3 );
  2947. } else if ( face instanceof THREE.Face4 ) {
  2948. face.centroid.addSelf( this.vertices[ face.a ] );
  2949. face.centroid.addSelf( this.vertices[ face.b ] );
  2950. face.centroid.addSelf( this.vertices[ face.c ] );
  2951. face.centroid.addSelf( this.vertices[ face.d ] );
  2952. face.centroid.divideScalar( 4 );
  2953. }
  2954. }
  2955. },
  2956. computeFaceNormals: function () {
  2957. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  2958. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  2959. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2960. face = this.faces[ f ];
  2961. vA = this.vertices[ face.a ];
  2962. vB = this.vertices[ face.b ];
  2963. vC = this.vertices[ face.c ];
  2964. cb.sub( vC, vB );
  2965. ab.sub( vA, vB );
  2966. cb.crossSelf( ab );
  2967. if ( !cb.isZero() ) {
  2968. cb.normalize();
  2969. }
  2970. face.normal.copy( cb );
  2971. }
  2972. },
  2973. computeVertexNormals: function () {
  2974. var v, vl, f, fl, face, vertices;
  2975. // create internal buffers for reuse when calling this method repeatedly
  2976. // (otherwise memory allocation / deallocation every frame is big resource hog)
  2977. if ( this.__tmpVertices === undefined ) {
  2978. this.__tmpVertices = new Array( this.vertices.length );
  2979. vertices = this.__tmpVertices;
  2980. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2981. vertices[ v ] = new THREE.Vector3();
  2982. }
  2983. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2984. face = this.faces[ f ];
  2985. if ( face instanceof THREE.Face3 ) {
  2986. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2987. } else if ( face instanceof THREE.Face4 ) {
  2988. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2989. }
  2990. }
  2991. } else {
  2992. vertices = this.__tmpVertices;
  2993. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2994. vertices[ v ].set( 0, 0, 0 );
  2995. }
  2996. }
  2997. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2998. face = this.faces[ f ];
  2999. if ( face instanceof THREE.Face3 ) {
  3000. vertices[ face.a ].addSelf( face.normal );
  3001. vertices[ face.b ].addSelf( face.normal );
  3002. vertices[ face.c ].addSelf( face.normal );
  3003. } else if ( face instanceof THREE.Face4 ) {
  3004. vertices[ face.a ].addSelf( face.normal );
  3005. vertices[ face.b ].addSelf( face.normal );
  3006. vertices[ face.c ].addSelf( face.normal );
  3007. vertices[ face.d ].addSelf( face.normal );
  3008. }
  3009. }
  3010. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3011. vertices[ v ].normalize();
  3012. }
  3013. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3014. face = this.faces[ f ];
  3015. if ( face instanceof THREE.Face3 ) {
  3016. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3017. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3018. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3019. } else if ( face instanceof THREE.Face4 ) {
  3020. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3021. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3022. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3023. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3024. }
  3025. }
  3026. },
  3027. computeMorphNormals: function () {
  3028. var i, il, f, fl, face;
  3029. // save original normals
  3030. // - create temp variables on first access
  3031. // otherwise just copy (for faster repeated calls)
  3032. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3033. face = this.faces[ f ];
  3034. if ( ! face.__originalFaceNormal ) {
  3035. face.__originalFaceNormal = face.normal.clone();
  3036. } else {
  3037. face.__originalFaceNormal.copy( face.normal );
  3038. }
  3039. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3040. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3041. if ( ! face.__originalVertexNormals[ i ] ) {
  3042. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3043. } else {
  3044. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3045. }
  3046. }
  3047. }
  3048. // use temp geometry to compute face and vertex normals for each morph
  3049. var tmpGeo = new THREE.Geometry();
  3050. tmpGeo.faces = this.faces;
  3051. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3052. // create on first access
  3053. if ( ! this.morphNormals[ i ] ) {
  3054. this.morphNormals[ i ] = {};
  3055. this.morphNormals[ i ].faceNormals = [];
  3056. this.morphNormals[ i ].vertexNormals = [];
  3057. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3058. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3059. var faceNormal, vertexNormals;
  3060. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3061. face = this.faces[ f ];
  3062. faceNormal = new THREE.Vector3();
  3063. if ( face instanceof THREE.Face3 ) {
  3064. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3065. } else {
  3066. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3067. }
  3068. dstNormalsFace.push( faceNormal );
  3069. dstNormalsVertex.push( vertexNormals );
  3070. }
  3071. }
  3072. var morphNormals = this.morphNormals[ i ];
  3073. // set vertices to morph target
  3074. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3075. // compute morph normals
  3076. tmpGeo.computeFaceNormals();
  3077. tmpGeo.computeVertexNormals();
  3078. // store morph normals
  3079. var faceNormal, vertexNormals;
  3080. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3081. face = this.faces[ f ];
  3082. faceNormal = morphNormals.faceNormals[ f ];
  3083. vertexNormals = morphNormals.vertexNormals[ f ];
  3084. faceNormal.copy( face.normal );
  3085. if ( face instanceof THREE.Face3 ) {
  3086. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3087. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3088. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3089. } else {
  3090. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3091. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3092. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3093. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3094. }
  3095. }
  3096. }
  3097. // restore original normals
  3098. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3099. face = this.faces[ f ];
  3100. face.normal = face.__originalFaceNormal;
  3101. face.vertexNormals = face.__originalVertexNormals;
  3102. }
  3103. },
  3104. computeTangents: function () {
  3105. // based on http://www.terathon.com/code/tangent.html
  3106. // tangents go to vertices
  3107. var f, fl, v, vl, i, il, vertexIndex,
  3108. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3109. x1, x2, y1, y2, z1, z2,
  3110. s1, s2, t1, t2, r, t, test,
  3111. tan1 = [], tan2 = [],
  3112. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3113. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3114. n = new THREE.Vector3(), w;
  3115. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3116. tan1[ v ] = new THREE.Vector3();
  3117. tan2[ v ] = new THREE.Vector3();
  3118. }
  3119. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  3120. vA = context.vertices[ a ];
  3121. vB = context.vertices[ b ];
  3122. vC = context.vertices[ c ];
  3123. uvA = uv[ ua ];
  3124. uvB = uv[ ub ];
  3125. uvC = uv[ uc ];
  3126. x1 = vB.x - vA.x;
  3127. x2 = vC.x - vA.x;
  3128. y1 = vB.y - vA.y;
  3129. y2 = vC.y - vA.y;
  3130. z1 = vB.z - vA.z;
  3131. z2 = vC.z - vA.z;
  3132. s1 = uvB.u - uvA.u;
  3133. s2 = uvC.u - uvA.u;
  3134. t1 = uvB.v - uvA.v;
  3135. t2 = uvC.v - uvA.v;
  3136. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3137. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  3138. ( t2 * y1 - t1 * y2 ) * r,
  3139. ( t2 * z1 - t1 * z2 ) * r );
  3140. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  3141. ( s1 * y2 - s2 * y1 ) * r,
  3142. ( s1 * z2 - s2 * z1 ) * r );
  3143. tan1[ a ].addSelf( sdir );
  3144. tan1[ b ].addSelf( sdir );
  3145. tan1[ c ].addSelf( sdir );
  3146. tan2[ a ].addSelf( tdir );
  3147. tan2[ b ].addSelf( tdir );
  3148. tan2[ c ].addSelf( tdir );
  3149. }
  3150. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3151. face = this.faces[ f ];
  3152. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  3153. if ( face instanceof THREE.Face3 ) {
  3154. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  3155. } else if ( face instanceof THREE.Face4 ) {
  3156. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  3157. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  3158. }
  3159. }
  3160. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  3161. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3162. face = this.faces[ f ];
  3163. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  3164. n.copy( face.vertexNormals[ i ] );
  3165. vertexIndex = face[ faceIndex[ i ] ];
  3166. t = tan1[ vertexIndex ];
  3167. // Gram-Schmidt orthogonalize
  3168. tmp.copy( t );
  3169. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3170. // Calculate handedness
  3171. tmp2.cross( face.vertexNormals[ i ], t );
  3172. test = tmp2.dot( tan2[ vertexIndex ] );
  3173. w = (test < 0.0) ? -1.0 : 1.0;
  3174. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  3175. }
  3176. }
  3177. this.hasTangents = true;
  3178. },
  3179. computeBoundingBox: function () {
  3180. if ( ! this.boundingBox ) {
  3181. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  3182. }
  3183. if ( this.vertices.length > 0 ) {
  3184. var position, firstPosition = this.vertices[ 0 ];
  3185. this.boundingBox.min.copy( firstPosition );
  3186. this.boundingBox.max.copy( firstPosition );
  3187. var min = this.boundingBox.min,
  3188. max = this.boundingBox.max;
  3189. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  3190. position = this.vertices[ v ];
  3191. if ( position.x < min.x ) {
  3192. min.x = position.x;
  3193. } else if ( position.x > max.x ) {
  3194. max.x = position.x;
  3195. }
  3196. if ( position.y < min.y ) {
  3197. min.y = position.y;
  3198. } else if ( position.y > max.y ) {
  3199. max.y = position.y;
  3200. }
  3201. if ( position.z < min.z ) {
  3202. min.z = position.z;
  3203. } else if ( position.z > max.z ) {
  3204. max.z = position.z;
  3205. }
  3206. }
  3207. } else {
  3208. this.boundingBox.min.set( 0, 0, 0 );
  3209. this.boundingBox.max.set( 0, 0, 0 );
  3210. }
  3211. },
  3212. computeBoundingSphere: function () {
  3213. var maxRadiusSq = 0;
  3214. if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
  3215. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  3216. var radiusSq = this.vertices[ i ].lengthSq();
  3217. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3218. }
  3219. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3220. },
  3221. /*
  3222. * Checks for duplicate vertices with hashmap.
  3223. * Duplicated vertices are removed
  3224. * and faces' vertices are updated.
  3225. */
  3226. mergeVertices: function () {
  3227. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  3228. var unique = [], changes = [];
  3229. var v, key;
  3230. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  3231. var precision = Math.pow( 10, precisionPoints );
  3232. var i,il, face;
  3233. var abcd = 'abcd', o, k, j, jl, u;
  3234. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  3235. v = this.vertices[ i ];
  3236. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  3237. if ( verticesMap[ key ] === undefined ) {
  3238. verticesMap[ key ] = i;
  3239. unique.push( this.vertices[ i ] );
  3240. changes[ i ] = unique.length - 1;
  3241. } else {
  3242. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3243. changes[ i ] = changes[ verticesMap[ key ] ];
  3244. }
  3245. };
  3246. // Start to patch face indices
  3247. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  3248. face = this.faces[ i ];
  3249. if ( face instanceof THREE.Face3 ) {
  3250. face.a = changes[ face.a ];
  3251. face.b = changes[ face.b ];
  3252. face.c = changes[ face.c ];
  3253. } else if ( face instanceof THREE.Face4 ) {
  3254. face.a = changes[ face.a ];
  3255. face.b = changes[ face.b ];
  3256. face.c = changes[ face.c ];
  3257. face.d = changes[ face.d ];
  3258. // check dups in (a, b, c, d) and convert to -> face3
  3259. o = [ face.a, face.b, face.c, face.d ];
  3260. for ( k = 3; k > 0; k -- ) {
  3261. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  3262. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  3263. o.splice( k, 1 );
  3264. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  3265. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  3266. u = this.faceVertexUvs[ j ][ i ];
  3267. if ( u ) u.splice( k, 1 );
  3268. }
  3269. this.faces[ i ].vertexColors = face.vertexColors;
  3270. break;
  3271. }
  3272. }
  3273. }
  3274. }
  3275. // Use unique set of vertices
  3276. var diff = this.vertices.length - unique.length;
  3277. this.vertices = unique;
  3278. return diff;
  3279. },
  3280. clone: function () {
  3281. // TODO
  3282. }
  3283. };
  3284. THREE.GeometryCount = 0;
  3285. /**
  3286. * @author alteredq / http://alteredqualia.com/
  3287. */
  3288. THREE.BufferGeometry = function () {
  3289. this.id = THREE.GeometryCount ++;
  3290. // attributes
  3291. this.attributes = {};
  3292. // attributes typed arrays are kept only if dynamic flag is set
  3293. this.dynamic = false;
  3294. // boundings
  3295. this.boundingBox = null;
  3296. this.boundingSphere = null;
  3297. this.hasTangents = false;
  3298. // for compatibility
  3299. this.morphTargets = [];
  3300. };
  3301. THREE.BufferGeometry.prototype = {
  3302. constructor : THREE.BufferGeometry,
  3303. applyMatrix: function ( matrix ) {
  3304. var positionArray;
  3305. var normalArray;
  3306. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  3307. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  3308. if ( positionArray !== undefined ) {
  3309. matrix.multiplyVector3Array( positionArray );
  3310. this.verticesNeedUpdate = true;
  3311. }
  3312. if ( normalArray !== undefined ) {
  3313. var matrixRotation = new THREE.Matrix4();
  3314. matrixRotation.extractRotation( matrix );
  3315. matrixRotation.multiplyVector3Array( normalArray );
  3316. this.normalsNeedUpdate = true;
  3317. }
  3318. },
  3319. computeBoundingBox: function () {
  3320. if ( ! this.boundingBox ) {
  3321. this.boundingBox = {
  3322. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  3323. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  3324. };
  3325. }
  3326. var positions = this.attributes[ "position" ].array;
  3327. if ( positions ) {
  3328. var bb = this.boundingBox;
  3329. var x, y, z;
  3330. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3331. x = positions[ i ];
  3332. y = positions[ i + 1 ];
  3333. z = positions[ i + 2 ];
  3334. // bounding box
  3335. if ( x < bb.min.x ) {
  3336. bb.min.x = x;
  3337. } else if ( x > bb.max.x ) {
  3338. bb.max.x = x;
  3339. }
  3340. if ( y < bb.min.y ) {
  3341. bb.min.y = y;
  3342. } else if ( y > bb.max.y ) {
  3343. bb.max.y = y;
  3344. }
  3345. if ( z < bb.min.z ) {
  3346. bb.min.z = z;
  3347. } else if ( z > bb.max.z ) {
  3348. bb.max.z = z;
  3349. }
  3350. }
  3351. }
  3352. if ( positions === undefined || positions.length === 0 ) {
  3353. this.boundingBox.min.set( 0, 0, 0 );
  3354. this.boundingBox.max.set( 0, 0, 0 );
  3355. }
  3356. },
  3357. computeBoundingSphere: function () {
  3358. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  3359. var positions = this.attributes[ "position" ].array;
  3360. if ( positions ) {
  3361. var radiusSq, maxRadiusSq = 0;
  3362. var x, y, z;
  3363. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3364. x = positions[ i ];
  3365. y = positions[ i + 1 ];
  3366. z = positions[ i + 2 ];
  3367. radiusSq = x * x + y * y + z * z;
  3368. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3369. }
  3370. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3371. }
  3372. },
  3373. computeVertexNormals: function () {
  3374. if ( this.attributes[ "position" ] && this.attributes[ "index" ] ) {
  3375. var i, il;
  3376. var j, jl;
  3377. var nVertexElements = this.attributes[ "position" ].array.length;
  3378. if ( this.attributes[ "normal" ] === undefined ) {
  3379. this.attributes[ "normal" ] = {
  3380. itemSize: 3,
  3381. array: new Float32Array( nVertexElements ),
  3382. numItems: nVertexElements
  3383. };
  3384. } else {
  3385. // reset existing normals to zero
  3386. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  3387. this.attributes[ "normal" ].array[ i ] = 0;
  3388. }
  3389. }
  3390. var offsets = this.offsets;
  3391. var indices = this.attributes[ "index" ].array;
  3392. var positions = this.attributes[ "position" ].array;
  3393. var normals = this.attributes[ "normal" ].array;
  3394. var vA, vB, vC, x, y, z,
  3395. pA = new THREE.Vector3(),
  3396. pB = new THREE.Vector3(),
  3397. pC = new THREE.Vector3(),
  3398. cb = new THREE.Vector3(),
  3399. ab = new THREE.Vector3();
  3400. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3401. var start = offsets[ j ].start;
  3402. var count = offsets[ j ].count;
  3403. var index = offsets[ j ].index;
  3404. for ( i = start, il = start + count; i < il; i += 3 ) {
  3405. vA = index + indices[ i ];
  3406. vB = index + indices[ i + 1 ];
  3407. vC = index + indices[ i + 2 ];
  3408. x = positions[ vA * 3 ];
  3409. y = positions[ vA * 3 + 1 ];
  3410. z = positions[ vA * 3 + 2 ];
  3411. pA.set( x, y, z );
  3412. x = positions[ vB * 3 ];
  3413. y = positions[ vB * 3 + 1 ];
  3414. z = positions[ vB * 3 + 2 ];
  3415. pB.set( x, y, z );
  3416. x = positions[ vC * 3 ];
  3417. y = positions[ vC * 3 + 1 ];
  3418. z = positions[ vC * 3 + 2 ];
  3419. pC.set( x, y, z );
  3420. cb.sub( pC, pB );
  3421. ab.sub( pA, pB );
  3422. cb.crossSelf( ab );
  3423. normals[ vA * 3 ] += cb.x;
  3424. normals[ vA * 3 + 1 ] += cb.y;
  3425. normals[ vA * 3 + 2 ] += cb.z;
  3426. normals[ vB * 3 ] += cb.x;
  3427. normals[ vB * 3 + 1 ] += cb.y;
  3428. normals[ vB * 3 + 2 ] += cb.z;
  3429. normals[ vC * 3 ] += cb.x;
  3430. normals[ vC * 3 + 1 ] += cb.y;
  3431. normals[ vC * 3 + 2 ] += cb.z;
  3432. }
  3433. }
  3434. // normalize normals
  3435. for ( i = 0, il = normals.length; i < il; i += 3 ) {
  3436. x = normals[ i ];
  3437. y = normals[ i + 1 ];
  3438. z = normals[ i + 2 ];
  3439. var n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  3440. normals[ i ] *= n;
  3441. normals[ i + 1 ] *= n;
  3442. normals[ i + 2 ] *= n;
  3443. }
  3444. this.normalsNeedUpdate = true;
  3445. }
  3446. },
  3447. computeTangents: function () {
  3448. // based on http://www.terathon.com/code/tangent.html
  3449. // (per vertex tangents)
  3450. if ( this.attributes[ "index" ] === undefined ||
  3451. this.attributes[ "position" ] === undefined ||
  3452. this.attributes[ "normal" ] === undefined ||
  3453. this.attributes[ "uv" ] === undefined ) {
  3454. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  3455. return;
  3456. }
  3457. var indices = this.attributes[ "index" ].array;
  3458. var positions = this.attributes[ "position" ].array;
  3459. var normals = this.attributes[ "normal" ].array;
  3460. var uvs = this.attributes[ "uv" ].array;
  3461. var nVertices = positions.length / 3;
  3462. if ( this.attributes[ "tangent" ] === undefined ) {
  3463. var nTangentElements = 4 * nVertices;
  3464. this.attributes[ "tangent" ] = {
  3465. itemSize: 4,
  3466. array: new Float32Array( nTangentElements ),
  3467. numItems: nTangentElements
  3468. };
  3469. }
  3470. var tangents = this.attributes[ "tangent" ].array;
  3471. var tan1 = [], tan2 = [];
  3472. for ( var k = 0; k < nVertices; k ++ ) {
  3473. tan1[ k ] = new THREE.Vector3();
  3474. tan2[ k ] = new THREE.Vector3();
  3475. }
  3476. var xA, yA, zA,
  3477. xB, yB, zB,
  3478. xC, yC, zC,
  3479. uA, vA,
  3480. uB, vB,
  3481. uC, vC,
  3482. x1, x2, y1, y2, z1, z2,
  3483. s1, s2, t1, t2, r;
  3484. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  3485. function handleTriangle( a, b, c ) {
  3486. xA = positions[ a * 3 ];
  3487. yA = positions[ a * 3 + 1 ];
  3488. zA = positions[ a * 3 + 2 ];
  3489. xB = positions[ b * 3 ];
  3490. yB = positions[ b * 3 + 1 ];
  3491. zB = positions[ b * 3 + 2 ];
  3492. xC = positions[ c * 3 ];
  3493. yC = positions[ c * 3 + 1 ];
  3494. zC = positions[ c * 3 + 2 ];
  3495. uA = uvs[ a * 2 ];
  3496. vA = uvs[ a * 2 + 1 ];
  3497. uB = uvs[ b * 2 ];
  3498. vB = uvs[ b * 2 + 1 ];
  3499. uC = uvs[ c * 2 ];
  3500. vC = uvs[ c * 2 + 1 ];
  3501. x1 = xB - xA;
  3502. x2 = xC - xA;
  3503. y1 = yB - yA;
  3504. y2 = yC - yA;
  3505. z1 = zB - zA;
  3506. z2 = zC - zA;
  3507. s1 = uB - uA;
  3508. s2 = uC - uA;
  3509. t1 = vB - vA;
  3510. t2 = vC - vA;
  3511. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3512. sdir.set(
  3513. ( t2 * x1 - t1 * x2 ) * r,
  3514. ( t2 * y1 - t1 * y2 ) * r,
  3515. ( t2 * z1 - t1 * z2 ) * r
  3516. );
  3517. tdir.set(
  3518. ( s1 * x2 - s2 * x1 ) * r,
  3519. ( s1 * y2 - s2 * y1 ) * r,
  3520. ( s1 * z2 - s2 * z1 ) * r
  3521. );
  3522. tan1[ a ].addSelf( sdir );
  3523. tan1[ b ].addSelf( sdir );
  3524. tan1[ c ].addSelf( sdir );
  3525. tan2[ a ].addSelf( tdir );
  3526. tan2[ b ].addSelf( tdir );
  3527. tan2[ c ].addSelf( tdir );
  3528. }
  3529. var i, il;
  3530. var j, jl;
  3531. var iA, iB, iC;
  3532. var offsets = this.offsets;
  3533. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3534. var start = offsets[ j ].start;
  3535. var count = offsets[ j ].count;
  3536. var index = offsets[ j ].index;
  3537. for ( i = start, il = start + count; i < il; i += 3 ) {
  3538. iA = index + indices[ i ];
  3539. iB = index + indices[ i + 1 ];
  3540. iC = index + indices[ i + 2 ];
  3541. handleTriangle( iA, iB, iC );
  3542. }
  3543. }
  3544. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  3545. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  3546. var w, t, test;
  3547. var nx, ny, nz;
  3548. function handleVertex( v ) {
  3549. n.x = normals[ v * 3 ];
  3550. n.y = normals[ v * 3 + 1 ];
  3551. n.z = normals[ v * 3 + 2 ];
  3552. n2.copy( n );
  3553. t = tan1[ v ];
  3554. // Gram-Schmidt orthogonalize
  3555. tmp.copy( t );
  3556. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3557. // Calculate handedness
  3558. tmp2.cross( n2, t );
  3559. test = tmp2.dot( tan2[ v ] );
  3560. w = ( test < 0.0 ) ? -1.0 : 1.0;
  3561. tangents[ v * 4 ] = tmp.x;
  3562. tangents[ v * 4 + 1 ] = tmp.y;
  3563. tangents[ v * 4 + 2 ] = tmp.z;
  3564. tangents[ v * 4 + 3 ] = w;
  3565. }
  3566. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3567. var start = offsets[ j ].start;
  3568. var count = offsets[ j ].count;
  3569. var index = offsets[ j ].index;
  3570. for ( i = start, il = start + count; i < il; i += 3 ) {
  3571. iA = index + indices[ i ];
  3572. iB = index + indices[ i + 1 ];
  3573. iC = index + indices[ i + 2 ];
  3574. handleVertex( iA );
  3575. handleVertex( iB );
  3576. handleVertex( iC );
  3577. }
  3578. }
  3579. this.hasTangents = true;
  3580. this.tangentsNeedUpdate = true;
  3581. }
  3582. };
  3583. /**
  3584. * Spline from Tween.js, slightly optimized (and trashed)
  3585. * http://sole.github.com/tween.js/examples/05_spline.html
  3586. *
  3587. * @author mrdoob / http://mrdoob.com/
  3588. * @author alteredq / http://alteredqualia.com/
  3589. */
  3590. THREE.Spline = function ( points ) {
  3591. this.points = points;
  3592. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3593. point, intPoint, weight, w2, w3,
  3594. pa, pb, pc, pd;
  3595. this.initFromArray = function( a ) {
  3596. this.points = [];
  3597. for ( var i = 0; i < a.length; i++ ) {
  3598. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3599. }
  3600. };
  3601. this.getPoint = function ( k ) {
  3602. point = ( this.points.length - 1 ) * k;
  3603. intPoint = Math.floor( point );
  3604. weight = point - intPoint;
  3605. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3606. c[ 1 ] = intPoint;
  3607. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3608. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3609. pa = this.points[ c[ 0 ] ];
  3610. pb = this.points[ c[ 1 ] ];
  3611. pc = this.points[ c[ 2 ] ];
  3612. pd = this.points[ c[ 3 ] ];
  3613. w2 = weight * weight;
  3614. w3 = weight * w2;
  3615. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3616. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3617. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3618. return v3;
  3619. };
  3620. this.getControlPointsArray = function () {
  3621. var i, p, l = this.points.length,
  3622. coords = [];
  3623. for ( i = 0; i < l; i ++ ) {
  3624. p = this.points[ i ];
  3625. coords[ i ] = [ p.x, p.y, p.z ];
  3626. }
  3627. return coords;
  3628. };
  3629. // approximate length by summing linear segments
  3630. this.getLength = function ( nSubDivisions ) {
  3631. var i, index, nSamples, position,
  3632. point = 0, intPoint = 0, oldIntPoint = 0,
  3633. oldPosition = new THREE.Vector3(),
  3634. tmpVec = new THREE.Vector3(),
  3635. chunkLengths = [],
  3636. totalLength = 0;
  3637. // first point has 0 length
  3638. chunkLengths[ 0 ] = 0;
  3639. if ( !nSubDivisions ) nSubDivisions = 100;
  3640. nSamples = this.points.length * nSubDivisions;
  3641. oldPosition.copy( this.points[ 0 ] );
  3642. for ( i = 1; i < nSamples; i ++ ) {
  3643. index = i / nSamples;
  3644. position = this.getPoint( index );
  3645. tmpVec.copy( position );
  3646. totalLength += tmpVec.distanceTo( oldPosition );
  3647. oldPosition.copy( position );
  3648. point = ( this.points.length - 1 ) * index;
  3649. intPoint = Math.floor( point );
  3650. if ( intPoint != oldIntPoint ) {
  3651. chunkLengths[ intPoint ] = totalLength;
  3652. oldIntPoint = intPoint;
  3653. }
  3654. }
  3655. // last point ends with total length
  3656. chunkLengths[ chunkLengths.length ] = totalLength;
  3657. return { chunks: chunkLengths, total: totalLength };
  3658. };
  3659. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3660. var i, j,
  3661. index, indexCurrent, indexNext,
  3662. linearDistance, realDistance,
  3663. sampling, position,
  3664. newpoints = [],
  3665. tmpVec = new THREE.Vector3(),
  3666. sl = this.getLength();
  3667. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3668. for ( i = 1; i < this.points.length; i++ ) {
  3669. //tmpVec.copy( this.points[ i - 1 ] );
  3670. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3671. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3672. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3673. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3674. indexNext = i / ( this.points.length - 1 );
  3675. for ( j = 1; j < sampling - 1; j++ ) {
  3676. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3677. position = this.getPoint( index );
  3678. newpoints.push( tmpVec.copy( position ).clone() );
  3679. }
  3680. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3681. }
  3682. this.points = newpoints;
  3683. };
  3684. // Catmull-Rom
  3685. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3686. var v0 = ( p2 - p0 ) * 0.5,
  3687. v1 = ( p3 - p1 ) * 0.5;
  3688. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3689. };
  3690. };
  3691. /**
  3692. * @author mrdoob / http://mrdoob.com/
  3693. * @author mikael emtinger / http://gomo.se/
  3694. */
  3695. THREE.Camera = function () {
  3696. THREE.Object3D.call( this );
  3697. this.matrixWorldInverse = new THREE.Matrix4();
  3698. this.projectionMatrix = new THREE.Matrix4();
  3699. this.projectionMatrixInverse = new THREE.Matrix4();
  3700. };
  3701. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  3702. THREE.Camera.prototype.lookAt = function ( vector ) {
  3703. // TODO: Add hierarchy support.
  3704. this.matrix.lookAt( this.position, vector, this.up );
  3705. if ( this.rotationAutoUpdate === true ) {
  3706. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3707. }
  3708. };
  3709. /**
  3710. * @author alteredq / http://alteredqualia.com/
  3711. */
  3712. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  3713. THREE.Camera.call( this );
  3714. this.left = left;
  3715. this.right = right;
  3716. this.top = top;
  3717. this.bottom = bottom;
  3718. this.near = ( near !== undefined ) ? near : 0.1;
  3719. this.far = ( far !== undefined ) ? far : 2000;
  3720. this.updateProjectionMatrix();
  3721. };
  3722. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  3723. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  3724. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  3725. };
  3726. /**
  3727. * @author mrdoob / http://mrdoob.com/
  3728. * @author greggman / http://games.greggman.com/
  3729. * @author zz85 / http://www.lab4games.net/zz85/blog
  3730. */
  3731. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  3732. THREE.Camera.call( this );
  3733. this.fov = fov !== undefined ? fov : 50;
  3734. this.aspect = aspect !== undefined ? aspect : 1;
  3735. this.near = near !== undefined ? near : 0.1;
  3736. this.far = far !== undefined ? far : 2000;
  3737. this.updateProjectionMatrix();
  3738. };
  3739. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  3740. /**
  3741. * Uses Focal Length (in mm) to estimate and set FOV
  3742. * 35mm (fullframe) camera is used if frame size is not specified;
  3743. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  3744. */
  3745. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  3746. if ( frameHeight === undefined ) frameHeight = 24;
  3747. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  3748. this.updateProjectionMatrix();
  3749. }
  3750. /**
  3751. * Sets an offset in a larger frustum. This is useful for multi-window or
  3752. * multi-monitor/multi-machine setups.
  3753. *
  3754. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  3755. * the monitors are in grid like this
  3756. *
  3757. * +---+---+---+
  3758. * | A | B | C |
  3759. * +---+---+---+
  3760. * | D | E | F |
  3761. * +---+---+---+
  3762. *
  3763. * then for each monitor you would call it like this
  3764. *
  3765. * var w = 1920;
  3766. * var h = 1080;
  3767. * var fullWidth = w * 3;
  3768. * var fullHeight = h * 2;
  3769. *
  3770. * --A--
  3771. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  3772. * --B--
  3773. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  3774. * --C--
  3775. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  3776. * --D--
  3777. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  3778. * --E--
  3779. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  3780. * --F--
  3781. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  3782. *
  3783. * Note there is no reason monitors have to be the same size or in a grid.
  3784. */
  3785. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  3786. this.fullWidth = fullWidth;
  3787. this.fullHeight = fullHeight;
  3788. this.x = x;
  3789. this.y = y;
  3790. this.width = width;
  3791. this.height = height;
  3792. this.updateProjectionMatrix();
  3793. };
  3794. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  3795. if ( this.fullWidth ) {
  3796. var aspect = this.fullWidth / this.fullHeight;
  3797. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  3798. var bottom = -top;
  3799. var left = aspect * bottom;
  3800. var right = aspect * top;
  3801. var width = Math.abs( right - left );
  3802. var height = Math.abs( top - bottom );
  3803. this.projectionMatrix.makeFrustum(
  3804. left + this.x * width / this.fullWidth,
  3805. left + ( this.x + this.width ) * width / this.fullWidth,
  3806. top - ( this.y + this.height ) * height / this.fullHeight,
  3807. top - this.y * height / this.fullHeight,
  3808. this.near,
  3809. this.far
  3810. );
  3811. } else {
  3812. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  3813. }
  3814. };
  3815. /**
  3816. * @author mrdoob / http://mrdoob.com/
  3817. * @author alteredq / http://alteredqualia.com/
  3818. */
  3819. THREE.Light = function ( hex ) {
  3820. THREE.Object3D.call( this );
  3821. this.color = new THREE.Color( hex );
  3822. };
  3823. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  3824. /**
  3825. * @author mrdoob / http://mrdoob.com/
  3826. */
  3827. THREE.AmbientLight = function ( hex ) {
  3828. THREE.Light.call( this, hex );
  3829. };
  3830. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  3831. /**
  3832. * @author mrdoob / http://mrdoob.com/
  3833. * @author alteredq / http://alteredqualia.com/
  3834. */
  3835. THREE.DirectionalLight = function ( hex, intensity, distance ) {
  3836. THREE.Light.call( this, hex );
  3837. this.position = new THREE.Vector3( 0, 1, 0 );
  3838. this.target = new THREE.Object3D();
  3839. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3840. this.distance = ( distance !== undefined ) ? distance : 0;
  3841. this.castShadow = false;
  3842. this.onlyShadow = false;
  3843. //
  3844. this.shadowCameraNear = 50;
  3845. this.shadowCameraFar = 5000;
  3846. this.shadowCameraLeft = -500;
  3847. this.shadowCameraRight = 500;
  3848. this.shadowCameraTop = 500;
  3849. this.shadowCameraBottom = -500;
  3850. this.shadowCameraVisible = false;
  3851. this.shadowBias = 0;
  3852. this.shadowDarkness = 0.5;
  3853. this.shadowMapWidth = 512;
  3854. this.shadowMapHeight = 512;
  3855. //
  3856. this.shadowCascade = false;
  3857. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  3858. this.shadowCascadeCount = 2;
  3859. this.shadowCascadeBias = [ 0, 0, 0 ];
  3860. this.shadowCascadeWidth = [ 512, 512, 512 ];
  3861. this.shadowCascadeHeight = [ 512, 512, 512 ];
  3862. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  3863. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  3864. this.shadowCascadeArray = [];
  3865. //
  3866. this.shadowMap = null;
  3867. this.shadowMapSize = null;
  3868. this.shadowCamera = null;
  3869. this.shadowMatrix = null;
  3870. };
  3871. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  3872. /**
  3873. * @author mrdoob / http://mrdoob.com/
  3874. */
  3875. THREE.PointLight = function ( hex, intensity, distance ) {
  3876. THREE.Light.call( this, hex );
  3877. this.position = new THREE.Vector3( 0, 0, 0 );
  3878. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3879. this.distance = ( distance !== undefined ) ? distance : 0;
  3880. };
  3881. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  3882. /**
  3883. * @author alteredq / http://alteredqualia.com/
  3884. */
  3885. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  3886. THREE.Light.call( this, hex );
  3887. this.position = new THREE.Vector3( 0, 1, 0 );
  3888. this.target = new THREE.Object3D();
  3889. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3890. this.distance = ( distance !== undefined ) ? distance : 0;
  3891. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  3892. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  3893. this.castShadow = false;
  3894. this.onlyShadow = false;
  3895. //
  3896. this.shadowCameraNear = 50;
  3897. this.shadowCameraFar = 5000;
  3898. this.shadowCameraFov = 50;
  3899. this.shadowCameraVisible = false;
  3900. this.shadowBias = 0;
  3901. this.shadowDarkness = 0.5;
  3902. this.shadowMapWidth = 512;
  3903. this.shadowMapHeight = 512;
  3904. //
  3905. this.shadowMap = null;
  3906. this.shadowMapSize = null;
  3907. this.shadowCamera = null;
  3908. this.shadowMatrix = null;
  3909. };
  3910. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  3911. /**
  3912. * @author alteredq / http://alteredqualia.com/
  3913. */
  3914. THREE.Loader = function ( showStatus ) {
  3915. this.showStatus = showStatus;
  3916. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  3917. this.onLoadStart = function () {};
  3918. this.onLoadProgress = function () {};
  3919. this.onLoadComplete = function () {};
  3920. };
  3921. THREE.Loader.prototype = {
  3922. constructor: THREE.Loader,
  3923. crossOrigin: 'anonymous',
  3924. addStatusElement: function () {
  3925. var e = document.createElement( "div" );
  3926. e.style.position = "absolute";
  3927. e.style.right = "0px";
  3928. e.style.top = "0px";
  3929. e.style.fontSize = "0.8em";
  3930. e.style.textAlign = "left";
  3931. e.style.background = "rgba(0,0,0,0.25)";
  3932. e.style.color = "#fff";
  3933. e.style.width = "120px";
  3934. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  3935. e.style.zIndex = 1000;
  3936. e.innerHTML = "Loading ...";
  3937. return e;
  3938. },
  3939. updateProgress: function ( progress ) {
  3940. var message = "Loaded ";
  3941. if ( progress.total ) {
  3942. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  3943. } else {
  3944. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  3945. }
  3946. this.statusDomElement.innerHTML = message;
  3947. },
  3948. extractUrlBase: function ( url ) {
  3949. var parts = url.split( '/' );
  3950. parts.pop();
  3951. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  3952. },
  3953. initMaterials: function ( scope, materials, texturePath ) {
  3954. scope.materials = [];
  3955. for ( var i = 0; i < materials.length; ++ i ) {
  3956. scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  3957. }
  3958. },
  3959. hasNormals: function ( scope ) {
  3960. var m, i, il = scope.materials.length;
  3961. for( i = 0; i < il; i ++ ) {
  3962. m = scope.materials[ i ];
  3963. if ( m instanceof THREE.ShaderMaterial ) return true;
  3964. }
  3965. return false;
  3966. },
  3967. createMaterial: function ( m, texturePath ) {
  3968. var _this = this;
  3969. function is_pow2( n ) {
  3970. var l = Math.log( n ) / Math.LN2;
  3971. return Math.floor( l ) == l;
  3972. }
  3973. function nearest_pow2( n ) {
  3974. var l = Math.log( n ) / Math.LN2;
  3975. return Math.pow( 2, Math.round( l ) );
  3976. }
  3977. function load_image( where, url ) {
  3978. var image = new Image();
  3979. image.onload = function () {
  3980. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  3981. var width = nearest_pow2( this.width );
  3982. var height = nearest_pow2( this.height );
  3983. where.image.width = width;
  3984. where.image.height = height;
  3985. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  3986. } else {
  3987. where.image = this;
  3988. }
  3989. where.needsUpdate = true;
  3990. };
  3991. image.crossOrigin = _this.crossOrigin;
  3992. image.src = url;
  3993. }
  3994. function create_texture( where, name, sourceFile, repeat, offset, wrap ) {
  3995. var texture = document.createElement( 'canvas' );
  3996. where[ name ] = new THREE.Texture( texture );
  3997. where[ name ].sourceFile = sourceFile;
  3998. if( repeat ) {
  3999. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4000. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4001. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4002. }
  4003. if ( offset ) {
  4004. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4005. }
  4006. if ( wrap ) {
  4007. var wrapMap = {
  4008. "repeat": THREE.RepeatWrapping,
  4009. "mirror": THREE.MirroredRepeatWrapping
  4010. }
  4011. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4012. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4013. }
  4014. load_image( where[ name ], texturePath + "/" + sourceFile );
  4015. }
  4016. function rgb2hex( rgb ) {
  4017. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4018. }
  4019. // defaults
  4020. var mtype = "MeshLambertMaterial";
  4021. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4022. // parameters from model file
  4023. if ( m.shading ) {
  4024. var shading = m.shading.toLowerCase();
  4025. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4026. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4027. }
  4028. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4029. mpars.blending = THREE[ m.blending ];
  4030. }
  4031. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4032. mpars.transparent = m.transparent;
  4033. }
  4034. if ( m.depthTest !== undefined ) {
  4035. mpars.depthTest = m.depthTest;
  4036. }
  4037. if ( m.depthWrite !== undefined ) {
  4038. mpars.depthWrite = m.depthWrite;
  4039. }
  4040. if ( m.visible !== undefined ) {
  4041. mpars.visible = m.visible;
  4042. }
  4043. if ( m.flipSided !== undefined ) {
  4044. mpars.side = THREE.BackSide;
  4045. }
  4046. if ( m.doubleSided !== undefined ) {
  4047. mpars.side = THREE.DoubleSide;
  4048. }
  4049. if ( m.wireframe !== undefined ) {
  4050. mpars.wireframe = m.wireframe;
  4051. }
  4052. if ( m.vertexColors !== undefined ) {
  4053. if ( m.vertexColors == "face" ) {
  4054. mpars.vertexColors = THREE.FaceColors;
  4055. } else if ( m.vertexColors ) {
  4056. mpars.vertexColors = THREE.VertexColors;
  4057. }
  4058. }
  4059. // colors
  4060. if ( m.colorDiffuse ) {
  4061. mpars.color = rgb2hex( m.colorDiffuse );
  4062. } else if ( m.DbgColor ) {
  4063. mpars.color = m.DbgColor;
  4064. }
  4065. if ( m.colorSpecular ) {
  4066. mpars.specular = rgb2hex( m.colorSpecular );
  4067. }
  4068. if ( m.colorAmbient ) {
  4069. mpars.ambient = rgb2hex( m.colorAmbient );
  4070. }
  4071. // modifiers
  4072. if ( m.transparency ) {
  4073. mpars.opacity = m.transparency;
  4074. }
  4075. if ( m.specularCoef ) {
  4076. mpars.shininess = m.specularCoef;
  4077. }
  4078. // textures
  4079. if ( m.mapDiffuse && texturePath ) {
  4080. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  4081. }
  4082. if ( m.mapLight && texturePath ) {
  4083. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  4084. }
  4085. if ( m.mapBump && texturePath ) {
  4086. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap );
  4087. }
  4088. if ( m.mapNormal && texturePath ) {
  4089. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  4090. }
  4091. if ( m.mapSpecular && texturePath ) {
  4092. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  4093. }
  4094. // special case for normal mapped material
  4095. if ( m.mapNormal ) {
  4096. var shader = THREE.ShaderUtils.lib[ "normal" ];
  4097. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  4098. uniforms[ "tNormal" ].texture = mpars.normalMap;
  4099. if ( m.mapNormalFactor ) {
  4100. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  4101. }
  4102. if ( mpars.map ) {
  4103. uniforms[ "tDiffuse" ].texture = mpars.map;
  4104. uniforms[ "enableDiffuse" ].value = true;
  4105. }
  4106. if ( mpars.specularMap ) {
  4107. uniforms[ "tSpecular" ].texture = mpars.specularMap;
  4108. uniforms[ "enableSpecular" ].value = true;
  4109. }
  4110. if ( mpars.lightMap ) {
  4111. uniforms[ "tAO" ].texture = mpars.lightMap;
  4112. uniforms[ "enableAO" ].value = true;
  4113. }
  4114. // for the moment don't handle displacement texture
  4115. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  4116. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  4117. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  4118. uniforms[ "uShininess" ].value = mpars.shininess;
  4119. if ( mpars.opacity !== undefined ) {
  4120. uniforms[ "uOpacity" ].value = mpars.opacity;
  4121. }
  4122. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  4123. var material = new THREE.ShaderMaterial( parameters );
  4124. } else {
  4125. var material = new THREE[ mtype ]( mpars );
  4126. }
  4127. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  4128. return material;
  4129. }
  4130. };
  4131. /**
  4132. * @author alteredq / http://alteredqualia.com/
  4133. */
  4134. THREE.BinaryLoader = function ( showStatus ) {
  4135. THREE.Loader.call( this, showStatus );
  4136. };
  4137. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  4138. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  4139. // - binary models consist of two files: JS and BIN
  4140. // - parameters
  4141. // - url (required)
  4142. // - callback (required)
  4143. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  4144. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  4145. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  4146. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4147. binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
  4148. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  4149. this.onLoadStart();
  4150. // #1 load JS part via web worker
  4151. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  4152. };
  4153. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  4154. var xhr = new XMLHttpRequest();
  4155. xhr.onreadystatechange = function () {
  4156. if ( xhr.readyState == 4 ) {
  4157. if ( xhr.status == 200 || xhr.status == 0 ) {
  4158. var json = JSON.parse( xhr.responseText );
  4159. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  4160. } else {
  4161. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4162. }
  4163. }
  4164. };
  4165. xhr.open( "GET", url, true );
  4166. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  4167. xhr.setRequestHeader( "Content-Type", "text/plain" );
  4168. xhr.send( null );
  4169. };
  4170. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  4171. var xhr = new XMLHttpRequest(),
  4172. url = binaryPath + "/" + json.buffers;
  4173. var length = 0;
  4174. xhr.onreadystatechange = function () {
  4175. if ( xhr.readyState == 4 ) {
  4176. if ( xhr.status == 200 || xhr.status == 0 ) {
  4177. var buffer = xhr.response;
  4178. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  4179. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  4180. } else {
  4181. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4182. }
  4183. } else if ( xhr.readyState == 3 ) {
  4184. if ( callbackProgress ) {
  4185. if ( length == 0 ) {
  4186. length = xhr.getResponseHeader( "Content-Length" );
  4187. }
  4188. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4189. }
  4190. } else if ( xhr.readyState == 2 ) {
  4191. length = xhr.getResponseHeader( "Content-Length" );
  4192. }
  4193. };
  4194. xhr.open( "GET", url, true );
  4195. xhr.responseType = "arraybuffer";
  4196. xhr.send( null );
  4197. };
  4198. // Binary AJAX parser
  4199. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
  4200. var Model = function ( texturePath ) {
  4201. var scope = this,
  4202. currentOffset = 0,
  4203. md,
  4204. normals = [],
  4205. uvs = [],
  4206. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  4207. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  4208. tri_size, quad_size,
  4209. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  4210. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  4211. THREE.Geometry.call( this );
  4212. THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
  4213. md = parseMetaData( data, currentOffset );
  4214. currentOffset += md.header_bytes;
  4215. /*
  4216. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4217. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  4218. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4219. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4220. */
  4221. // buffers sizes
  4222. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  4223. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  4224. len_tri_flat = md.ntri_flat * ( tri_size );
  4225. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  4226. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  4227. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  4228. len_quad_flat = md.nquad_flat * ( quad_size );
  4229. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  4230. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  4231. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  4232. // read buffers
  4233. currentOffset += init_vertices( currentOffset );
  4234. currentOffset += init_normals( currentOffset );
  4235. currentOffset += handlePadding( md.nnormals * 3 );
  4236. currentOffset += init_uvs( currentOffset );
  4237. start_tri_flat = currentOffset;
  4238. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  4239. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  4240. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  4241. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  4242. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  4243. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  4244. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  4245. // have to first process faces with uvs
  4246. // so that face and uv indices match
  4247. init_triangles_flat_uv( start_tri_flat_uv );
  4248. init_triangles_smooth_uv( start_tri_smooth_uv );
  4249. init_quads_flat_uv( start_quad_flat_uv );
  4250. init_quads_smooth_uv( start_quad_smooth_uv );
  4251. // now we can process untextured faces
  4252. init_triangles_flat( start_tri_flat );
  4253. init_triangles_smooth( start_tri_smooth );
  4254. init_quads_flat( start_quad_flat );
  4255. init_quads_smooth( start_quad_smooth );
  4256. this.computeCentroids();
  4257. this.computeFaceNormals();
  4258. if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
  4259. function handlePadding( n ) {
  4260. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  4261. };
  4262. function parseMetaData( data, offset ) {
  4263. var metaData = {
  4264. 'signature' :parseString( data, offset, 12 ),
  4265. 'header_bytes' :parseUChar8( data, offset + 12 ),
  4266. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  4267. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  4268. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  4269. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  4270. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  4271. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  4272. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  4273. 'nvertices' :parseUInt32( data, offset + 20 ),
  4274. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  4275. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  4276. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  4277. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  4278. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  4279. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  4280. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  4281. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  4282. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  4283. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  4284. };
  4285. /*
  4286. console.log( "signature: " + metaData.signature );
  4287. console.log( "header_bytes: " + metaData.header_bytes );
  4288. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  4289. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  4290. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  4291. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  4292. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  4293. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  4294. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  4295. console.log( "nvertices: " + metaData.nvertices );
  4296. console.log( "nnormals: " + metaData.nnormals );
  4297. console.log( "nuvs: " + metaData.nuvs );
  4298. console.log( "ntri_flat: " + metaData.ntri_flat );
  4299. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  4300. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  4301. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  4302. console.log( "nquad_flat: " + metaData.nquad_flat );
  4303. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  4304. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  4305. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  4306. var total = metaData.header_bytes
  4307. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  4308. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  4309. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  4310. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  4311. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  4312. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  4313. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  4314. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  4315. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  4316. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  4317. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  4318. console.log( "total bytes: " + total );
  4319. */
  4320. return metaData;
  4321. };
  4322. function parseString( data, offset, length ) {
  4323. var charArray = new Uint8Array( data, offset, length );
  4324. var text = "";
  4325. for ( var i = 0; i < length; i ++ ) {
  4326. text += String.fromCharCode( charArray[ offset + i ] );
  4327. }
  4328. return text;
  4329. };
  4330. function parseUChar8( data, offset ) {
  4331. var charArray = new Uint8Array( data, offset, 1 );
  4332. return charArray[ 0 ];
  4333. };
  4334. function parseUInt32( data, offset ) {
  4335. var intArray = new Uint32Array( data, offset, 1 );
  4336. return intArray[ 0 ];
  4337. };
  4338. function init_vertices( start ) {
  4339. var nElements = md.nvertices;
  4340. var coordArray = new Float32Array( data, start, nElements * 3 );
  4341. var i, x, y, z;
  4342. for( i = 0; i < nElements; i ++ ) {
  4343. x = coordArray[ i * 3 ];
  4344. y = coordArray[ i * 3 + 1 ];
  4345. z = coordArray[ i * 3 + 2 ];
  4346. vertex( scope, x, y, z );
  4347. }
  4348. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  4349. };
  4350. function init_normals( start ) {
  4351. var nElements = md.nnormals;
  4352. if ( nElements ) {
  4353. var normalArray = new Int8Array( data, start, nElements * 3 );
  4354. var i, x, y, z;
  4355. for( i = 0; i < nElements; i ++ ) {
  4356. x = normalArray[ i * 3 ];
  4357. y = normalArray[ i * 3 + 1 ];
  4358. z = normalArray[ i * 3 + 2 ];
  4359. normals.push( x/127, y/127, z/127 );
  4360. }
  4361. }
  4362. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  4363. };
  4364. function init_uvs( start ) {
  4365. var nElements = md.nuvs;
  4366. if ( nElements ) {
  4367. var uvArray = new Float32Array( data, start, nElements * 2 );
  4368. var i, u, v;
  4369. for( i = 0; i < nElements; i ++ ) {
  4370. u = uvArray[ i * 2 ];
  4371. v = uvArray[ i * 2 + 1 ];
  4372. uvs.push( u, v );
  4373. }
  4374. }
  4375. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  4376. };
  4377. function init_uvs3( nElements, offset ) {
  4378. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  4379. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  4380. for( i = 0; i < nElements; i ++ ) {
  4381. uva = uvIndexBuffer[ i * 3 ];
  4382. uvb = uvIndexBuffer[ i * 3 + 1 ];
  4383. uvc = uvIndexBuffer[ i * 3 + 2 ];
  4384. u1 = uvs[ uva*2 ];
  4385. v1 = uvs[ uva*2 + 1 ];
  4386. u2 = uvs[ uvb*2 ];
  4387. v2 = uvs[ uvb*2 + 1 ];
  4388. u3 = uvs[ uvc*2 ];
  4389. v3 = uvs[ uvc*2 + 1 ];
  4390. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  4391. }
  4392. };
  4393. function init_uvs4( nElements, offset ) {
  4394. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  4395. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  4396. for( i = 0; i < nElements; i ++ ) {
  4397. uva = uvIndexBuffer[ i * 4 ];
  4398. uvb = uvIndexBuffer[ i * 4 + 1 ];
  4399. uvc = uvIndexBuffer[ i * 4 + 2 ];
  4400. uvd = uvIndexBuffer[ i * 4 + 3 ];
  4401. u1 = uvs[ uva*2 ];
  4402. v1 = uvs[ uva*2 + 1 ];
  4403. u2 = uvs[ uvb*2 ];
  4404. v2 = uvs[ uvb*2 + 1 ];
  4405. u3 = uvs[ uvc*2 ];
  4406. v3 = uvs[ uvc*2 + 1 ];
  4407. u4 = uvs[ uvd*2 ];
  4408. v4 = uvs[ uvd*2 + 1 ];
  4409. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  4410. }
  4411. };
  4412. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  4413. var i, a, b, c, m;
  4414. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4415. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4416. for( i = 0; i < nElements; i ++ ) {
  4417. a = vertexIndexBuffer[ i * 3 ];
  4418. b = vertexIndexBuffer[ i * 3 + 1 ];
  4419. c = vertexIndexBuffer[ i * 3 + 2 ];
  4420. m = materialIndexBuffer[ i ];
  4421. f3( scope, a, b, c, m );
  4422. }
  4423. };
  4424. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  4425. var i, a, b, c, d, m;
  4426. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4427. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4428. for( i = 0; i < nElements; i ++ ) {
  4429. a = vertexIndexBuffer[ i * 4 ];
  4430. b = vertexIndexBuffer[ i * 4 + 1 ];
  4431. c = vertexIndexBuffer[ i * 4 + 2 ];
  4432. d = vertexIndexBuffer[ i * 4 + 3 ];
  4433. m = materialIndexBuffer[ i ];
  4434. f4( scope, a, b, c, d, m );
  4435. }
  4436. };
  4437. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4438. var i, a, b, c, m;
  4439. var na, nb, nc;
  4440. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4441. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  4442. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4443. for( i = 0; i < nElements; i ++ ) {
  4444. a = vertexIndexBuffer[ i * 3 ];
  4445. b = vertexIndexBuffer[ i * 3 + 1 ];
  4446. c = vertexIndexBuffer[ i * 3 + 2 ];
  4447. na = normalIndexBuffer[ i * 3 ];
  4448. nb = normalIndexBuffer[ i * 3 + 1 ];
  4449. nc = normalIndexBuffer[ i * 3 + 2 ];
  4450. m = materialIndexBuffer[ i ];
  4451. f3n( scope, normals, a, b, c, m, na, nb, nc );
  4452. }
  4453. };
  4454. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4455. var i, a, b, c, d, m;
  4456. var na, nb, nc, nd;
  4457. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4458. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  4459. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4460. for( i = 0; i < nElements; i ++ ) {
  4461. a = vertexIndexBuffer[ i * 4 ];
  4462. b = vertexIndexBuffer[ i * 4 + 1 ];
  4463. c = vertexIndexBuffer[ i * 4 + 2 ];
  4464. d = vertexIndexBuffer[ i * 4 + 3 ];
  4465. na = normalIndexBuffer[ i * 4 ];
  4466. nb = normalIndexBuffer[ i * 4 + 1 ];
  4467. nc = normalIndexBuffer[ i * 4 + 2 ];
  4468. nd = normalIndexBuffer[ i * 4 + 3 ];
  4469. m = materialIndexBuffer[ i ];
  4470. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  4471. }
  4472. };
  4473. function init_triangles_flat( start ) {
  4474. var nElements = md.ntri_flat;
  4475. if ( nElements ) {
  4476. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4477. init_faces3_flat( nElements, start, offsetMaterials );
  4478. }
  4479. };
  4480. function init_triangles_flat_uv( start ) {
  4481. var nElements = md.ntri_flat_uv;
  4482. if ( nElements ) {
  4483. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4484. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4485. init_faces3_flat( nElements, start, offsetMaterials );
  4486. init_uvs3( nElements, offsetUvs );
  4487. }
  4488. };
  4489. function init_triangles_smooth( start ) {
  4490. var nElements = md.ntri_smooth;
  4491. if ( nElements ) {
  4492. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4493. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4494. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4495. }
  4496. };
  4497. function init_triangles_smooth_uv( start ) {
  4498. var nElements = md.ntri_smooth_uv;
  4499. if ( nElements ) {
  4500. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4501. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4502. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4503. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4504. init_uvs3( nElements, offsetUvs );
  4505. }
  4506. };
  4507. function init_quads_flat( start ) {
  4508. var nElements = md.nquad_flat;
  4509. if ( nElements ) {
  4510. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4511. init_faces4_flat( nElements, start, offsetMaterials );
  4512. }
  4513. };
  4514. function init_quads_flat_uv( start ) {
  4515. var nElements = md.nquad_flat_uv;
  4516. if ( nElements ) {
  4517. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4518. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4519. init_faces4_flat( nElements, start, offsetMaterials );
  4520. init_uvs4( nElements, offsetUvs );
  4521. }
  4522. };
  4523. function init_quads_smooth( start ) {
  4524. var nElements = md.nquad_smooth;
  4525. if ( nElements ) {
  4526. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4527. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4528. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4529. }
  4530. };
  4531. function init_quads_smooth_uv( start ) {
  4532. var nElements = md.nquad_smooth_uv;
  4533. if ( nElements ) {
  4534. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4535. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4536. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4537. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4538. init_uvs4( nElements, offsetUvs );
  4539. }
  4540. };
  4541. };
  4542. function vertex ( scope, x, y, z ) {
  4543. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  4544. };
  4545. function f3 ( scope, a, b, c, mi ) {
  4546. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  4547. };
  4548. function f4 ( scope, a, b, c, d, mi ) {
  4549. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  4550. };
  4551. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  4552. var nax = normals[ na*3 ],
  4553. nay = normals[ na*3 + 1 ],
  4554. naz = normals[ na*3 + 2 ],
  4555. nbx = normals[ nb*3 ],
  4556. nby = normals[ nb*3 + 1 ],
  4557. nbz = normals[ nb*3 + 2 ],
  4558. ncx = normals[ nc*3 ],
  4559. ncy = normals[ nc*3 + 1 ],
  4560. ncz = normals[ nc*3 + 2 ];
  4561. scope.faces.push( new THREE.Face3( a, b, c,
  4562. [new THREE.Vector3( nax, nay, naz ),
  4563. new THREE.Vector3( nbx, nby, nbz ),
  4564. new THREE.Vector3( ncx, ncy, ncz )],
  4565. null,
  4566. mi ) );
  4567. };
  4568. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  4569. var nax = normals[ na*3 ],
  4570. nay = normals[ na*3 + 1 ],
  4571. naz = normals[ na*3 + 2 ],
  4572. nbx = normals[ nb*3 ],
  4573. nby = normals[ nb*3 + 1 ],
  4574. nbz = normals[ nb*3 + 2 ],
  4575. ncx = normals[ nc*3 ],
  4576. ncy = normals[ nc*3 + 1 ],
  4577. ncz = normals[ nc*3 + 2 ],
  4578. ndx = normals[ nd*3 ],
  4579. ndy = normals[ nd*3 + 1 ],
  4580. ndz = normals[ nd*3 + 2 ];
  4581. scope.faces.push( new THREE.Face4( a, b, c, d,
  4582. [new THREE.Vector3( nax, nay, naz ),
  4583. new THREE.Vector3( nbx, nby, nbz ),
  4584. new THREE.Vector3( ncx, ncy, ncz ),
  4585. new THREE.Vector3( ndx, ndy, ndz )],
  4586. null,
  4587. mi ) );
  4588. };
  4589. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  4590. var uv = [];
  4591. uv.push( new THREE.UV( u1, v1 ) );
  4592. uv.push( new THREE.UV( u2, v2 ) );
  4593. uv.push( new THREE.UV( u3, v3 ) );
  4594. where.push( uv );
  4595. };
  4596. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  4597. var uv = [];
  4598. uv.push( new THREE.UV( u1, v1 ) );
  4599. uv.push( new THREE.UV( u2, v2 ) );
  4600. uv.push( new THREE.UV( u3, v3 ) );
  4601. uv.push( new THREE.UV( u4, v4 ) );
  4602. where.push( uv );
  4603. };
  4604. Model.prototype = Object.create( THREE.Geometry.prototype );
  4605. callback( new Model( texturePath ) );
  4606. };
  4607. /**
  4608. * @author mrdoob / http://mrdoob.com/
  4609. */
  4610. THREE.ImageLoader = function () {
  4611. THREE.EventTarget.call( this );
  4612. this.crossOrigin = null;
  4613. };
  4614. THREE.ImageLoader.prototype = {
  4615. constructor: THREE.ImageLoader,
  4616. load: function ( url, image ) {
  4617. var scope = this;
  4618. if ( image === undefined ) image = new Image();
  4619. image.addEventListener( 'load', function () {
  4620. scope.dispatchEvent( { type: 'load', content: image } );
  4621. }, false );
  4622. image.addEventListener( 'error', function () {
  4623. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4624. }, false );
  4625. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  4626. image.src = url;
  4627. }
  4628. }
  4629. /**
  4630. * @author mrdoob / http://mrdoob.com/
  4631. * @author alteredq / http://alteredqualia.com/
  4632. */
  4633. THREE.JSONLoader = function ( showStatus ) {
  4634. THREE.Loader.call( this, showStatus );
  4635. };
  4636. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  4637. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  4638. var scope = this;
  4639. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4640. this.onLoadStart();
  4641. this.loadAjaxJSON( this, url, callback, texturePath );
  4642. };
  4643. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  4644. var xhr = new XMLHttpRequest();
  4645. var length = 0;
  4646. xhr.onreadystatechange = function () {
  4647. if ( xhr.readyState === xhr.DONE ) {
  4648. if ( xhr.status === 200 || xhr.status === 0 ) {
  4649. if ( xhr.responseText ) {
  4650. var json = JSON.parse( xhr.responseText );
  4651. context.createModel( json, callback, texturePath );
  4652. } else {
  4653. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  4654. }
  4655. // in context of more complex asset initialization
  4656. // do not block on single failed file
  4657. // maybe should go even one more level up
  4658. context.onLoadComplete();
  4659. } else {
  4660. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4661. }
  4662. } else if ( xhr.readyState === xhr.LOADING ) {
  4663. if ( callbackProgress ) {
  4664. if ( length === 0 ) {
  4665. length = xhr.getResponseHeader( "Content-Length" );
  4666. }
  4667. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4668. }
  4669. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  4670. length = xhr.getResponseHeader( "Content-Length" );
  4671. }
  4672. };
  4673. xhr.open( "GET", url, true );
  4674. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "application/json; charset=x-user-defined" );
  4675. xhr.setRequestHeader( "Content-Type", "application/json" );
  4676. xhr.send( null );
  4677. };
  4678. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  4679. var scope = this,
  4680. geometry = new THREE.Geometry(),
  4681. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  4682. this.initMaterials( geometry, json.materials, texturePath );
  4683. parseModel( scale );
  4684. parseSkin();
  4685. parseMorphing( scale );
  4686. geometry.computeCentroids();
  4687. geometry.computeFaceNormals();
  4688. if ( this.hasNormals( geometry ) ) geometry.computeTangents();
  4689. function parseModel( scale ) {
  4690. function isBitSet( value, position ) {
  4691. return value & ( 1 << position );
  4692. }
  4693. var i, j, fi,
  4694. offset, zLength, nVertices,
  4695. colorIndex, normalIndex, uvIndex, materialIndex,
  4696. type,
  4697. isQuad,
  4698. hasMaterial,
  4699. hasFaceUv, hasFaceVertexUv,
  4700. hasFaceNormal, hasFaceVertexNormal,
  4701. hasFaceColor, hasFaceVertexColor,
  4702. vertex, face, color, normal,
  4703. uvLayer, uvs, u, v,
  4704. faces = json.faces,
  4705. vertices = json.vertices,
  4706. normals = json.normals,
  4707. colors = json.colors,
  4708. nUvLayers = 0;
  4709. // disregard empty arrays
  4710. for ( i = 0; i < json.uvs.length; i++ ) {
  4711. if ( json.uvs[ i ].length ) nUvLayers ++;
  4712. }
  4713. for ( i = 0; i < nUvLayers; i++ ) {
  4714. geometry.faceUvs[ i ] = [];
  4715. geometry.faceVertexUvs[ i ] = [];
  4716. }
  4717. offset = 0;
  4718. zLength = vertices.length;
  4719. while ( offset < zLength ) {
  4720. vertex = new THREE.Vector3();
  4721. vertex.x = vertices[ offset ++ ] * scale;
  4722. vertex.y = vertices[ offset ++ ] * scale;
  4723. vertex.z = vertices[ offset ++ ] * scale;
  4724. geometry.vertices.push( vertex );
  4725. }
  4726. offset = 0;
  4727. zLength = faces.length;
  4728. while ( offset < zLength ) {
  4729. type = faces[ offset ++ ];
  4730. isQuad = isBitSet( type, 0 );
  4731. hasMaterial = isBitSet( type, 1 );
  4732. hasFaceUv = isBitSet( type, 2 );
  4733. hasFaceVertexUv = isBitSet( type, 3 );
  4734. hasFaceNormal = isBitSet( type, 4 );
  4735. hasFaceVertexNormal = isBitSet( type, 5 );
  4736. hasFaceColor = isBitSet( type, 6 );
  4737. hasFaceVertexColor = isBitSet( type, 7 );
  4738. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  4739. if ( isQuad ) {
  4740. face = new THREE.Face4();
  4741. face.a = faces[ offset ++ ];
  4742. face.b = faces[ offset ++ ];
  4743. face.c = faces[ offset ++ ];
  4744. face.d = faces[ offset ++ ];
  4745. nVertices = 4;
  4746. } else {
  4747. face = new THREE.Face3();
  4748. face.a = faces[ offset ++ ];
  4749. face.b = faces[ offset ++ ];
  4750. face.c = faces[ offset ++ ];
  4751. nVertices = 3;
  4752. }
  4753. if ( hasMaterial ) {
  4754. materialIndex = faces[ offset ++ ];
  4755. face.materialIndex = materialIndex;
  4756. }
  4757. // to get face <=> uv index correspondence
  4758. fi = geometry.faces.length;
  4759. if ( hasFaceUv ) {
  4760. for ( i = 0; i < nUvLayers; i++ ) {
  4761. uvLayer = json.uvs[ i ];
  4762. uvIndex = faces[ offset ++ ];
  4763. u = uvLayer[ uvIndex * 2 ];
  4764. v = uvLayer[ uvIndex * 2 + 1 ];
  4765. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  4766. }
  4767. }
  4768. if ( hasFaceVertexUv ) {
  4769. for ( i = 0; i < nUvLayers; i++ ) {
  4770. uvLayer = json.uvs[ i ];
  4771. uvs = [];
  4772. for ( j = 0; j < nVertices; j ++ ) {
  4773. uvIndex = faces[ offset ++ ];
  4774. u = uvLayer[ uvIndex * 2 ];
  4775. v = uvLayer[ uvIndex * 2 + 1 ];
  4776. uvs[ j ] = new THREE.UV( u, v );
  4777. }
  4778. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  4779. }
  4780. }
  4781. if ( hasFaceNormal ) {
  4782. normalIndex = faces[ offset ++ ] * 3;
  4783. normal = new THREE.Vector3();
  4784. normal.x = normals[ normalIndex ++ ];
  4785. normal.y = normals[ normalIndex ++ ];
  4786. normal.z = normals[ normalIndex ];
  4787. face.normal = normal;
  4788. }
  4789. if ( hasFaceVertexNormal ) {
  4790. for ( i = 0; i < nVertices; i++ ) {
  4791. normalIndex = faces[ offset ++ ] * 3;
  4792. normal = new THREE.Vector3();
  4793. normal.x = normals[ normalIndex ++ ];
  4794. normal.y = normals[ normalIndex ++ ];
  4795. normal.z = normals[ normalIndex ];
  4796. face.vertexNormals.push( normal );
  4797. }
  4798. }
  4799. if ( hasFaceColor ) {
  4800. colorIndex = faces[ offset ++ ];
  4801. color = new THREE.Color( colors[ colorIndex ] );
  4802. face.color = color;
  4803. }
  4804. if ( hasFaceVertexColor ) {
  4805. for ( i = 0; i < nVertices; i++ ) {
  4806. colorIndex = faces[ offset ++ ];
  4807. color = new THREE.Color( colors[ colorIndex ] );
  4808. face.vertexColors.push( color );
  4809. }
  4810. }
  4811. geometry.faces.push( face );
  4812. }
  4813. };
  4814. function parseSkin() {
  4815. var i, l, x, y, z, w, a, b, c, d;
  4816. if ( json.skinWeights ) {
  4817. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  4818. x = json.skinWeights[ i ];
  4819. y = json.skinWeights[ i + 1 ];
  4820. z = 0;
  4821. w = 0;
  4822. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  4823. }
  4824. }
  4825. if ( json.skinIndices ) {
  4826. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  4827. a = json.skinIndices[ i ];
  4828. b = json.skinIndices[ i + 1 ];
  4829. c = 0;
  4830. d = 0;
  4831. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  4832. }
  4833. }
  4834. geometry.bones = json.bones;
  4835. geometry.animation = json.animation;
  4836. };
  4837. function parseMorphing( scale ) {
  4838. if ( json.morphTargets !== undefined ) {
  4839. var i, l, v, vl, dstVertices, srcVertices;
  4840. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  4841. geometry.morphTargets[ i ] = {};
  4842. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  4843. geometry.morphTargets[ i ].vertices = [];
  4844. dstVertices = geometry.morphTargets[ i ].vertices;
  4845. srcVertices = json.morphTargets [ i ].vertices;
  4846. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  4847. var vertex = new THREE.Vector3();
  4848. vertex.x = srcVertices[ v ] * scale;
  4849. vertex.y = srcVertices[ v + 1 ] * scale;
  4850. vertex.z = srcVertices[ v + 2 ] * scale;
  4851. dstVertices.push( vertex );
  4852. }
  4853. }
  4854. }
  4855. if ( json.morphColors !== undefined ) {
  4856. var i, l, c, cl, dstColors, srcColors, color;
  4857. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  4858. geometry.morphColors[ i ] = {};
  4859. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  4860. geometry.morphColors[ i ].colors = [];
  4861. dstColors = geometry.morphColors[ i ].colors;
  4862. srcColors = json.morphColors [ i ].colors;
  4863. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  4864. color = new THREE.Color( 0xffaa00 );
  4865. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  4866. dstColors.push( color );
  4867. }
  4868. }
  4869. }
  4870. };
  4871. callback( geometry );
  4872. };
  4873. /**
  4874. * @author mrdoob / http://mrdoob.com/
  4875. * @author alteredq / http://alteredqualia.com/
  4876. */
  4877. THREE.GeometryLoader = function () {
  4878. THREE.EventTarget.call( this );
  4879. this.crossOrigin = null;
  4880. this.path = null;
  4881. };
  4882. THREE.GeometryLoader.prototype = {
  4883. constructor: THREE.GeometryLoader,
  4884. load: function ( url ) {
  4885. var scope = this;
  4886. var geometry = null;
  4887. if ( scope.path === null ) {
  4888. var parts = url.split( '/' ); parts.pop();
  4889. scope.path = ( parts.length < 1 ? '.' : parts.join( '/' ) );
  4890. }
  4891. //
  4892. var xhr = new XMLHttpRequest();
  4893. xhr.addEventListener( 'load', function ( event ) {
  4894. if ( event.target.responseText ) {
  4895. geometry = scope.parse( JSON.parse( event.target.responseText ), monitor );
  4896. } else {
  4897. scope.dispatchEvent( { type: 'error', message: 'Invalid file [' + url + ']' } );
  4898. }
  4899. }, false );
  4900. xhr.addEventListener( 'error', function () {
  4901. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4902. }, false );
  4903. xhr.open( 'GET', url, true );
  4904. xhr.setRequestHeader( "Content-Type", "application/json" );
  4905. xhr.send( null );
  4906. //
  4907. var monitor = new THREE.LoadingMonitor();
  4908. monitor.addEventListener( 'load', function ( event ) {
  4909. scope.dispatchEvent( { type: 'load', content: geometry } );
  4910. } );
  4911. monitor.add( xhr );
  4912. },
  4913. parse: function ( data, monitor ) {
  4914. var scope = this;
  4915. var geometry = new THREE.Geometry();
  4916. var scale = ( data.scale !== undefined ) ? 1 / data.scale : 1;
  4917. // materials
  4918. if ( data.materials ) {
  4919. geometry.materials = [];
  4920. for ( var i = 0; i < data.materials.length; ++ i ) {
  4921. var m = data.materials[ i ];
  4922. function isPow2( n ) {
  4923. var l = Math.log( n ) / Math.LN2;
  4924. return Math.floor( l ) == l;
  4925. }
  4926. function nearestPow2( n ) {
  4927. var l = Math.log( n ) / Math.LN2;
  4928. return Math.pow( 2, Math.round( l ) );
  4929. }
  4930. function createTexture( where, name, sourceFile, repeat, offset, wrap ) {
  4931. where[ name ] = new THREE.Texture();
  4932. where[ name ].sourceFile = sourceFile;
  4933. if ( repeat ) {
  4934. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4935. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4936. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4937. }
  4938. if ( offset ) {
  4939. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4940. }
  4941. if ( wrap ) {
  4942. var wrapMap = {
  4943. "repeat": THREE.RepeatWrapping,
  4944. "mirror": THREE.MirroredRepeatWrapping
  4945. }
  4946. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4947. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4948. }
  4949. // load image
  4950. var texture = where[ name ];
  4951. var loader = new THREE.ImageLoader();
  4952. loader.addEventListener( 'load', function ( event ) {
  4953. var image = event.content;
  4954. if ( !isPow2( image.width ) || !isPow2( image.height ) ) {
  4955. var width = nearestPow2( image.width );
  4956. var height = nearestPow2( image.height );
  4957. texture.image = document.createElement( 'canvas' );
  4958. texture.image.width = width;
  4959. texture.image.height = height;
  4960. texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
  4961. } else {
  4962. texture.image = image;
  4963. }
  4964. texture.needsUpdate = true;
  4965. } );
  4966. loader.crossOrigin = scope.crossOrigin;
  4967. loader.load( scope.path + '/' + sourceFile );
  4968. if ( monitor ) monitor.add( loader );
  4969. }
  4970. function rgb2hex( rgb ) {
  4971. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4972. }
  4973. // defaults
  4974. var mtype = "MeshLambertMaterial";
  4975. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4976. // parameters from model file
  4977. if ( m.shading ) {
  4978. var shading = m.shading.toLowerCase();
  4979. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4980. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4981. }
  4982. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4983. mpars.blending = THREE[ m.blending ];
  4984. }
  4985. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4986. mpars.transparent = m.transparent;
  4987. }
  4988. if ( m.depthTest !== undefined ) {
  4989. mpars.depthTest = m.depthTest;
  4990. }
  4991. if ( m.depthWrite !== undefined ) {
  4992. mpars.depthWrite = m.depthWrite;
  4993. }
  4994. if ( m.vertexColors !== undefined ) {
  4995. if ( m.vertexColors == "face" ) {
  4996. mpars.vertexColors = THREE.FaceColors;
  4997. } else if ( m.vertexColors ) {
  4998. mpars.vertexColors = THREE.VertexColors;
  4999. }
  5000. }
  5001. // colors
  5002. if ( m.colorDiffuse ) {
  5003. mpars.color = rgb2hex( m.colorDiffuse );
  5004. } else if ( m.DbgColor ) {
  5005. mpars.color = m.DbgColor;
  5006. }
  5007. if ( m.colorSpecular ) {
  5008. mpars.specular = rgb2hex( m.colorSpecular );
  5009. }
  5010. if ( m.colorAmbient ) {
  5011. mpars.ambient = rgb2hex( m.colorAmbient );
  5012. }
  5013. // modifiers
  5014. if ( m.transparency ) {
  5015. mpars.opacity = m.transparency;
  5016. }
  5017. if ( m.specularCoef ) {
  5018. mpars.shininess = m.specularCoef;
  5019. }
  5020. if ( m.visible !== undefined ) {
  5021. mpars.visible = m.visible;
  5022. }
  5023. if ( m.flipSided !== undefined ) {
  5024. mpars.side = THREE.BackSide;
  5025. }
  5026. if ( m.doubleSided !== undefined ) {
  5027. mpars.side = THREE.DoubleSide;
  5028. }
  5029. if ( m.wireframe !== undefined ) {
  5030. mpars.wireframe = m.wireframe;
  5031. }
  5032. // textures
  5033. if ( m.mapDiffuse ) {
  5034. createTexture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  5035. }
  5036. if ( m.mapLight ) {
  5037. createTexture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  5038. }
  5039. if ( m.mapBump ) {
  5040. createTexture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap );
  5041. }
  5042. if ( m.mapNormal ) {
  5043. createTexture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  5044. }
  5045. if ( m.mapSpecular ) {
  5046. createTexture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  5047. }
  5048. // special case for normal mapped material
  5049. if ( m.mapNormal ) {
  5050. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5051. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5052. uniforms[ "tNormal" ].texture = mpars.normalMap;
  5053. if ( m.mapNormalFactor ) {
  5054. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  5055. }
  5056. if ( mpars.map ) {
  5057. uniforms[ "tDiffuse" ].texture = mpars.map;
  5058. uniforms[ "enableDiffuse" ].value = true;
  5059. }
  5060. if ( mpars.specularMap ) {
  5061. uniforms[ "tSpecular" ].texture = mpars.specularMap;
  5062. uniforms[ "enableSpecular" ].value = true;
  5063. }
  5064. if ( mpars.lightMap ) {
  5065. uniforms[ "tAO" ].texture = mpars.lightMap;
  5066. uniforms[ "enableAO" ].value = true;
  5067. }
  5068. // for the moment don't handle displacement texture
  5069. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5070. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5071. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5072. uniforms[ "uShininess" ].value = mpars.shininess;
  5073. if ( mpars.opacity !== undefined ) {
  5074. uniforms[ "uOpacity" ].value = mpars.opacity;
  5075. }
  5076. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5077. var material = new THREE.ShaderMaterial( parameters );
  5078. } else {
  5079. var material = new THREE[ mtype ]( mpars );
  5080. }
  5081. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5082. geometry.materials[ i ] = material;
  5083. }
  5084. }
  5085. // geometry
  5086. function isBitSet( value, position ) {
  5087. return value & ( 1 << position );
  5088. }
  5089. var faces = data.faces;
  5090. var vertices = data.vertices;
  5091. var normals = data.normals;
  5092. var colors = data.colors;
  5093. var nUvLayers = 0;
  5094. // disregard empty arrays
  5095. if ( data.uvs ) {
  5096. for ( var i = 0; i < data.uvs.length; i ++ ) {
  5097. if ( data.uvs[ i ].length ) nUvLayers ++;
  5098. }
  5099. }
  5100. for ( var i = 0; i < nUvLayers; i ++ ) {
  5101. geometry.faceUvs[ i ] = [];
  5102. geometry.faceVertexUvs[ i ] = [];
  5103. }
  5104. var offset = 0;
  5105. var zLength = vertices.length;
  5106. while ( offset < zLength ) {
  5107. var vertex = new THREE.Vector3();
  5108. vertex.x = vertices[ offset ++ ] * scale;
  5109. vertex.y = vertices[ offset ++ ] * scale;
  5110. vertex.z = vertices[ offset ++ ] * scale;
  5111. geometry.vertices.push( vertex );
  5112. }
  5113. offset = 0;
  5114. zLength = faces.length;
  5115. while ( offset < zLength ) {
  5116. var type = faces[ offset ++ ];
  5117. var isQuad = isBitSet( type, 0 );
  5118. var hasMaterial = isBitSet( type, 1 );
  5119. var hasFaceUv = isBitSet( type, 2 );
  5120. var hasFaceVertexUv = isBitSet( type, 3 );
  5121. var hasFaceNormal = isBitSet( type, 4 );
  5122. var hasFaceVertexNormal = isBitSet( type, 5 );
  5123. var hasFaceColor = isBitSet( type, 6 );
  5124. var hasFaceVertexColor = isBitSet( type, 7 );
  5125. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5126. if ( isQuad ) {
  5127. var face = new THREE.Face4();
  5128. face.a = faces[ offset ++ ];
  5129. face.b = faces[ offset ++ ];
  5130. face.c = faces[ offset ++ ];
  5131. face.d = faces[ offset ++ ];
  5132. var nVertices = 4;
  5133. } else {
  5134. var face = new THREE.Face3();
  5135. face.a = faces[ offset ++ ];
  5136. face.b = faces[ offset ++ ];
  5137. face.c = faces[ offset ++ ];
  5138. var nVertices = 3;
  5139. }
  5140. if ( hasMaterial ) {
  5141. var materialIndex = faces[ offset ++ ];
  5142. face.materialIndex = materialIndex;
  5143. }
  5144. // to get face <=> uv index correspondence
  5145. var fi = geometry.faces.length;
  5146. if ( hasFaceUv ) {
  5147. for ( var i = 0; i < nUvLayers; i ++ ) {
  5148. var uvLayer = data.uvs[ i ];
  5149. var uvIndex = faces[ offset ++ ];
  5150. var u = uvLayer[ uvIndex * 2 ];
  5151. var v = uvLayer[ uvIndex * 2 + 1 ];
  5152. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5153. }
  5154. }
  5155. if ( hasFaceVertexUv ) {
  5156. for ( var i = 0; i < nUvLayers; i ++ ) {
  5157. var uvLayer = data.uvs[ i ];
  5158. var uvs = [];
  5159. for ( var j = 0; j < nVertices; j ++ ) {
  5160. var uvIndex = faces[ offset ++ ];
  5161. var u = uvLayer[ uvIndex * 2 ];
  5162. var v = uvLayer[ uvIndex * 2 + 1 ];
  5163. uvs[ j ] = new THREE.UV( u, v );
  5164. }
  5165. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5166. }
  5167. }
  5168. if ( hasFaceNormal ) {
  5169. var normalIndex = faces[ offset ++ ] * 3;
  5170. var normal = new THREE.Vector3();
  5171. normal.x = normals[ normalIndex ++ ];
  5172. normal.y = normals[ normalIndex ++ ];
  5173. normal.z = normals[ normalIndex ];
  5174. face.normal = normal;
  5175. }
  5176. if ( hasFaceVertexNormal ) {
  5177. for ( i = 0; i < nVertices; i ++ ) {
  5178. var normalIndex = faces[ offset ++ ] * 3;
  5179. var normal = new THREE.Vector3();
  5180. normal.x = normals[ normalIndex ++ ];
  5181. normal.y = normals[ normalIndex ++ ];
  5182. normal.z = normals[ normalIndex ];
  5183. face.vertexNormals.push( normal );
  5184. }
  5185. }
  5186. if ( hasFaceColor ) {
  5187. var colorIndex = faces[ offset ++ ];
  5188. face.color = new THREE.Color( colors[ colorIndex ] );
  5189. }
  5190. if ( hasFaceVertexColor ) {
  5191. for ( var i = 0; i < nVertices; i ++ ) {
  5192. var colorIndex = faces[ offset ++ ];
  5193. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  5194. }
  5195. }
  5196. geometry.faces.push( face );
  5197. }
  5198. // skin
  5199. if ( data.skinWeights ) {
  5200. for ( var i = 0, l = data.skinWeights.length; i < l; i += 2 ) {
  5201. var x = data.skinWeights[ i ];
  5202. var y = data.skinWeights[ i + 1 ];
  5203. var z = 0;
  5204. var w = 0;
  5205. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5206. }
  5207. }
  5208. if ( data.skinIndices ) {
  5209. for ( var i = 0, l = data.skinIndices.length; i < l; i += 2 ) {
  5210. var a = data.skinIndices[ i ];
  5211. var b = data.skinIndices[ i + 1 ];
  5212. var c = 0;
  5213. var d = 0;
  5214. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5215. }
  5216. }
  5217. geometry.bones = data.bones;
  5218. geometry.animation = data.animation;
  5219. // morphing
  5220. if ( data.morphTargets ) {
  5221. for ( var i = 0, l = data.morphTargets.length; i < l; i ++ ) {
  5222. geometry.morphTargets[ i ] = {};
  5223. geometry.morphTargets[ i ].name = data.morphTargets[ i ].name;
  5224. geometry.morphTargets[ i ].vertices = [];
  5225. var dstVertices = geometry.morphTargets[ i ].vertices;
  5226. var srcVertices = data.morphTargets [ i ].vertices;
  5227. for( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5228. var vertex = new THREE.Vector3();
  5229. vertex.x = srcVertices[ v ] * scale;
  5230. vertex.y = srcVertices[ v + 1 ] * scale;
  5231. vertex.z = srcVertices[ v + 2 ] * scale;
  5232. dstVertices.push( vertex );
  5233. }
  5234. }
  5235. }
  5236. if ( data.morphColors ) {
  5237. for ( var i = 0, l = data.morphColors.length; i < l; i++ ) {
  5238. geometry.morphColors[ i ] = {};
  5239. geometry.morphColors[ i ].name = data.morphColors[ i ].name;
  5240. geometry.morphColors[ i ].colors = [];
  5241. var dstColors = geometry.morphColors[ i ].colors;
  5242. var srcColors = data.morphColors [ i ].colors;
  5243. for ( var c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5244. var color = new THREE.Color( 0xffaa00 );
  5245. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5246. dstColors.push( color );
  5247. }
  5248. }
  5249. }
  5250. geometry.computeCentroids();
  5251. geometry.computeFaceNormals();
  5252. return geometry;
  5253. }
  5254. };
  5255. /**
  5256. * @author alteredq / http://alteredqualia.com/
  5257. */
  5258. THREE.SceneLoader = function () {
  5259. this.onLoadStart = function () {};
  5260. this.onLoadProgress = function() {};
  5261. this.onLoadComplete = function () {};
  5262. this.callbackSync = function () {};
  5263. this.callbackProgress = function () {};
  5264. };
  5265. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5266. THREE.SceneLoader.prototype.load = function( url, callbackFinished ) {
  5267. var context = this;
  5268. var xhr = new XMLHttpRequest();
  5269. xhr.onreadystatechange = function () {
  5270. if ( xhr.readyState === 4 ) {
  5271. if ( xhr.status === 200 || xhr.status === 0 ) {
  5272. var json = JSON.parse( xhr.responseText );
  5273. context.createScene( json, callbackFinished, url );
  5274. } else {
  5275. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5276. }
  5277. }
  5278. };
  5279. xhr.open( "GET", url, true );
  5280. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "application/json; charset=x-user-defined" );
  5281. xhr.setRequestHeader( "Content-Type", "application/json" );
  5282. xhr.send( null );
  5283. };
  5284. THREE.SceneLoader.prototype.createScene = function ( json, callbackFinished, url ) {
  5285. var scope = this;
  5286. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5287. var dg, dm, dd, dl, dc, df, dt,
  5288. g, o, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  5289. geometry, material, camera, fog,
  5290. texture, images,
  5291. light,
  5292. data, binLoader, jsonLoader,
  5293. counter_models, counter_textures,
  5294. total_models, total_textures,
  5295. result;
  5296. data = json;
  5297. binLoader = new THREE.BinaryLoader();
  5298. jsonLoader = new THREE.JSONLoader();
  5299. counter_models = 0;
  5300. counter_textures = 0;
  5301. result = {
  5302. scene: new THREE.Scene(),
  5303. geometries: {},
  5304. materials: {},
  5305. textures: {},
  5306. objects: {},
  5307. cameras: {},
  5308. lights: {},
  5309. fogs: {},
  5310. empties: {}
  5311. };
  5312. if ( data.transform ) {
  5313. var position = data.transform.position,
  5314. rotation = data.transform.rotation,
  5315. scale = data.transform.scale;
  5316. if ( position )
  5317. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5318. if ( rotation )
  5319. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5320. if ( scale )
  5321. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5322. if ( position || rotation || scale ) {
  5323. result.scene.updateMatrix();
  5324. result.scene.updateMatrixWorld();
  5325. }
  5326. }
  5327. function get_url( source_url, url_type ) {
  5328. if ( url_type == "relativeToHTML" ) {
  5329. return source_url;
  5330. } else {
  5331. return urlBase + "/" + source_url;
  5332. }
  5333. };
  5334. // the toplevel loader function, delegates to handle_children
  5335. function handle_objects() {
  5336. handle_children( result.scene, data.objects );
  5337. }
  5338. // handle all the children from the loaded json and attach them to given parent
  5339. function handle_children( parent, children ) {
  5340. var object;
  5341. for ( dd in children ) {
  5342. // check by id if child has already been handled,
  5343. // if not, create new object
  5344. if ( result.objects[ dd ] === undefined ) {
  5345. o = children[ dd ];
  5346. if ( o.geometry !== undefined ) {
  5347. geometry = result.geometries[ o.geometry ];
  5348. // geometry already loaded
  5349. if ( geometry ) {
  5350. var hasNormals = false;
  5351. // not anymore support for multiple materials
  5352. // shouldn't really be array
  5353. material = result.materials[ o.materials[ 0 ] ];
  5354. hasNormals = material instanceof THREE.ShaderMaterial;
  5355. if ( hasNormals ) {
  5356. geometry.computeTangents();
  5357. }
  5358. p = o.position;
  5359. r = o.rotation;
  5360. q = o.quaternion;
  5361. s = o.scale;
  5362. m = o.matrix;
  5363. // turn off quaternions, for the moment
  5364. q = 0;
  5365. if ( o.materials.length == 0 ) {
  5366. material = new THREE.MeshFaceMaterial();
  5367. }
  5368. // dirty hack to handle meshes with multiple materials
  5369. // just use face materials defined in model
  5370. if ( o.materials.length > 1 ) {
  5371. material = new THREE.MeshFaceMaterial();
  5372. }
  5373. object = new THREE.Mesh( geometry, material );
  5374. object.name = dd;
  5375. if ( m ) {
  5376. object.matrixAutoUpdate = false;
  5377. object.matrix.set(
  5378. m[0], m[1], m[2], m[3],
  5379. m[4], m[5], m[6], m[7],
  5380. m[8], m[9], m[10], m[11],
  5381. m[12], m[13], m[14], m[15]
  5382. );
  5383. } else {
  5384. object.position.set( p[0], p[1], p[2] );
  5385. if ( q ) {
  5386. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5387. object.useQuaternion = true;
  5388. } else {
  5389. object.rotation.set( r[0], r[1], r[2] );
  5390. }
  5391. object.scale.set( s[0], s[1], s[2] );
  5392. }
  5393. object.visible = o.visible;
  5394. object.castShadow = o.castShadow;
  5395. object.receiveShadow = o.receiveShadow;
  5396. parent.add( object );
  5397. result.objects[ dd ] = object;
  5398. }
  5399. // pure Object3D
  5400. } else {
  5401. p = o.position;
  5402. r = o.rotation;
  5403. q = o.quaternion;
  5404. s = o.scale;
  5405. // turn off quaternions, for the moment
  5406. q = 0;
  5407. object = new THREE.Object3D();
  5408. object.name = dd;
  5409. object.position.set( p[0], p[1], p[2] );
  5410. if ( q ) {
  5411. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5412. object.useQuaternion = true;
  5413. } else {
  5414. object.rotation.set( r[0], r[1], r[2] );
  5415. }
  5416. object.scale.set( s[0], s[1], s[2] );
  5417. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  5418. parent.add( object );
  5419. result.objects[ dd ] = object;
  5420. result.empties[ dd ] = object;
  5421. }
  5422. if ( o.properties !== undefined) {
  5423. for ( var key in o.properties ) {
  5424. var value = o.properties[ key ];
  5425. object.properties[ key ] = value;
  5426. }
  5427. }
  5428. if ( o.children !== undefined ) {
  5429. handle_children( object, o.children );
  5430. }
  5431. }
  5432. }
  5433. };
  5434. function handle_mesh( geo, id ) {
  5435. result.geometries[ id ] = geo;
  5436. handle_objects();
  5437. };
  5438. function create_callback( id ) {
  5439. return function( geo ) {
  5440. handle_mesh( geo, id );
  5441. counter_models -= 1;
  5442. scope.onLoadComplete();
  5443. async_callback_gate();
  5444. }
  5445. };
  5446. function create_callback_embed( id ) {
  5447. return function( geo ) {
  5448. result.geometries[ id ] = geo;
  5449. }
  5450. };
  5451. function async_callback_gate() {
  5452. var progress = {
  5453. totalModels : total_models,
  5454. totalTextures : total_textures,
  5455. loadedModels : total_models - counter_models,
  5456. loadedTextures : total_textures - counter_textures
  5457. };
  5458. scope.callbackProgress( progress, result );
  5459. scope.onLoadProgress();
  5460. if ( counter_models === 0 && counter_textures === 0 ) {
  5461. callbackFinished( result );
  5462. }
  5463. };
  5464. var callbackTexture = function ( count ) {
  5465. counter_textures -= count;
  5466. async_callback_gate();
  5467. scope.onLoadComplete();
  5468. };
  5469. // must use this instead of just directly calling callbackTexture
  5470. // because of closure in the calling context loop
  5471. var generateTextureCallback = function ( count ) {
  5472. return function() {
  5473. callbackTexture( count );
  5474. };
  5475. };
  5476. // first go synchronous elements
  5477. // cameras
  5478. for( dc in data.cameras ) {
  5479. c = data.cameras[ dc ];
  5480. if ( c.type === "perspective" ) {
  5481. camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );
  5482. } else if ( c.type === "ortho" ) {
  5483. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  5484. }
  5485. p = c.position;
  5486. t = c.target;
  5487. u = c.up;
  5488. camera.position.set( p[0], p[1], p[2] );
  5489. camera.target = new THREE.Vector3( t[0], t[1], t[2] );
  5490. if ( u ) camera.up.set( u[0], u[1], u[2] );
  5491. result.cameras[ dc ] = camera;
  5492. }
  5493. // lights
  5494. var hex, intensity;
  5495. for ( dl in data.lights ) {
  5496. l = data.lights[ dl ];
  5497. hex = ( l.color !== undefined ) ? l.color : 0xffffff;
  5498. intensity = ( l.intensity !== undefined ) ? l.intensity : 1;
  5499. if ( l.type === "directional" ) {
  5500. p = l.direction;
  5501. light = new THREE.DirectionalLight( hex, intensity );
  5502. light.position.set( p[0], p[1], p[2] );
  5503. light.position.normalize();
  5504. } else if ( l.type === "point" ) {
  5505. p = l.position;
  5506. d = l.distance;
  5507. light = new THREE.PointLight( hex, intensity, d );
  5508. light.position.set( p[0], p[1], p[2] );
  5509. } else if ( l.type === "ambient" ) {
  5510. light = new THREE.AmbientLight( hex );
  5511. }
  5512. result.scene.add( light );
  5513. result.lights[ dl ] = light;
  5514. }
  5515. // fogs
  5516. for( df in data.fogs ) {
  5517. f = data.fogs[ df ];
  5518. if ( f.type === "linear" ) {
  5519. fog = new THREE.Fog( 0x000000, f.near, f.far );
  5520. } else if ( f.type === "exp2" ) {
  5521. fog = new THREE.FogExp2( 0x000000, f.density );
  5522. }
  5523. c = f.color;
  5524. fog.color.setRGB( c[0], c[1], c[2] );
  5525. result.fogs[ df ] = fog;
  5526. }
  5527. // defaults
  5528. if ( result.cameras && data.defaults.camera ) {
  5529. result.currentCamera = result.cameras[ data.defaults.camera ];
  5530. }
  5531. if ( result.fogs && data.defaults.fog ) {
  5532. result.scene.fog = result.fogs[ data.defaults.fog ];
  5533. }
  5534. c = data.defaults.bgcolor;
  5535. result.bgColor = new THREE.Color();
  5536. result.bgColor.setRGB( c[0], c[1], c[2] );
  5537. result.bgColorAlpha = data.defaults.bgalpha;
  5538. // now come potentially asynchronous elements
  5539. // geometries
  5540. // count how many models will be loaded asynchronously
  5541. for( dg in data.geometries ) {
  5542. g = data.geometries[ dg ];
  5543. if ( g.type == "bin_mesh" || g.type == "ascii_mesh" ) {
  5544. counter_models += 1;
  5545. scope.onLoadStart();
  5546. }
  5547. }
  5548. total_models = counter_models;
  5549. for ( dg in data.geometries ) {
  5550. g = data.geometries[ dg ];
  5551. if ( g.type === "cube" ) {
  5552. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.segmentsWidth, g.segmentsHeight, g.segmentsDepth, null, g.flipped, g.sides );
  5553. result.geometries[ dg ] = geometry;
  5554. } else if ( g.type === "plane" ) {
  5555. geometry = new THREE.PlaneGeometry( g.width, g.height, g.segmentsWidth, g.segmentsHeight );
  5556. result.geometries[ dg ] = geometry;
  5557. } else if ( g.type === "sphere" ) {
  5558. geometry = new THREE.SphereGeometry( g.radius, g.segmentsWidth, g.segmentsHeight );
  5559. result.geometries[ dg ] = geometry;
  5560. } else if ( g.type === "cylinder" ) {
  5561. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  5562. result.geometries[ dg ] = geometry;
  5563. } else if ( g.type === "torus" ) {
  5564. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  5565. result.geometries[ dg ] = geometry;
  5566. } else if ( g.type === "icosahedron" ) {
  5567. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  5568. result.geometries[ dg ] = geometry;
  5569. } else if ( g.type === "bin_mesh" ) {
  5570. binLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  5571. } else if ( g.type === "ascii_mesh" ) {
  5572. jsonLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  5573. } else if ( g.type === "embedded_mesh" ) {
  5574. var modelJson = data.embeds[ g.id ],
  5575. texture_path = "";
  5576. // pass metadata along to jsonLoader so it knows the format version
  5577. modelJson.metadata = data.metadata;
  5578. if ( modelJson ) {
  5579. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  5580. }
  5581. }
  5582. }
  5583. // textures
  5584. // count how many textures will be loaded asynchronously
  5585. for( dt in data.textures ) {
  5586. tt = data.textures[ dt ];
  5587. if( tt.url instanceof Array ) {
  5588. counter_textures += tt.url.length;
  5589. for( var n = 0; n < tt.url.length; n ++ ) {
  5590. scope.onLoadStart();
  5591. }
  5592. } else {
  5593. counter_textures += 1;
  5594. scope.onLoadStart();
  5595. }
  5596. }
  5597. total_textures = counter_textures;
  5598. for( dt in data.textures ) {
  5599. tt = data.textures[ dt ];
  5600. if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined ) {
  5601. tt.mapping = new THREE[ tt.mapping ]();
  5602. }
  5603. if( tt.url instanceof Array ) {
  5604. var count = tt.url.length;
  5605. var url_array = [];
  5606. for( var i = 0; i < count; i ++ ) {
  5607. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  5608. }
  5609. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5610. } else {
  5611. texture = THREE.ImageUtils.loadTexture( get_url( tt.url, data.urlBaseType ), tt.mapping, generateTextureCallback( 1 ) );
  5612. if ( THREE[ tt.minFilter ] !== undefined )
  5613. texture.minFilter = THREE[ tt.minFilter ];
  5614. if ( THREE[ tt.magFilter ] !== undefined )
  5615. texture.magFilter = THREE[ tt.magFilter ];
  5616. if ( tt.repeat ) {
  5617. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  5618. if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  5619. if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  5620. }
  5621. if ( tt.offset ) {
  5622. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  5623. }
  5624. // handle wrap after repeat so that default repeat can be overriden
  5625. if ( tt.wrap ) {
  5626. var wrapMap = {
  5627. "repeat" : THREE.RepeatWrapping,
  5628. "mirror" : THREE.MirroredRepeatWrapping
  5629. }
  5630. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  5631. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  5632. }
  5633. }
  5634. result.textures[ dt ] = texture;
  5635. }
  5636. // materials
  5637. for ( dm in data.materials ) {
  5638. m = data.materials[ dm ];
  5639. for ( pp in m.parameters ) {
  5640. if ( pp === "envMap" || pp === "map" || pp === "lightMap" ) {
  5641. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  5642. } else if ( pp === "shading" ) {
  5643. m.parameters[ pp ] = ( m.parameters[ pp ] == "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  5644. } else if ( pp === "blending" ) {
  5645. m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  5646. } else if ( pp === "combine" ) {
  5647. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  5648. } else if ( pp === "vertexColors" ) {
  5649. if ( m.parameters[ pp ] == "face" ) {
  5650. m.parameters[ pp ] = THREE.FaceColors;
  5651. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  5652. } else if ( m.parameters[ pp ] ) {
  5653. m.parameters[ pp ] = THREE.VertexColors;
  5654. }
  5655. }
  5656. }
  5657. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  5658. m.parameters.transparent = true;
  5659. }
  5660. if ( m.parameters.normalMap ) {
  5661. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5662. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5663. var diffuse = m.parameters.color;
  5664. var specular = m.parameters.specular;
  5665. var ambient = m.parameters.ambient;
  5666. var shininess = m.parameters.shininess;
  5667. uniforms[ "tNormal" ].texture = result.textures[ m.parameters.normalMap ];
  5668. if ( m.parameters.normalMapFactor ) {
  5669. uniforms[ "uNormalScale" ].value = m.parameters.normalMapFactor;
  5670. }
  5671. if ( m.parameters.map ) {
  5672. uniforms[ "tDiffuse" ].texture = m.parameters.map;
  5673. uniforms[ "enableDiffuse" ].value = true;
  5674. }
  5675. if ( m.parameters.lightMap ) {
  5676. uniforms[ "tAO" ].texture = m.parameters.lightMap;
  5677. uniforms[ "enableAO" ].value = true;
  5678. }
  5679. if ( m.parameters.specularMap ) {
  5680. uniforms[ "tSpecular" ].texture = result.textures[ m.parameters.specularMap ];
  5681. uniforms[ "enableSpecular" ].value = true;
  5682. }
  5683. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  5684. uniforms[ "uSpecularColor" ].value.setHex( specular );
  5685. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  5686. uniforms[ "uShininess" ].value = shininess;
  5687. if ( m.parameters.opacity ) {
  5688. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  5689. }
  5690. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5691. material = new THREE.ShaderMaterial( parameters );
  5692. } else {
  5693. material = new THREE[ m.type ]( m.parameters );
  5694. }
  5695. result.materials[ dm ] = material;
  5696. }
  5697. // objects ( synchronous init of procedural primitives )
  5698. handle_objects();
  5699. // synchronous callback
  5700. scope.callbackSync( result );
  5701. // just in case there are no async elements
  5702. async_callback_gate();
  5703. };
  5704. /**
  5705. * @author mrdoob / http://mrdoob.com/
  5706. */
  5707. THREE.TextureLoader = function () {
  5708. THREE.EventTarget.call( this );
  5709. this.crossOrigin = null;
  5710. };
  5711. THREE.TextureLoader.prototype = {
  5712. constructor: THREE.TextureLoader,
  5713. load: function ( url ) {
  5714. var scope = this;
  5715. var image = new Image();
  5716. image.addEventListener( 'load', function () {
  5717. var texture = new THREE.Texture( image );
  5718. texture.needsUpdate = true;
  5719. scope.dispatchEvent( { type: 'load', content: texture } );
  5720. }, false );
  5721. image.addEventListener( 'error', function () {
  5722. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5723. }, false );
  5724. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5725. image.src = url;
  5726. }
  5727. }
  5728. /**
  5729. * @author mrdoob / http://mrdoob.com/
  5730. * @author alteredq / http://alteredqualia.com/
  5731. */
  5732. THREE.Material = function () {
  5733. this.id = THREE.MaterialCount ++;
  5734. this.name = '';
  5735. this.side = THREE.FrontSide;
  5736. this.opacity = 1;
  5737. this.transparent = false;
  5738. this.blending = THREE.NormalBlending;
  5739. this.blendSrc = THREE.SrcAlphaFactor;
  5740. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  5741. this.blendEquation = THREE.AddEquation;
  5742. this.depthTest = true;
  5743. this.depthWrite = true;
  5744. this.polygonOffset = false;
  5745. this.polygonOffsetFactor = 0;
  5746. this.polygonOffsetUnits = 0;
  5747. this.alphaTest = 0;
  5748. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  5749. this.visible = true;
  5750. this.needsUpdate = true;
  5751. };
  5752. THREE.Material.prototype.setValues = function ( values ) {
  5753. if ( values === undefined ) return;
  5754. for ( var key in values ) {
  5755. var newValue = values[ key ];
  5756. if ( newValue === undefined ) {
  5757. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5758. continue;
  5759. }
  5760. if ( key in this ) {
  5761. var currentValue = this[ key ];
  5762. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  5763. currentValue.copy( newValue );
  5764. } else if ( currentValue instanceof THREE.Color && typeof( newValue ) === "number" ) {
  5765. currentValue.setHex( newValue );
  5766. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  5767. currentValue.copy( newValue );
  5768. } else {
  5769. this[ key ] = newValue;
  5770. }
  5771. }
  5772. }
  5773. };
  5774. THREE.Material.prototype.clone = function ( material ) {
  5775. if ( material === undefined ) material = new THREE.Material();
  5776. material.name = this.name;
  5777. material.side = this.side;
  5778. material.opacity = this.opacity;
  5779. material.transparent = this.transparent;
  5780. material.blending = this.blending;
  5781. material.blendSrc = this.blendSrc;
  5782. material.blendDst = this.blendDst;
  5783. material.blendEquation = this.blendEquation;
  5784. material.depthTest = this.depthTest;
  5785. material.depthWrite = this.depthWrite;
  5786. material.polygonOffset = this.polygonOffset;
  5787. material.polygonOffsetFactor = this.polygonOffsetFactor;
  5788. material.polygonOffsetUnits = this.polygonOffsetUnits;
  5789. material.alphaTest = this.alphaTest;
  5790. material.overdraw = this.overdraw;
  5791. material.visible = this.visible;
  5792. return material;
  5793. };
  5794. THREE.MaterialCount = 0;
  5795. /**
  5796. * @author mrdoob / http://mrdoob.com/
  5797. * @author alteredq / http://alteredqualia.com/
  5798. *
  5799. * parameters = {
  5800. * color: <hex>,
  5801. * opacity: <float>,
  5802. *
  5803. * blending: THREE.NormalBlending,
  5804. * depthTest: <bool>,
  5805. *
  5806. * linewidth: <float>,
  5807. * linecap: "round",
  5808. * linejoin: "round",
  5809. *
  5810. * vertexColors: <bool>
  5811. *
  5812. * fog: <bool>
  5813. * }
  5814. */
  5815. THREE.LineBasicMaterial = function ( parameters ) {
  5816. THREE.Material.call( this );
  5817. this.color = new THREE.Color( 0xffffff );
  5818. this.linewidth = 1;
  5819. this.linecap = 'round';
  5820. this.linejoin = 'round';
  5821. this.vertexColors = false;
  5822. this.fog = true;
  5823. this.setValues( parameters );
  5824. };
  5825. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  5826. THREE.LineBasicMaterial.prototype.clone = function () {
  5827. var material = new THREE.LineBasicMaterial();
  5828. THREE.Material.prototype.clone.call( this, material );
  5829. material.color.copy( this.color );
  5830. material.linewidth = this.linewidth;
  5831. material.linecap = this.linecap;
  5832. material.linejoin = this.linejoin;
  5833. material.vertexColors = this.vertexColors;
  5834. material.fog = this.fog;
  5835. return material;
  5836. };
  5837. /**
  5838. * @author mrdoob / http://mrdoob.com/
  5839. * @author alteredq / http://alteredqualia.com/
  5840. *
  5841. * parameters = {
  5842. * color: <hex>,
  5843. * opacity: <float>,
  5844. * map: new THREE.Texture( <Image> ),
  5845. *
  5846. * lightMap: new THREE.Texture( <Image> ),
  5847. *
  5848. * specularMap: new THREE.Texture( <Image> ),
  5849. *
  5850. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  5851. * combine: THREE.Multiply,
  5852. * reflectivity: <float>,
  5853. * refractionRatio: <float>,
  5854. *
  5855. * shading: THREE.SmoothShading,
  5856. * blending: THREE.NormalBlending,
  5857. * depthTest: <bool>,
  5858. *
  5859. * wireframe: <boolean>,
  5860. * wireframeLinewidth: <float>,
  5861. *
  5862. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  5863. *
  5864. * skinning: <bool>,
  5865. * morphTargets: <bool>,
  5866. *
  5867. * fog: <bool>
  5868. * }
  5869. */
  5870. THREE.MeshBasicMaterial = function ( parameters ) {
  5871. THREE.Material.call( this );
  5872. this.color = new THREE.Color( 0xffffff ); // emissive
  5873. this.map = null;
  5874. this.lightMap = null;
  5875. this.specularMap = null;
  5876. this.envMap = null;
  5877. this.combine = THREE.MultiplyOperation;
  5878. this.reflectivity = 1;
  5879. this.refractionRatio = 0.98;
  5880. this.fog = true;
  5881. this.shading = THREE.SmoothShading;
  5882. this.wireframe = false;
  5883. this.wireframeLinewidth = 1;
  5884. this.wireframeLinecap = 'round';
  5885. this.wireframeLinejoin = 'round';
  5886. this.vertexColors = THREE.NoColors;
  5887. this.skinning = false;
  5888. this.morphTargets = false;
  5889. this.setValues( parameters );
  5890. };
  5891. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  5892. THREE.MeshBasicMaterial.prototype.clone = function () {
  5893. var material = new THREE.MeshBasicMaterial();
  5894. THREE.Material.prototype.clone.call( this, material );
  5895. material.color.copy( this.color );
  5896. material.map = this.map;
  5897. material.lightMap = this.lightMap;
  5898. material.specularMap = this.specularMap;
  5899. material.envMap = this.envMap;
  5900. material.combine = this.combine;
  5901. material.reflectivity = this.reflectivity;
  5902. material.refractionRatio = this.refractionRatio;
  5903. material.fog = this.fog;
  5904. material.shading = this.shading;
  5905. material.wireframe = this.wireframe;
  5906. material.wireframeLinewidth = this.wireframeLinewidth;
  5907. material.wireframeLinecap = this.wireframeLinecap;
  5908. material.wireframeLinejoin = this.wireframeLinejoin;
  5909. material.vertexColors = this.vertexColors;
  5910. material.skinning = this.skinning;
  5911. material.morphTargets = this.morphTargets;
  5912. return material;
  5913. };
  5914. /**
  5915. * @author mrdoob / http://mrdoob.com/
  5916. * @author alteredq / http://alteredqualia.com/
  5917. *
  5918. * parameters = {
  5919. * color: <hex>,
  5920. * ambient: <hex>,
  5921. * emissive: <hex>,
  5922. * opacity: <float>,
  5923. *
  5924. * map: new THREE.Texture( <Image> ),
  5925. *
  5926. * lightMap: new THREE.Texture( <Image> ),
  5927. *
  5928. * specularMap: new THREE.Texture( <Image> ),
  5929. *
  5930. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  5931. * combine: THREE.Multiply,
  5932. * reflectivity: <float>,
  5933. * refractionRatio: <float>,
  5934. *
  5935. * shading: THREE.SmoothShading,
  5936. * blending: THREE.NormalBlending,
  5937. * depthTest: <bool>,
  5938. *
  5939. * wireframe: <boolean>,
  5940. * wireframeLinewidth: <float>,
  5941. *
  5942. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  5943. *
  5944. * skinning: <bool>,
  5945. * morphTargets: <bool>,
  5946. * morphNormals: <bool>,
  5947. *
  5948. * fog: <bool>
  5949. * }
  5950. */
  5951. THREE.MeshLambertMaterial = function ( parameters ) {
  5952. THREE.Material.call( this );
  5953. this.color = new THREE.Color( 0xffffff ); // diffuse
  5954. this.ambient = new THREE.Color( 0xffffff );
  5955. this.emissive = new THREE.Color( 0x000000 );
  5956. this.wrapAround = false;
  5957. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  5958. this.map = null;
  5959. this.lightMap = null;
  5960. this.specularMap = null;
  5961. this.envMap = null;
  5962. this.combine = THREE.MultiplyOperation;
  5963. this.reflectivity = 1;
  5964. this.refractionRatio = 0.98;
  5965. this.fog = true;
  5966. this.shading = THREE.SmoothShading;
  5967. this.wireframe = false;
  5968. this.wireframeLinewidth = 1;
  5969. this.wireframeLinecap = 'round';
  5970. this.wireframeLinejoin = 'round';
  5971. this.vertexColors = THREE.NoColors;
  5972. this.skinning = false;
  5973. this.morphTargets = false;
  5974. this.morphNormals = false;
  5975. this.setValues( parameters );
  5976. };
  5977. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  5978. THREE.MeshLambertMaterial.prototype.clone = function () {
  5979. var material = new THREE.MeshLambertMaterial();
  5980. THREE.Material.prototype.clone.call( this, material );
  5981. material.color.copy( this.color );
  5982. material.ambient.copy( this.ambient );
  5983. material.emissive.copy( this.emissive );
  5984. material.wrapAround = this.wrapAround;
  5985. material.wrapRGB.copy( this.wrapRGB );
  5986. material.map = this.map;
  5987. material.lightMap = this.lightMap;
  5988. material.specularMap = this.specularMap;
  5989. material.envMap = this.envMap;
  5990. material.combine = this.combine;
  5991. material.reflectivity = this.reflectivity;
  5992. material.refractionRatio = this.refractionRatio;
  5993. material.fog = this.fog;
  5994. material.shading = this.shading;
  5995. material.wireframe = this.wireframe;
  5996. material.wireframeLinewidth = this.wireframeLinewidth;
  5997. material.wireframeLinecap = this.wireframeLinecap;
  5998. material.wireframeLinejoin = this.wireframeLinejoin;
  5999. material.vertexColors = this.vertexColors;
  6000. material.skinning = this.skinning;
  6001. material.morphTargets = this.morphTargets;
  6002. material.morphNormals = this.morphNormals;
  6003. return material;
  6004. };
  6005. /**
  6006. * @author mrdoob / http://mrdoob.com/
  6007. * @author alteredq / http://alteredqualia.com/
  6008. *
  6009. * parameters = {
  6010. * color: <hex>,
  6011. * ambient: <hex>,
  6012. * emissive: <hex>,
  6013. * specular: <hex>,
  6014. * shininess: <float>,
  6015. * opacity: <float>,
  6016. *
  6017. * map: new THREE.Texture( <Image> ),
  6018. *
  6019. * lightMap: new THREE.Texture( <Image> ),
  6020. *
  6021. * bumpMap: new THREE.Texture( <Image> ),
  6022. * bumpScale: <float>,
  6023. *
  6024. * specularMap: new THREE.Texture( <Image> ),
  6025. *
  6026. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6027. * combine: THREE.Multiply,
  6028. * reflectivity: <float>,
  6029. * refractionRatio: <float>,
  6030. *
  6031. * shading: THREE.SmoothShading,
  6032. * blending: THREE.NormalBlending,
  6033. * depthTest: <bool>,
  6034. *
  6035. * wireframe: <boolean>,
  6036. * wireframeLinewidth: <float>,
  6037. *
  6038. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6039. *
  6040. * skinning: <bool>,
  6041. * morphTargets: <bool>,
  6042. * morphNormals: <bool>,
  6043. *
  6044. * fog: <bool>
  6045. * }
  6046. */
  6047. THREE.MeshPhongMaterial = function ( parameters ) {
  6048. THREE.Material.call( this );
  6049. this.color = new THREE.Color( 0xffffff ); // diffuse
  6050. this.ambient = new THREE.Color( 0xffffff );
  6051. this.emissive = new THREE.Color( 0x000000 );
  6052. this.specular = new THREE.Color( 0x111111 );
  6053. this.shininess = 30;
  6054. this.metal = false;
  6055. this.perPixel = false;
  6056. this.wrapAround = false;
  6057. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6058. this.map = null;
  6059. this.lightMap = null;
  6060. this.bumpMap = null;
  6061. this.bumpScale = 1;
  6062. this.specularMap = null;
  6063. this.envMap = null;
  6064. this.combine = THREE.MultiplyOperation;
  6065. this.reflectivity = 1;
  6066. this.refractionRatio = 0.98;
  6067. this.fog = true;
  6068. this.shading = THREE.SmoothShading;
  6069. this.wireframe = false;
  6070. this.wireframeLinewidth = 1;
  6071. this.wireframeLinecap = 'round';
  6072. this.wireframeLinejoin = 'round';
  6073. this.vertexColors = THREE.NoColors;
  6074. this.skinning = false;
  6075. this.morphTargets = false;
  6076. this.morphNormals = false;
  6077. this.setValues( parameters );
  6078. };
  6079. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6080. THREE.MeshPhongMaterial.prototype.clone = function () {
  6081. var material = new THREE.MeshPhongMaterial();
  6082. THREE.Material.prototype.clone.call( this, material );
  6083. material.color.copy( this.color );
  6084. material.ambient.copy( this.ambient );
  6085. material.emissive.copy( this.emissive );
  6086. material.specular.copy( this.specular );
  6087. material.shininess = this.shininess;
  6088. material.metal = this.metal;
  6089. material.perPixel = this.perPixel;
  6090. material.wrapAround = this.wrapAround;
  6091. material.wrapRGB.copy( this.wrapRGB );
  6092. material.map = this.map;
  6093. material.lightMap = this.lightMap;
  6094. material.bumpMap = this.bumpMap;
  6095. material.bumpScale= this.bumpScale;
  6096. material.specularMap = this.specularMap;
  6097. material.envMap = this.envMap;
  6098. material.combine = this.combine;
  6099. material.reflectivity = this.reflectivity;
  6100. material.refractionRatio = this.refractionRatio;
  6101. material.fog = this.fog;
  6102. material.shading = this.shading;
  6103. material.wireframe = this.wireframe;
  6104. material.wireframeLinewidth = this.wireframeLinewidth;
  6105. material.wireframeLinecap = this.wireframeLinecap;
  6106. material.wireframeLinejoin = this.wireframeLinejoin;
  6107. material.vertexColors = this.vertexColors;
  6108. material.skinning = this.skinning;
  6109. material.morphTargets = this.morphTargets;
  6110. material.morphNormals = this.morphNormals;
  6111. return material;
  6112. };
  6113. /**
  6114. * @author mrdoob / http://mrdoob.com/
  6115. * @author alteredq / http://alteredqualia.com/
  6116. *
  6117. * parameters = {
  6118. * opacity: <float>,
  6119. * blending: THREE.NormalBlending,
  6120. * depthTest: <bool>,
  6121. * wireframe: <boolean>,
  6122. * wireframeLinewidth: <float>
  6123. * }
  6124. */
  6125. THREE.MeshDepthMaterial = function ( parameters ) {
  6126. THREE.Material.call( this );
  6127. this.wireframe = false;
  6128. this.wireframeLinewidth = 1;
  6129. this.setValues( parameters );
  6130. };
  6131. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6132. THREE.MeshDepthMaterial.prototype.clone = function () {
  6133. var material = new THREE.LineBasicMaterial();
  6134. THREE.Material.prototype.clone.call( this, material );
  6135. material.wireframe = this.wireframe;
  6136. material.wireframeLinewidth = this.wireframeLinewidth;
  6137. return material;
  6138. };
  6139. /**
  6140. * @author mrdoob / http://mrdoob.com/
  6141. *
  6142. * parameters = {
  6143. * opacity: <float>,
  6144. * shading: THREE.FlatShading,
  6145. * blending: THREE.NormalBlending,
  6146. * depthTest: <bool>,
  6147. * wireframe: <boolean>,
  6148. * wireframeLinewidth: <float>
  6149. * }
  6150. */
  6151. THREE.MeshNormalMaterial = function ( parameters ) {
  6152. THREE.Material.call( this, parameters );
  6153. this.shading = THREE.FlatShading;
  6154. this.wireframe = false;
  6155. this.wireframeLinewidth = 1;
  6156. this.setValues( parameters );
  6157. };
  6158. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6159. THREE.MeshNormalMaterial.prototype.clone = function () {
  6160. var material = new THREE.MeshNormalMaterial();
  6161. THREE.Material.prototype.clone.call( this, material );
  6162. material.shading = this.shading;
  6163. material.wireframe = this.wireframe;
  6164. material.wireframeLinewidth = this.wireframeLinewidth;
  6165. return material;
  6166. };
  6167. /**
  6168. * @author mrdoob / http://mrdoob.com/
  6169. */
  6170. THREE.MeshFaceMaterial = function () {};
  6171. THREE.MeshFaceMaterial.prototype.clone = function () {
  6172. return new THREE.MeshFaceMaterial();
  6173. };
  6174. /**
  6175. * @author mrdoob / http://mrdoob.com/
  6176. * @author alteredq / http://alteredqualia.com/
  6177. *
  6178. * parameters = {
  6179. * color: <hex>,
  6180. * opacity: <float>,
  6181. * map: new THREE.Texture( <Image> ),
  6182. *
  6183. * size: <float>,
  6184. *
  6185. * blending: THREE.NormalBlending,
  6186. * depthTest: <bool>,
  6187. *
  6188. * vertexColors: <bool>,
  6189. *
  6190. * fog: <bool>
  6191. * }
  6192. */
  6193. THREE.ParticleBasicMaterial = function ( parameters ) {
  6194. THREE.Material.call( this );
  6195. this.color = new THREE.Color( 0xffffff );
  6196. this.map = null;
  6197. this.size = 1;
  6198. this.sizeAttenuation = true;
  6199. this.vertexColors = false;
  6200. this.fog = true;
  6201. this.setValues( parameters );
  6202. };
  6203. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6204. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6205. var material = new THREE.ParticleBasicMaterial();
  6206. THREE.Material.prototype.clone.call( this, material );
  6207. material.color.copy( this.color );
  6208. material.map = this.map;
  6209. material.size = this.size;
  6210. material.sizeAttenuation = this.sizeAttenuation;
  6211. material.vertexColors = this.vertexColors;
  6212. material.fog = this.fog;
  6213. return material;
  6214. };
  6215. /**
  6216. * @author mrdoob / http://mrdoob.com/
  6217. *
  6218. * parameters = {
  6219. * color: <hex>,
  6220. * program: <function>,
  6221. * opacity: <float>,
  6222. * blending: THREE.NormalBlending
  6223. * }
  6224. */
  6225. THREE.ParticleCanvasMaterial = function ( parameters ) {
  6226. THREE.Material.call( this );
  6227. this.color = new THREE.Color( 0xffffff );
  6228. this.program = function ( context, color ) {};
  6229. this.setValues( parameters );
  6230. };
  6231. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  6232. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  6233. var material = new THREE.ParticleCanvasMaterial();
  6234. THREE.Material.prototype.clone.call( this, material );
  6235. material.color.copy( this.color );
  6236. material.program = this.program;
  6237. return material;
  6238. };
  6239. /**
  6240. * @author mrdoob / http://mrdoob.com/
  6241. */
  6242. THREE.ParticleDOMMaterial = function ( domElement ) {
  6243. this.domElement = domElement;
  6244. };
  6245. THREE.ParticleDOMMaterial.prototype.clone = function(){
  6246. return new THREE.ParticleDOMMaterial( this.domElement );
  6247. };
  6248. /**
  6249. * @author alteredq / http://alteredqualia.com/
  6250. *
  6251. * parameters = {
  6252. * fragmentShader: <string>,
  6253. * vertexShader: <string>,
  6254. *
  6255. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  6256. *
  6257. * shading: THREE.SmoothShading,
  6258. * blending: THREE.NormalBlending,
  6259. * depthTest: <bool>,
  6260. *
  6261. * wireframe: <boolean>,
  6262. * wireframeLinewidth: <float>,
  6263. *
  6264. * lights: <bool>,
  6265. *
  6266. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6267. *
  6268. * skinning: <bool>,
  6269. * morphTargets: <bool>,
  6270. * morphNormals: <bool>,
  6271. *
  6272. * fog: <bool>
  6273. * }
  6274. */
  6275. THREE.ShaderMaterial = function ( parameters ) {
  6276. THREE.Material.call( this );
  6277. this.fragmentShader = "void main() {}";
  6278. this.vertexShader = "void main() {}";
  6279. this.uniforms = {};
  6280. this.attributes = null;
  6281. this.shading = THREE.SmoothShading;
  6282. this.wireframe = false;
  6283. this.wireframeLinewidth = 1;
  6284. this.fog = false; // set to use scene fog
  6285. this.lights = false; // set to use scene lights
  6286. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  6287. this.skinning = false; // set to use skinning attribute streams
  6288. this.morphTargets = false; // set to use morph targets
  6289. this.morphNormals = false; // set to use morph normals
  6290. this.setValues( parameters );
  6291. };
  6292. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  6293. THREE.ShaderMaterial.prototype.clone = function () {
  6294. var material = new THREE.ShaderMaterial();
  6295. THREE.Material.prototype.clone.call( this, material );
  6296. material.fragmentShader = this.fragmentShader;
  6297. material.vertexShader = this.vertexShader;
  6298. material.uniforms = this.uniforms;
  6299. material.attributes = this.attributes;
  6300. material.shading = this.shading;
  6301. material.wireframe = this.wireframe;
  6302. material.wireframeLinewidth = this.wireframeLinewidth;
  6303. material.fog = this.fog;
  6304. material.lights = this.lights;
  6305. material.vertexColors = this.vertexColors;
  6306. material.skinning = this.skinning;
  6307. material.morphTargets = this.morphTargets;
  6308. material.morphNormals = this.morphNormals;
  6309. return material;
  6310. };
  6311. /**
  6312. * @author mrdoob / http://mrdoob.com/
  6313. * @author alteredq / http://alteredqualia.com/
  6314. * @author szimek / https://github.com/szimek/
  6315. */
  6316. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  6317. this.id = THREE.TextureCount ++;
  6318. this.image = image;
  6319. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  6320. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  6321. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  6322. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  6323. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  6324. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6325. this.format = format !== undefined ? format : THREE.RGBAFormat;
  6326. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  6327. this.offset = new THREE.Vector2( 0, 0 );
  6328. this.repeat = new THREE.Vector2( 1, 1 );
  6329. this.generateMipmaps = true;
  6330. this.premultiplyAlpha = false;
  6331. this.flipY = true;
  6332. this.needsUpdate = false;
  6333. this.onUpdate = null;
  6334. };
  6335. THREE.Texture.prototype = {
  6336. constructor: THREE.Texture,
  6337. clone: function () {
  6338. var clonedTexture = new THREE.Texture( this.image, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter, this.format, this.type, this.anisotropy );
  6339. clonedTexture.offset.copy( this.offset );
  6340. clonedTexture.repeat.copy( this.repeat );
  6341. clonedTexture.generateMipmaps = this.generateMipmaps;
  6342. clonedTexture.premultiplyAlpha = this.premultiplyAlpha;
  6343. clonedTexture.flipY = this.flipY;
  6344. return clonedTexture;
  6345. }
  6346. };
  6347. THREE.TextureCount = 0;
  6348. /**
  6349. * @author alteredq / http://alteredqualia.com/
  6350. */
  6351. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6352. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6353. this.image = { data: data, width: width, height: height };
  6354. };
  6355. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  6356. THREE.DataTexture.prototype.clone = function () {
  6357. var clonedTexture = new THREE.DataTexture( this.image.data, this.image.width, this.image.height, this.format, this.type, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter );
  6358. clonedTexture.offset.copy( this.offset );
  6359. clonedTexture.repeat.copy( this.repeat );
  6360. return clonedTexture;
  6361. };
  6362. /**
  6363. * @author mrdoob / http://mrdoob.com/
  6364. */
  6365. THREE.Particle = function ( material ) {
  6366. THREE.Object3D.call( this );
  6367. this.material = material;
  6368. };
  6369. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  6370. /**
  6371. * @author alteredq / http://alteredqualia.com/
  6372. */
  6373. THREE.ParticleSystem = function ( geometry, material ) {
  6374. THREE.Object3D.call( this );
  6375. this.geometry = geometry;
  6376. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  6377. this.sortParticles = false;
  6378. if ( this.geometry ) {
  6379. // calc bound radius
  6380. if( !this.geometry.boundingSphere ) {
  6381. this.geometry.computeBoundingSphere();
  6382. }
  6383. this.boundRadius = geometry.boundingSphere.radius;
  6384. }
  6385. this.frustumCulled = false;
  6386. };
  6387. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  6388. /**
  6389. * @author mrdoob / http://mrdoob.com/
  6390. */
  6391. THREE.Line = function ( geometry, material, type ) {
  6392. THREE.Object3D.call( this );
  6393. this.geometry = geometry;
  6394. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6395. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  6396. if ( this.geometry ) {
  6397. if ( ! this.geometry.boundingSphere ) {
  6398. this.geometry.computeBoundingSphere();
  6399. }
  6400. }
  6401. };
  6402. THREE.LineStrip = 0;
  6403. THREE.LinePieces = 1;
  6404. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  6405. /**
  6406. * @author mrdoob / http://mrdoob.com/
  6407. * @author alteredq / http://alteredqualia.com/
  6408. * @author mikael emtinger / http://gomo.se/
  6409. */
  6410. THREE.Mesh = function ( geometry, material ) {
  6411. THREE.Object3D.call( this );
  6412. this.geometry = geometry;
  6413. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  6414. if ( this.geometry ) {
  6415. // calc bound radius
  6416. if ( ! this.geometry.boundingSphere ) {
  6417. this.geometry.computeBoundingSphere();
  6418. }
  6419. this.boundRadius = geometry.boundingSphere.radius;
  6420. // setup morph targets
  6421. if( this.geometry.morphTargets.length ) {
  6422. this.morphTargetBase = -1;
  6423. this.morphTargetForcedOrder = [];
  6424. this.morphTargetInfluences = [];
  6425. this.morphTargetDictionary = {};
  6426. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  6427. this.morphTargetInfluences.push( 0 );
  6428. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  6429. }
  6430. }
  6431. }
  6432. }
  6433. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  6434. /*
  6435. * Get Morph Target Index by Name
  6436. */
  6437. THREE.Mesh.prototype.getMorphTargetIndexByName = function( name ) {
  6438. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  6439. return this.morphTargetDictionary[ name ];
  6440. }
  6441. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  6442. return 0;
  6443. }
  6444. /**
  6445. * @author mikael emtinger / http://gomo.se/
  6446. * @author alteredq / http://alteredqualia.com/
  6447. */
  6448. THREE.Bone = function( belongsToSkin ) {
  6449. THREE.Object3D.call( this );
  6450. this.skin = belongsToSkin;
  6451. this.skinMatrix = new THREE.Matrix4();
  6452. };
  6453. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  6454. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  6455. // update local
  6456. if ( this.matrixAutoUpdate ) {
  6457. forceUpdate |= this.updateMatrix();
  6458. }
  6459. // update skin matrix
  6460. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  6461. if( parentSkinMatrix ) {
  6462. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  6463. } else {
  6464. this.skinMatrix.copy( this.matrix );
  6465. }
  6466. this.matrixWorldNeedsUpdate = false;
  6467. forceUpdate = true;
  6468. }
  6469. // update children
  6470. var child, i, l = this.children.length;
  6471. for ( i = 0; i < l; i ++ ) {
  6472. this.children[ i ].update( this.skinMatrix, forceUpdate );
  6473. }
  6474. };
  6475. /**
  6476. * @author mikael emtinger / http://gomo.se/
  6477. * @author alteredq / http://alteredqualia.com/
  6478. */
  6479. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  6480. THREE.Mesh.call( this, geometry, material );
  6481. //
  6482. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  6483. // init bones
  6484. this.identityMatrix = new THREE.Matrix4();
  6485. this.bones = [];
  6486. this.boneMatrices = [];
  6487. var b, bone, gbone, p, q, s;
  6488. if ( this.geometry.bones !== undefined ) {
  6489. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  6490. gbone = this.geometry.bones[ b ];
  6491. p = gbone.pos;
  6492. q = gbone.rotq;
  6493. s = gbone.scl;
  6494. bone = this.addBone();
  6495. bone.name = gbone.name;
  6496. bone.position.set( p[0], p[1], p[2] );
  6497. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  6498. bone.useQuaternion = true;
  6499. if ( s !== undefined ) {
  6500. bone.scale.set( s[0], s[1], s[2] );
  6501. } else {
  6502. bone.scale.set( 1, 1, 1 );
  6503. }
  6504. }
  6505. for ( b = 0; b < this.bones.length; b ++ ) {
  6506. gbone = this.geometry.bones[ b ];
  6507. bone = this.bones[ b ];
  6508. if ( gbone.parent === -1 ) {
  6509. this.add( bone );
  6510. } else {
  6511. this.bones[ gbone.parent ].add( bone );
  6512. }
  6513. }
  6514. //
  6515. var nBones = this.bones.length;
  6516. if ( this.useVertexTexture ) {
  6517. // layout (1 matrix = 4 pixels)
  6518. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  6519. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  6520. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  6521. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  6522. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  6523. var size;
  6524. if ( nBones > 256 )
  6525. size = 64;
  6526. else if ( nBones > 64 )
  6527. size = 32;
  6528. else if ( nBones > 16 )
  6529. size = 16;
  6530. else
  6531. size = 8;
  6532. this.boneTextureWidth = size;
  6533. this.boneTextureHeight = size;
  6534. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  6535. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  6536. this.boneTexture.minFilter = THREE.NearestFilter;
  6537. this.boneTexture.magFilter = THREE.NearestFilter;
  6538. this.boneTexture.generateMipmaps = false;
  6539. this.boneTexture.flipY = false;
  6540. } else {
  6541. this.boneMatrices = new Float32Array( 16 * nBones );
  6542. }
  6543. this.pose();
  6544. }
  6545. };
  6546. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  6547. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  6548. if ( bone === undefined ) {
  6549. bone = new THREE.Bone( this );
  6550. }
  6551. this.bones.push( bone );
  6552. return bone;
  6553. };
  6554. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  6555. this.matrixAutoUpdate && this.updateMatrix();
  6556. // update matrixWorld
  6557. if ( this.matrixWorldNeedsUpdate || force ) {
  6558. if ( this.parent ) {
  6559. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  6560. } else {
  6561. this.matrixWorld.copy( this.matrix );
  6562. }
  6563. this.matrixWorldNeedsUpdate = false;
  6564. force = true;
  6565. }
  6566. // update children
  6567. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6568. var child = this.children[ i ];
  6569. if ( child instanceof THREE.Bone ) {
  6570. child.update( this.identityMatrix, false );
  6571. } else {
  6572. child.updateMatrixWorld( true );
  6573. }
  6574. }
  6575. // make a snapshot of the bones' rest position
  6576. if ( this.boneInverses == undefined ) {
  6577. this.boneInverses = [];
  6578. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6579. var inverse = new THREE.Matrix4();
  6580. inverse.getInverse( this.bones[ b ].skinMatrix );
  6581. this.boneInverses.push( inverse );
  6582. }
  6583. }
  6584. // flatten bone matrices to array
  6585. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6586. // compute the offset between the current and the original transform;
  6587. //TODO: we could get rid of this multiplication step if the skinMatrix
  6588. // was already representing the offset; however, this requires some
  6589. // major changes to the animation system
  6590. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  6591. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  6592. }
  6593. if ( this.useVertexTexture ) {
  6594. this.boneTexture.needsUpdate = true;
  6595. }
  6596. };
  6597. /*
  6598. * Pose
  6599. */
  6600. THREE.SkinnedMesh.prototype.pose = function() {
  6601. this.updateMatrixWorld( true );
  6602. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  6603. // normalize weights
  6604. var sw = this.geometry.skinWeights[ i ];
  6605. var scale = 1.0 / sw.lengthManhattan();
  6606. if ( scale !== Infinity ) {
  6607. sw.multiplyScalar( scale );
  6608. } else {
  6609. sw.set( 1 ); // this will be normalized by the shader anyway
  6610. }
  6611. }
  6612. };
  6613. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  6614. /**
  6615. * @author alteredq / http://alteredqualia.com/
  6616. */
  6617. THREE.MorphAnimMesh = function ( geometry, material ) {
  6618. THREE.Mesh.call( this, geometry, material );
  6619. // API
  6620. this.duration = 1000; // milliseconds
  6621. this.mirroredLoop = false;
  6622. this.time = 0;
  6623. // internals
  6624. this.lastKeyframe = 0;
  6625. this.currentKeyframe = 0;
  6626. this.direction = 1;
  6627. this.directionBackwards = false;
  6628. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  6629. };
  6630. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  6631. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  6632. this.startKeyframe = start;
  6633. this.endKeyframe = end;
  6634. this.length = this.endKeyframe - this.startKeyframe + 1;
  6635. };
  6636. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  6637. this.direction = 1;
  6638. this.directionBackwards = false;
  6639. };
  6640. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  6641. this.direction = -1;
  6642. this.directionBackwards = true;
  6643. };
  6644. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  6645. var geometry = this.geometry;
  6646. if ( ! geometry.animations ) geometry.animations = {};
  6647. var firstAnimation, animations = geometry.animations;
  6648. var pattern = /([a-z]+)(\d+)/;
  6649. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  6650. var morph = geometry.morphTargets[ i ];
  6651. var parts = morph.name.match( pattern );
  6652. if ( parts && parts.length > 1 ) {
  6653. var label = parts[ 1 ];
  6654. var num = parts[ 2 ];
  6655. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  6656. var animation = animations[ label ];
  6657. if ( i < animation.start ) animation.start = i;
  6658. if ( i > animation.end ) animation.end = i;
  6659. if ( ! firstAnimation ) firstAnimation = label;
  6660. }
  6661. }
  6662. geometry.firstAnimation = firstAnimation;
  6663. };
  6664. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  6665. if ( ! this.geometry.animations ) this.geometry.animations = {};
  6666. this.geometry.animations[ label ] = { start: start, end: end };
  6667. };
  6668. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  6669. var animation = this.geometry.animations[ label ];
  6670. if ( animation ) {
  6671. this.setFrameRange( animation.start, animation.end );
  6672. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  6673. this.time = 0;
  6674. } else {
  6675. console.warn( "animation[" + label + "] undefined" );
  6676. }
  6677. };
  6678. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  6679. var frameTime = this.duration / this.length;
  6680. this.time += this.direction * delta;
  6681. if ( this.mirroredLoop ) {
  6682. if ( this.time > this.duration || this.time < 0 ) {
  6683. this.direction *= -1;
  6684. if ( this.time > this.duration ) {
  6685. this.time = this.duration;
  6686. this.directionBackwards = true;
  6687. }
  6688. if ( this.time < 0 ) {
  6689. this.time = 0;
  6690. this.directionBackwards = false;
  6691. }
  6692. }
  6693. } else {
  6694. this.time = this.time % this.duration;
  6695. if ( this.time < 0 ) this.time += this.duration;
  6696. }
  6697. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  6698. if ( keyframe !== this.currentKeyframe ) {
  6699. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  6700. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  6701. this.morphTargetInfluences[ keyframe ] = 0;
  6702. this.lastKeyframe = this.currentKeyframe;
  6703. this.currentKeyframe = keyframe;
  6704. }
  6705. var mix = ( this.time % frameTime ) / frameTime;
  6706. if ( this.directionBackwards ) {
  6707. mix = 1 - mix;
  6708. }
  6709. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  6710. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  6711. };
  6712. /**
  6713. * @author alteredq / http://alteredqualia.com/
  6714. */
  6715. THREE.Ribbon = function ( geometry, material ) {
  6716. THREE.Object3D.call( this );
  6717. this.geometry = geometry;
  6718. this.material = material;
  6719. };
  6720. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  6721. /**
  6722. * @author mikael emtinger / http://gomo.se/
  6723. * @author alteredq / http://alteredqualia.com/
  6724. * @author mrdoob / http://mrdoob.com/
  6725. */
  6726. THREE.LOD = function () {
  6727. THREE.Object3D.call( this );
  6728. this.LODs = [];
  6729. };
  6730. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  6731. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  6732. if ( visibleAtDistance === undefined ) {
  6733. visibleAtDistance = 0;
  6734. }
  6735. visibleAtDistance = Math.abs( visibleAtDistance );
  6736. for ( var l = 0; l < this.LODs.length; l ++ ) {
  6737. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  6738. break;
  6739. }
  6740. }
  6741. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  6742. this.add( object3D );
  6743. };
  6744. THREE.LOD.prototype.update = function ( camera ) {
  6745. if ( this.LODs.length > 1 ) {
  6746. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  6747. var inverse = camera.matrixWorldInverse;
  6748. 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] );
  6749. this.LODs[ 0 ].object3D.visible = true;
  6750. for ( var l = 1; l < this.LODs.length; l ++ ) {
  6751. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  6752. this.LODs[ l - 1 ].object3D.visible = false;
  6753. this.LODs[ l ].object3D.visible = true;
  6754. } else {
  6755. break;
  6756. }
  6757. }
  6758. for( ; l < this.LODs.length; l ++ ) {
  6759. this.LODs[ l ].object3D.visible = false;
  6760. }
  6761. }
  6762. };
  6763. /**
  6764. * @author mikael emtinger / http://gomo.se/
  6765. */
  6766. THREE.Sprite = function ( parameters ) {
  6767. THREE.Object3D.call( this );
  6768. this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  6769. this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();
  6770. this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;
  6771. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  6772. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  6773. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  6774. this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
  6775. this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
  6776. this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
  6777. this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
  6778. this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center;
  6779. this.rotation3d = this.rotation;
  6780. this.rotation = 0;
  6781. this.opacity = 1;
  6782. this.uvOffset = new THREE.Vector2( 0, 0 );
  6783. this.uvScale = new THREE.Vector2( 1, 1 );
  6784. };
  6785. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  6786. /*
  6787. * Custom update matrix
  6788. */
  6789. THREE.Sprite.prototype.updateMatrix = function () {
  6790. this.matrix.setPosition( this.position );
  6791. this.rotation3d.set( 0, 0, this.rotation );
  6792. this.matrix.setRotationFromEuler( this.rotation3d );
  6793. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  6794. this.matrix.scale( this.scale );
  6795. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  6796. }
  6797. this.matrixWorldNeedsUpdate = true;
  6798. };
  6799. /*
  6800. * Alignment
  6801. */
  6802. THREE.SpriteAlignment = {};
  6803. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  6804. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  6805. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  6806. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  6807. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  6808. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  6809. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  6810. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  6811. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  6812. /**
  6813. * @author mrdoob / http://mrdoob.com/
  6814. */
  6815. THREE.Scene = function () {
  6816. THREE.Object3D.call( this );
  6817. this.fog = null;
  6818. this.overrideMaterial = null;
  6819. this.matrixAutoUpdate = false;
  6820. this.__objects = [];
  6821. this.__lights = [];
  6822. this.__objectsAdded = [];
  6823. this.__objectsRemoved = [];
  6824. };
  6825. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  6826. THREE.Scene.prototype.__addObject = function ( object ) {
  6827. if ( object instanceof THREE.Light ) {
  6828. if ( this.__lights.indexOf( object ) === - 1 ) {
  6829. this.__lights.push( object );
  6830. }
  6831. if ( object.target && object.target.parent === undefined ) {
  6832. this.add( object.target );
  6833. }
  6834. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  6835. if ( this.__objects.indexOf( object ) === - 1 ) {
  6836. this.__objects.push( object );
  6837. this.__objectsAdded.push( object );
  6838. // check if previously removed
  6839. var i = this.__objectsRemoved.indexOf( object );
  6840. if ( i !== -1 ) {
  6841. this.__objectsRemoved.splice( i, 1 );
  6842. }
  6843. }
  6844. }
  6845. for ( var c = 0; c < object.children.length; c ++ ) {
  6846. this.__addObject( object.children[ c ] );
  6847. }
  6848. };
  6849. THREE.Scene.prototype.__removeObject = function ( object ) {
  6850. if ( object instanceof THREE.Light ) {
  6851. var i = this.__lights.indexOf( object );
  6852. if ( i !== -1 ) {
  6853. this.__lights.splice( i, 1 );
  6854. }
  6855. } else if ( !( object instanceof THREE.Camera ) ) {
  6856. var i = this.__objects.indexOf( object );
  6857. if( i !== -1 ) {
  6858. this.__objects.splice( i, 1 );
  6859. this.__objectsRemoved.push( object );
  6860. // check if previously added
  6861. var ai = this.__objectsAdded.indexOf( object );
  6862. if ( ai !== -1 ) {
  6863. this.__objectsAdded.splice( ai, 1 );
  6864. }
  6865. }
  6866. }
  6867. for ( var c = 0; c < object.children.length; c ++ ) {
  6868. this.__removeObject( object.children[ c ] );
  6869. }
  6870. };
  6871. /**
  6872. * @author mrdoob / http://mrdoob.com/
  6873. * @author alteredq / http://alteredqualia.com/
  6874. */
  6875. THREE.Fog = function ( hex, near, far ) {
  6876. this.color = new THREE.Color( hex );
  6877. this.near = ( near !== undefined ) ? near : 1;
  6878. this.far = ( far !== undefined ) ? far : 1000;
  6879. };
  6880. /**
  6881. * @author mrdoob / http://mrdoob.com/
  6882. * @author alteredq / http://alteredqualia.com/
  6883. */
  6884. THREE.FogExp2 = function ( hex, density ) {
  6885. this.color = new THREE.Color( hex );
  6886. this.density = ( density !== undefined ) ? density : 0.00025;
  6887. };
  6888. /**
  6889. * @author mrdoob / http://mrdoob.com/
  6890. */
  6891. THREE.CanvasRenderer = function ( parameters ) {
  6892. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  6893. parameters = parameters || {};
  6894. var _this = this,
  6895. _renderData, _elements, _lights,
  6896. _projector = new THREE.Projector(),
  6897. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  6898. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  6899. _context = _canvas.getContext( '2d' ),
  6900. _clearColor = new THREE.Color( 0x000000 ),
  6901. _clearOpacity = 0,
  6902. _contextGlobalAlpha = 1,
  6903. _contextGlobalCompositeOperation = 0,
  6904. _contextStrokeStyle = null,
  6905. _contextFillStyle = null,
  6906. _contextLineWidth = null,
  6907. _contextLineCap = null,
  6908. _contextLineJoin = null,
  6909. _v1, _v2, _v3, _v4,
  6910. _v5 = new THREE.RenderableVertex(),
  6911. _v6 = new THREE.RenderableVertex(),
  6912. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  6913. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  6914. _color = new THREE.Color(),
  6915. _color1 = new THREE.Color(),
  6916. _color2 = new THREE.Color(),
  6917. _color3 = new THREE.Color(),
  6918. _color4 = new THREE.Color(),
  6919. _patterns = [], _imagedatas = [],
  6920. _near, _far,
  6921. _image, _uvs,
  6922. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  6923. _clipRect = new THREE.Rectangle(),
  6924. _clearRect = new THREE.Rectangle(),
  6925. _bboxRect = new THREE.Rectangle(),
  6926. _enableLighting = false,
  6927. _ambientLight = new THREE.Color(),
  6928. _directionalLights = new THREE.Color(),
  6929. _pointLights = new THREE.Color(),
  6930. _pi2 = Math.PI * 2,
  6931. _vector3 = new THREE.Vector3(), // Needed for PointLight
  6932. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  6933. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  6934. _pixelMap = document.createElement( 'canvas' );
  6935. _pixelMap.width = _pixelMap.height = 2;
  6936. _pixelMapContext = _pixelMap.getContext( '2d' );
  6937. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  6938. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  6939. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  6940. _pixelMapData = _pixelMapImage.data;
  6941. _gradientMap = document.createElement( 'canvas' );
  6942. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  6943. _gradientMapContext = _gradientMap.getContext( '2d' );
  6944. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  6945. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  6946. _gradientMapQuality --; // Fix UVs
  6947. this.domElement = _canvas;
  6948. this.autoClear = true;
  6949. this.sortObjects = true;
  6950. this.sortElements = true;
  6951. this.info = {
  6952. render: {
  6953. vertices: 0,
  6954. faces: 0
  6955. }
  6956. }
  6957. this.setSize = function ( width, height ) {
  6958. _canvasWidth = width;
  6959. _canvasHeight = height;
  6960. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  6961. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  6962. _canvas.width = _canvasWidth;
  6963. _canvas.height = _canvasHeight;
  6964. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6965. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6966. _contextGlobalAlpha = 1;
  6967. _contextGlobalCompositeOperation = 0;
  6968. _contextStrokeStyle = null;
  6969. _contextFillStyle = null;
  6970. _contextLineWidth = null;
  6971. _contextLineCap = null;
  6972. _contextLineJoin = null;
  6973. };
  6974. this.setClearColor = function ( color, opacity ) {
  6975. _clearColor.copy( color );
  6976. _clearOpacity = opacity !== undefined ? opacity : 1;
  6977. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6978. };
  6979. this.setClearColorHex = function ( hex, opacity ) {
  6980. _clearColor.setHex( hex );
  6981. _clearOpacity = opacity !== undefined ? opacity : 1;
  6982. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6983. };
  6984. this.clear = function () {
  6985. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  6986. if ( _clearRect.isEmpty() === false ) {
  6987. _clearRect.minSelf( _clipRect );
  6988. _clearRect.inflate( 2 );
  6989. if ( _clearOpacity < 1 ) {
  6990. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  6991. }
  6992. if ( _clearOpacity > 0 ) {
  6993. setBlending( THREE.NormalBlending );
  6994. setOpacity( 1 );
  6995. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  6996. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  6997. }
  6998. _clearRect.empty();
  6999. }
  7000. };
  7001. this.render = function ( scene, camera ) {
  7002. if ( camera instanceof THREE.Camera === false ) {
  7003. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7004. return;
  7005. }
  7006. var e, el, element, material;
  7007. this.autoClear === true ? this.clear() : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7008. _this.info.render.vertices = 0;
  7009. _this.info.render.faces = 0;
  7010. _renderData = _projector.projectScene( scene, camera, this.sortElements );
  7011. _elements = _renderData.elements;
  7012. _lights = _renderData.lights;
  7013. /* DEBUG
  7014. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7015. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  7016. */
  7017. _enableLighting = _lights.length > 0;
  7018. if ( _enableLighting === true ) {
  7019. calculateLights( _lights );
  7020. }
  7021. for ( e = 0, el = _elements.length; e < el; e++ ) {
  7022. element = _elements[ e ];
  7023. material = element.material;
  7024. if ( material === undefined || material.visible === false ) continue;
  7025. _bboxRect.empty();
  7026. if ( element instanceof THREE.RenderableParticle ) {
  7027. _v1 = element;
  7028. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7029. renderParticle( _v1, element, material, scene );
  7030. } else if ( element instanceof THREE.RenderableLine ) {
  7031. _v1 = element.v1; _v2 = element.v2;
  7032. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7033. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7034. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7035. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7036. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7037. renderLine( _v1, _v2, element, material, scene );
  7038. }
  7039. } else if ( element instanceof THREE.RenderableFace3 ) {
  7040. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7041. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7042. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7043. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7044. if ( material.overdraw === true ) {
  7045. expand( _v1.positionScreen, _v2.positionScreen );
  7046. expand( _v2.positionScreen, _v3.positionScreen );
  7047. expand( _v3.positionScreen, _v1.positionScreen );
  7048. }
  7049. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  7050. _v2.positionScreen.x, _v2.positionScreen.y,
  7051. _v3.positionScreen.x, _v3.positionScreen.y );
  7052. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7053. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7054. }
  7055. } else if ( element instanceof THREE.RenderableFace4 ) {
  7056. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7057. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7058. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7059. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7060. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7061. _v5.positionScreen.copy( _v2.positionScreen );
  7062. _v6.positionScreen.copy( _v4.positionScreen );
  7063. if ( material.overdraw === true ) {
  7064. expand( _v1.positionScreen, _v2.positionScreen );
  7065. expand( _v2.positionScreen, _v4.positionScreen );
  7066. expand( _v4.positionScreen, _v1.positionScreen );
  7067. expand( _v3.positionScreen, _v5.positionScreen );
  7068. expand( _v3.positionScreen, _v6.positionScreen );
  7069. }
  7070. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7071. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7072. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  7073. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  7074. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7075. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  7076. }
  7077. }
  7078. /* DEBUG
  7079. _context.lineWidth = 1;
  7080. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  7081. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  7082. */
  7083. _clearRect.addRectangle( _bboxRect );
  7084. }
  7085. /* DEBUG
  7086. _context.lineWidth = 1;
  7087. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  7088. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  7089. */
  7090. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  7091. //
  7092. function calculateLights( lights ) {
  7093. var l, ll, light, lightColor;
  7094. _ambientLight.setRGB( 0, 0, 0 );
  7095. _directionalLights.setRGB( 0, 0, 0 );
  7096. _pointLights.setRGB( 0, 0, 0 );
  7097. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  7098. light = lights[ l ];
  7099. lightColor = light.color;
  7100. if ( light instanceof THREE.AmbientLight ) {
  7101. _ambientLight.r += lightColor.r;
  7102. _ambientLight.g += lightColor.g;
  7103. _ambientLight.b += lightColor.b;
  7104. } else if ( light instanceof THREE.DirectionalLight ) {
  7105. // for particles
  7106. _directionalLights.r += lightColor.r;
  7107. _directionalLights.g += lightColor.g;
  7108. _directionalLights.b += lightColor.b;
  7109. } else if ( light instanceof THREE.PointLight ) {
  7110. // for particles
  7111. _pointLights.r += lightColor.r;
  7112. _pointLights.g += lightColor.g;
  7113. _pointLights.b += lightColor.b;
  7114. }
  7115. }
  7116. }
  7117. function calculateLight( lights, position, normal, color ) {
  7118. var l, ll, light, lightColor, lightPosition, amount;
  7119. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  7120. light = lights[ l ];
  7121. lightColor = light.color;
  7122. if ( light instanceof THREE.DirectionalLight ) {
  7123. lightPosition = light.matrixWorld.getPosition().normalize();
  7124. amount = normal.dot( lightPosition );
  7125. if ( amount <= 0 ) continue;
  7126. amount *= light.intensity;
  7127. color.r += lightColor.r * amount;
  7128. color.g += lightColor.g * amount;
  7129. color.b += lightColor.b * amount;
  7130. } else if ( light instanceof THREE.PointLight ) {
  7131. lightPosition = light.matrixWorld.getPosition();
  7132. amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  7133. if ( amount <= 0 ) continue;
  7134. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  7135. if ( amount == 0 ) continue;
  7136. amount *= light.intensity;
  7137. color.r += lightColor.r * amount;
  7138. color.g += lightColor.g * amount;
  7139. color.b += lightColor.b * amount;
  7140. }
  7141. }
  7142. }
  7143. function renderParticle( v1, element, material, scene ) {
  7144. setOpacity( material.opacity );
  7145. setBlending( material.blending );
  7146. var width, height, scaleX, scaleY,
  7147. bitmap, bitmapWidth, bitmapHeight;
  7148. if ( material instanceof THREE.ParticleBasicMaterial ) {
  7149. if ( material.map === null ) {
  7150. scaleX = element.object.scale.x;
  7151. scaleY = element.object.scale.y;
  7152. // TODO: Be able to disable this
  7153. scaleX *= element.scale.x * _canvasWidthHalf;
  7154. scaleY *= element.scale.y * _canvasHeightHalf;
  7155. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  7156. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7157. return;
  7158. }
  7159. setFillStyle( material.color.getContextStyle() );
  7160. _context.save();
  7161. _context.translate( v1.x, v1.y );
  7162. _context.rotate( - element.rotation );
  7163. _context.scale( scaleX, scaleY );
  7164. _context.fillRect( -1, -1, 2, 2 );
  7165. _context.restore();
  7166. } else {
  7167. bitmap = material.map.image;
  7168. bitmapWidth = bitmap.width >> 1;
  7169. bitmapHeight = bitmap.height >> 1;
  7170. scaleX = element.scale.x * _canvasWidthHalf;
  7171. scaleY = element.scale.y * _canvasHeightHalf;
  7172. width = scaleX * bitmapWidth;
  7173. height = scaleY * bitmapHeight;
  7174. // TODO: Rotations break this...
  7175. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7176. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7177. return;
  7178. }
  7179. _context.save();
  7180. _context.translate( v1.x, v1.y );
  7181. _context.rotate( - element.rotation );
  7182. _context.scale( scaleX, - scaleY );
  7183. _context.translate( - bitmapWidth, - bitmapHeight );
  7184. _context.drawImage( bitmap, 0, 0 );
  7185. _context.restore();
  7186. }
  7187. /* DEBUG
  7188. setStrokeStyle( 'rgb(255,255,0)' );
  7189. _context.beginPath();
  7190. _context.moveTo( v1.x - 10, v1.y );
  7191. _context.lineTo( v1.x + 10, v1.y );
  7192. _context.moveTo( v1.x, v1.y - 10 );
  7193. _context.lineTo( v1.x, v1.y + 10 );
  7194. _context.stroke();
  7195. */
  7196. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  7197. width = element.scale.x * _canvasWidthHalf;
  7198. height = element.scale.y * _canvasHeightHalf;
  7199. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7200. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7201. return;
  7202. }
  7203. setStrokeStyle( material.color.getContextStyle() );
  7204. setFillStyle( material.color.getContextStyle() );
  7205. _context.save();
  7206. _context.translate( v1.x, v1.y );
  7207. _context.rotate( - element.rotation );
  7208. _context.scale( width, height );
  7209. material.program( _context );
  7210. _context.restore();
  7211. }
  7212. }
  7213. function renderLine( v1, v2, element, material, scene ) {
  7214. setOpacity( material.opacity );
  7215. setBlending( material.blending );
  7216. _context.beginPath();
  7217. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  7218. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  7219. if ( material instanceof THREE.LineBasicMaterial ) {
  7220. setLineWidth( material.linewidth );
  7221. setLineCap( material.linecap );
  7222. setLineJoin( material.linejoin );
  7223. setStrokeStyle( material.color.getContextStyle() );
  7224. _context.stroke();
  7225. _bboxRect.inflate( material.linewidth * 2 );
  7226. }
  7227. }
  7228. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  7229. _this.info.render.vertices += 3;
  7230. _this.info.render.faces ++;
  7231. setOpacity( material.opacity );
  7232. setBlending( material.blending );
  7233. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7234. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7235. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7236. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  7237. if ( material instanceof THREE.MeshBasicMaterial ) {
  7238. if ( material.map !== null ) {
  7239. if ( material.map.mapping instanceof THREE.UVMapping ) {
  7240. _uvs = element.uvs[ 0 ];
  7241. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].u, _uvs[ uv1 ].v, _uvs[ uv2 ].u, _uvs[ uv2 ].v, _uvs[ uv3 ].u, _uvs[ uv3 ].v, material.map );
  7242. }
  7243. } else if ( material.envMap !== null ) {
  7244. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  7245. var cameraMatrix = camera.matrixWorldInverse;
  7246. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  7247. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7248. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7249. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  7250. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7251. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7252. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  7253. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7254. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7255. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  7256. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  7257. }*/
  7258. } else {
  7259. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7260. }
  7261. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  7262. if ( _enableLighting === true ) {
  7263. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  7264. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  7265. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  7266. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  7267. calculateLight( _lights, element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7268. calculateLight( _lights, element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7269. calculateLight( _lights, element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  7270. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  7271. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  7272. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  7273. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  7274. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  7275. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  7276. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  7277. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  7278. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  7279. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7280. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7281. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7282. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7283. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7284. } else {
  7285. _color.r = _ambientLight.r;
  7286. _color.g = _ambientLight.g;
  7287. _color.b = _ambientLight.b;
  7288. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  7289. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  7290. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  7291. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  7292. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7293. }
  7294. } else {
  7295. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7296. }
  7297. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7298. _near = camera.near;
  7299. _far = camera.far;
  7300. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7301. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7302. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7303. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7304. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7305. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7306. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7307. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7308. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7309. _color.r = normalToComponent( element.normalWorld.x );
  7310. _color.g = normalToComponent( element.normalWorld.y );
  7311. _color.b = normalToComponent( element.normalWorld.z );
  7312. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7313. }
  7314. }
  7315. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  7316. _this.info.render.vertices += 4;
  7317. _this.info.render.faces ++;
  7318. setOpacity( material.opacity );
  7319. setBlending( material.blending );
  7320. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  7321. // Let renderFace3() handle this
  7322. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  7323. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  7324. return;
  7325. }
  7326. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7327. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7328. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7329. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  7330. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  7331. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  7332. if ( material instanceof THREE.MeshBasicMaterial ) {
  7333. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7334. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7335. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  7336. if ( _enableLighting === true ) {
  7337. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  7338. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  7339. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  7340. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  7341. calculateLight( _lights, element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7342. calculateLight( _lights, element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7343. calculateLight( _lights, element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  7344. calculateLight( _lights, element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  7345. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  7346. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  7347. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  7348. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  7349. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  7350. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  7351. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  7352. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  7353. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  7354. _color4.r = Math.max( 0, Math.min( material.color.r * _color4.r, 1 ) );
  7355. _color4.g = Math.max( 0, Math.min( material.color.g * _color4.g, 1 ) );
  7356. _color4.b = Math.max( 0, Math.min( material.color.b * _color4.b, 1 ) );
  7357. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7358. // TODO: UVs are incorrect, v4->v3?
  7359. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7360. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7361. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7362. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7363. } else {
  7364. _color.r = _ambientLight.r;
  7365. _color.g = _ambientLight.g;
  7366. _color.b = _ambientLight.b;
  7367. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  7368. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  7369. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  7370. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  7371. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7372. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7373. }
  7374. } else {
  7375. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7376. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7377. }
  7378. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7379. _color.r = normalToComponent( element.normalWorld.x );
  7380. _color.g = normalToComponent( element.normalWorld.y );
  7381. _color.b = normalToComponent( element.normalWorld.z );
  7382. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7383. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7384. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7385. _near = camera.near;
  7386. _far = camera.far;
  7387. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7388. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7389. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  7390. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7391. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7392. // TODO: UVs are incorrect, v4->v3?
  7393. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7394. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7395. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7396. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7397. }
  7398. }
  7399. //
  7400. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  7401. _context.beginPath();
  7402. _context.moveTo( x0, y0 );
  7403. _context.lineTo( x1, y1 );
  7404. _context.lineTo( x2, y2 );
  7405. _context.closePath();
  7406. }
  7407. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  7408. _context.beginPath();
  7409. _context.moveTo( x0, y0 );
  7410. _context.lineTo( x1, y1 );
  7411. _context.lineTo( x2, y2 );
  7412. _context.lineTo( x3, y3 );
  7413. _context.closePath();
  7414. }
  7415. function strokePath( color, linewidth, linecap, linejoin ) {
  7416. setLineWidth( linewidth );
  7417. setLineCap( linecap );
  7418. setLineJoin( linejoin );
  7419. setStrokeStyle( color.getContextStyle() );
  7420. _context.stroke();
  7421. _bboxRect.inflate( linewidth * 2 );
  7422. }
  7423. function fillPath( color ) {
  7424. setFillStyle( color.getContextStyle() );
  7425. _context.fill();
  7426. }
  7427. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  7428. if ( texture.image === undefined || texture.image.width === 0 ) return;
  7429. if ( texture.needsUpdate === true || _patterns[ texture.id ] === undefined ) {
  7430. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  7431. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  7432. _patterns[ texture.id ] = _context.createPattern( texture.image, repeatX === true && repeatY === true ? 'repeat' : repeatX === true && repeatY === false ? 'repeat-x' : repeatX === false && repeatY === true ? 'repeat-y' : 'no-repeat' );
  7433. texture.needsUpdate = false;
  7434. }
  7435. setFillStyle( _patterns[ texture.id ] );
  7436. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7437. var a, b, c, d, e, f, det, idet,
  7438. offsetX = texture.offset.x / texture.repeat.x,
  7439. offsetY = texture.offset.y / texture.repeat.y,
  7440. width = texture.image.width * texture.repeat.x,
  7441. height = texture.image.height * texture.repeat.y;
  7442. u0 = ( u0 + offsetX ) * width;
  7443. v0 = ( 1.0 - v0 + offsetY ) * height;
  7444. u1 = ( u1 + offsetX ) * width;
  7445. v1 = ( 1.0 - v1 + offsetY ) * height;
  7446. u2 = ( u2 + offsetX ) * width;
  7447. v2 = ( 1.0 - v2 + offsetY ) * height;
  7448. x1 -= x0; y1 -= y0;
  7449. x2 -= x0; y2 -= y0;
  7450. u1 -= u0; v1 -= v0;
  7451. u2 -= u0; v2 -= v0;
  7452. det = u1 * v2 - u2 * v1;
  7453. if ( det === 0 ) {
  7454. if ( _imagedatas[ texture.id ] === undefined ) {
  7455. var canvas = document.createElement( 'canvas' )
  7456. canvas.width = texture.image.width;
  7457. canvas.height = texture.image.height;
  7458. var context = canvas.getContext( '2d' );
  7459. context.drawImage( texture.image, 0, 0 );
  7460. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  7461. // variables cannot be deleted in ES5 strict mode
  7462. //delete canvas;
  7463. }
  7464. var data = _imagedatas[ texture.id ];
  7465. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  7466. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  7467. fillPath( _color );
  7468. return;
  7469. }
  7470. idet = 1 / det;
  7471. a = ( v2 * x1 - v1 * x2 ) * idet;
  7472. b = ( v2 * y1 - v1 * y2 ) * idet;
  7473. c = ( u1 * x2 - u2 * x1 ) * idet;
  7474. d = ( u1 * y2 - u2 * y1 ) * idet;
  7475. e = x0 - a * u0 - c * v0;
  7476. f = y0 - b * u0 - d * v0;
  7477. _context.save();
  7478. _context.transform( a, b, c, d, e, f );
  7479. _context.fill();
  7480. _context.restore();
  7481. }
  7482. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  7483. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7484. var a, b, c, d, e, f, det, idet,
  7485. width = image.width - 1,
  7486. height = image.height - 1;
  7487. u0 *= width; v0 *= height;
  7488. u1 *= width; v1 *= height;
  7489. u2 *= width; v2 *= height;
  7490. x1 -= x0; y1 -= y0;
  7491. x2 -= x0; y2 -= y0;
  7492. u1 -= u0; v1 -= v0;
  7493. u2 -= u0; v2 -= v0;
  7494. det = u1 * v2 - u2 * v1;
  7495. idet = 1 / det;
  7496. a = ( v2 * x1 - v1 * x2 ) * idet;
  7497. b = ( v2 * y1 - v1 * y2 ) * idet;
  7498. c = ( u1 * x2 - u2 * x1 ) * idet;
  7499. d = ( u1 * y2 - u2 * y1 ) * idet;
  7500. e = x0 - a * u0 - c * v0;
  7501. f = y0 - b * u0 - d * v0;
  7502. _context.save();
  7503. _context.transform( a, b, c, d, e, f );
  7504. _context.clip();
  7505. _context.drawImage( image, 0, 0 );
  7506. _context.restore();
  7507. }
  7508. function getGradientTexture( color1, color2, color3, color4 ) {
  7509. // http://mrdoob.com/blog/post/710
  7510. var c1r = ~~ ( color1.r * 255 ), c1g = ~~ ( color1.g * 255 ), c1b = ~~ ( color1.b * 255 ),
  7511. c2r = ~~ ( color2.r * 255 ), c2g = ~~ ( color2.g * 255 ), c2b = ~~ ( color2.b * 255 ),
  7512. c3r = ~~ ( color3.r * 255 ), c3g = ~~ ( color3.g * 255 ), c3b = ~~ ( color3.b * 255 ),
  7513. c4r = ~~ ( color4.r * 255 ), c4g = ~~ ( color4.g * 255 ), c4b = ~~ ( color4.b * 255 );
  7514. _pixelMapData[ 0 ] = c1r < 0 ? 0 : c1r > 255 ? 255 : c1r;
  7515. _pixelMapData[ 1 ] = c1g < 0 ? 0 : c1g > 255 ? 255 : c1g;
  7516. _pixelMapData[ 2 ] = c1b < 0 ? 0 : c1b > 255 ? 255 : c1b;
  7517. _pixelMapData[ 4 ] = c2r < 0 ? 0 : c2r > 255 ? 255 : c2r;
  7518. _pixelMapData[ 5 ] = c2g < 0 ? 0 : c2g > 255 ? 255 : c2g;
  7519. _pixelMapData[ 6 ] = c2b < 0 ? 0 : c2b > 255 ? 255 : c2b;
  7520. _pixelMapData[ 8 ] = c3r < 0 ? 0 : c3r > 255 ? 255 : c3r;
  7521. _pixelMapData[ 9 ] = c3g < 0 ? 0 : c3g > 255 ? 255 : c3g;
  7522. _pixelMapData[ 10 ] = c3b < 0 ? 0 : c3b > 255 ? 255 : c3b;
  7523. _pixelMapData[ 12 ] = c4r < 0 ? 0 : c4r > 255 ? 255 : c4r;
  7524. _pixelMapData[ 13 ] = c4g < 0 ? 0 : c4g > 255 ? 255 : c4g;
  7525. _pixelMapData[ 14 ] = c4b < 0 ? 0 : c4b > 255 ? 255 : c4b;
  7526. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  7527. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  7528. return _gradientMap;
  7529. }
  7530. function smoothstep( value, min, max ) {
  7531. var x = ( value - min ) / ( max - min );
  7532. return x * x * ( 3 - 2 * x );
  7533. }
  7534. function normalToComponent( normal ) {
  7535. var component = ( normal + 1 ) * 0.5;
  7536. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  7537. }
  7538. // Hide anti-alias gaps
  7539. function expand( v1, v2 ) {
  7540. var x = v2.x - v1.x, y = v2.y - v1.y,
  7541. det = x * x + y * y, idet;
  7542. if ( det === 0 ) return;
  7543. idet = 1 / Math.sqrt( det );
  7544. x *= idet; y *= idet;
  7545. v2.x += x; v2.y += y;
  7546. v1.x -= x; v1.y -= y;
  7547. }
  7548. };
  7549. // Context cached methods.
  7550. function setOpacity( value ) {
  7551. if ( _contextGlobalAlpha !== value ) {
  7552. _context.globalAlpha = value;
  7553. _contextGlobalAlpha = value;
  7554. }
  7555. }
  7556. function setBlending( value ) {
  7557. if ( _contextGlobalCompositeOperation !== value ) {
  7558. if ( value === THREE.NormalBlending ) {
  7559. _context.globalCompositeOperation = 'source-over';
  7560. } else if ( value === THREE.AdditiveBlending ) {
  7561. _context.globalCompositeOperation = 'lighter';
  7562. } else if ( value === THREE.SubtractiveBlending ) {
  7563. _context.globalCompositeOperation = 'darker';
  7564. }
  7565. _contextGlobalCompositeOperation = value;
  7566. }
  7567. }
  7568. function setLineWidth( value ) {
  7569. if ( _contextLineWidth !== value ) {
  7570. _context.lineWidth = value;
  7571. _contextLineWidth = value;
  7572. }
  7573. }
  7574. function setLineCap( value ) {
  7575. // "butt", "round", "square"
  7576. if ( _contextLineCap !== value ) {
  7577. _context.lineCap = value;
  7578. _contextLineCap = value;
  7579. }
  7580. }
  7581. function setLineJoin( value ) {
  7582. // "round", "bevel", "miter"
  7583. if ( _contextLineJoin !== value ) {
  7584. _context.lineJoin = value;
  7585. _contextLineJoin = value;
  7586. }
  7587. }
  7588. function setStrokeStyle( value ) {
  7589. if ( _contextStrokeStyle !== value ) {
  7590. _context.strokeStyle = value;
  7591. _contextStrokeStyle = value;
  7592. }
  7593. }
  7594. function setFillStyle( value ) {
  7595. if ( _contextFillStyle !== value ) {
  7596. _context.fillStyle = value;
  7597. _contextFillStyle = value;
  7598. }
  7599. }
  7600. };
  7601. /**
  7602. * @author alteredq / http://alteredqualia.com/
  7603. * @author mrdoob / http://mrdoob.com/
  7604. * @author mikael emtinger / http://gomo.se/
  7605. */
  7606. THREE.ShaderChunk = {
  7607. // FOG
  7608. fog_pars_fragment: [
  7609. "#ifdef USE_FOG",
  7610. "uniform vec3 fogColor;",
  7611. "#ifdef FOG_EXP2",
  7612. "uniform float fogDensity;",
  7613. "#else",
  7614. "uniform float fogNear;",
  7615. "uniform float fogFar;",
  7616. "#endif",
  7617. "#endif"
  7618. ].join("\n"),
  7619. fog_fragment: [
  7620. "#ifdef USE_FOG",
  7621. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  7622. "#ifdef FOG_EXP2",
  7623. "const float LOG2 = 1.442695;",
  7624. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  7625. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  7626. "#else",
  7627. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  7628. "#endif",
  7629. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  7630. "#endif"
  7631. ].join("\n"),
  7632. // ENVIRONMENT MAP
  7633. envmap_pars_fragment: [
  7634. "#ifdef USE_ENVMAP",
  7635. "uniform float reflectivity;",
  7636. "uniform samplerCube envMap;",
  7637. "uniform float flipEnvMap;",
  7638. "uniform int combine;",
  7639. "#ifdef USE_BUMPMAP",
  7640. "uniform bool useRefract;",
  7641. "uniform float refractionRatio;",
  7642. "#else",
  7643. "varying vec3 vReflect;",
  7644. "#endif",
  7645. "#endif"
  7646. ].join("\n"),
  7647. envmap_fragment: [
  7648. "#ifdef USE_ENVMAP",
  7649. "vec3 reflectVec;",
  7650. "#ifdef USE_BUMPMAP",
  7651. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  7652. "if ( useRefract ) {",
  7653. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  7654. "} else { ",
  7655. "reflectVec = reflect( cameraToVertex, normal );",
  7656. "}",
  7657. "#else",
  7658. "reflectVec = vReflect;",
  7659. "#endif",
  7660. "#ifdef DOUBLE_SIDED",
  7661. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  7662. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  7663. "#else",
  7664. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  7665. "#endif",
  7666. "#ifdef GAMMA_INPUT",
  7667. "cubeColor.xyz *= cubeColor.xyz;",
  7668. "#endif",
  7669. "if ( combine == 1 ) {",
  7670. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  7671. "} else {",
  7672. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  7673. "}",
  7674. "#endif"
  7675. ].join("\n"),
  7676. envmap_pars_vertex: [
  7677. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP )",
  7678. "varying vec3 vReflect;",
  7679. "uniform float refractionRatio;",
  7680. "uniform bool useRefract;",
  7681. "#endif"
  7682. ].join("\n"),
  7683. envmap_vertex : [
  7684. "#ifdef USE_ENVMAP",
  7685. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  7686. "#endif",
  7687. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP )",
  7688. "vec3 nWorld = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * normal;",
  7689. "if ( useRefract ) {",
  7690. "vReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refractionRatio );",
  7691. "} else {",
  7692. "vReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );",
  7693. "}",
  7694. "#endif"
  7695. ].join("\n"),
  7696. // COLOR MAP (particles)
  7697. map_particle_pars_fragment: [
  7698. "#ifdef USE_MAP",
  7699. "uniform sampler2D map;",
  7700. "#endif"
  7701. ].join("\n"),
  7702. map_particle_fragment: [
  7703. "#ifdef USE_MAP",
  7704. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  7705. "#endif"
  7706. ].join("\n"),
  7707. // COLOR MAP (triangles)
  7708. map_pars_vertex: [
  7709. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_SPECULARMAP )",
  7710. "varying vec2 vUv;",
  7711. "uniform vec4 offsetRepeat;",
  7712. "#endif"
  7713. ].join("\n"),
  7714. map_pars_fragment: [
  7715. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_SPECULARMAP )",
  7716. "varying vec2 vUv;",
  7717. "#endif",
  7718. "#ifdef USE_MAP",
  7719. "uniform sampler2D map;",
  7720. "#endif",
  7721. ].join("\n"),
  7722. map_vertex: [
  7723. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_SPECULARMAP )",
  7724. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  7725. "#endif"
  7726. ].join("\n"),
  7727. map_fragment: [
  7728. "#ifdef USE_MAP",
  7729. "#ifdef GAMMA_INPUT",
  7730. "vec4 texelColor = texture2D( map, vUv );",
  7731. "texelColor.xyz *= texelColor.xyz;",
  7732. "gl_FragColor = gl_FragColor * texelColor;",
  7733. "#else",
  7734. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  7735. "#endif",
  7736. "#endif"
  7737. ].join("\n"),
  7738. // LIGHT MAP
  7739. lightmap_pars_fragment: [
  7740. "#ifdef USE_LIGHTMAP",
  7741. "varying vec2 vUv2;",
  7742. "uniform sampler2D lightMap;",
  7743. "#endif"
  7744. ].join("\n"),
  7745. lightmap_pars_vertex: [
  7746. "#ifdef USE_LIGHTMAP",
  7747. "varying vec2 vUv2;",
  7748. "#endif"
  7749. ].join("\n"),
  7750. lightmap_fragment: [
  7751. "#ifdef USE_LIGHTMAP",
  7752. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  7753. "#endif"
  7754. ].join("\n"),
  7755. lightmap_vertex: [
  7756. "#ifdef USE_LIGHTMAP",
  7757. "vUv2 = uv2;",
  7758. "#endif"
  7759. ].join("\n"),
  7760. // BUMP MAP
  7761. bumpmap_pars_fragment: [
  7762. "#ifdef USE_BUMPMAP",
  7763. "uniform sampler2D bumpMap;",
  7764. "uniform float bumpScale;",
  7765. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  7766. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  7767. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  7768. "vec2 dHdxy_fwd() {",
  7769. "vec2 dSTdx = dFdx( vUv );",
  7770. "vec2 dSTdy = dFdy( vUv );",
  7771. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  7772. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  7773. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  7774. "return vec2( dBx, dBy );",
  7775. "}",
  7776. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  7777. "vec3 vSigmaX = dFdx( surf_pos );",
  7778. "vec3 vSigmaY = dFdy( surf_pos );",
  7779. "vec3 vN = surf_norm;", // normalized
  7780. "vec3 R1 = cross( vSigmaY, vN );",
  7781. "vec3 R2 = cross( vN, vSigmaX );",
  7782. "float fDet = dot( vSigmaX, R1 );",
  7783. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  7784. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  7785. "}",
  7786. "#endif"
  7787. ].join("\n"),
  7788. // SPECULAR MAP
  7789. specularmap_pars_fragment: [
  7790. "#ifdef USE_SPECULARMAP",
  7791. "uniform sampler2D specularMap;",
  7792. "#endif"
  7793. ].join("\n"),
  7794. specularmap_fragment: [
  7795. "float specularStrength;",
  7796. "#ifdef USE_SPECULARMAP",
  7797. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  7798. "specularStrength = texelSpecular.r;",
  7799. "#else",
  7800. "specularStrength = 1.0;",
  7801. "#endif"
  7802. ].join("\n"),
  7803. // LIGHTS LAMBERT
  7804. lights_lambert_pars_vertex: [
  7805. "uniform vec3 ambient;",
  7806. "uniform vec3 diffuse;",
  7807. "uniform vec3 emissive;",
  7808. "uniform vec3 ambientLightColor;",
  7809. "#if MAX_DIR_LIGHTS > 0",
  7810. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  7811. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  7812. "#endif",
  7813. "#if MAX_POINT_LIGHTS > 0",
  7814. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  7815. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  7816. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  7817. "#endif",
  7818. "#if MAX_SPOT_LIGHTS > 0",
  7819. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  7820. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  7821. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  7822. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  7823. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  7824. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  7825. "#endif",
  7826. "#ifdef WRAP_AROUND",
  7827. "uniform vec3 wrapRGB;",
  7828. "#endif"
  7829. ].join("\n"),
  7830. lights_lambert_vertex: [
  7831. "vLightFront = vec3( 0.0 );",
  7832. "#ifdef DOUBLE_SIDED",
  7833. "vLightBack = vec3( 0.0 );",
  7834. "#endif",
  7835. "transformedNormal = normalize( transformedNormal );",
  7836. "#if MAX_DIR_LIGHTS > 0",
  7837. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  7838. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  7839. "vec3 dirVector = normalize( lDirection.xyz );",
  7840. "float dotProduct = dot( transformedNormal, dirVector );",
  7841. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  7842. "#ifdef DOUBLE_SIDED",
  7843. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  7844. "#ifdef WRAP_AROUND",
  7845. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  7846. "#endif",
  7847. "#endif",
  7848. "#ifdef WRAP_AROUND",
  7849. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  7850. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  7851. "#ifdef DOUBLE_SIDED",
  7852. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  7853. "#endif",
  7854. "#endif",
  7855. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  7856. "#ifdef DOUBLE_SIDED",
  7857. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  7858. "#endif",
  7859. "}",
  7860. "#endif",
  7861. "#if MAX_POINT_LIGHTS > 0",
  7862. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  7863. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  7864. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7865. "float lDistance = 1.0;",
  7866. "if ( pointLightDistance[ i ] > 0.0 )",
  7867. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  7868. "lVector = normalize( lVector );",
  7869. "float dotProduct = dot( transformedNormal, lVector );",
  7870. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  7871. "#ifdef DOUBLE_SIDED",
  7872. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  7873. "#ifdef WRAP_AROUND",
  7874. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  7875. "#endif",
  7876. "#endif",
  7877. "#ifdef WRAP_AROUND",
  7878. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  7879. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  7880. "#ifdef DOUBLE_SIDED",
  7881. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  7882. "#endif",
  7883. "#endif",
  7884. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  7885. "#ifdef DOUBLE_SIDED",
  7886. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  7887. "#endif",
  7888. "}",
  7889. "#endif",
  7890. "#if MAX_SPOT_LIGHTS > 0",
  7891. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  7892. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  7893. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7894. "lVector = normalize( lVector );",
  7895. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - mPosition.xyz ) );",
  7896. "if ( spotEffect > spotLightAngle[ i ] ) {",
  7897. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  7898. "float lDistance = 1.0;",
  7899. "if ( spotLightDistance[ i ] > 0.0 )",
  7900. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  7901. "float dotProduct = dot( transformedNormal, lVector );",
  7902. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  7903. "#ifdef DOUBLE_SIDED",
  7904. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  7905. "#ifdef WRAP_AROUND",
  7906. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  7907. "#endif",
  7908. "#endif",
  7909. "#ifdef WRAP_AROUND",
  7910. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  7911. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  7912. "#ifdef DOUBLE_SIDED",
  7913. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  7914. "#endif",
  7915. "#endif",
  7916. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  7917. "#ifdef DOUBLE_SIDED",
  7918. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  7919. "#endif",
  7920. "}",
  7921. "}",
  7922. "#endif",
  7923. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  7924. "#ifdef DOUBLE_SIDED",
  7925. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  7926. "#endif"
  7927. ].join("\n"),
  7928. // LIGHTS PHONG
  7929. lights_phong_pars_vertex: [
  7930. "#ifndef PHONG_PER_PIXEL",
  7931. "#if MAX_POINT_LIGHTS > 0",
  7932. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  7933. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  7934. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  7935. "#endif",
  7936. "#if MAX_SPOT_LIGHTS > 0",
  7937. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  7938. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  7939. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  7940. "#endif",
  7941. "#endif",
  7942. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  7943. "varying vec3 vWorldPosition;",
  7944. "#endif"
  7945. ].join("\n"),
  7946. lights_phong_vertex: [
  7947. "#ifndef PHONG_PER_PIXEL",
  7948. "#if MAX_POINT_LIGHTS > 0",
  7949. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  7950. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  7951. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7952. "float lDistance = 1.0;",
  7953. "if ( pointLightDistance[ i ] > 0.0 )",
  7954. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  7955. "vPointLight[ i ] = vec4( lVector, lDistance );",
  7956. "}",
  7957. "#endif",
  7958. "#if MAX_SPOT_LIGHTS > 0",
  7959. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  7960. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  7961. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7962. "float lDistance = 1.0;",
  7963. "if ( spotLightDistance[ i ] > 0.0 )",
  7964. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  7965. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  7966. "}",
  7967. "#endif",
  7968. "#endif",
  7969. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  7970. "vWorldPosition = mPosition.xyz;",
  7971. "#endif"
  7972. ].join("\n"),
  7973. lights_phong_pars_fragment: [
  7974. "uniform vec3 ambientLightColor;",
  7975. "#if MAX_DIR_LIGHTS > 0",
  7976. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  7977. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  7978. "#endif",
  7979. "#if MAX_POINT_LIGHTS > 0",
  7980. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  7981. "#ifdef PHONG_PER_PIXEL",
  7982. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  7983. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  7984. "#else",
  7985. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  7986. "#endif",
  7987. "#endif",
  7988. "#if MAX_SPOT_LIGHTS > 0",
  7989. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  7990. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  7991. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  7992. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  7993. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  7994. "#ifdef PHONG_PER_PIXEL",
  7995. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  7996. "#else",
  7997. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  7998. "#endif",
  7999. "#endif",
  8000. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8001. "varying vec3 vWorldPosition;",
  8002. "#endif",
  8003. "#ifdef WRAP_AROUND",
  8004. "uniform vec3 wrapRGB;",
  8005. "#endif",
  8006. "varying vec3 vViewPosition;",
  8007. "varying vec3 vNormal;"
  8008. ].join("\n"),
  8009. lights_phong_fragment: [
  8010. "vec3 normal = normalize( vNormal );",
  8011. "vec3 viewPosition = normalize( vViewPosition );",
  8012. "#ifdef DOUBLE_SIDED",
  8013. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8014. "#endif",
  8015. "#ifdef USE_BUMPMAP",
  8016. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  8017. "#endif",
  8018. "#if MAX_POINT_LIGHTS > 0",
  8019. "vec3 pointDiffuse = vec3( 0.0 );",
  8020. "vec3 pointSpecular = vec3( 0.0 );",
  8021. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8022. "#ifdef PHONG_PER_PIXEL",
  8023. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8024. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8025. "float lDistance = 1.0;",
  8026. "if ( pointLightDistance[ i ] > 0.0 )",
  8027. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8028. "lVector = normalize( lVector );",
  8029. "#else",
  8030. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  8031. "float lDistance = vPointLight[ i ].w;",
  8032. "#endif",
  8033. // diffuse
  8034. "float dotProduct = dot( normal, lVector );",
  8035. "#ifdef WRAP_AROUND",
  8036. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  8037. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8038. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  8039. "#else",
  8040. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  8041. "#endif",
  8042. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  8043. // specular
  8044. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  8045. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  8046. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  8047. "#ifdef PHYSICALLY_BASED_SHADING",
  8048. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8049. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8050. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  8051. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  8052. "#else",
  8053. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  8054. "#endif",
  8055. "}",
  8056. "#endif",
  8057. "#if MAX_SPOT_LIGHTS > 0",
  8058. "vec3 spotDiffuse = vec3( 0.0 );",
  8059. "vec3 spotSpecular = vec3( 0.0 );",
  8060. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8061. "#ifdef PHONG_PER_PIXEL",
  8062. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8063. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8064. "float lDistance = 1.0;",
  8065. "if ( spotLightDistance[ i ] > 0.0 )",
  8066. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8067. "lVector = normalize( lVector );",
  8068. "#else",
  8069. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  8070. "float lDistance = vSpotLight[ i ].w;",
  8071. "#endif",
  8072. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  8073. "if ( spotEffect > spotLightAngle[ i ] ) {",
  8074. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  8075. // diffuse
  8076. "float dotProduct = dot( normal, lVector );",
  8077. "#ifdef WRAP_AROUND",
  8078. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  8079. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8080. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  8081. "#else",
  8082. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  8083. "#endif",
  8084. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  8085. // specular
  8086. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  8087. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  8088. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  8089. "#ifdef PHYSICALLY_BASED_SHADING",
  8090. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8091. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8092. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  8093. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  8094. "#else",
  8095. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  8096. "#endif",
  8097. "}",
  8098. "}",
  8099. "#endif",
  8100. "#if MAX_DIR_LIGHTS > 0",
  8101. "vec3 dirDiffuse = vec3( 0.0 );",
  8102. "vec3 dirSpecular = vec3( 0.0 );" ,
  8103. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8104. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8105. "vec3 dirVector = normalize( lDirection.xyz );",
  8106. // diffuse
  8107. "float dotProduct = dot( normal, dirVector );",
  8108. "#ifdef WRAP_AROUND",
  8109. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  8110. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8111. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  8112. "#else",
  8113. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  8114. "#endif",
  8115. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  8116. // specular
  8117. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  8118. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  8119. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  8120. "#ifdef PHYSICALLY_BASED_SHADING",
  8121. /*
  8122. // fresnel term from skin shader
  8123. "const float F0 = 0.128;",
  8124. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  8125. "float exponential = pow( base, 5.0 );",
  8126. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  8127. */
  8128. /*
  8129. // fresnel term from fresnel shader
  8130. "const float mFresnelBias = 0.08;",
  8131. "const float mFresnelScale = 0.3;",
  8132. "const float mFresnelPower = 5.0;",
  8133. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  8134. */
  8135. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8136. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8137. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  8138. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  8139. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  8140. "#else",
  8141. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  8142. "#endif",
  8143. "}",
  8144. "#endif",
  8145. "vec3 totalDiffuse = vec3( 0.0 );",
  8146. "vec3 totalSpecular = vec3( 0.0 );",
  8147. "#if MAX_DIR_LIGHTS > 0",
  8148. "totalDiffuse += dirDiffuse;",
  8149. "totalSpecular += dirSpecular;",
  8150. "#endif",
  8151. "#if MAX_POINT_LIGHTS > 0",
  8152. "totalDiffuse += pointDiffuse;",
  8153. "totalSpecular += pointSpecular;",
  8154. "#endif",
  8155. "#if MAX_SPOT_LIGHTS > 0",
  8156. "totalDiffuse += spotDiffuse;",
  8157. "totalSpecular += spotSpecular;",
  8158. "#endif",
  8159. "#ifdef METAL",
  8160. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  8161. "#else",
  8162. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  8163. "#endif"
  8164. ].join("\n"),
  8165. // VERTEX COLORS
  8166. color_pars_fragment: [
  8167. "#ifdef USE_COLOR",
  8168. "varying vec3 vColor;",
  8169. "#endif"
  8170. ].join("\n"),
  8171. color_fragment: [
  8172. "#ifdef USE_COLOR",
  8173. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  8174. "#endif"
  8175. ].join("\n"),
  8176. color_pars_vertex: [
  8177. "#ifdef USE_COLOR",
  8178. "varying vec3 vColor;",
  8179. "#endif"
  8180. ].join("\n"),
  8181. color_vertex: [
  8182. "#ifdef USE_COLOR",
  8183. "#ifdef GAMMA_INPUT",
  8184. "vColor = color * color;",
  8185. "#else",
  8186. "vColor = color;",
  8187. "#endif",
  8188. "#endif"
  8189. ].join("\n"),
  8190. // SKINNING
  8191. skinning_pars_vertex: [
  8192. "#ifdef USE_SKINNING",
  8193. "#ifdef BONE_TEXTURE",
  8194. "uniform sampler2D boneTexture;",
  8195. "mat4 getBoneMatrix( const in float i ) {",
  8196. "float j = i * 4.0;",
  8197. "float x = mod( j, N_BONE_PIXEL_X );",
  8198. "float y = floor( j / N_BONE_PIXEL_X );",
  8199. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  8200. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  8201. "y = dy * ( y + 0.5 );",
  8202. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  8203. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  8204. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  8205. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  8206. "mat4 bone = mat4( v1, v2, v3, v4 );",
  8207. "return bone;",
  8208. "}",
  8209. "#else",
  8210. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  8211. "mat4 getBoneMatrix( const in float i ) {",
  8212. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  8213. "return bone;",
  8214. "}",
  8215. "#endif",
  8216. "#endif"
  8217. ].join("\n"),
  8218. skinbase_vertex: [
  8219. "#ifdef USE_SKINNING",
  8220. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  8221. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  8222. "#endif"
  8223. ].join("\n"),
  8224. skinning_vertex: [
  8225. "#ifdef USE_SKINNING",
  8226. "#ifdef USE_MORPHTARGETS",
  8227. "vec4 skinVertex = vec4( morphed, 1.0 );",
  8228. "#else",
  8229. "vec4 skinVertex = vec4( position, 1.0 );",
  8230. "#endif",
  8231. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  8232. "skinned += boneMatY * skinVertex * skinWeight.y;",
  8233. "#endif"
  8234. ].join("\n"),
  8235. // MORPHING
  8236. morphtarget_pars_vertex: [
  8237. "#ifdef USE_MORPHTARGETS",
  8238. "#ifndef USE_MORPHNORMALS",
  8239. "uniform float morphTargetInfluences[ 8 ];",
  8240. "#else",
  8241. "uniform float morphTargetInfluences[ 4 ];",
  8242. "#endif",
  8243. "#endif"
  8244. ].join("\n"),
  8245. morphtarget_vertex: [
  8246. "#ifdef USE_MORPHTARGETS",
  8247. "vec3 morphed = vec3( 0.0 );",
  8248. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  8249. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  8250. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  8251. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  8252. "#ifndef USE_MORPHNORMALS",
  8253. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  8254. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  8255. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  8256. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  8257. "#endif",
  8258. "morphed += position;",
  8259. //"gl_Position = projectionMatrix * modelViewMatrix * vec4( morphed, 1.0 );",
  8260. "#endif"
  8261. ].join("\n"),
  8262. default_vertex : [
  8263. "#ifdef USE_SKINNING",
  8264. "gl_Position = projectionMatrix * modelViewMatrix * skinned;",
  8265. "#endif",
  8266. "#ifndef USE_SKINNING",
  8267. "#ifdef USE_MORPHTARGETS",
  8268. "gl_Position = projectionMatrix * modelViewMatrix * vec4( morphed, 1.0 );",
  8269. "#endif",
  8270. "#endif",
  8271. "#ifndef USE_MORPHTARGETS",
  8272. "#ifndef USE_SKINNING",
  8273. "gl_Position = projectionMatrix * mvPosition;",
  8274. "#endif",
  8275. "#endif"
  8276. ].join("\n"),
  8277. morphnormal_vertex: [
  8278. "#ifdef USE_MORPHNORMALS",
  8279. "vec3 morphedNormal = vec3( 0.0 );",
  8280. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  8281. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  8282. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  8283. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  8284. "morphedNormal += normal;",
  8285. "#endif"
  8286. ].join("\n"),
  8287. skinnormal_vertex: [
  8288. "#ifdef USE_SKINNING",
  8289. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  8290. "skinMatrix += skinWeight.y * boneMatY;",
  8291. "#ifdef USE_MORPHNORMALS",
  8292. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  8293. "#else",
  8294. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  8295. "#endif",
  8296. "#endif"
  8297. ].join("\n"),
  8298. defaultnormal_vertex: [
  8299. "vec3 transformedNormal;",
  8300. "#ifdef USE_SKINNING",
  8301. "transformedNormal = skinnedNormal.xyz;",
  8302. "#endif",
  8303. "#ifndef USE_SKINNING",
  8304. "#ifdef USE_MORPHNORMALS",
  8305. "transformedNormal = morphedNormal;",
  8306. "#endif",
  8307. "#endif",
  8308. "#ifndef USE_MORPHNORMALS",
  8309. "#ifndef USE_SKINNING",
  8310. "transformedNormal = normal;",
  8311. "#endif",
  8312. "#endif",
  8313. "transformedNormal = normalMatrix * transformedNormal;",
  8314. ].join("\n"),
  8315. // SHADOW MAP
  8316. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  8317. // http://spidergl.org/example.php?id=6
  8318. // http://fabiensanglard.net/shadowmapping
  8319. shadowmap_pars_fragment: [
  8320. "#ifdef USE_SHADOWMAP",
  8321. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  8322. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  8323. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  8324. "uniform float shadowBias[ MAX_SHADOWS ];",
  8325. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8326. "float unpackDepth( const in vec4 rgba_depth ) {",
  8327. "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 );",
  8328. "float depth = dot( rgba_depth, bit_shift );",
  8329. "return depth;",
  8330. "}",
  8331. "#endif"
  8332. ].join("\n"),
  8333. shadowmap_fragment: [
  8334. "#ifdef USE_SHADOWMAP",
  8335. "#ifdef SHADOWMAP_DEBUG",
  8336. "vec3 frustumColors[3];",
  8337. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  8338. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  8339. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  8340. "#endif",
  8341. "#ifdef SHADOWMAP_CASCADE",
  8342. "int inFrustumCount = 0;",
  8343. "#endif",
  8344. "float fDepth;",
  8345. "vec3 shadowColor = vec3( 1.0 );",
  8346. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8347. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  8348. // "if ( something && something )" breaks ATI OpenGL shader compiler
  8349. // "if ( all( something, something ) )" using this instead
  8350. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  8351. "bool inFrustum = all( inFrustumVec );",
  8352. // don't shadow pixels outside of light frustum
  8353. // use just first frustum (for cascades)
  8354. // don't shadow pixels behind far plane of light frustum
  8355. "#ifdef SHADOWMAP_CASCADE",
  8356. "inFrustumCount += int( inFrustum );",
  8357. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  8358. "#else",
  8359. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  8360. "#endif",
  8361. "bool frustumTest = all( frustumTestVec );",
  8362. "if ( frustumTest ) {",
  8363. "shadowCoord.z += shadowBias[ i ];",
  8364. "#ifdef SHADOWMAP_SOFT",
  8365. // Percentage-close filtering
  8366. // (9 pixel kernel)
  8367. // http://fabiensanglard.net/shadowmappingPCF/
  8368. "float shadow = 0.0;",
  8369. /*
  8370. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  8371. // must enroll loop manually
  8372. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  8373. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  8374. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  8375. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  8376. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  8377. "float fDepth = unpackDepth( rgbaDepth );",
  8378. "if ( fDepth < shadowCoord.z )",
  8379. "shadow += 1.0;",
  8380. "}",
  8381. "shadow /= 9.0;",
  8382. */
  8383. "const float shadowDelta = 1.0 / 9.0;",
  8384. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  8385. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  8386. "float dx0 = -1.25 * xPixelOffset;",
  8387. "float dy0 = -1.25 * yPixelOffset;",
  8388. "float dx1 = 1.25 * xPixelOffset;",
  8389. "float dy1 = 1.25 * yPixelOffset;",
  8390. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  8391. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8392. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  8393. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8394. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  8395. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8396. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  8397. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8398. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  8399. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8400. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  8401. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8402. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  8403. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8404. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  8405. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8406. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  8407. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8408. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  8409. "#else",
  8410. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  8411. "float fDepth = unpackDepth( rgbaDepth );",
  8412. "if ( fDepth < shadowCoord.z )",
  8413. // spot with multiple shadows is darker
  8414. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  8415. // spot with multiple shadows has the same color as single shadow spot
  8416. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  8417. "#endif",
  8418. "}",
  8419. "#ifdef SHADOWMAP_DEBUG",
  8420. "#ifdef SHADOWMAP_CASCADE",
  8421. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  8422. "#else",
  8423. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  8424. "#endif",
  8425. "#endif",
  8426. "}",
  8427. "#ifdef GAMMA_OUTPUT",
  8428. "shadowColor *= shadowColor;",
  8429. "#endif",
  8430. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  8431. "#endif"
  8432. ].join("\n"),
  8433. shadowmap_pars_vertex: [
  8434. "#ifdef USE_SHADOWMAP",
  8435. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8436. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  8437. "#endif"
  8438. ].join("\n"),
  8439. shadowmap_vertex: [
  8440. "#ifdef USE_SHADOWMAP",
  8441. "vec4 transformedPosition;",
  8442. "#ifdef USE_SKINNING",
  8443. "transformedPosition = modelMatrix * skinned;",
  8444. "#else",
  8445. "#ifdef USE_MORPHTARGETS",
  8446. "transformedPosition = modelMatrix * vec4( morphed, 1.0 );",
  8447. "#else",
  8448. "transformedPosition = modelMatrix * vec4( position, 1.0 );",
  8449. "#endif",
  8450. "#endif",
  8451. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8452. "vShadowCoord[ i ] = shadowMatrix[ i ] * transformedPosition;",
  8453. "}",
  8454. "#endif"
  8455. ].join("\n"),
  8456. // ALPHATEST
  8457. alphatest_fragment: [
  8458. "#ifdef ALPHATEST",
  8459. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  8460. "#endif"
  8461. ].join("\n"),
  8462. // LINEAR SPACE
  8463. linear_to_gamma_fragment: [
  8464. "#ifdef GAMMA_OUTPUT",
  8465. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  8466. "#endif"
  8467. ].join("\n"),
  8468. };
  8469. THREE.UniformsUtils = {
  8470. merge: function ( uniforms ) {
  8471. var u, p, tmp, merged = {};
  8472. for ( u = 0; u < uniforms.length; u++ ) {
  8473. tmp = this.clone( uniforms[ u ] );
  8474. for ( p in tmp ) {
  8475. merged[ p ] = tmp[ p ];
  8476. }
  8477. }
  8478. return merged;
  8479. },
  8480. clone: function ( uniforms_src ) {
  8481. var u, p, parameter, parameter_src, uniforms_dst = {};
  8482. for ( u in uniforms_src ) {
  8483. uniforms_dst[ u ] = {};
  8484. for ( p in uniforms_src[ u ] ) {
  8485. parameter_src = uniforms_src[ u ][ p ];
  8486. if ( parameter_src instanceof THREE.Color ||
  8487. parameter_src instanceof THREE.Vector2 ||
  8488. parameter_src instanceof THREE.Vector3 ||
  8489. parameter_src instanceof THREE.Vector4 ||
  8490. parameter_src instanceof THREE.Matrix4 ||
  8491. parameter_src instanceof THREE.Texture ) {
  8492. uniforms_dst[ u ][ p ] = parameter_src.clone();
  8493. } else if ( parameter_src instanceof Array ) {
  8494. uniforms_dst[ u ][ p ] = parameter_src.slice();
  8495. } else {
  8496. uniforms_dst[ u ][ p ] = parameter_src;
  8497. }
  8498. }
  8499. }
  8500. return uniforms_dst;
  8501. }
  8502. };
  8503. THREE.UniformsLib = {
  8504. common: {
  8505. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8506. "opacity" : { type: "f", value: 1.0 },
  8507. "map" : { type: "t", value: 0, texture: null },
  8508. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  8509. "lightMap" : { type: "t", value: 2, texture: null },
  8510. "specularMap" : { type: "t", value: 3, texture: null },
  8511. "envMap" : { type: "t", value: 1, texture: null },
  8512. "flipEnvMap" : { type: "f", value: -1 },
  8513. "useRefract" : { type: "i", value: 0 },
  8514. "reflectivity" : { type: "f", value: 1.0 },
  8515. "refractionRatio" : { type: "f", value: 0.98 },
  8516. "combine" : { type: "i", value: 0 },
  8517. "morphTargetInfluences" : { type: "f", value: 0 }
  8518. },
  8519. bump: {
  8520. "bumpMap" : { type: "t", value: 4, texture: null },
  8521. "bumpScale" : { type: "f", value: 1 }
  8522. },
  8523. fog : {
  8524. "fogDensity" : { type: "f", value: 0.00025 },
  8525. "fogNear" : { type: "f", value: 1 },
  8526. "fogFar" : { type: "f", value: 2000 },
  8527. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8528. },
  8529. lights: {
  8530. "ambientLightColor" : { type: "fv", value: [] },
  8531. "directionalLightDirection" : { type: "fv", value: [] },
  8532. "directionalLightColor" : { type: "fv", value: [] },
  8533. "pointLightColor" : { type: "fv", value: [] },
  8534. "pointLightPosition" : { type: "fv", value: [] },
  8535. "pointLightDistance" : { type: "fv1", value: [] },
  8536. "spotLightColor" : { type: "fv", value: [] },
  8537. "spotLightPosition" : { type: "fv", value: [] },
  8538. "spotLightDirection" : { type: "fv", value: [] },
  8539. "spotLightDistance" : { type: "fv1", value: [] },
  8540. "spotLightAngle" : { type: "fv1", value: [] },
  8541. "spotLightExponent" : { type: "fv1", value: [] }
  8542. },
  8543. particle: {
  8544. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8545. "opacity" : { type: "f", value: 1.0 },
  8546. "size" : { type: "f", value: 1.0 },
  8547. "scale" : { type: "f", value: 1.0 },
  8548. "map" : { type: "t", value: 0, texture: null },
  8549. "fogDensity" : { type: "f", value: 0.00025 },
  8550. "fogNear" : { type: "f", value: 1 },
  8551. "fogFar" : { type: "f", value: 2000 },
  8552. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8553. },
  8554. shadowmap: {
  8555. "shadowMap": { type: "tv", value: 6, texture: [] },
  8556. "shadowMapSize": { type: "v2v", value: [] },
  8557. "shadowBias" : { type: "fv1", value: [] },
  8558. "shadowDarkness": { type: "fv1", value: [] },
  8559. "shadowMatrix" : { type: "m4v", value: [] },
  8560. }
  8561. };
  8562. THREE.ShaderLib = {
  8563. 'depth': {
  8564. uniforms: {
  8565. "mNear": { type: "f", value: 1.0 },
  8566. "mFar" : { type: "f", value: 2000.0 },
  8567. "opacity" : { type: "f", value: 1.0 }
  8568. },
  8569. vertexShader: [
  8570. "void main() {",
  8571. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  8572. "}"
  8573. ].join("\n"),
  8574. fragmentShader: [
  8575. "uniform float mNear;",
  8576. "uniform float mFar;",
  8577. "uniform float opacity;",
  8578. "void main() {",
  8579. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8580. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  8581. "gl_FragColor = vec4( vec3( color ), opacity );",
  8582. "}"
  8583. ].join("\n")
  8584. },
  8585. 'normal': {
  8586. uniforms: {
  8587. "opacity" : { type: "f", value: 1.0 }
  8588. },
  8589. vertexShader: [
  8590. "varying vec3 vNormal;",
  8591. "void main() {",
  8592. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8593. "vNormal = normalMatrix * normal;",
  8594. "gl_Position = projectionMatrix * mvPosition;",
  8595. "}"
  8596. ].join("\n"),
  8597. fragmentShader: [
  8598. "uniform float opacity;",
  8599. "varying vec3 vNormal;",
  8600. "void main() {",
  8601. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  8602. "}"
  8603. ].join("\n")
  8604. },
  8605. 'basic': {
  8606. uniforms: THREE.UniformsUtils.merge( [
  8607. THREE.UniformsLib[ "common" ],
  8608. THREE.UniformsLib[ "fog" ],
  8609. THREE.UniformsLib[ "shadowmap" ]
  8610. ] ),
  8611. vertexShader: [
  8612. THREE.ShaderChunk[ "map_pars_vertex" ],
  8613. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  8614. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  8615. THREE.ShaderChunk[ "color_pars_vertex" ],
  8616. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8617. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8618. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8619. "void main() {",
  8620. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8621. THREE.ShaderChunk[ "map_vertex" ],
  8622. THREE.ShaderChunk[ "lightmap_vertex" ],
  8623. THREE.ShaderChunk[ "envmap_vertex" ],
  8624. THREE.ShaderChunk[ "color_vertex" ],
  8625. THREE.ShaderChunk[ "skinbase_vertex" ],
  8626. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8627. THREE.ShaderChunk[ "skinning_vertex" ],
  8628. THREE.ShaderChunk[ "default_vertex" ],
  8629. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8630. "}"
  8631. ].join("\n"),
  8632. fragmentShader: [
  8633. "uniform vec3 diffuse;",
  8634. "uniform float opacity;",
  8635. THREE.ShaderChunk[ "color_pars_fragment" ],
  8636. THREE.ShaderChunk[ "map_pars_fragment" ],
  8637. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  8638. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  8639. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8640. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8641. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  8642. "void main() {",
  8643. "gl_FragColor = vec4( diffuse, opacity );",
  8644. THREE.ShaderChunk[ "map_fragment" ],
  8645. THREE.ShaderChunk[ "alphatest_fragment" ],
  8646. THREE.ShaderChunk[ "specularmap_fragment" ],
  8647. THREE.ShaderChunk[ "lightmap_fragment" ],
  8648. THREE.ShaderChunk[ "color_fragment" ],
  8649. THREE.ShaderChunk[ "envmap_fragment" ],
  8650. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8651. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  8652. THREE.ShaderChunk[ "fog_fragment" ],
  8653. "}"
  8654. ].join("\n")
  8655. },
  8656. 'lambert': {
  8657. uniforms: THREE.UniformsUtils.merge( [
  8658. THREE.UniformsLib[ "common" ],
  8659. THREE.UniformsLib[ "fog" ],
  8660. THREE.UniformsLib[ "lights" ],
  8661. THREE.UniformsLib[ "shadowmap" ],
  8662. {
  8663. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  8664. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  8665. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  8666. }
  8667. ] ),
  8668. vertexShader: [
  8669. "varying vec3 vLightFront;",
  8670. "#ifdef DOUBLE_SIDED",
  8671. "varying vec3 vLightBack;",
  8672. "#endif",
  8673. THREE.ShaderChunk[ "map_pars_vertex" ],
  8674. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  8675. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  8676. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  8677. THREE.ShaderChunk[ "color_pars_vertex" ],
  8678. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8679. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8680. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8681. "void main() {",
  8682. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8683. THREE.ShaderChunk[ "map_vertex" ],
  8684. THREE.ShaderChunk[ "lightmap_vertex" ],
  8685. THREE.ShaderChunk[ "envmap_vertex" ],
  8686. THREE.ShaderChunk[ "color_vertex" ],
  8687. THREE.ShaderChunk[ "morphnormal_vertex" ],
  8688. THREE.ShaderChunk[ "skinbase_vertex" ],
  8689. THREE.ShaderChunk[ "skinnormal_vertex" ],
  8690. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  8691. "#ifndef USE_ENVMAP",
  8692. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  8693. "#endif",
  8694. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  8695. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8696. THREE.ShaderChunk[ "skinning_vertex" ],
  8697. THREE.ShaderChunk[ "default_vertex" ],
  8698. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8699. "}"
  8700. ].join("\n"),
  8701. fragmentShader: [
  8702. "uniform float opacity;",
  8703. "varying vec3 vLightFront;",
  8704. "#ifdef DOUBLE_SIDED",
  8705. "varying vec3 vLightBack;",
  8706. "#endif",
  8707. THREE.ShaderChunk[ "color_pars_fragment" ],
  8708. THREE.ShaderChunk[ "map_pars_fragment" ],
  8709. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  8710. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  8711. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8712. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8713. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  8714. "void main() {",
  8715. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  8716. THREE.ShaderChunk[ "map_fragment" ],
  8717. THREE.ShaderChunk[ "alphatest_fragment" ],
  8718. THREE.ShaderChunk[ "specularmap_fragment" ],
  8719. "#ifdef DOUBLE_SIDED",
  8720. //"float isFront = float( gl_FrontFacing );",
  8721. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  8722. "if ( gl_FrontFacing )",
  8723. "gl_FragColor.xyz *= vLightFront;",
  8724. "else",
  8725. "gl_FragColor.xyz *= vLightBack;",
  8726. "#else",
  8727. "gl_FragColor.xyz *= vLightFront;",
  8728. "#endif",
  8729. THREE.ShaderChunk[ "lightmap_fragment" ],
  8730. THREE.ShaderChunk[ "color_fragment" ],
  8731. THREE.ShaderChunk[ "envmap_fragment" ],
  8732. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8733. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  8734. THREE.ShaderChunk[ "fog_fragment" ],
  8735. "}"
  8736. ].join("\n")
  8737. },
  8738. 'phong': {
  8739. uniforms: THREE.UniformsUtils.merge( [
  8740. THREE.UniformsLib[ "common" ],
  8741. THREE.UniformsLib[ "bump" ],
  8742. THREE.UniformsLib[ "fog" ],
  8743. THREE.UniformsLib[ "lights" ],
  8744. THREE.UniformsLib[ "shadowmap" ],
  8745. {
  8746. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  8747. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  8748. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  8749. "shininess": { type: "f", value: 30 },
  8750. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  8751. }
  8752. ] ),
  8753. vertexShader: [
  8754. "varying vec3 vViewPosition;",
  8755. "varying vec3 vNormal;",
  8756. THREE.ShaderChunk[ "map_pars_vertex" ],
  8757. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  8758. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  8759. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  8760. THREE.ShaderChunk[ "color_pars_vertex" ],
  8761. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8762. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8763. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8764. "void main() {",
  8765. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8766. THREE.ShaderChunk[ "map_vertex" ],
  8767. THREE.ShaderChunk[ "lightmap_vertex" ],
  8768. THREE.ShaderChunk[ "envmap_vertex" ],
  8769. THREE.ShaderChunk[ "color_vertex" ],
  8770. "#ifndef USE_ENVMAP",
  8771. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  8772. "#endif",
  8773. "vViewPosition = -mvPosition.xyz;",
  8774. THREE.ShaderChunk[ "morphnormal_vertex" ],
  8775. THREE.ShaderChunk[ "skinbase_vertex" ],
  8776. THREE.ShaderChunk[ "skinnormal_vertex" ],
  8777. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  8778. "vNormal = transformedNormal;",
  8779. THREE.ShaderChunk[ "lights_phong_vertex" ],
  8780. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8781. THREE.ShaderChunk[ "skinning_vertex" ],
  8782. THREE.ShaderChunk[ "default_vertex" ],
  8783. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8784. "}"
  8785. ].join("\n"),
  8786. fragmentShader: [
  8787. "uniform vec3 diffuse;",
  8788. "uniform float opacity;",
  8789. "uniform vec3 ambient;",
  8790. "uniform vec3 emissive;",
  8791. "uniform vec3 specular;",
  8792. "uniform float shininess;",
  8793. THREE.ShaderChunk[ "color_pars_fragment" ],
  8794. THREE.ShaderChunk[ "map_pars_fragment" ],
  8795. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  8796. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  8797. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8798. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  8799. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8800. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  8801. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  8802. "void main() {",
  8803. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  8804. THREE.ShaderChunk[ "map_fragment" ],
  8805. THREE.ShaderChunk[ "alphatest_fragment" ],
  8806. THREE.ShaderChunk[ "specularmap_fragment" ],
  8807. THREE.ShaderChunk[ "lights_phong_fragment" ],
  8808. THREE.ShaderChunk[ "lightmap_fragment" ],
  8809. THREE.ShaderChunk[ "color_fragment" ],
  8810. THREE.ShaderChunk[ "envmap_fragment" ],
  8811. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8812. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  8813. THREE.ShaderChunk[ "fog_fragment" ],
  8814. "}"
  8815. ].join("\n")
  8816. },
  8817. 'particle_basic': {
  8818. uniforms: THREE.UniformsUtils.merge( [
  8819. THREE.UniformsLib[ "particle" ],
  8820. THREE.UniformsLib[ "shadowmap" ]
  8821. ] ),
  8822. vertexShader: [
  8823. "uniform float size;",
  8824. "uniform float scale;",
  8825. THREE.ShaderChunk[ "color_pars_vertex" ],
  8826. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8827. "void main() {",
  8828. THREE.ShaderChunk[ "color_vertex" ],
  8829. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8830. "#ifdef USE_SIZEATTENUATION",
  8831. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  8832. "#else",
  8833. "gl_PointSize = size;",
  8834. "#endif",
  8835. "gl_Position = projectionMatrix * mvPosition;",
  8836. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8837. "}"
  8838. ].join("\n"),
  8839. fragmentShader: [
  8840. "uniform vec3 psColor;",
  8841. "uniform float opacity;",
  8842. THREE.ShaderChunk[ "color_pars_fragment" ],
  8843. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  8844. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8845. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8846. "void main() {",
  8847. "gl_FragColor = vec4( psColor, opacity );",
  8848. THREE.ShaderChunk[ "map_particle_fragment" ],
  8849. THREE.ShaderChunk[ "alphatest_fragment" ],
  8850. THREE.ShaderChunk[ "color_fragment" ],
  8851. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8852. THREE.ShaderChunk[ "fog_fragment" ],
  8853. "}"
  8854. ].join("\n")
  8855. },
  8856. // Depth encoding into RGBA texture
  8857. // based on SpiderGL shadow map example
  8858. // http://spidergl.org/example.php?id=6
  8859. // originally from
  8860. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  8861. // see also here:
  8862. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  8863. 'depthRGBA': {
  8864. uniforms: {},
  8865. vertexShader: [
  8866. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8867. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8868. "void main() {",
  8869. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8870. THREE.ShaderChunk[ "skinbase_vertex" ],
  8871. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8872. THREE.ShaderChunk[ "skinning_vertex" ],
  8873. THREE.ShaderChunk[ "default_vertex" ],
  8874. "}"
  8875. ].join("\n"),
  8876. fragmentShader: [
  8877. "vec4 pack_depth( const in float depth ) {",
  8878. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  8879. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  8880. "vec4 res = fract( depth * bit_shift );",
  8881. "res -= res.xxyz * bit_mask;",
  8882. "return res;",
  8883. "}",
  8884. "void main() {",
  8885. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  8886. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  8887. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  8888. //"gl_FragData[ 0 ] = pack_depth( z );",
  8889. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  8890. "}"
  8891. ].join("\n")
  8892. }
  8893. };
  8894. /**
  8895. * @author supereggbert / http://www.paulbrunt.co.uk/
  8896. * @author mrdoob / http://mrdoob.com/
  8897. * @author alteredq / http://alteredqualia.com/
  8898. * @author szimek / https://github.com/szimek/
  8899. */
  8900. THREE.WebGLRenderer = function ( parameters ) {
  8901. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  8902. parameters = parameters || {};
  8903. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  8904. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  8905. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  8906. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  8907. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  8908. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  8909. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  8910. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  8911. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,
  8912. _maxLights = parameters.maxLights !== undefined ? parameters.maxLights : 4;
  8913. // public properties
  8914. this.domElement = _canvas;
  8915. this.context = null;
  8916. // clearing
  8917. this.autoClear = true;
  8918. this.autoClearColor = true;
  8919. this.autoClearDepth = true;
  8920. this.autoClearStencil = true;
  8921. // scene graph
  8922. this.sortObjects = true;
  8923. this.autoUpdateObjects = true;
  8924. this.autoUpdateScene = true;
  8925. // physically based shading
  8926. this.gammaInput = false;
  8927. this.gammaOutput = false;
  8928. this.physicallyBasedShading = false;
  8929. // shadow map
  8930. this.shadowMapEnabled = false;
  8931. this.shadowMapAutoUpdate = true;
  8932. this.shadowMapSoft = true;
  8933. this.shadowMapCullFrontFaces = true;
  8934. this.shadowMapDebug = false;
  8935. this.shadowMapCascade = false;
  8936. // morphs
  8937. this.maxMorphTargets = 8;
  8938. this.maxMorphNormals = 4;
  8939. // flags
  8940. this.autoScaleCubemaps = true;
  8941. // custom render plugins
  8942. this.renderPluginsPre = [];
  8943. this.renderPluginsPost = [];
  8944. // info
  8945. this.info = {
  8946. memory: {
  8947. programs: 0,
  8948. geometries: 0,
  8949. textures: 0
  8950. },
  8951. render: {
  8952. calls: 0,
  8953. vertices: 0,
  8954. faces: 0,
  8955. points: 0
  8956. }
  8957. };
  8958. // internal properties
  8959. var _this = this,
  8960. _programs = [],
  8961. _programs_counter = 0,
  8962. // internal state cache
  8963. _currentProgram = null,
  8964. _currentFramebuffer = null,
  8965. _currentMaterialId = -1,
  8966. _currentGeometryGroupHash = null,
  8967. _currentCamera = null,
  8968. _geometryGroupCounter = 0,
  8969. // GL state cache
  8970. _oldDoubleSided = -1,
  8971. _oldFlipSided = -1,
  8972. _oldBlending = -1,
  8973. _oldBlendEquation = -1,
  8974. _oldBlendSrc = -1,
  8975. _oldBlendDst = -1,
  8976. _oldDepthTest = -1,
  8977. _oldDepthWrite = -1,
  8978. _oldPolygonOffset = null,
  8979. _oldPolygonOffsetFactor = null,
  8980. _oldPolygonOffsetUnits = null,
  8981. _oldLineWidth = null,
  8982. _viewportX = 0,
  8983. _viewportY = 0,
  8984. _viewportWidth = 0,
  8985. _viewportHeight = 0,
  8986. _currentWidth = 0,
  8987. _currentHeight = 0,
  8988. // frustum
  8989. _frustum = new THREE.Frustum(),
  8990. // camera matrices cache
  8991. _projScreenMatrix = new THREE.Matrix4(),
  8992. _projScreenMatrixPS = new THREE.Matrix4(),
  8993. _vector3 = new THREE.Vector4(),
  8994. // light arrays cache
  8995. _direction = new THREE.Vector3(),
  8996. _lightsNeedUpdate = true,
  8997. _lights = {
  8998. ambient: [ 0, 0, 0 ],
  8999. directional: { length: 0, colors: new Array(), positions: new Array() },
  9000. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  9001. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), angles: new Array(), exponents: new Array() }
  9002. };
  9003. // initialize
  9004. var _gl;
  9005. var _glExtensionTextureFloat;
  9006. var _glExtensionStandardDerivatives;
  9007. var _glExtensionTextureFilterAnisotropic;
  9008. initGL();
  9009. setDefaultGLState();
  9010. this.context = _gl;
  9011. // GPU capabilities
  9012. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ),
  9013. _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ),
  9014. _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9015. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  9016. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  9017. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  9018. // API
  9019. this.getContext = function () {
  9020. return _gl;
  9021. };
  9022. this.supportsVertexTextures = function () {
  9023. return _supportsVertexTextures;
  9024. };
  9025. this.getMaxAnisotropy = function () {
  9026. return _maxAnisotropy;
  9027. };
  9028. this.setSize = function ( width, height ) {
  9029. _canvas.width = width;
  9030. _canvas.height = height;
  9031. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  9032. };
  9033. this.setViewport = function ( x, y, width, height ) {
  9034. _viewportX = x !== undefined ? x : 0;
  9035. _viewportY = y !== undefined ? y : 0;
  9036. _viewportWidth = width !== undefined ? width : _canvas.width;
  9037. _viewportHeight = height !== undefined ? height : _canvas.height;
  9038. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  9039. };
  9040. this.setScissor = function ( x, y, width, height ) {
  9041. _gl.scissor( x, y, width, height );
  9042. };
  9043. this.enableScissorTest = function ( enable ) {
  9044. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  9045. };
  9046. // Clearing
  9047. this.setClearColorHex = function ( hex, alpha ) {
  9048. _clearColor.setHex( hex );
  9049. _clearAlpha = alpha;
  9050. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9051. };
  9052. this.setClearColor = function ( color, alpha ) {
  9053. _clearColor.copy( color );
  9054. _clearAlpha = alpha;
  9055. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9056. };
  9057. this.getClearColor = function () {
  9058. return _clearColor;
  9059. };
  9060. this.getClearAlpha = function () {
  9061. return _clearAlpha;
  9062. };
  9063. this.clear = function ( color, depth, stencil ) {
  9064. var bits = 0;
  9065. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  9066. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  9067. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  9068. _gl.clear( bits );
  9069. };
  9070. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  9071. this.setRenderTarget( renderTarget );
  9072. this.clear( color, depth, stencil );
  9073. };
  9074. // Plugins
  9075. this.addPostPlugin = function ( plugin ) {
  9076. plugin.init( this );
  9077. this.renderPluginsPost.push( plugin );
  9078. };
  9079. this.addPrePlugin = function ( plugin ) {
  9080. plugin.init( this );
  9081. this.renderPluginsPre.push( plugin );
  9082. };
  9083. // Deallocation
  9084. this.deallocateObject = function ( object ) {
  9085. if ( ! object.__webglInit ) return;
  9086. object.__webglInit = false;
  9087. delete object._modelViewMatrix;
  9088. delete object._normalMatrix;
  9089. delete object._normalMatrixArray;
  9090. delete object._modelViewMatrixArray;
  9091. delete object._modelMatrixArray;
  9092. if ( object instanceof THREE.Mesh ) {
  9093. for ( var g in object.geometry.geometryGroups ) {
  9094. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  9095. }
  9096. } else if ( object instanceof THREE.Ribbon ) {
  9097. deleteRibbonBuffers( object.geometry );
  9098. } else if ( object instanceof THREE.Line ) {
  9099. deleteLineBuffers( object.geometry );
  9100. } else if ( object instanceof THREE.ParticleSystem ) {
  9101. deleteParticleBuffers( object.geometry );
  9102. }
  9103. };
  9104. this.deallocateTexture = function ( texture ) {
  9105. if ( ! texture.__webglInit ) return;
  9106. texture.__webglInit = false;
  9107. _gl.deleteTexture( texture.__webglTexture );
  9108. _this.info.memory.textures --;
  9109. };
  9110. this.deallocateRenderTarget = function ( renderTarget ) {
  9111. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  9112. _gl.deleteTexture( renderTarget.__webglTexture );
  9113. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9114. for ( var i = 0; i < 6; i ++ ) {
  9115. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  9116. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  9117. }
  9118. } else {
  9119. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  9120. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  9121. }
  9122. };
  9123. this.deallocateMaterial = function ( material ) {
  9124. var program = material.program;
  9125. if ( ! program ) return;
  9126. material.program = undefined;
  9127. // only deallocate GL program if this was the last use of shared program
  9128. // assumed there is only single copy of any program in the _programs list
  9129. // (that's how it's constructed)
  9130. var i, il, programInfo;
  9131. var deleteProgram = false;
  9132. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9133. programInfo = _programs[ i ];
  9134. if ( programInfo.program === program ) {
  9135. programInfo.usedTimes --;
  9136. if ( programInfo.usedTimes === 0 ) {
  9137. deleteProgram = true;
  9138. }
  9139. break;
  9140. }
  9141. }
  9142. if ( deleteProgram ) {
  9143. // avoid using array.splice, this is costlier than creating new array from scratch
  9144. var newPrograms = [];
  9145. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9146. programInfo = _programs[ i ];
  9147. if ( programInfo.program !== program ) {
  9148. newPrograms.push( programInfo );
  9149. }
  9150. }
  9151. _programs = newPrograms;
  9152. _gl.deleteProgram( program );
  9153. _this.info.memory.programs --;
  9154. }
  9155. };
  9156. // Rendering
  9157. this.updateShadowMap = function ( scene, camera ) {
  9158. _currentProgram = null;
  9159. _oldBlending = -1;
  9160. _oldDepthTest = -1;
  9161. _oldDepthWrite = -1;
  9162. _currentGeometryGroupHash = -1;
  9163. _currentMaterialId = -1;
  9164. _lightsNeedUpdate = true;
  9165. _oldDoubleSided = -1;
  9166. _oldFlipSided = -1;
  9167. this.shadowMapPlugin.update( scene, camera );
  9168. };
  9169. // Internal functions
  9170. // Buffer allocation
  9171. function createParticleBuffers ( geometry ) {
  9172. geometry.__webglVertexBuffer = _gl.createBuffer();
  9173. geometry.__webglColorBuffer = _gl.createBuffer();
  9174. _this.info.geometries ++;
  9175. };
  9176. function createLineBuffers ( geometry ) {
  9177. geometry.__webglVertexBuffer = _gl.createBuffer();
  9178. geometry.__webglColorBuffer = _gl.createBuffer();
  9179. _this.info.memory.geometries ++;
  9180. };
  9181. function createRibbonBuffers ( geometry ) {
  9182. geometry.__webglVertexBuffer = _gl.createBuffer();
  9183. geometry.__webglColorBuffer = _gl.createBuffer();
  9184. _this.info.memory.geometries ++;
  9185. };
  9186. function createMeshBuffers ( geometryGroup ) {
  9187. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  9188. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  9189. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  9190. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  9191. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  9192. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  9193. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  9194. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  9195. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  9196. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  9197. var m, ml;
  9198. if ( geometryGroup.numMorphTargets ) {
  9199. geometryGroup.__webglMorphTargetsBuffers = [];
  9200. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9201. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  9202. }
  9203. }
  9204. if ( geometryGroup.numMorphNormals ) {
  9205. geometryGroup.__webglMorphNormalsBuffers = [];
  9206. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9207. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  9208. }
  9209. }
  9210. _this.info.memory.geometries ++;
  9211. };
  9212. // Buffer deallocation
  9213. function deleteParticleBuffers ( geometry ) {
  9214. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9215. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9216. _this.info.memory.geometries --;
  9217. };
  9218. function deleteLineBuffers ( geometry ) {
  9219. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9220. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9221. _this.info.memory.geometries --;
  9222. };
  9223. function deleteRibbonBuffers ( geometry ) {
  9224. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9225. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9226. _this.info.memory.geometries --;
  9227. };
  9228. function deleteMeshBuffers ( geometryGroup ) {
  9229. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  9230. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  9231. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  9232. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  9233. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  9234. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  9235. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  9236. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  9237. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  9238. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  9239. var m, ml;
  9240. if ( geometryGroup.numMorphTargets ) {
  9241. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9242. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  9243. }
  9244. }
  9245. if ( geometryGroup.numMorphNormals ) {
  9246. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9247. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  9248. }
  9249. }
  9250. if ( geometryGroup.__webglCustomAttributesList ) {
  9251. for ( var id in geometryGroup.__webglCustomAttributesList ) {
  9252. _gl.deleteBuffer( geometryGroup.__webglCustomAttributesList[ id ].buffer );
  9253. }
  9254. }
  9255. _this.info.memory.geometries --;
  9256. };
  9257. // Buffer initialization
  9258. function initCustomAttributes ( geometry, object ) {
  9259. var nvertices = geometry.vertices.length;
  9260. var material = object.material;
  9261. if ( material.attributes ) {
  9262. if ( geometry.__webglCustomAttributesList === undefined ) {
  9263. geometry.__webglCustomAttributesList = [];
  9264. }
  9265. for ( var a in material.attributes ) {
  9266. var attribute = material.attributes[ a ];
  9267. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9268. attribute.__webglInitialized = true;
  9269. var size = 1; // "f" and "i"
  9270. if ( attribute.type === "v2" ) size = 2;
  9271. else if ( attribute.type === "v3" ) size = 3;
  9272. else if ( attribute.type === "v4" ) size = 4;
  9273. else if ( attribute.type === "c" ) size = 3;
  9274. attribute.size = size;
  9275. attribute.array = new Float32Array( nvertices * size );
  9276. attribute.buffer = _gl.createBuffer();
  9277. attribute.buffer.belongsToAttribute = a;
  9278. attribute.needsUpdate = true;
  9279. }
  9280. geometry.__webglCustomAttributesList.push( attribute );
  9281. }
  9282. }
  9283. };
  9284. function initParticleBuffers ( geometry, object ) {
  9285. var nvertices = geometry.vertices.length;
  9286. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9287. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9288. geometry.__sortArray = [];
  9289. geometry.__webglParticleCount = nvertices;
  9290. initCustomAttributes ( geometry, object );
  9291. };
  9292. function initLineBuffers ( geometry, object ) {
  9293. var nvertices = geometry.vertices.length;
  9294. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9295. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9296. geometry.__webglLineCount = nvertices;
  9297. initCustomAttributes ( geometry, object );
  9298. };
  9299. function initRibbonBuffers ( geometry ) {
  9300. var nvertices = geometry.vertices.length;
  9301. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9302. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9303. geometry.__webglVertexCount = nvertices;
  9304. };
  9305. function initMeshBuffers ( geometryGroup, object ) {
  9306. var geometry = object.geometry,
  9307. faces3 = geometryGroup.faces3,
  9308. faces4 = geometryGroup.faces4,
  9309. nvertices = faces3.length * 3 + faces4.length * 4,
  9310. ntris = faces3.length * 1 + faces4.length * 2,
  9311. nlines = faces3.length * 3 + faces4.length * 4,
  9312. material = getBufferMaterial( object, geometryGroup ),
  9313. uvType = bufferGuessUVType( material ),
  9314. normalType = bufferGuessNormalType( material ),
  9315. vertexColorType = bufferGuessVertexColorType( material );
  9316. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  9317. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  9318. if ( normalType ) {
  9319. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  9320. }
  9321. if ( geometry.hasTangents ) {
  9322. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  9323. }
  9324. if ( vertexColorType ) {
  9325. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  9326. }
  9327. if ( uvType ) {
  9328. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  9329. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  9330. }
  9331. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  9332. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  9333. }
  9334. }
  9335. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  9336. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  9337. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  9338. }
  9339. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  9340. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  9341. var m, ml;
  9342. if ( geometryGroup.numMorphTargets ) {
  9343. geometryGroup.__morphTargetsArrays = [];
  9344. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9345. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  9346. }
  9347. }
  9348. if ( geometryGroup.numMorphNormals ) {
  9349. geometryGroup.__morphNormalsArrays = [];
  9350. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9351. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  9352. }
  9353. }
  9354. geometryGroup.__webglFaceCount = ntris * 3;
  9355. geometryGroup.__webglLineCount = nlines * 2;
  9356. // custom attributes
  9357. if ( material.attributes ) {
  9358. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  9359. geometryGroup.__webglCustomAttributesList = [];
  9360. }
  9361. for ( var a in material.attributes ) {
  9362. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  9363. // attribute buffers which are correctly indexed in the setMeshBuffers function
  9364. var originalAttribute = material.attributes[ a ];
  9365. var attribute = {};
  9366. for ( var property in originalAttribute ) {
  9367. attribute[ property ] = originalAttribute[ property ];
  9368. }
  9369. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9370. attribute.__webglInitialized = true;
  9371. var size = 1; // "f" and "i"
  9372. if( attribute.type === "v2" ) size = 2;
  9373. else if( attribute.type === "v3" ) size = 3;
  9374. else if( attribute.type === "v4" ) size = 4;
  9375. else if( attribute.type === "c" ) size = 3;
  9376. attribute.size = size;
  9377. attribute.array = new Float32Array( nvertices * size );
  9378. attribute.buffer = _gl.createBuffer();
  9379. attribute.buffer.belongsToAttribute = a;
  9380. originalAttribute.needsUpdate = true;
  9381. attribute.__original = originalAttribute;
  9382. }
  9383. geometryGroup.__webglCustomAttributesList.push( attribute );
  9384. }
  9385. }
  9386. geometryGroup.__inittedArrays = true;
  9387. };
  9388. function getBufferMaterial( object, geometryGroup ) {
  9389. if ( object.material && ! ( object.material instanceof THREE.MeshFaceMaterial ) ) {
  9390. return object.material;
  9391. } else if ( geometryGroup.materialIndex >= 0 ) {
  9392. return object.geometry.materials[ geometryGroup.materialIndex ];
  9393. }
  9394. };
  9395. function materialNeedsSmoothNormals ( material ) {
  9396. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  9397. };
  9398. function bufferGuessNormalType ( material ) {
  9399. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  9400. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  9401. return false;
  9402. }
  9403. if ( materialNeedsSmoothNormals( material ) ) {
  9404. return THREE.SmoothShading;
  9405. } else {
  9406. return THREE.FlatShading;
  9407. }
  9408. };
  9409. function bufferGuessVertexColorType ( material ) {
  9410. if ( material.vertexColors ) {
  9411. return material.vertexColors;
  9412. }
  9413. return false;
  9414. };
  9415. function bufferGuessUVType ( material ) {
  9416. // material must use some texture to require uvs
  9417. if ( material.map || material.lightMap || material.bumpMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  9418. return true;
  9419. }
  9420. return false;
  9421. };
  9422. //
  9423. function initDirectBuffers( geometry ) {
  9424. var a, attribute, type;
  9425. for ( a in geometry.attributes ) {
  9426. if ( a === "index" ) {
  9427. type = _gl.ELEMENT_ARRAY_BUFFER;
  9428. } else {
  9429. type = _gl.ARRAY_BUFFER;
  9430. }
  9431. attribute = geometry.attributes[ a ];
  9432. attribute.buffer = _gl.createBuffer();
  9433. _gl.bindBuffer( type, attribute.buffer );
  9434. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  9435. }
  9436. };
  9437. // Buffer setting
  9438. function setParticleBuffers ( geometry, hint, object ) {
  9439. var v, c, vertex, offset, index, color,
  9440. vertices = geometry.vertices,
  9441. vl = vertices.length,
  9442. colors = geometry.colors,
  9443. cl = colors.length,
  9444. vertexArray = geometry.__vertexArray,
  9445. colorArray = geometry.__colorArray,
  9446. sortArray = geometry.__sortArray,
  9447. dirtyVertices = geometry.verticesNeedUpdate,
  9448. dirtyElements = geometry.elementsNeedUpdate,
  9449. dirtyColors = geometry.colorsNeedUpdate,
  9450. customAttributes = geometry.__webglCustomAttributesList,
  9451. i, il,
  9452. a, ca, cal, value,
  9453. customAttribute;
  9454. if ( object.sortParticles ) {
  9455. _projScreenMatrixPS.copy( _projScreenMatrix );
  9456. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  9457. for ( v = 0; v < vl; v ++ ) {
  9458. vertex = vertices[ v ];
  9459. _vector3.copy( vertex );
  9460. _projScreenMatrixPS.multiplyVector3( _vector3 );
  9461. sortArray[ v ] = [ _vector3.z, v ];
  9462. }
  9463. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  9464. for ( v = 0; v < vl; v ++ ) {
  9465. vertex = vertices[ sortArray[v][1] ];
  9466. offset = v * 3;
  9467. vertexArray[ offset ] = vertex.x;
  9468. vertexArray[ offset + 1 ] = vertex.y;
  9469. vertexArray[ offset + 2 ] = vertex.z;
  9470. }
  9471. for ( c = 0; c < cl; c ++ ) {
  9472. offset = c * 3;
  9473. color = colors[ sortArray[c][1] ];
  9474. colorArray[ offset ] = color.r;
  9475. colorArray[ offset + 1 ] = color.g;
  9476. colorArray[ offset + 2 ] = color.b;
  9477. }
  9478. if ( customAttributes ) {
  9479. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9480. customAttribute = customAttributes[ i ];
  9481. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  9482. offset = 0;
  9483. cal = customAttribute.value.length;
  9484. if ( customAttribute.size === 1 ) {
  9485. for ( ca = 0; ca < cal; ca ++ ) {
  9486. index = sortArray[ ca ][ 1 ];
  9487. customAttribute.array[ ca ] = customAttribute.value[ index ];
  9488. }
  9489. } else if ( customAttribute.size === 2 ) {
  9490. for ( ca = 0; ca < cal; ca ++ ) {
  9491. index = sortArray[ ca ][ 1 ];
  9492. value = customAttribute.value[ index ];
  9493. customAttribute.array[ offset ] = value.x;
  9494. customAttribute.array[ offset + 1 ] = value.y;
  9495. offset += 2;
  9496. }
  9497. } else if ( customAttribute.size === 3 ) {
  9498. if ( customAttribute.type === "c" ) {
  9499. for ( ca = 0; ca < cal; ca ++ ) {
  9500. index = sortArray[ ca ][ 1 ];
  9501. value = customAttribute.value[ index ];
  9502. customAttribute.array[ offset ] = value.r;
  9503. customAttribute.array[ offset + 1 ] = value.g;
  9504. customAttribute.array[ offset + 2 ] = value.b;
  9505. offset += 3;
  9506. }
  9507. } else {
  9508. for ( ca = 0; ca < cal; ca ++ ) {
  9509. index = sortArray[ ca ][ 1 ];
  9510. value = customAttribute.value[ index ];
  9511. customAttribute.array[ offset ] = value.x;
  9512. customAttribute.array[ offset + 1 ] = value.y;
  9513. customAttribute.array[ offset + 2 ] = value.z;
  9514. offset += 3;
  9515. }
  9516. }
  9517. } else if ( customAttribute.size === 4 ) {
  9518. for ( ca = 0; ca < cal; ca ++ ) {
  9519. index = sortArray[ ca ][ 1 ];
  9520. value = customAttribute.value[ index ];
  9521. customAttribute.array[ offset ] = value.x;
  9522. customAttribute.array[ offset + 1 ] = value.y;
  9523. customAttribute.array[ offset + 2 ] = value.z;
  9524. customAttribute.array[ offset + 3 ] = value.w;
  9525. offset += 4;
  9526. }
  9527. }
  9528. }
  9529. }
  9530. } else {
  9531. if ( dirtyVertices ) {
  9532. for ( v = 0; v < vl; v ++ ) {
  9533. vertex = vertices[ v ];
  9534. offset = v * 3;
  9535. vertexArray[ offset ] = vertex.x;
  9536. vertexArray[ offset + 1 ] = vertex.y;
  9537. vertexArray[ offset + 2 ] = vertex.z;
  9538. }
  9539. }
  9540. if ( dirtyColors ) {
  9541. for ( c = 0; c < cl; c ++ ) {
  9542. color = colors[ c ];
  9543. offset = c * 3;
  9544. colorArray[ offset ] = color.r;
  9545. colorArray[ offset + 1 ] = color.g;
  9546. colorArray[ offset + 2 ] = color.b;
  9547. }
  9548. }
  9549. if ( customAttributes ) {
  9550. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9551. customAttribute = customAttributes[ i ];
  9552. if ( customAttribute.needsUpdate &&
  9553. ( customAttribute.boundTo === undefined ||
  9554. customAttribute.boundTo === "vertices") ) {
  9555. cal = customAttribute.value.length;
  9556. offset = 0;
  9557. if ( customAttribute.size === 1 ) {
  9558. for ( ca = 0; ca < cal; ca ++ ) {
  9559. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  9560. }
  9561. } else if ( customAttribute.size === 2 ) {
  9562. for ( ca = 0; ca < cal; ca ++ ) {
  9563. value = customAttribute.value[ ca ];
  9564. customAttribute.array[ offset ] = value.x;
  9565. customAttribute.array[ offset + 1 ] = value.y;
  9566. offset += 2;
  9567. }
  9568. } else if ( customAttribute.size === 3 ) {
  9569. if ( customAttribute.type === "c" ) {
  9570. for ( ca = 0; ca < cal; ca ++ ) {
  9571. value = customAttribute.value[ ca ];
  9572. customAttribute.array[ offset ] = value.r;
  9573. customAttribute.array[ offset + 1 ] = value.g;
  9574. customAttribute.array[ offset + 2 ] = value.b;
  9575. offset += 3;
  9576. }
  9577. } else {
  9578. for ( ca = 0; ca < cal; ca ++ ) {
  9579. value = customAttribute.value[ ca ];
  9580. customAttribute.array[ offset ] = value.x;
  9581. customAttribute.array[ offset + 1 ] = value.y;
  9582. customAttribute.array[ offset + 2 ] = value.z;
  9583. offset += 3;
  9584. }
  9585. }
  9586. } else if ( customAttribute.size === 4 ) {
  9587. for ( ca = 0; ca < cal; ca ++ ) {
  9588. value = customAttribute.value[ ca ];
  9589. customAttribute.array[ offset ] = value.x;
  9590. customAttribute.array[ offset + 1 ] = value.y;
  9591. customAttribute.array[ offset + 2 ] = value.z;
  9592. customAttribute.array[ offset + 3 ] = value.w;
  9593. offset += 4;
  9594. }
  9595. }
  9596. }
  9597. }
  9598. }
  9599. }
  9600. if ( dirtyVertices || object.sortParticles ) {
  9601. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  9602. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9603. }
  9604. if ( dirtyColors || object.sortParticles ) {
  9605. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  9606. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  9607. }
  9608. if ( customAttributes ) {
  9609. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9610. customAttribute = customAttributes[ i ];
  9611. if ( customAttribute.needsUpdate || object.sortParticles ) {
  9612. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  9613. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  9614. }
  9615. }
  9616. }
  9617. };
  9618. function setLineBuffers ( geometry, hint ) {
  9619. var v, c, vertex, offset, color,
  9620. vertices = geometry.vertices,
  9621. colors = geometry.colors,
  9622. vl = vertices.length,
  9623. cl = colors.length,
  9624. vertexArray = geometry.__vertexArray,
  9625. colorArray = geometry.__colorArray,
  9626. dirtyVertices = geometry.verticesNeedUpdate,
  9627. dirtyColors = geometry.colorsNeedUpdate,
  9628. customAttributes = geometry.__webglCustomAttributesList,
  9629. i, il,
  9630. a, ca, cal, value,
  9631. customAttribute;
  9632. if ( dirtyVertices ) {
  9633. for ( v = 0; v < vl; v ++ ) {
  9634. vertex = vertices[ v ];
  9635. offset = v * 3;
  9636. vertexArray[ offset ] = vertex.x;
  9637. vertexArray[ offset + 1 ] = vertex.y;
  9638. vertexArray[ offset + 2 ] = vertex.z;
  9639. }
  9640. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  9641. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9642. }
  9643. if ( dirtyColors ) {
  9644. for ( c = 0; c < cl; c ++ ) {
  9645. color = colors[ c ];
  9646. offset = c * 3;
  9647. colorArray[ offset ] = color.r;
  9648. colorArray[ offset + 1 ] = color.g;
  9649. colorArray[ offset + 2 ] = color.b;
  9650. }
  9651. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  9652. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  9653. }
  9654. if ( customAttributes ) {
  9655. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9656. customAttribute = customAttributes[ i ];
  9657. if ( customAttribute.needsUpdate &&
  9658. ( customAttribute.boundTo === undefined ||
  9659. customAttribute.boundTo === "vertices" ) ) {
  9660. offset = 0;
  9661. cal = customAttribute.value.length;
  9662. if ( customAttribute.size === 1 ) {
  9663. for ( ca = 0; ca < cal; ca ++ ) {
  9664. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  9665. }
  9666. } else if ( customAttribute.size === 2 ) {
  9667. for ( ca = 0; ca < cal; ca ++ ) {
  9668. value = customAttribute.value[ ca ];
  9669. customAttribute.array[ offset ] = value.x;
  9670. customAttribute.array[ offset + 1 ] = value.y;
  9671. offset += 2;
  9672. }
  9673. } else if ( customAttribute.size === 3 ) {
  9674. if ( customAttribute.type === "c" ) {
  9675. for ( ca = 0; ca < cal; ca ++ ) {
  9676. value = customAttribute.value[ ca ];
  9677. customAttribute.array[ offset ] = value.r;
  9678. customAttribute.array[ offset + 1 ] = value.g;
  9679. customAttribute.array[ offset + 2 ] = value.b;
  9680. offset += 3;
  9681. }
  9682. } else {
  9683. for ( ca = 0; ca < cal; ca ++ ) {
  9684. value = customAttribute.value[ ca ];
  9685. customAttribute.array[ offset ] = value.x;
  9686. customAttribute.array[ offset + 1 ] = value.y;
  9687. customAttribute.array[ offset + 2 ] = value.z;
  9688. offset += 3;
  9689. }
  9690. }
  9691. } else if ( customAttribute.size === 4 ) {
  9692. for ( ca = 0; ca < cal; ca ++ ) {
  9693. value = customAttribute.value[ ca ];
  9694. customAttribute.array[ offset ] = value.x;
  9695. customAttribute.array[ offset + 1 ] = value.y;
  9696. customAttribute.array[ offset + 2 ] = value.z;
  9697. customAttribute.array[ offset + 3 ] = value.w;
  9698. offset += 4;
  9699. }
  9700. }
  9701. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  9702. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  9703. }
  9704. }
  9705. }
  9706. };
  9707. function setRibbonBuffers ( geometry, hint ) {
  9708. var v, c, vertex, offset, color,
  9709. vertices = geometry.vertices,
  9710. colors = geometry.colors,
  9711. vl = vertices.length,
  9712. cl = colors.length,
  9713. vertexArray = geometry.__vertexArray,
  9714. colorArray = geometry.__colorArray,
  9715. dirtyVertices = geometry.verticesNeedUpdate,
  9716. dirtyColors = geometry.colorsNeedUpdate;
  9717. if ( dirtyVertices ) {
  9718. for ( v = 0; v < vl; v ++ ) {
  9719. vertex = vertices[ v ];
  9720. offset = v * 3;
  9721. vertexArray[ offset ] = vertex.x;
  9722. vertexArray[ offset + 1 ] = vertex.y;
  9723. vertexArray[ offset + 2 ] = vertex.z;
  9724. }
  9725. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  9726. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9727. }
  9728. if ( dirtyColors ) {
  9729. for ( c = 0; c < cl; c ++ ) {
  9730. color = colors[ c ];
  9731. offset = c * 3;
  9732. colorArray[ offset ] = color.r;
  9733. colorArray[ offset + 1 ] = color.g;
  9734. colorArray[ offset + 2 ] = color.b;
  9735. }
  9736. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  9737. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  9738. }
  9739. };
  9740. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  9741. if ( ! geometryGroup.__inittedArrays ) {
  9742. // console.log( object );
  9743. return;
  9744. }
  9745. var normalType = bufferGuessNormalType( material ),
  9746. vertexColorType = bufferGuessVertexColorType( material ),
  9747. uvType = bufferGuessUVType( material ),
  9748. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  9749. var f, fl, fi, face,
  9750. vertexNormals, faceNormal, normal,
  9751. vertexColors, faceColor,
  9752. vertexTangents,
  9753. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  9754. c1, c2, c3, c4,
  9755. sw1, sw2, sw3, sw4,
  9756. si1, si2, si3, si4,
  9757. sa1, sa2, sa3, sa4,
  9758. sb1, sb2, sb3, sb4,
  9759. m, ml, i, il,
  9760. vn, uvi, uv2i,
  9761. vk, vkl, vka,
  9762. nka, chf, faceVertexNormals,
  9763. a,
  9764. vertexIndex = 0,
  9765. offset = 0,
  9766. offset_uv = 0,
  9767. offset_uv2 = 0,
  9768. offset_face = 0,
  9769. offset_normal = 0,
  9770. offset_tangent = 0,
  9771. offset_line = 0,
  9772. offset_color = 0,
  9773. offset_skin = 0,
  9774. offset_morphTarget = 0,
  9775. offset_custom = 0,
  9776. offset_customSrc = 0,
  9777. value,
  9778. vertexArray = geometryGroup.__vertexArray,
  9779. uvArray = geometryGroup.__uvArray,
  9780. uv2Array = geometryGroup.__uv2Array,
  9781. normalArray = geometryGroup.__normalArray,
  9782. tangentArray = geometryGroup.__tangentArray,
  9783. colorArray = geometryGroup.__colorArray,
  9784. skinIndexArray = geometryGroup.__skinIndexArray,
  9785. skinWeightArray = geometryGroup.__skinWeightArray,
  9786. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  9787. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  9788. customAttributes = geometryGroup.__webglCustomAttributesList,
  9789. customAttribute,
  9790. faceArray = geometryGroup.__faceArray,
  9791. lineArray = geometryGroup.__lineArray,
  9792. geometry = object.geometry, // this is shared for all chunks
  9793. dirtyVertices = geometry.verticesNeedUpdate,
  9794. dirtyElements = geometry.elementsNeedUpdate,
  9795. dirtyUvs = geometry.uvsNeedUpdate,
  9796. dirtyNormals = geometry.normalsNeedUpdate,
  9797. dirtyTangents = geometry.tangentsNeedUpdate,
  9798. dirtyColors = geometry.colorsNeedUpdate,
  9799. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  9800. vertices = geometry.vertices,
  9801. chunk_faces3 = geometryGroup.faces3,
  9802. chunk_faces4 = geometryGroup.faces4,
  9803. obj_faces = geometry.faces,
  9804. obj_uvs = geometry.faceVertexUvs[ 0 ],
  9805. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  9806. obj_colors = geometry.colors,
  9807. obj_skinIndices = geometry.skinIndices,
  9808. obj_skinWeights = geometry.skinWeights,
  9809. morphTargets = geometry.morphTargets,
  9810. morphNormals = geometry.morphNormals;
  9811. if ( dirtyVertices ) {
  9812. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  9813. face = obj_faces[ chunk_faces3[ f ] ];
  9814. v1 = vertices[ face.a ];
  9815. v2 = vertices[ face.b ];
  9816. v3 = vertices[ face.c ];
  9817. vertexArray[ offset ] = v1.x;
  9818. vertexArray[ offset + 1 ] = v1.y;
  9819. vertexArray[ offset + 2 ] = v1.z;
  9820. vertexArray[ offset + 3 ] = v2.x;
  9821. vertexArray[ offset + 4 ] = v2.y;
  9822. vertexArray[ offset + 5 ] = v2.z;
  9823. vertexArray[ offset + 6 ] = v3.x;
  9824. vertexArray[ offset + 7 ] = v3.y;
  9825. vertexArray[ offset + 8 ] = v3.z;
  9826. offset += 9;
  9827. }
  9828. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  9829. face = obj_faces[ chunk_faces4[ f ] ];
  9830. v1 = vertices[ face.a ];
  9831. v2 = vertices[ face.b ];
  9832. v3 = vertices[ face.c ];
  9833. v4 = vertices[ face.d ];
  9834. vertexArray[ offset ] = v1.x;
  9835. vertexArray[ offset + 1 ] = v1.y;
  9836. vertexArray[ offset + 2 ] = v1.z;
  9837. vertexArray[ offset + 3 ] = v2.x;
  9838. vertexArray[ offset + 4 ] = v2.y;
  9839. vertexArray[ offset + 5 ] = v2.z;
  9840. vertexArray[ offset + 6 ] = v3.x;
  9841. vertexArray[ offset + 7 ] = v3.y;
  9842. vertexArray[ offset + 8 ] = v3.z;
  9843. vertexArray[ offset + 9 ] = v4.x;
  9844. vertexArray[ offset + 10 ] = v4.y;
  9845. vertexArray[ offset + 11 ] = v4.z;
  9846. offset += 12;
  9847. }
  9848. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  9849. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9850. }
  9851. if ( dirtyMorphTargets ) {
  9852. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  9853. offset_morphTarget = 0;
  9854. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  9855. chf = chunk_faces3[ f ];
  9856. face = obj_faces[ chf ];
  9857. // morph positions
  9858. v1 = morphTargets[ vk ].vertices[ face.a ];
  9859. v2 = morphTargets[ vk ].vertices[ face.b ];
  9860. v3 = morphTargets[ vk ].vertices[ face.c ];
  9861. vka = morphTargetsArrays[ vk ];
  9862. vka[ offset_morphTarget ] = v1.x;
  9863. vka[ offset_morphTarget + 1 ] = v1.y;
  9864. vka[ offset_morphTarget + 2 ] = v1.z;
  9865. vka[ offset_morphTarget + 3 ] = v2.x;
  9866. vka[ offset_morphTarget + 4 ] = v2.y;
  9867. vka[ offset_morphTarget + 5 ] = v2.z;
  9868. vka[ offset_morphTarget + 6 ] = v3.x;
  9869. vka[ offset_morphTarget + 7 ] = v3.y;
  9870. vka[ offset_morphTarget + 8 ] = v3.z;
  9871. // morph normals
  9872. if ( material.morphNormals ) {
  9873. if ( needsSmoothNormals ) {
  9874. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  9875. n1 = faceVertexNormals.a;
  9876. n2 = faceVertexNormals.b;
  9877. n3 = faceVertexNormals.c;
  9878. } else {
  9879. n1 = morphNormals[ vk ].faceNormals[ chf ];
  9880. n2 = n1;
  9881. n3 = n1;
  9882. }
  9883. nka = morphNormalsArrays[ vk ];
  9884. nka[ offset_morphTarget ] = n1.x;
  9885. nka[ offset_morphTarget + 1 ] = n1.y;
  9886. nka[ offset_morphTarget + 2 ] = n1.z;
  9887. nka[ offset_morphTarget + 3 ] = n2.x;
  9888. nka[ offset_morphTarget + 4 ] = n2.y;
  9889. nka[ offset_morphTarget + 5 ] = n2.z;
  9890. nka[ offset_morphTarget + 6 ] = n3.x;
  9891. nka[ offset_morphTarget + 7 ] = n3.y;
  9892. nka[ offset_morphTarget + 8 ] = n3.z;
  9893. }
  9894. //
  9895. offset_morphTarget += 9;
  9896. }
  9897. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  9898. chf = chunk_faces4[ f ];
  9899. face = obj_faces[ chf ];
  9900. // morph positions
  9901. v1 = morphTargets[ vk ].vertices[ face.a ];
  9902. v2 = morphTargets[ vk ].vertices[ face.b ];
  9903. v3 = morphTargets[ vk ].vertices[ face.c ];
  9904. v4 = morphTargets[ vk ].vertices[ face.d ];
  9905. vka = morphTargetsArrays[ vk ];
  9906. vka[ offset_morphTarget ] = v1.x;
  9907. vka[ offset_morphTarget + 1 ] = v1.y;
  9908. vka[ offset_morphTarget + 2 ] = v1.z;
  9909. vka[ offset_morphTarget + 3 ] = v2.x;
  9910. vka[ offset_morphTarget + 4 ] = v2.y;
  9911. vka[ offset_morphTarget + 5 ] = v2.z;
  9912. vka[ offset_morphTarget + 6 ] = v3.x;
  9913. vka[ offset_morphTarget + 7 ] = v3.y;
  9914. vka[ offset_morphTarget + 8 ] = v3.z;
  9915. vka[ offset_morphTarget + 9 ] = v4.x;
  9916. vka[ offset_morphTarget + 10 ] = v4.y;
  9917. vka[ offset_morphTarget + 11 ] = v4.z;
  9918. // morph normals
  9919. if ( material.morphNormals ) {
  9920. if ( needsSmoothNormals ) {
  9921. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  9922. n1 = faceVertexNormals.a;
  9923. n2 = faceVertexNormals.b;
  9924. n3 = faceVertexNormals.c;
  9925. n4 = faceVertexNormals.d;
  9926. } else {
  9927. n1 = morphNormals[ vk ].faceNormals[ chf ];
  9928. n2 = n1;
  9929. n3 = n1;
  9930. n4 = n1;
  9931. }
  9932. nka = morphNormalsArrays[ vk ];
  9933. nka[ offset_morphTarget ] = n1.x;
  9934. nka[ offset_morphTarget + 1 ] = n1.y;
  9935. nka[ offset_morphTarget + 2 ] = n1.z;
  9936. nka[ offset_morphTarget + 3 ] = n2.x;
  9937. nka[ offset_morphTarget + 4 ] = n2.y;
  9938. nka[ offset_morphTarget + 5 ] = n2.z;
  9939. nka[ offset_morphTarget + 6 ] = n3.x;
  9940. nka[ offset_morphTarget + 7 ] = n3.y;
  9941. nka[ offset_morphTarget + 8 ] = n3.z;
  9942. nka[ offset_morphTarget + 9 ] = n4.x;
  9943. nka[ offset_morphTarget + 10 ] = n4.y;
  9944. nka[ offset_morphTarget + 11 ] = n4.z;
  9945. }
  9946. //
  9947. offset_morphTarget += 12;
  9948. }
  9949. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  9950. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  9951. if ( material.morphNormals ) {
  9952. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  9953. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  9954. }
  9955. }
  9956. }
  9957. if ( obj_skinWeights.length ) {
  9958. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  9959. face = obj_faces[ chunk_faces3[ f ] ];
  9960. // weights
  9961. sw1 = obj_skinWeights[ face.a ];
  9962. sw2 = obj_skinWeights[ face.b ];
  9963. sw3 = obj_skinWeights[ face.c ];
  9964. skinWeightArray[ offset_skin ] = sw1.x;
  9965. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  9966. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  9967. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  9968. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  9969. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  9970. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  9971. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  9972. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  9973. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  9974. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  9975. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  9976. // indices
  9977. si1 = obj_skinIndices[ face.a ];
  9978. si2 = obj_skinIndices[ face.b ];
  9979. si3 = obj_skinIndices[ face.c ];
  9980. skinIndexArray[ offset_skin ] = si1.x;
  9981. skinIndexArray[ offset_skin + 1 ] = si1.y;
  9982. skinIndexArray[ offset_skin + 2 ] = si1.z;
  9983. skinIndexArray[ offset_skin + 3 ] = si1.w;
  9984. skinIndexArray[ offset_skin + 4 ] = si2.x;
  9985. skinIndexArray[ offset_skin + 5 ] = si2.y;
  9986. skinIndexArray[ offset_skin + 6 ] = si2.z;
  9987. skinIndexArray[ offset_skin + 7 ] = si2.w;
  9988. skinIndexArray[ offset_skin + 8 ] = si3.x;
  9989. skinIndexArray[ offset_skin + 9 ] = si3.y;
  9990. skinIndexArray[ offset_skin + 10 ] = si3.z;
  9991. skinIndexArray[ offset_skin + 11 ] = si3.w;
  9992. offset_skin += 12;
  9993. }
  9994. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  9995. face = obj_faces[ chunk_faces4[ f ] ];
  9996. // weights
  9997. sw1 = obj_skinWeights[ face.a ];
  9998. sw2 = obj_skinWeights[ face.b ];
  9999. sw3 = obj_skinWeights[ face.c ];
  10000. sw4 = obj_skinWeights[ face.d ];
  10001. skinWeightArray[ offset_skin ] = sw1.x;
  10002. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10003. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10004. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10005. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10006. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10007. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10008. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10009. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10010. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10011. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10012. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10013. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  10014. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  10015. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  10016. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  10017. // indices
  10018. si1 = obj_skinIndices[ face.a ];
  10019. si2 = obj_skinIndices[ face.b ];
  10020. si3 = obj_skinIndices[ face.c ];
  10021. si4 = obj_skinIndices[ face.d ];
  10022. skinIndexArray[ offset_skin ] = si1.x;
  10023. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10024. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10025. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10026. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10027. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10028. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10029. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10030. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10031. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10032. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10033. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10034. skinIndexArray[ offset_skin + 12 ] = si4.x;
  10035. skinIndexArray[ offset_skin + 13 ] = si4.y;
  10036. skinIndexArray[ offset_skin + 14 ] = si4.z;
  10037. skinIndexArray[ offset_skin + 15 ] = si4.w;
  10038. offset_skin += 16;
  10039. }
  10040. if ( offset_skin > 0 ) {
  10041. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10042. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  10043. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10044. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  10045. }
  10046. }
  10047. if ( dirtyColors && vertexColorType ) {
  10048. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10049. face = obj_faces[ chunk_faces3[ f ] ];
  10050. vertexColors = face.vertexColors;
  10051. faceColor = face.color;
  10052. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  10053. c1 = vertexColors[ 0 ];
  10054. c2 = vertexColors[ 1 ];
  10055. c3 = vertexColors[ 2 ];
  10056. } else {
  10057. c1 = faceColor;
  10058. c2 = faceColor;
  10059. c3 = faceColor;
  10060. }
  10061. colorArray[ offset_color ] = c1.r;
  10062. colorArray[ offset_color + 1 ] = c1.g;
  10063. colorArray[ offset_color + 2 ] = c1.b;
  10064. colorArray[ offset_color + 3 ] = c2.r;
  10065. colorArray[ offset_color + 4 ] = c2.g;
  10066. colorArray[ offset_color + 5 ] = c2.b;
  10067. colorArray[ offset_color + 6 ] = c3.r;
  10068. colorArray[ offset_color + 7 ] = c3.g;
  10069. colorArray[ offset_color + 8 ] = c3.b;
  10070. offset_color += 9;
  10071. }
  10072. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10073. face = obj_faces[ chunk_faces4[ f ] ];
  10074. vertexColors = face.vertexColors;
  10075. faceColor = face.color;
  10076. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  10077. c1 = vertexColors[ 0 ];
  10078. c2 = vertexColors[ 1 ];
  10079. c3 = vertexColors[ 2 ];
  10080. c4 = vertexColors[ 3 ];
  10081. } else {
  10082. c1 = faceColor;
  10083. c2 = faceColor;
  10084. c3 = faceColor;
  10085. c4 = faceColor;
  10086. }
  10087. colorArray[ offset_color ] = c1.r;
  10088. colorArray[ offset_color + 1 ] = c1.g;
  10089. colorArray[ offset_color + 2 ] = c1.b;
  10090. colorArray[ offset_color + 3 ] = c2.r;
  10091. colorArray[ offset_color + 4 ] = c2.g;
  10092. colorArray[ offset_color + 5 ] = c2.b;
  10093. colorArray[ offset_color + 6 ] = c3.r;
  10094. colorArray[ offset_color + 7 ] = c3.g;
  10095. colorArray[ offset_color + 8 ] = c3.b;
  10096. colorArray[ offset_color + 9 ] = c4.r;
  10097. colorArray[ offset_color + 10 ] = c4.g;
  10098. colorArray[ offset_color + 11 ] = c4.b;
  10099. offset_color += 12;
  10100. }
  10101. if ( offset_color > 0 ) {
  10102. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10103. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10104. }
  10105. }
  10106. if ( dirtyTangents && geometry.hasTangents ) {
  10107. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10108. face = obj_faces[ chunk_faces3[ f ] ];
  10109. vertexTangents = face.vertexTangents;
  10110. t1 = vertexTangents[ 0 ];
  10111. t2 = vertexTangents[ 1 ];
  10112. t3 = vertexTangents[ 2 ];
  10113. tangentArray[ offset_tangent ] = t1.x;
  10114. tangentArray[ offset_tangent + 1 ] = t1.y;
  10115. tangentArray[ offset_tangent + 2 ] = t1.z;
  10116. tangentArray[ offset_tangent + 3 ] = t1.w;
  10117. tangentArray[ offset_tangent + 4 ] = t2.x;
  10118. tangentArray[ offset_tangent + 5 ] = t2.y;
  10119. tangentArray[ offset_tangent + 6 ] = t2.z;
  10120. tangentArray[ offset_tangent + 7 ] = t2.w;
  10121. tangentArray[ offset_tangent + 8 ] = t3.x;
  10122. tangentArray[ offset_tangent + 9 ] = t3.y;
  10123. tangentArray[ offset_tangent + 10 ] = t3.z;
  10124. tangentArray[ offset_tangent + 11 ] = t3.w;
  10125. offset_tangent += 12;
  10126. }
  10127. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10128. face = obj_faces[ chunk_faces4[ f ] ];
  10129. vertexTangents = face.vertexTangents;
  10130. t1 = vertexTangents[ 0 ];
  10131. t2 = vertexTangents[ 1 ];
  10132. t3 = vertexTangents[ 2 ];
  10133. t4 = vertexTangents[ 3 ];
  10134. tangentArray[ offset_tangent ] = t1.x;
  10135. tangentArray[ offset_tangent + 1 ] = t1.y;
  10136. tangentArray[ offset_tangent + 2 ] = t1.z;
  10137. tangentArray[ offset_tangent + 3 ] = t1.w;
  10138. tangentArray[ offset_tangent + 4 ] = t2.x;
  10139. tangentArray[ offset_tangent + 5 ] = t2.y;
  10140. tangentArray[ offset_tangent + 6 ] = t2.z;
  10141. tangentArray[ offset_tangent + 7 ] = t2.w;
  10142. tangentArray[ offset_tangent + 8 ] = t3.x;
  10143. tangentArray[ offset_tangent + 9 ] = t3.y;
  10144. tangentArray[ offset_tangent + 10 ] = t3.z;
  10145. tangentArray[ offset_tangent + 11 ] = t3.w;
  10146. tangentArray[ offset_tangent + 12 ] = t4.x;
  10147. tangentArray[ offset_tangent + 13 ] = t4.y;
  10148. tangentArray[ offset_tangent + 14 ] = t4.z;
  10149. tangentArray[ offset_tangent + 15 ] = t4.w;
  10150. offset_tangent += 16;
  10151. }
  10152. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10153. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  10154. }
  10155. if ( dirtyNormals && normalType ) {
  10156. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10157. face = obj_faces[ chunk_faces3[ f ] ];
  10158. vertexNormals = face.vertexNormals;
  10159. faceNormal = face.normal;
  10160. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  10161. for ( i = 0; i < 3; i ++ ) {
  10162. vn = vertexNormals[ i ];
  10163. normalArray[ offset_normal ] = vn.x;
  10164. normalArray[ offset_normal + 1 ] = vn.y;
  10165. normalArray[ offset_normal + 2 ] = vn.z;
  10166. offset_normal += 3;
  10167. }
  10168. } else {
  10169. for ( i = 0; i < 3; i ++ ) {
  10170. normalArray[ offset_normal ] = faceNormal.x;
  10171. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10172. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10173. offset_normal += 3;
  10174. }
  10175. }
  10176. }
  10177. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10178. face = obj_faces[ chunk_faces4[ f ] ];
  10179. vertexNormals = face.vertexNormals;
  10180. faceNormal = face.normal;
  10181. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  10182. for ( i = 0; i < 4; i ++ ) {
  10183. vn = vertexNormals[ i ];
  10184. normalArray[ offset_normal ] = vn.x;
  10185. normalArray[ offset_normal + 1 ] = vn.y;
  10186. normalArray[ offset_normal + 2 ] = vn.z;
  10187. offset_normal += 3;
  10188. }
  10189. } else {
  10190. for ( i = 0; i < 4; i ++ ) {
  10191. normalArray[ offset_normal ] = faceNormal.x;
  10192. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10193. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10194. offset_normal += 3;
  10195. }
  10196. }
  10197. }
  10198. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10199. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10200. }
  10201. if ( dirtyUvs && obj_uvs && uvType ) {
  10202. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10203. fi = chunk_faces3[ f ];
  10204. face = obj_faces[ fi ];
  10205. uv = obj_uvs[ fi ];
  10206. if ( uv === undefined ) continue;
  10207. for ( i = 0; i < 3; i ++ ) {
  10208. uvi = uv[ i ];
  10209. uvArray[ offset_uv ] = uvi.u;
  10210. uvArray[ offset_uv + 1 ] = uvi.v;
  10211. offset_uv += 2;
  10212. }
  10213. }
  10214. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10215. fi = chunk_faces4[ f ];
  10216. face = obj_faces[ fi ];
  10217. uv = obj_uvs[ fi ];
  10218. if ( uv === undefined ) continue;
  10219. for ( i = 0; i < 4; i ++ ) {
  10220. uvi = uv[ i ];
  10221. uvArray[ offset_uv ] = uvi.u;
  10222. uvArray[ offset_uv + 1 ] = uvi.v;
  10223. offset_uv += 2;
  10224. }
  10225. }
  10226. if ( offset_uv > 0 ) {
  10227. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10228. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  10229. }
  10230. }
  10231. if ( dirtyUvs && obj_uvs2 && uvType ) {
  10232. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10233. fi = chunk_faces3[ f ];
  10234. face = obj_faces[ fi ];
  10235. uv2 = obj_uvs2[ fi ];
  10236. if ( uv2 === undefined ) continue;
  10237. for ( i = 0; i < 3; i ++ ) {
  10238. uv2i = uv2[ i ];
  10239. uv2Array[ offset_uv2 ] = uv2i.u;
  10240. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10241. offset_uv2 += 2;
  10242. }
  10243. }
  10244. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10245. fi = chunk_faces4[ f ];
  10246. face = obj_faces[ fi ];
  10247. uv2 = obj_uvs2[ fi ];
  10248. if ( uv2 === undefined ) continue;
  10249. for ( i = 0; i < 4; i ++ ) {
  10250. uv2i = uv2[ i ];
  10251. uv2Array[ offset_uv2 ] = uv2i.u;
  10252. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10253. offset_uv2 += 2;
  10254. }
  10255. }
  10256. if ( offset_uv2 > 0 ) {
  10257. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10258. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  10259. }
  10260. }
  10261. if ( dirtyElements ) {
  10262. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10263. face = obj_faces[ chunk_faces3[ f ] ];
  10264. faceArray[ offset_face ] = vertexIndex;
  10265. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10266. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  10267. offset_face += 3;
  10268. lineArray[ offset_line ] = vertexIndex;
  10269. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10270. lineArray[ offset_line + 2 ] = vertexIndex;
  10271. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  10272. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10273. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10274. offset_line += 6;
  10275. vertexIndex += 3;
  10276. }
  10277. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10278. face = obj_faces[ chunk_faces4[ f ] ];
  10279. faceArray[ offset_face ] = vertexIndex;
  10280. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10281. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  10282. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  10283. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  10284. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  10285. offset_face += 6;
  10286. lineArray[ offset_line ] = vertexIndex;
  10287. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10288. lineArray[ offset_line + 2 ] = vertexIndex;
  10289. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  10290. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10291. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10292. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  10293. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  10294. offset_line += 8;
  10295. vertexIndex += 4;
  10296. }
  10297. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10298. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  10299. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10300. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  10301. }
  10302. if ( customAttributes ) {
  10303. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10304. customAttribute = customAttributes[ i ];
  10305. if ( ! customAttribute.__original.needsUpdate ) continue;
  10306. offset_custom = 0;
  10307. offset_customSrc = 0;
  10308. if ( customAttribute.size === 1 ) {
  10309. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10310. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10311. face = obj_faces[ chunk_faces3[ f ] ];
  10312. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10313. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10314. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10315. offset_custom += 3;
  10316. }
  10317. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10318. face = obj_faces[ chunk_faces4[ f ] ];
  10319. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10320. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10321. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10322. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  10323. offset_custom += 4;
  10324. }
  10325. } else if ( customAttribute.boundTo === "faces" ) {
  10326. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10327. value = customAttribute.value[ chunk_faces3[ f ] ];
  10328. customAttribute.array[ offset_custom ] = value;
  10329. customAttribute.array[ offset_custom + 1 ] = value;
  10330. customAttribute.array[ offset_custom + 2 ] = value;
  10331. offset_custom += 3;
  10332. }
  10333. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10334. value = customAttribute.value[ chunk_faces4[ f ] ];
  10335. customAttribute.array[ offset_custom ] = value;
  10336. customAttribute.array[ offset_custom + 1 ] = value;
  10337. customAttribute.array[ offset_custom + 2 ] = value;
  10338. customAttribute.array[ offset_custom + 3 ] = value;
  10339. offset_custom += 4;
  10340. }
  10341. }
  10342. } else if ( customAttribute.size === 2 ) {
  10343. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10344. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10345. face = obj_faces[ chunk_faces3[ f ] ];
  10346. v1 = customAttribute.value[ face.a ];
  10347. v2 = customAttribute.value[ face.b ];
  10348. v3 = customAttribute.value[ face.c ];
  10349. customAttribute.array[ offset_custom ] = v1.x;
  10350. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10351. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10352. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10353. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10354. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10355. offset_custom += 6;
  10356. }
  10357. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10358. face = obj_faces[ chunk_faces4[ f ] ];
  10359. v1 = customAttribute.value[ face.a ];
  10360. v2 = customAttribute.value[ face.b ];
  10361. v3 = customAttribute.value[ face.c ];
  10362. v4 = customAttribute.value[ face.d ];
  10363. customAttribute.array[ offset_custom ] = v1.x;
  10364. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10365. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10366. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10367. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10368. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10369. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10370. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10371. offset_custom += 8;
  10372. }
  10373. } else if ( customAttribute.boundTo === "faces" ) {
  10374. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10375. value = customAttribute.value[ chunk_faces3[ f ] ];
  10376. v1 = value;
  10377. v2 = value;
  10378. v3 = value;
  10379. customAttribute.array[ offset_custom ] = v1.x;
  10380. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10381. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10382. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10383. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10384. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10385. offset_custom += 6;
  10386. }
  10387. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10388. value = customAttribute.value[ chunk_faces4[ f ] ];
  10389. v1 = value;
  10390. v2 = value;
  10391. v3 = value;
  10392. v4 = value;
  10393. customAttribute.array[ offset_custom ] = v1.x;
  10394. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10395. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10396. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10397. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10398. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10399. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10400. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10401. offset_custom += 8;
  10402. }
  10403. }
  10404. } else if ( customAttribute.size === 3 ) {
  10405. var pp;
  10406. if ( customAttribute.type === "c" ) {
  10407. pp = [ "r", "g", "b" ];
  10408. } else {
  10409. pp = [ "x", "y", "z" ];
  10410. }
  10411. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10412. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10413. face = obj_faces[ chunk_faces3[ f ] ];
  10414. v1 = customAttribute.value[ face.a ];
  10415. v2 = customAttribute.value[ face.b ];
  10416. v3 = customAttribute.value[ face.c ];
  10417. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10418. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10419. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10420. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10421. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10422. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10423. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10424. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10425. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10426. offset_custom += 9;
  10427. }
  10428. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10429. face = obj_faces[ chunk_faces4[ f ] ];
  10430. v1 = customAttribute.value[ face.a ];
  10431. v2 = customAttribute.value[ face.b ];
  10432. v3 = customAttribute.value[ face.c ];
  10433. v4 = customAttribute.value[ face.d ];
  10434. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10435. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10436. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10437. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10438. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10439. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10440. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10441. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10442. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10443. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10444. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10445. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10446. offset_custom += 12;
  10447. }
  10448. } else if ( customAttribute.boundTo === "faces" ) {
  10449. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10450. value = customAttribute.value[ chunk_faces3[ f ] ];
  10451. v1 = value;
  10452. v2 = value;
  10453. v3 = value;
  10454. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10455. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10456. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10457. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10458. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10459. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10460. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10461. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10462. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10463. offset_custom += 9;
  10464. }
  10465. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10466. value = customAttribute.value[ chunk_faces4[ f ] ];
  10467. v1 = value;
  10468. v2 = value;
  10469. v3 = value;
  10470. v4 = value;
  10471. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10472. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10473. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10474. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10475. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10476. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10477. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10478. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10479. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10480. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10481. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10482. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10483. offset_custom += 12;
  10484. }
  10485. } else if ( customAttribute.boundTo === "faceVertices" ) {
  10486. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10487. value = customAttribute.value[ chunk_faces3[ f ] ];
  10488. v1 = value[ 0 ];
  10489. v2 = value[ 1 ];
  10490. v3 = value[ 2 ];
  10491. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10492. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10493. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10494. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10495. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10496. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10497. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10498. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10499. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10500. offset_custom += 9;
  10501. }
  10502. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10503. value = customAttribute.value[ chunk_faces4[ f ] ];
  10504. v1 = value[ 0 ];
  10505. v2 = value[ 1 ];
  10506. v3 = value[ 2 ];
  10507. v4 = value[ 3 ];
  10508. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10509. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10510. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10511. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10512. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10513. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10514. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10515. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10516. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10517. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10518. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10519. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10520. offset_custom += 12;
  10521. }
  10522. }
  10523. } else if ( customAttribute.size === 4 ) {
  10524. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10525. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10526. face = obj_faces[ chunk_faces3[ f ] ];
  10527. v1 = customAttribute.value[ face.a ];
  10528. v2 = customAttribute.value[ face.b ];
  10529. v3 = customAttribute.value[ face.c ];
  10530. customAttribute.array[ offset_custom ] = v1.x;
  10531. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10532. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10533. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10534. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10535. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10536. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10537. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10538. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10539. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10540. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10541. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10542. offset_custom += 12;
  10543. }
  10544. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10545. face = obj_faces[ chunk_faces4[ f ] ];
  10546. v1 = customAttribute.value[ face.a ];
  10547. v2 = customAttribute.value[ face.b ];
  10548. v3 = customAttribute.value[ face.c ];
  10549. v4 = customAttribute.value[ face.d ];
  10550. customAttribute.array[ offset_custom ] = v1.x;
  10551. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10552. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10553. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10554. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10555. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10556. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10557. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10558. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10559. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10560. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10561. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10562. customAttribute.array[ offset_custom + 12 ] = v4.x;
  10563. customAttribute.array[ offset_custom + 13 ] = v4.y;
  10564. customAttribute.array[ offset_custom + 14 ] = v4.z;
  10565. customAttribute.array[ offset_custom + 15 ] = v4.w;
  10566. offset_custom += 16;
  10567. }
  10568. } else if ( customAttribute.boundTo === "faces" ) {
  10569. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10570. value = customAttribute.value[ chunk_faces3[ f ] ];
  10571. v1 = value;
  10572. v2 = value;
  10573. v3 = value;
  10574. customAttribute.array[ offset_custom ] = v1.x;
  10575. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10576. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10577. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10578. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10579. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10580. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10581. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10582. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10583. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10584. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10585. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10586. offset_custom += 12;
  10587. }
  10588. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10589. value = customAttribute.value[ chunk_faces4[ f ] ];
  10590. v1 = value;
  10591. v2 = value;
  10592. v3 = value;
  10593. v4 = value;
  10594. customAttribute.array[ offset_custom ] = v1.x;
  10595. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10596. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10597. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10598. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10599. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10600. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10601. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10602. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10603. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10604. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10605. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10606. customAttribute.array[ offset_custom + 12 ] = v4.x;
  10607. customAttribute.array[ offset_custom + 13 ] = v4.y;
  10608. customAttribute.array[ offset_custom + 14 ] = v4.z;
  10609. customAttribute.array[ offset_custom + 15 ] = v4.w;
  10610. offset_custom += 16;
  10611. }
  10612. } else if ( customAttribute.boundTo === "faceVertices" ) {
  10613. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10614. value = customAttribute.value[ chunk_faces3[ f ] ];
  10615. v1 = value[ 0 ];
  10616. v2 = value[ 1 ];
  10617. v3 = value[ 2 ];
  10618. customAttribute.array[ offset_custom ] = v1.x;
  10619. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10620. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10621. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10622. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10623. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10624. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10625. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10626. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10627. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10628. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10629. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10630. offset_custom += 12;
  10631. }
  10632. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10633. value = customAttribute.value[ chunk_faces4[ f ] ];
  10634. v1 = value[ 0 ];
  10635. v2 = value[ 1 ];
  10636. v3 = value[ 2 ];
  10637. v4 = value[ 3 ];
  10638. customAttribute.array[ offset_custom ] = v1.x;
  10639. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10640. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10641. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10642. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10643. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10644. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10645. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10646. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10647. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10648. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10649. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10650. customAttribute.array[ offset_custom + 12 ] = v4.x;
  10651. customAttribute.array[ offset_custom + 13 ] = v4.y;
  10652. customAttribute.array[ offset_custom + 14 ] = v4.z;
  10653. customAttribute.array[ offset_custom + 15 ] = v4.w;
  10654. offset_custom += 16;
  10655. }
  10656. }
  10657. }
  10658. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10659. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10660. }
  10661. }
  10662. if ( dispose ) {
  10663. delete geometryGroup.__inittedArrays;
  10664. delete geometryGroup.__colorArray;
  10665. delete geometryGroup.__normalArray;
  10666. delete geometryGroup.__tangentArray;
  10667. delete geometryGroup.__uvArray;
  10668. delete geometryGroup.__uv2Array;
  10669. delete geometryGroup.__faceArray;
  10670. delete geometryGroup.__vertexArray;
  10671. delete geometryGroup.__lineArray;
  10672. delete geometryGroup.__skinIndexArray;
  10673. delete geometryGroup.__skinWeightArray;
  10674. }
  10675. };
  10676. function setDirectBuffers ( geometry, hint, dispose ) {
  10677. var attributes = geometry.attributes;
  10678. var index = attributes[ "index" ];
  10679. var position = attributes[ "position" ];
  10680. var normal = attributes[ "normal" ];
  10681. var uv = attributes[ "uv" ];
  10682. var color = attributes[ "color" ];
  10683. var tangent = attributes[ "tangent" ];
  10684. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  10685. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  10686. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  10687. }
  10688. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  10689. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  10690. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  10691. }
  10692. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  10693. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  10694. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  10695. }
  10696. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  10697. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  10698. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  10699. }
  10700. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  10701. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  10702. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  10703. }
  10704. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  10705. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  10706. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  10707. }
  10708. if ( dispose ) {
  10709. for ( var i in geometry.attributes ) {
  10710. delete geometry.attributes[ i ].array;
  10711. }
  10712. }
  10713. };
  10714. // Buffer rendering
  10715. this.renderBufferImmediate = function ( object, program, material ) {
  10716. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  10717. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  10718. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  10719. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  10720. if ( object.hasPositions ) {
  10721. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  10722. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  10723. _gl.enableVertexAttribArray( program.attributes.position );
  10724. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  10725. }
  10726. if ( object.hasNormals ) {
  10727. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  10728. if ( material.shading === THREE.FlatShading ) {
  10729. var nx, ny, nz,
  10730. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  10731. normalArray,
  10732. i, il = object.count * 3;
  10733. for( i = 0; i < il; i += 9 ) {
  10734. normalArray = object.normalArray;
  10735. nax = normalArray[ i ];
  10736. nay = normalArray[ i + 1 ];
  10737. naz = normalArray[ i + 2 ];
  10738. nbx = normalArray[ i + 3 ];
  10739. nby = normalArray[ i + 4 ];
  10740. nbz = normalArray[ i + 5 ];
  10741. ncx = normalArray[ i + 6 ];
  10742. ncy = normalArray[ i + 7 ];
  10743. ncz = normalArray[ i + 8 ];
  10744. nx = ( nax + nbx + ncx ) / 3;
  10745. ny = ( nay + nby + ncy ) / 3;
  10746. nz = ( naz + nbz + ncz ) / 3;
  10747. normalArray[ i ] = nx;
  10748. normalArray[ i + 1 ] = ny;
  10749. normalArray[ i + 2 ] = nz;
  10750. normalArray[ i + 3 ] = nx;
  10751. normalArray[ i + 4 ] = ny;
  10752. normalArray[ i + 5 ] = nz;
  10753. normalArray[ i + 6 ] = nx;
  10754. normalArray[ i + 7 ] = ny;
  10755. normalArray[ i + 8 ] = nz;
  10756. }
  10757. }
  10758. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  10759. _gl.enableVertexAttribArray( program.attributes.normal );
  10760. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  10761. }
  10762. if ( object.hasUvs && material.map ) {
  10763. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  10764. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  10765. _gl.enableVertexAttribArray( program.attributes.uv );
  10766. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  10767. }
  10768. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  10769. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  10770. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  10771. _gl.enableVertexAttribArray( program.attributes.color );
  10772. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  10773. }
  10774. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  10775. object.count = 0;
  10776. };
  10777. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  10778. if ( material.visible === false ) return;
  10779. var program, attributes, linewidth, primitives, a, attribute;
  10780. program = setProgram( camera, lights, fog, material, object );
  10781. attributes = program.attributes;
  10782. var updateBuffers = false,
  10783. wireframeBit = material.wireframe ? 1 : 0,
  10784. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  10785. if ( geometryHash !== _currentGeometryGroupHash ) {
  10786. _currentGeometryGroupHash = geometryHash;
  10787. updateBuffers = true;
  10788. }
  10789. // render mesh
  10790. if ( object instanceof THREE.Mesh ) {
  10791. var offsets = geometry.offsets;
  10792. // if there is more than 1 chunk
  10793. // must set attribute pointers to use new offsets for each chunk
  10794. // even if geometry and materials didn't change
  10795. if ( offsets.length > 1 ) updateBuffers = true;
  10796. for ( var i = 0, il = offsets.length; i < il; ++ i ) {
  10797. var startIndex = offsets[ i ].index;
  10798. if ( updateBuffers ) {
  10799. // vertices
  10800. var position = geometry.attributes[ "position" ];
  10801. var positionSize = position.itemSize;
  10802. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  10803. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  10804. // normals
  10805. var normal = geometry.attributes[ "normal" ];
  10806. if ( attributes.normal >= 0 && normal ) {
  10807. var normalSize = normal.itemSize;
  10808. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  10809. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  10810. }
  10811. // uvs
  10812. var uv = geometry.attributes[ "uv" ];
  10813. if ( attributes.uv >= 0 && uv ) {
  10814. if ( uv.buffer ) {
  10815. var uvSize = uv.itemSize;
  10816. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  10817. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  10818. _gl.enableVertexAttribArray( attributes.uv );
  10819. } else {
  10820. _gl.disableVertexAttribArray( attributes.uv );
  10821. }
  10822. }
  10823. // colors
  10824. var color = geometry.attributes[ "color" ];
  10825. if ( attributes.color >= 0 && color ) {
  10826. var colorSize = color.itemSize;
  10827. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  10828. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  10829. }
  10830. // tangents
  10831. var tangent = geometry.attributes[ "tangent" ];
  10832. if ( attributes.tangent >= 0 && tangent ) {
  10833. var tangentSize = tangent.itemSize;
  10834. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  10835. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  10836. }
  10837. // indices
  10838. var index = geometry.attributes[ "index" ];
  10839. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  10840. }
  10841. // render indexed triangles
  10842. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  10843. _this.info.render.calls ++;
  10844. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  10845. _this.info.render.faces += offsets[ i ].count / 3;
  10846. }
  10847. }
  10848. };
  10849. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  10850. if ( material.visible === false ) return;
  10851. var program, attributes, linewidth, primitives, a, attribute, i, il;
  10852. program = setProgram( camera, lights, fog, material, object );
  10853. attributes = program.attributes;
  10854. var updateBuffers = false,
  10855. wireframeBit = material.wireframe ? 1 : 0,
  10856. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  10857. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  10858. _currentGeometryGroupHash = geometryGroupHash;
  10859. updateBuffers = true;
  10860. }
  10861. // vertices
  10862. if ( !material.morphTargets && attributes.position >= 0 ) {
  10863. if ( updateBuffers ) {
  10864. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10865. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  10866. }
  10867. } else {
  10868. if ( object.morphTargetBase ) {
  10869. setupMorphTargets( material, geometryGroup, object );
  10870. }
  10871. }
  10872. if ( updateBuffers ) {
  10873. // custom attributes
  10874. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  10875. if ( geometryGroup.__webglCustomAttributesList ) {
  10876. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  10877. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  10878. if( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  10879. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  10880. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  10881. }
  10882. }
  10883. }
  10884. // colors
  10885. if ( attributes.color >= 0 ) {
  10886. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10887. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  10888. }
  10889. // normals
  10890. if ( attributes.normal >= 0 ) {
  10891. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10892. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  10893. }
  10894. // tangents
  10895. if ( attributes.tangent >= 0 ) {
  10896. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10897. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  10898. }
  10899. // uvs
  10900. if ( attributes.uv >= 0 ) {
  10901. if ( geometryGroup.__webglUVBuffer ) {
  10902. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10903. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  10904. _gl.enableVertexAttribArray( attributes.uv );
  10905. } else {
  10906. _gl.disableVertexAttribArray( attributes.uv );
  10907. }
  10908. }
  10909. if ( attributes.uv2 >= 0 ) {
  10910. if ( geometryGroup.__webglUV2Buffer ) {
  10911. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10912. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  10913. _gl.enableVertexAttribArray( attributes.uv2 );
  10914. } else {
  10915. _gl.disableVertexAttribArray( attributes.uv2 );
  10916. }
  10917. }
  10918. if ( material.skinning &&
  10919. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  10920. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10921. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  10922. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10923. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  10924. }
  10925. }
  10926. // render mesh
  10927. if ( object instanceof THREE.Mesh ) {
  10928. // wireframe
  10929. if ( material.wireframe ) {
  10930. setLineWidth( material.wireframeLinewidth );
  10931. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10932. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  10933. // triangles
  10934. } else {
  10935. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10936. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  10937. }
  10938. _this.info.render.calls ++;
  10939. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  10940. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  10941. // render lines
  10942. } else if ( object instanceof THREE.Line ) {
  10943. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  10944. setLineWidth( material.linewidth );
  10945. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  10946. _this.info.render.calls ++;
  10947. // render particles
  10948. } else if ( object instanceof THREE.ParticleSystem ) {
  10949. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  10950. _this.info.render.calls ++;
  10951. _this.info.render.points += geometryGroup.__webglParticleCount;
  10952. // render ribbon
  10953. } else if ( object instanceof THREE.Ribbon ) {
  10954. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  10955. _this.info.render.calls ++;
  10956. }
  10957. };
  10958. function setupMorphTargets ( material, geometryGroup, object ) {
  10959. // set base
  10960. var attributes = material.program.attributes;
  10961. if ( object.morphTargetBase !== -1 ) {
  10962. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  10963. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  10964. } else if ( attributes.position >= 0 ) {
  10965. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10966. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  10967. }
  10968. if ( object.morphTargetForcedOrder.length ) {
  10969. // set forced order
  10970. var m = 0;
  10971. var order = object.morphTargetForcedOrder;
  10972. var influences = object.morphTargetInfluences;
  10973. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  10974. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  10975. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  10976. if ( material.morphNormals ) {
  10977. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  10978. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  10979. }
  10980. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  10981. m ++;
  10982. }
  10983. } else {
  10984. // find the most influencing
  10985. var influence, activeInfluenceIndices = [];
  10986. var influences = object.morphTargetInfluences;
  10987. var i, il = influences.length;
  10988. for ( i = 0; i < il; i ++ ) {
  10989. influence = influences[ i ];
  10990. if ( influence > 0 ) {
  10991. activeInfluenceIndices.push( [ i, influence ] );
  10992. }
  10993. }
  10994. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  10995. activeInfluenceIndices.sort( numericalSort );
  10996. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  10997. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  10998. activeInfluenceIndices.sort( numericalSort );
  10999. } else if ( activeInfluenceIndices.length === 0 ) {
  11000. activeInfluenceIndices.push( [ 0, 0 ] );
  11001. };
  11002. var influenceIndex, m = 0;
  11003. while ( m < material.numSupportedMorphTargets ) {
  11004. if ( activeInfluenceIndices[ m ] ) {
  11005. influenceIndex = activeInfluenceIndices[ m ][ 0 ];
  11006. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  11007. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11008. if ( material.morphNormals ) {
  11009. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  11010. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11011. }
  11012. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11013. } else {
  11014. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11015. if ( material.morphNormals ) {
  11016. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11017. }
  11018. object.__webglMorphTargetInfluences[ m ] = 0;
  11019. }
  11020. m ++;
  11021. }
  11022. }
  11023. // load updated influences uniform
  11024. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11025. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11026. }
  11027. };
  11028. // Sorting
  11029. function painterSort ( a, b ) {
  11030. return b.z - a.z;
  11031. };
  11032. function numericalSort ( a, b ) {
  11033. return b[ 1 ] - a[ 1 ];
  11034. };
  11035. // Rendering
  11036. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11037. if ( camera instanceof THREE.Camera === false ) {
  11038. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11039. return;
  11040. }
  11041. var i, il,
  11042. webglObject, object,
  11043. renderList,
  11044. lights = scene.__lights,
  11045. fog = scene.fog;
  11046. // reset caching for this frame
  11047. _currentMaterialId = -1;
  11048. _lightsNeedUpdate = true;
  11049. // update scene graph
  11050. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11051. // update camera matrices and frustum
  11052. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11053. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  11054. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  11055. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11056. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  11057. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  11058. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11059. _frustum.setFromMatrix( _projScreenMatrix );
  11060. // update WebGL objects
  11061. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11062. // custom render plugins (pre pass)
  11063. renderPlugins( this.renderPluginsPre, scene, camera );
  11064. //
  11065. _this.info.render.calls = 0;
  11066. _this.info.render.vertices = 0;
  11067. _this.info.render.faces = 0;
  11068. _this.info.render.points = 0;
  11069. this.setRenderTarget( renderTarget );
  11070. if ( this.autoClear || forceClear ) {
  11071. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11072. }
  11073. // set matrices for regular objects (frustum culled)
  11074. renderList = scene.__webglObjects;
  11075. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11076. webglObject = renderList[ i ];
  11077. object = webglObject.object;
  11078. webglObject.render = false;
  11079. if ( object.visible ) {
  11080. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11081. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11082. setupMatrices( object, camera );
  11083. unrollBufferMaterial( webglObject );
  11084. webglObject.render = true;
  11085. if ( this.sortObjects ) {
  11086. if ( object.renderDepth ) {
  11087. webglObject.z = object.renderDepth;
  11088. } else {
  11089. _vector3.copy( object.matrixWorld.getPosition() );
  11090. _projScreenMatrix.multiplyVector3( _vector3 );
  11091. webglObject.z = _vector3.z;
  11092. }
  11093. }
  11094. }
  11095. }
  11096. }
  11097. if ( this.sortObjects ) {
  11098. renderList.sort( painterSort );
  11099. }
  11100. // set matrices for immediate objects
  11101. renderList = scene.__webglObjectsImmediate;
  11102. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11103. webglObject = renderList[ i ];
  11104. object = webglObject.object;
  11105. if ( object.visible ) {
  11106. /*
  11107. if ( object.matrixAutoUpdate ) {
  11108. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11109. }
  11110. */
  11111. setupMatrices( object, camera );
  11112. unrollImmediateBufferMaterial( webglObject );
  11113. }
  11114. }
  11115. if ( scene.overrideMaterial ) {
  11116. var material = scene.overrideMaterial;
  11117. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11118. this.setDepthTest( material.depthTest );
  11119. this.setDepthWrite( material.depthWrite );
  11120. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11121. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11122. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11123. } else {
  11124. // opaque pass (front-to-back order)
  11125. this.setBlending( THREE.NormalBlending );
  11126. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  11127. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  11128. // transparent pass (back-to-front order)
  11129. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  11130. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  11131. }
  11132. // custom render plugins (post pass)
  11133. renderPlugins( this.renderPluginsPost, scene, camera );
  11134. // Generate mipmap if we're using any kind of mipmap filtering
  11135. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11136. updateRenderTargetMipmap( renderTarget );
  11137. }
  11138. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11139. this.setDepthTest( true );
  11140. this.setDepthWrite( true );
  11141. // _gl.finish();
  11142. };
  11143. function renderPlugins( plugins, scene, camera ) {
  11144. if ( ! plugins.length ) return;
  11145. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11146. // reset state for plugin (to start from clean slate)
  11147. _currentProgram = null;
  11148. _currentCamera = null;
  11149. _oldBlending = -1;
  11150. _oldDepthTest = -1;
  11151. _oldDepthWrite = -1;
  11152. _oldDoubleSided = -1;
  11153. _oldFlipSided = -1;
  11154. _currentGeometryGroupHash = -1;
  11155. _currentMaterialId = -1;
  11156. _lightsNeedUpdate = true;
  11157. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  11158. // reset state after plugin (anything could have changed)
  11159. _currentProgram = null;
  11160. _currentCamera = null;
  11161. _oldBlending = -1;
  11162. _oldDepthTest = -1;
  11163. _oldDepthWrite = -1;
  11164. _oldDoubleSided = -1;
  11165. _oldFlipSided = -1;
  11166. _currentGeometryGroupHash = -1;
  11167. _currentMaterialId = -1;
  11168. _lightsNeedUpdate = true;
  11169. }
  11170. };
  11171. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11172. var webglObject, object, buffer, material, start, end, delta;
  11173. if ( reverse ) {
  11174. start = renderList.length - 1;
  11175. end = -1;
  11176. delta = -1;
  11177. } else {
  11178. start = 0;
  11179. end = renderList.length;
  11180. delta = 1;
  11181. }
  11182. for ( var i = start; i !== end; i += delta ) {
  11183. webglObject = renderList[ i ];
  11184. if ( webglObject.render ) {
  11185. object = webglObject.object;
  11186. buffer = webglObject.buffer;
  11187. if ( overrideMaterial ) {
  11188. material = overrideMaterial;
  11189. } else {
  11190. material = webglObject[ materialType ];
  11191. if ( ! material ) continue;
  11192. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11193. _this.setDepthTest( material.depthTest );
  11194. _this.setDepthWrite( material.depthWrite );
  11195. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11196. }
  11197. _this.setMaterialFaces( material );
  11198. if ( buffer instanceof THREE.BufferGeometry ) {
  11199. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11200. } else {
  11201. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11202. }
  11203. }
  11204. }
  11205. };
  11206. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11207. var webglObject, object, material, program;
  11208. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11209. webglObject = renderList[ i ];
  11210. object = webglObject.object;
  11211. if ( object.visible ) {
  11212. if ( overrideMaterial ) {
  11213. material = overrideMaterial;
  11214. } else {
  11215. material = webglObject[ materialType ];
  11216. if ( ! material ) continue;
  11217. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11218. _this.setDepthTest( material.depthTest );
  11219. _this.setDepthWrite( material.depthWrite );
  11220. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11221. }
  11222. _this.renderImmediateObject( camera, lights, fog, material, object );
  11223. }
  11224. }
  11225. };
  11226. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  11227. var program = setProgram( camera, lights, fog, material, object );
  11228. _currentGeometryGroupHash = -1;
  11229. _this.setMaterialFaces( material );
  11230. if ( object.immediateRenderCallback ) {
  11231. object.immediateRenderCallback( program, _gl, _frustum );
  11232. } else {
  11233. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  11234. }
  11235. };
  11236. function unrollImmediateBufferMaterial ( globject ) {
  11237. var object = globject.object,
  11238. material = object.material;
  11239. if ( material.transparent ) {
  11240. globject.transparent = material;
  11241. globject.opaque = null;
  11242. } else {
  11243. globject.opaque = material;
  11244. globject.transparent = null;
  11245. }
  11246. };
  11247. function unrollBufferMaterial ( globject ) {
  11248. var object = globject.object,
  11249. buffer = globject.buffer,
  11250. material, materialIndex, meshMaterial;
  11251. meshMaterial = object.material;
  11252. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  11253. materialIndex = buffer.materialIndex;
  11254. if ( materialIndex >= 0 ) {
  11255. material = object.geometry.materials[ materialIndex ];
  11256. if ( material.transparent ) {
  11257. globject.transparent = material;
  11258. globject.opaque = null;
  11259. } else {
  11260. globject.opaque = material;
  11261. globject.transparent = null;
  11262. }
  11263. }
  11264. } else {
  11265. material = meshMaterial;
  11266. if ( material ) {
  11267. if ( material.transparent ) {
  11268. globject.transparent = material;
  11269. globject.opaque = null;
  11270. } else {
  11271. globject.opaque = material;
  11272. globject.transparent = null;
  11273. }
  11274. }
  11275. }
  11276. };
  11277. // Geometry splitting
  11278. function sortFacesByMaterial ( geometry ) {
  11279. var f, fl, face, materialIndex, vertices,
  11280. materialHash, groupHash,
  11281. hash_map = {};
  11282. var numMorphTargets = geometry.morphTargets.length;
  11283. var numMorphNormals = geometry.morphNormals.length;
  11284. geometry.geometryGroups = {};
  11285. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  11286. face = geometry.faces[ f ];
  11287. materialIndex = face.materialIndex;
  11288. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  11289. if ( hash_map[ materialHash ] === undefined ) {
  11290. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  11291. }
  11292. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11293. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11294. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11295. }
  11296. vertices = face instanceof THREE.Face3 ? 3 : 4;
  11297. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  11298. hash_map[ materialHash ].counter += 1;
  11299. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11300. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11301. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11302. }
  11303. }
  11304. if ( face instanceof THREE.Face3 ) {
  11305. geometry.geometryGroups[ groupHash ].faces3.push( f );
  11306. } else {
  11307. geometry.geometryGroups[ groupHash ].faces4.push( f );
  11308. }
  11309. geometry.geometryGroups[ groupHash ].vertices += vertices;
  11310. }
  11311. geometry.geometryGroupsList = [];
  11312. for ( var g in geometry.geometryGroups ) {
  11313. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  11314. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  11315. }
  11316. };
  11317. // Objects refresh
  11318. this.initWebGLObjects = function ( scene ) {
  11319. if ( !scene.__webglObjects ) {
  11320. scene.__webglObjects = [];
  11321. scene.__webglObjectsImmediate = [];
  11322. scene.__webglSprites = [];
  11323. scene.__webglFlares = [];
  11324. }
  11325. while ( scene.__objectsAdded.length ) {
  11326. addObject( scene.__objectsAdded[ 0 ], scene );
  11327. scene.__objectsAdded.splice( 0, 1 );
  11328. }
  11329. while ( scene.__objectsRemoved.length ) {
  11330. removeObject( scene.__objectsRemoved[ 0 ], scene );
  11331. scene.__objectsRemoved.splice( 0, 1 );
  11332. }
  11333. // update must be called after objects adding / removal
  11334. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  11335. updateObject( scene.__webglObjects[ o ].object );
  11336. }
  11337. };
  11338. // Objects adding
  11339. function addObject ( object, scene ) {
  11340. var g, geometry, geometryGroup;
  11341. if ( ! object.__webglInit ) {
  11342. object.__webglInit = true;
  11343. object._modelViewMatrix = new THREE.Matrix4();
  11344. object._normalMatrix = new THREE.Matrix3();
  11345. if ( object instanceof THREE.Mesh ) {
  11346. geometry = object.geometry;
  11347. if ( geometry instanceof THREE.Geometry ) {
  11348. if ( geometry.geometryGroups === undefined ) {
  11349. sortFacesByMaterial( geometry );
  11350. }
  11351. // create separate VBOs per geometry chunk
  11352. for ( g in geometry.geometryGroups ) {
  11353. geometryGroup = geometry.geometryGroups[ g ];
  11354. // initialise VBO on the first access
  11355. if ( ! geometryGroup.__webglVertexBuffer ) {
  11356. createMeshBuffers( geometryGroup );
  11357. initMeshBuffers( geometryGroup, object );
  11358. geometry.verticesNeedUpdate = true;
  11359. geometry.morphTargetsNeedUpdate = true;
  11360. geometry.elementsNeedUpdate = true;
  11361. geometry.uvsNeedUpdate = true;
  11362. geometry.normalsNeedUpdate = true;
  11363. geometry.tangentsNeedUpdate = true;
  11364. geometry.colorsNeedUpdate = true;
  11365. }
  11366. }
  11367. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11368. initDirectBuffers( geometry );
  11369. }
  11370. } else if ( object instanceof THREE.Ribbon ) {
  11371. geometry = object.geometry;
  11372. if( ! geometry.__webglVertexBuffer ) {
  11373. createRibbonBuffers( geometry );
  11374. initRibbonBuffers( geometry );
  11375. geometry.verticesNeedUpdate = true;
  11376. geometry.colorsNeedUpdate = true;
  11377. }
  11378. } else if ( object instanceof THREE.Line ) {
  11379. geometry = object.geometry;
  11380. if( ! geometry.__webglVertexBuffer ) {
  11381. createLineBuffers( geometry );
  11382. initLineBuffers( geometry, object );
  11383. geometry.verticesNeedUpdate = true;
  11384. geometry.colorsNeedUpdate = true;
  11385. }
  11386. } else if ( object instanceof THREE.ParticleSystem ) {
  11387. geometry = object.geometry;
  11388. if ( ! geometry.__webglVertexBuffer ) {
  11389. createParticleBuffers( geometry );
  11390. initParticleBuffers( geometry, object );
  11391. geometry.verticesNeedUpdate = true;
  11392. geometry.colorsNeedUpdate = true;
  11393. }
  11394. }
  11395. }
  11396. if ( ! object.__webglActive ) {
  11397. if ( object instanceof THREE.Mesh ) {
  11398. geometry = object.geometry;
  11399. if ( geometry instanceof THREE.BufferGeometry ) {
  11400. addBuffer( scene.__webglObjects, geometry, object );
  11401. } else {
  11402. for ( g in geometry.geometryGroups ) {
  11403. geometryGroup = geometry.geometryGroups[ g ];
  11404. addBuffer( scene.__webglObjects, geometryGroup, object );
  11405. }
  11406. }
  11407. } else if ( object instanceof THREE.Ribbon ||
  11408. object instanceof THREE.Line ||
  11409. object instanceof THREE.ParticleSystem ) {
  11410. geometry = object.geometry;
  11411. addBuffer( scene.__webglObjects, geometry, object );
  11412. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11413. addBufferImmediate( scene.__webglObjectsImmediate, object );
  11414. } else if ( object instanceof THREE.Sprite ) {
  11415. scene.__webglSprites.push( object );
  11416. } else if ( object instanceof THREE.LensFlare ) {
  11417. scene.__webglFlares.push( object );
  11418. }
  11419. object.__webglActive = true;
  11420. }
  11421. };
  11422. function addBuffer ( objlist, buffer, object ) {
  11423. objlist.push(
  11424. {
  11425. buffer: buffer,
  11426. object: object,
  11427. opaque: null,
  11428. transparent: null
  11429. }
  11430. );
  11431. };
  11432. function addBufferImmediate ( objlist, object ) {
  11433. objlist.push(
  11434. {
  11435. object: object,
  11436. opaque: null,
  11437. transparent: null
  11438. }
  11439. );
  11440. };
  11441. // Objects updates
  11442. function updateObject ( object ) {
  11443. var geometry = object.geometry,
  11444. geometryGroup, customAttributesDirty, material;
  11445. if ( object instanceof THREE.Mesh ) {
  11446. if ( geometry instanceof THREE.BufferGeometry ) {
  11447. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  11448. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11449. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  11450. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  11451. }
  11452. geometry.verticesNeedUpdate = false;
  11453. geometry.elementsNeedUpdate = false;
  11454. geometry.uvsNeedUpdate = false;
  11455. geometry.normalsNeedUpdate = false;
  11456. geometry.colorsNeedUpdate = false;
  11457. geometry.tangentsNeedUpdate = false;
  11458. } else {
  11459. // check all geometry groups
  11460. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  11461. geometryGroup = geometry.geometryGroupsList[ i ];
  11462. material = getBufferMaterial( object, geometryGroup );
  11463. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11464. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  11465. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11466. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  11467. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  11468. }
  11469. }
  11470. geometry.verticesNeedUpdate = false;
  11471. geometry.morphTargetsNeedUpdate = false;
  11472. geometry.elementsNeedUpdate = false;
  11473. geometry.uvsNeedUpdate = false;
  11474. geometry.normalsNeedUpdate = false;
  11475. geometry.colorsNeedUpdate = false;
  11476. geometry.tangentsNeedUpdate = false;
  11477. material.attributes && clearCustomAttributes( material );
  11478. }
  11479. } else if ( object instanceof THREE.Ribbon ) {
  11480. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  11481. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  11482. }
  11483. geometry.verticesNeedUpdate = false;
  11484. geometry.colorsNeedUpdate = false;
  11485. } else if ( object instanceof THREE.Line ) {
  11486. material = getBufferMaterial( object, geometryGroup );
  11487. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11488. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) {
  11489. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  11490. }
  11491. geometry.verticesNeedUpdate = false;
  11492. geometry.colorsNeedUpdate = false;
  11493. material.attributes && clearCustomAttributes( material );
  11494. } else if ( object instanceof THREE.ParticleSystem ) {
  11495. material = getBufferMaterial( object, geometryGroup );
  11496. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11497. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  11498. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  11499. }
  11500. geometry.verticesNeedUpdate = false;
  11501. geometry.colorsNeedUpdate = false;
  11502. material.attributes && clearCustomAttributes( material );
  11503. }
  11504. };
  11505. // Objects updates - custom attributes check
  11506. function areCustomAttributesDirty ( material ) {
  11507. for ( var a in material.attributes ) {
  11508. if ( material.attributes[ a ].needsUpdate ) return true;
  11509. }
  11510. return false;
  11511. };
  11512. function clearCustomAttributes ( material ) {
  11513. for ( var a in material.attributes ) {
  11514. material.attributes[ a ].needsUpdate = false;
  11515. }
  11516. };
  11517. // Objects removal
  11518. function removeObject ( object, scene ) {
  11519. if ( object instanceof THREE.Mesh ||
  11520. object instanceof THREE.ParticleSystem ||
  11521. object instanceof THREE.Ribbon ||
  11522. object instanceof THREE.Line ) {
  11523. removeInstances( scene.__webglObjects, object );
  11524. } else if ( object instanceof THREE.Sprite ) {
  11525. removeInstancesDirect( scene.__webglSprites, object );
  11526. } else if ( object instanceof THREE.LensFlare ) {
  11527. removeInstancesDirect( scene.__webglFlares, object );
  11528. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11529. removeInstances( scene.__webglObjectsImmediate, object );
  11530. }
  11531. object.__webglActive = false;
  11532. };
  11533. function removeInstances ( objlist, object ) {
  11534. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  11535. if ( objlist[ o ].object === object ) {
  11536. objlist.splice( o, 1 );
  11537. }
  11538. }
  11539. };
  11540. function removeInstancesDirect ( objlist, object ) {
  11541. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  11542. if ( objlist[ o ] === object ) {
  11543. objlist.splice( o, 1 );
  11544. }
  11545. }
  11546. };
  11547. // Materials
  11548. this.initMaterial = function ( material, lights, fog, object ) {
  11549. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  11550. if ( material instanceof THREE.MeshDepthMaterial ) {
  11551. shaderID = 'depth';
  11552. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  11553. shaderID = 'normal';
  11554. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  11555. shaderID = 'basic';
  11556. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  11557. shaderID = 'lambert';
  11558. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  11559. shaderID = 'phong';
  11560. } else if ( material instanceof THREE.LineBasicMaterial ) {
  11561. shaderID = 'basic';
  11562. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  11563. shaderID = 'particle_basic';
  11564. }
  11565. if ( shaderID ) {
  11566. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  11567. }
  11568. // heuristics to create shader parameters according to lights in the scene
  11569. // (not to blow over maxLights budget)
  11570. maxLightCount = allocateLights( lights );
  11571. maxShadows = allocateShadows( lights );
  11572. maxBones = allocateBones( object );
  11573. parameters = {
  11574. map: !!material.map,
  11575. envMap: !!material.envMap,
  11576. lightMap: !!material.lightMap,
  11577. bumpMap: !!material.bumpMap,
  11578. specularMap: !!material.specularMap,
  11579. vertexColors: material.vertexColors,
  11580. fog: fog,
  11581. useFog: material.fog,
  11582. sizeAttenuation: material.sizeAttenuation,
  11583. skinning: material.skinning,
  11584. maxBones: maxBones,
  11585. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  11586. boneTextureWidth: object && object.boneTextureWidth,
  11587. boneTextureHeight: object && object.boneTextureHeight,
  11588. morphTargets: material.morphTargets,
  11589. morphNormals: material.morphNormals,
  11590. maxMorphTargets: this.maxMorphTargets,
  11591. maxMorphNormals: this.maxMorphNormals,
  11592. maxDirLights: maxLightCount.directional,
  11593. maxPointLights: maxLightCount.point,
  11594. maxSpotLights: maxLightCount.spot,
  11595. maxShadows: maxShadows,
  11596. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  11597. shadowMapSoft: this.shadowMapSoft,
  11598. shadowMapDebug: this.shadowMapDebug,
  11599. shadowMapCascade: this.shadowMapCascade,
  11600. alphaTest: material.alphaTest,
  11601. metal: material.metal,
  11602. perPixel: material.perPixel,
  11603. wrapAround: material.wrapAround,
  11604. doubleSided: material.side === THREE.DoubleSide
  11605. };
  11606. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, parameters );
  11607. var attributes = material.program.attributes;
  11608. if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
  11609. if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
  11610. if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
  11611. if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );
  11612. if ( material.skinning &&
  11613. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11614. _gl.enableVertexAttribArray( attributes.skinIndex );
  11615. _gl.enableVertexAttribArray( attributes.skinWeight );
  11616. }
  11617. if ( material.attributes ) {
  11618. for ( a in material.attributes ) {
  11619. if( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );
  11620. }
  11621. }
  11622. if ( material.morphTargets ) {
  11623. material.numSupportedMorphTargets = 0;
  11624. var id, base = "morphTarget";
  11625. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  11626. id = base + i;
  11627. if ( attributes[ id ] >= 0 ) {
  11628. _gl.enableVertexAttribArray( attributes[ id ] );
  11629. material.numSupportedMorphTargets ++;
  11630. }
  11631. }
  11632. }
  11633. if ( material.morphNormals ) {
  11634. material.numSupportedMorphNormals = 0;
  11635. var id, base = "morphNormal";
  11636. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  11637. id = base + i;
  11638. if ( attributes[ id ] >= 0 ) {
  11639. _gl.enableVertexAttribArray( attributes[ id ] );
  11640. material.numSupportedMorphNormals ++;
  11641. }
  11642. }
  11643. }
  11644. material.uniformsList = [];
  11645. for ( u in material.uniforms ) {
  11646. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  11647. }
  11648. };
  11649. function setMaterialShaders( material, shaders ) {
  11650. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  11651. material.vertexShader = shaders.vertexShader;
  11652. material.fragmentShader = shaders.fragmentShader;
  11653. };
  11654. function setProgram( camera, lights, fog, material, object ) {
  11655. if ( material.needsUpdate ) {
  11656. if ( material.program ) _this.deallocateMaterial( material );
  11657. _this.initMaterial( material, lights, fog, object );
  11658. material.needsUpdate = false;
  11659. }
  11660. if ( material.morphTargets ) {
  11661. if ( ! object.__webglMorphTargetInfluences ) {
  11662. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  11663. }
  11664. }
  11665. var refreshMaterial = false;
  11666. var program = material.program,
  11667. p_uniforms = program.uniforms,
  11668. m_uniforms = material.uniforms;
  11669. if ( program !== _currentProgram ) {
  11670. _gl.useProgram( program );
  11671. _currentProgram = program;
  11672. refreshMaterial = true;
  11673. }
  11674. if ( material.id !== _currentMaterialId ) {
  11675. _currentMaterialId = material.id;
  11676. refreshMaterial = true;
  11677. }
  11678. if ( refreshMaterial || camera !== _currentCamera ) {
  11679. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  11680. if ( camera !== _currentCamera ) _currentCamera = camera;
  11681. }
  11682. if ( refreshMaterial ) {
  11683. // refresh uniforms common to several materials
  11684. if ( fog && material.fog ) {
  11685. refreshUniformsFog( m_uniforms, fog );
  11686. }
  11687. if ( material instanceof THREE.MeshPhongMaterial ||
  11688. material instanceof THREE.MeshLambertMaterial ||
  11689. material.lights ) {
  11690. if ( _lightsNeedUpdate ) {
  11691. setupLights( program, lights );
  11692. _lightsNeedUpdate = false;
  11693. }
  11694. refreshUniformsLights( m_uniforms, _lights );
  11695. }
  11696. if ( material instanceof THREE.MeshBasicMaterial ||
  11697. material instanceof THREE.MeshLambertMaterial ||
  11698. material instanceof THREE.MeshPhongMaterial ) {
  11699. refreshUniformsCommon( m_uniforms, material );
  11700. }
  11701. // refresh single material specific uniforms
  11702. if ( material instanceof THREE.LineBasicMaterial ) {
  11703. refreshUniformsLine( m_uniforms, material );
  11704. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  11705. refreshUniformsParticle( m_uniforms, material );
  11706. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  11707. refreshUniformsPhong( m_uniforms, material );
  11708. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  11709. refreshUniformsLambert( m_uniforms, material );
  11710. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  11711. m_uniforms.mNear.value = camera.near;
  11712. m_uniforms.mFar.value = camera.far;
  11713. m_uniforms.opacity.value = material.opacity;
  11714. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  11715. m_uniforms.opacity.value = material.opacity;
  11716. }
  11717. if ( object.receiveShadow && ! material._shadowPass ) {
  11718. refreshUniformsShadow( m_uniforms, lights );
  11719. }
  11720. // load common uniforms
  11721. loadUniformsGeneric( program, material.uniformsList );
  11722. // load material specific uniforms
  11723. // (shader material also gets them for the sake of genericity)
  11724. if ( material instanceof THREE.ShaderMaterial ||
  11725. material instanceof THREE.MeshPhongMaterial ||
  11726. material.envMap ) {
  11727. if ( p_uniforms.cameraPosition !== null ) {
  11728. var position = camera.matrixWorld.getPosition();
  11729. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  11730. }
  11731. }
  11732. if ( material instanceof THREE.MeshPhongMaterial ||
  11733. material instanceof THREE.MeshLambertMaterial ||
  11734. material instanceof THREE.ShaderMaterial ||
  11735. material.skinning ) {
  11736. if ( p_uniforms.viewMatrix !== null ) {
  11737. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  11738. }
  11739. }
  11740. }
  11741. if ( material.skinning ) {
  11742. if ( _supportsBoneTextures && object.useVertexTexture ) {
  11743. if ( p_uniforms.boneTexture !== null ) {
  11744. // shadowMap texture array starts from 6
  11745. // texture unit 12 should leave space for 6 shadowmaps
  11746. var textureUnit = 12;
  11747. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  11748. _this.setTexture( object.boneTexture, textureUnit );
  11749. }
  11750. } else {
  11751. if ( p_uniforms.boneGlobalMatrices !== null ) {
  11752. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  11753. }
  11754. }
  11755. }
  11756. loadUniformsMatrices( p_uniforms, object );
  11757. if ( p_uniforms.modelMatrix !== null ) {
  11758. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  11759. }
  11760. return program;
  11761. };
  11762. // Uniforms (refresh uniforms objects)
  11763. function refreshUniformsCommon ( uniforms, material ) {
  11764. uniforms.opacity.value = material.opacity;
  11765. if ( _this.gammaInput ) {
  11766. uniforms.diffuse.value.copyGammaToLinear( material.color );
  11767. } else {
  11768. uniforms.diffuse.value = material.color;
  11769. }
  11770. uniforms.map.texture = material.map;
  11771. uniforms.lightMap.texture = material.lightMap;
  11772. uniforms.specularMap.texture = material.specularMap;
  11773. if ( material.bumpMap ) {
  11774. uniforms.bumpMap.texture = material.bumpMap;
  11775. uniforms.bumpScale.value = material.bumpScale;
  11776. }
  11777. // uv repeat and offset setting priorities
  11778. // 1. color map
  11779. // 2. specular map
  11780. // 3. bump map
  11781. var uvScaleMap;
  11782. if ( material.map ) {
  11783. uvScaleMap = material.map;
  11784. } else if ( material.specularMap ) {
  11785. uvScaleMap = material.specularMap;
  11786. } else if ( material.bumpMap ) {
  11787. uvScaleMap = material.bumpMap;
  11788. }
  11789. if ( uvScaleMap !== undefined ) {
  11790. var offset = uvScaleMap.offset;
  11791. var repeat = uvScaleMap.repeat;
  11792. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  11793. }
  11794. uniforms.envMap.texture = material.envMap;
  11795. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  11796. if ( _this.gammaInput ) {
  11797. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  11798. uniforms.reflectivity.value = material.reflectivity;
  11799. } else {
  11800. uniforms.reflectivity.value = material.reflectivity;
  11801. }
  11802. uniforms.refractionRatio.value = material.refractionRatio;
  11803. uniforms.combine.value = material.combine;
  11804. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  11805. };
  11806. function refreshUniformsLine ( uniforms, material ) {
  11807. uniforms.diffuse.value = material.color;
  11808. uniforms.opacity.value = material.opacity;
  11809. };
  11810. function refreshUniformsParticle ( uniforms, material ) {
  11811. uniforms.psColor.value = material.color;
  11812. uniforms.opacity.value = material.opacity;
  11813. uniforms.size.value = material.size;
  11814. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  11815. uniforms.map.texture = material.map;
  11816. };
  11817. function refreshUniformsFog ( uniforms, fog ) {
  11818. uniforms.fogColor.value = fog.color;
  11819. if ( fog instanceof THREE.Fog ) {
  11820. uniforms.fogNear.value = fog.near;
  11821. uniforms.fogFar.value = fog.far;
  11822. } else if ( fog instanceof THREE.FogExp2 ) {
  11823. uniforms.fogDensity.value = fog.density;
  11824. }
  11825. };
  11826. function refreshUniformsPhong ( uniforms, material ) {
  11827. uniforms.shininess.value = material.shininess;
  11828. if ( _this.gammaInput ) {
  11829. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  11830. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  11831. uniforms.specular.value.copyGammaToLinear( material.specular );
  11832. } else {
  11833. uniforms.ambient.value = material.ambient;
  11834. uniforms.emissive.value = material.emissive;
  11835. uniforms.specular.value = material.specular;
  11836. }
  11837. if ( material.wrapAround ) {
  11838. uniforms.wrapRGB.value.copy( material.wrapRGB );
  11839. }
  11840. };
  11841. function refreshUniformsLambert ( uniforms, material ) {
  11842. if ( _this.gammaInput ) {
  11843. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  11844. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  11845. } else {
  11846. uniforms.ambient.value = material.ambient;
  11847. uniforms.emissive.value = material.emissive;
  11848. }
  11849. if ( material.wrapAround ) {
  11850. uniforms.wrapRGB.value.copy( material.wrapRGB );
  11851. }
  11852. };
  11853. function refreshUniformsLights ( uniforms, lights ) {
  11854. uniforms.ambientLightColor.value = lights.ambient;
  11855. uniforms.directionalLightColor.value = lights.directional.colors;
  11856. uniforms.directionalLightDirection.value = lights.directional.positions;
  11857. uniforms.pointLightColor.value = lights.point.colors;
  11858. uniforms.pointLightPosition.value = lights.point.positions;
  11859. uniforms.pointLightDistance.value = lights.point.distances;
  11860. uniforms.spotLightColor.value = lights.spot.colors;
  11861. uniforms.spotLightPosition.value = lights.spot.positions;
  11862. uniforms.spotLightDistance.value = lights.spot.distances;
  11863. uniforms.spotLightDirection.value = lights.spot.directions;
  11864. uniforms.spotLightAngle.value = lights.spot.angles;
  11865. uniforms.spotLightExponent.value = lights.spot.exponents;
  11866. };
  11867. function refreshUniformsShadow ( uniforms, lights ) {
  11868. if ( uniforms.shadowMatrix ) {
  11869. var j = 0;
  11870. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  11871. var light = lights[ i ];
  11872. if ( ! light.castShadow ) continue;
  11873. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  11874. uniforms.shadowMap.texture[ j ] = light.shadowMap;
  11875. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  11876. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  11877. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  11878. uniforms.shadowBias.value[ j ] = light.shadowBias;
  11879. j ++;
  11880. }
  11881. }
  11882. }
  11883. };
  11884. // Uniforms (load to GPU)
  11885. function loadUniformsMatrices ( uniforms, object ) {
  11886. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  11887. if ( uniforms.normalMatrix ) {
  11888. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  11889. }
  11890. };
  11891. function loadUniformsGeneric ( program, uniforms ) {
  11892. var uniform, value, type, location, texture, i, il, j, jl, offset;
  11893. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  11894. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  11895. if ( !location ) continue;
  11896. uniform = uniforms[ j ][ 0 ];
  11897. type = uniform.type;
  11898. value = uniform.value;
  11899. if ( type === "i" ) { // single integer
  11900. _gl.uniform1i( location, value );
  11901. } else if ( type === "f" ) { // single float
  11902. _gl.uniform1f( location, value );
  11903. } else if ( type === "v2" ) { // single THREE.Vector2
  11904. _gl.uniform2f( location, value.x, value.y );
  11905. } else if ( type === "v3" ) { // single THREE.Vector3
  11906. _gl.uniform3f( location, value.x, value.y, value.z );
  11907. } else if ( type === "v4" ) { // single THREE.Vector4
  11908. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  11909. } else if ( type === "c" ) { // single THREE.Color
  11910. _gl.uniform3f( location, value.r, value.g, value.b );
  11911. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  11912. _gl.uniform1iv( location, value );
  11913. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  11914. _gl.uniform3iv( location, value );
  11915. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  11916. _gl.uniform1fv( location, value );
  11917. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  11918. _gl.uniform3fv( location, value );
  11919. } else if ( type === "v2v" ) { // array of THREE.Vector2
  11920. if ( uniform._array === undefined ) {
  11921. uniform._array = new Float32Array( 2 * value.length );
  11922. }
  11923. for ( i = 0, il = value.length; i < il; i ++ ) {
  11924. offset = i * 2;
  11925. uniform._array[ offset ] = value[ i ].x;
  11926. uniform._array[ offset + 1 ] = value[ i ].y;
  11927. }
  11928. _gl.uniform2fv( location, uniform._array );
  11929. } else if ( type === "v3v" ) { // array of THREE.Vector3
  11930. if ( uniform._array === undefined ) {
  11931. uniform._array = new Float32Array( 3 * value.length );
  11932. }
  11933. for ( i = 0, il = value.length; i < il; i ++ ) {
  11934. offset = i * 3;
  11935. uniform._array[ offset ] = value[ i ].x;
  11936. uniform._array[ offset + 1 ] = value[ i ].y;
  11937. uniform._array[ offset + 2 ] = value[ i ].z;
  11938. }
  11939. _gl.uniform3fv( location, uniform._array );
  11940. } else if ( type === "v4v" ) { // array of THREE.Vector4
  11941. if ( uniform._array === undefined ) {
  11942. uniform._array = new Float32Array( 4 * value.length );
  11943. }
  11944. for ( i = 0, il = value.length; i < il; i ++ ) {
  11945. offset = i * 4;
  11946. uniform._array[ offset ] = value[ i ].x;
  11947. uniform._array[ offset + 1 ] = value[ i ].y;
  11948. uniform._array[ offset + 2 ] = value[ i ].z;
  11949. uniform._array[ offset + 3 ] = value[ i ].w;
  11950. }
  11951. _gl.uniform4fv( location, uniform._array );
  11952. } else if ( type === "m4") { // single THREE.Matrix4
  11953. if ( uniform._array === undefined ) {
  11954. uniform._array = new Float32Array( 16 );
  11955. }
  11956. value.flattenToArray( uniform._array );
  11957. _gl.uniformMatrix4fv( location, false, uniform._array );
  11958. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  11959. if ( uniform._array === undefined ) {
  11960. uniform._array = new Float32Array( 16 * value.length );
  11961. }
  11962. for ( i = 0, il = value.length; i < il; i ++ ) {
  11963. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  11964. }
  11965. _gl.uniformMatrix4fv( location, false, uniform._array );
  11966. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  11967. _gl.uniform1i( location, value );
  11968. texture = uniform.texture;
  11969. if ( !texture ) continue;
  11970. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  11971. setCubeTexture( texture, value );
  11972. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  11973. setCubeTextureDynamic( texture, value );
  11974. } else {
  11975. _this.setTexture( texture, value );
  11976. }
  11977. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  11978. if ( uniform._array === undefined ) {
  11979. uniform._array = [];
  11980. for( i = 0, il = uniform.texture.length; i < il; i ++ ) {
  11981. uniform._array[ i ] = value + i;
  11982. }
  11983. }
  11984. _gl.uniform1iv( location, uniform._array );
  11985. for( i = 0, il = uniform.texture.length; i < il; i ++ ) {
  11986. texture = uniform.texture[ i ];
  11987. if ( !texture ) continue;
  11988. _this.setTexture( texture, uniform._array[ i ] );
  11989. }
  11990. }
  11991. }
  11992. };
  11993. function setupMatrices ( object, camera ) {
  11994. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  11995. object._normalMatrix.getInverse( object._modelViewMatrix );
  11996. object._normalMatrix.transpose();
  11997. };
  11998. function setupLights ( program, lights ) {
  11999. var l, ll, light, n,
  12000. r = 0, g = 0, b = 0,
  12001. color, position, intensity, distance,
  12002. zlights = _lights,
  12003. dcolors = zlights.directional.colors,
  12004. dpositions = zlights.directional.positions,
  12005. pcolors = zlights.point.colors,
  12006. ppositions = zlights.point.positions,
  12007. pdistances = zlights.point.distances,
  12008. scolors = zlights.spot.colors,
  12009. spositions = zlights.spot.positions,
  12010. sdistances = zlights.spot.distances,
  12011. sdirections = zlights.spot.directions,
  12012. sangles = zlights.spot.angles,
  12013. sexponents = zlights.spot.exponents,
  12014. dlength = 0,
  12015. plength = 0,
  12016. slength = 0,
  12017. doffset = 0,
  12018. poffset = 0,
  12019. soffset = 0;
  12020. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12021. light = lights[ l ];
  12022. if ( light.onlyShadow || ! light.visible ) continue;
  12023. color = light.color;
  12024. intensity = light.intensity;
  12025. distance = light.distance;
  12026. if ( light instanceof THREE.AmbientLight ) {
  12027. if ( _this.gammaInput ) {
  12028. r += color.r * color.r;
  12029. g += color.g * color.g;
  12030. b += color.b * color.b;
  12031. } else {
  12032. r += color.r;
  12033. g += color.g;
  12034. b += color.b;
  12035. }
  12036. } else if ( light instanceof THREE.DirectionalLight ) {
  12037. doffset = dlength * 3;
  12038. if ( _this.gammaInput ) {
  12039. dcolors[ doffset ] = color.r * color.r * intensity * intensity;
  12040. dcolors[ doffset + 1 ] = color.g * color.g * intensity * intensity;
  12041. dcolors[ doffset + 2 ] = color.b * color.b * intensity * intensity;
  12042. } else {
  12043. dcolors[ doffset ] = color.r * intensity;
  12044. dcolors[ doffset + 1 ] = color.g * intensity;
  12045. dcolors[ doffset + 2 ] = color.b * intensity;
  12046. }
  12047. _direction.copy( light.matrixWorld.getPosition() );
  12048. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12049. _direction.normalize();
  12050. dpositions[ doffset ] = _direction.x;
  12051. dpositions[ doffset + 1 ] = _direction.y;
  12052. dpositions[ doffset + 2 ] = _direction.z;
  12053. dlength += 1;
  12054. } else if( light instanceof THREE.PointLight ) {
  12055. poffset = plength * 3;
  12056. if ( _this.gammaInput ) {
  12057. pcolors[ poffset ] = color.r * color.r * intensity * intensity;
  12058. pcolors[ poffset + 1 ] = color.g * color.g * intensity * intensity;
  12059. pcolors[ poffset + 2 ] = color.b * color.b * intensity * intensity;
  12060. } else {
  12061. pcolors[ poffset ] = color.r * intensity;
  12062. pcolors[ poffset + 1 ] = color.g * intensity;
  12063. pcolors[ poffset + 2 ] = color.b * intensity;
  12064. }
  12065. position = light.matrixWorld.getPosition();
  12066. ppositions[ poffset ] = position.x;
  12067. ppositions[ poffset + 1 ] = position.y;
  12068. ppositions[ poffset + 2 ] = position.z;
  12069. pdistances[ plength ] = distance;
  12070. plength += 1;
  12071. } else if( light instanceof THREE.SpotLight ) {
  12072. soffset = slength * 3;
  12073. if ( _this.gammaInput ) {
  12074. scolors[ soffset ] = color.r * color.r * intensity * intensity;
  12075. scolors[ soffset + 1 ] = color.g * color.g * intensity * intensity;
  12076. scolors[ soffset + 2 ] = color.b * color.b * intensity * intensity;
  12077. } else {
  12078. scolors[ soffset ] = color.r * intensity;
  12079. scolors[ soffset + 1 ] = color.g * intensity;
  12080. scolors[ soffset + 2 ] = color.b * intensity;
  12081. }
  12082. position = light.matrixWorld.getPosition();
  12083. spositions[ soffset ] = position.x;
  12084. spositions[ soffset + 1 ] = position.y;
  12085. spositions[ soffset + 2 ] = position.z;
  12086. sdistances[ slength ] = distance;
  12087. _direction.copy( position );
  12088. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12089. _direction.normalize();
  12090. sdirections[ soffset ] = _direction.x;
  12091. sdirections[ soffset + 1 ] = _direction.y;
  12092. sdirections[ soffset + 2 ] = _direction.z;
  12093. sangles[ slength ] = Math.cos( light.angle );
  12094. sexponents[ slength ] = light.exponent;
  12095. slength += 1;
  12096. }
  12097. }
  12098. // null eventual remains from removed lights
  12099. // (this is to avoid if in shader)
  12100. for ( l = dlength * 3, ll = dcolors.length; l < ll; l ++ ) dcolors[ l ] = 0.0;
  12101. for ( l = plength * 3, ll = pcolors.length; l < ll; l ++ ) pcolors[ l ] = 0.0;
  12102. for ( l = slength * 3, ll = scolors.length; l < ll; l ++ ) scolors[ l ] = 0.0;
  12103. zlights.directional.length = dlength;
  12104. zlights.point.length = plength;
  12105. zlights.spot.length = slength;
  12106. zlights.ambient[ 0 ] = r;
  12107. zlights.ambient[ 1 ] = g;
  12108. zlights.ambient[ 2 ] = b;
  12109. };
  12110. // GL state setting
  12111. this.setFaceCulling = function ( cullFace, frontFace ) {
  12112. if ( cullFace ) {
  12113. if ( !frontFace || frontFace === "ccw" ) {
  12114. _gl.frontFace( _gl.CCW );
  12115. } else {
  12116. _gl.frontFace( _gl.CW );
  12117. }
  12118. if( cullFace === "back" ) {
  12119. _gl.cullFace( _gl.BACK );
  12120. } else if( cullFace === "front" ) {
  12121. _gl.cullFace( _gl.FRONT );
  12122. } else {
  12123. _gl.cullFace( _gl.FRONT_AND_BACK );
  12124. }
  12125. _gl.enable( _gl.CULL_FACE );
  12126. } else {
  12127. _gl.disable( _gl.CULL_FACE );
  12128. }
  12129. };
  12130. this.setMaterialFaces = function ( material ) {
  12131. var doubleSided = material.side === THREE.DoubleSide;
  12132. var flipSided = material.side === THREE.BackSide;
  12133. if ( _oldDoubleSided !== doubleSided ) {
  12134. if ( doubleSided ) {
  12135. _gl.disable( _gl.CULL_FACE );
  12136. } else {
  12137. _gl.enable( _gl.CULL_FACE );
  12138. }
  12139. _oldDoubleSided = doubleSided;
  12140. }
  12141. if ( _oldFlipSided !== flipSided ) {
  12142. if ( flipSided ) {
  12143. _gl.frontFace( _gl.CW );
  12144. } else {
  12145. _gl.frontFace( _gl.CCW );
  12146. }
  12147. _oldFlipSided = flipSided;
  12148. }
  12149. };
  12150. this.setDepthTest = function ( depthTest ) {
  12151. if ( _oldDepthTest !== depthTest ) {
  12152. if ( depthTest ) {
  12153. _gl.enable( _gl.DEPTH_TEST );
  12154. } else {
  12155. _gl.disable( _gl.DEPTH_TEST );
  12156. }
  12157. _oldDepthTest = depthTest;
  12158. }
  12159. };
  12160. this.setDepthWrite = function ( depthWrite ) {
  12161. if ( _oldDepthWrite !== depthWrite ) {
  12162. _gl.depthMask( depthWrite );
  12163. _oldDepthWrite = depthWrite;
  12164. }
  12165. };
  12166. function setLineWidth ( width ) {
  12167. if ( width !== _oldLineWidth ) {
  12168. _gl.lineWidth( width );
  12169. _oldLineWidth = width;
  12170. }
  12171. };
  12172. function setPolygonOffset ( polygonoffset, factor, units ) {
  12173. if ( _oldPolygonOffset !== polygonoffset ) {
  12174. if ( polygonoffset ) {
  12175. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  12176. } else {
  12177. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  12178. }
  12179. _oldPolygonOffset = polygonoffset;
  12180. }
  12181. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  12182. _gl.polygonOffset( factor, units );
  12183. _oldPolygonOffsetFactor = factor;
  12184. _oldPolygonOffsetUnits = units;
  12185. }
  12186. };
  12187. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  12188. if ( blending !== _oldBlending ) {
  12189. if ( blending === THREE.NoBlending ) {
  12190. _gl.disable( _gl.BLEND );
  12191. } else if ( blending === THREE.AdditiveBlending ) {
  12192. _gl.enable( _gl.BLEND );
  12193. _gl.blendEquation( _gl.FUNC_ADD );
  12194. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  12195. } else if ( blending === THREE.SubtractiveBlending ) {
  12196. // TODO: Find blendFuncSeparate() combination
  12197. _gl.enable( _gl.BLEND );
  12198. _gl.blendEquation( _gl.FUNC_ADD );
  12199. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  12200. } else if ( blending === THREE.MultiplyBlending ) {
  12201. // TODO: Find blendFuncSeparate() combination
  12202. _gl.enable( _gl.BLEND );
  12203. _gl.blendEquation( _gl.FUNC_ADD );
  12204. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  12205. } else if ( blending === THREE.CustomBlending ) {
  12206. _gl.enable( _gl.BLEND );
  12207. } else {
  12208. _gl.enable( _gl.BLEND );
  12209. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  12210. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  12211. }
  12212. _oldBlending = blending;
  12213. }
  12214. if ( blending === THREE.CustomBlending ) {
  12215. if ( blendEquation !== _oldBlendEquation ) {
  12216. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  12217. _oldBlendEquation = blendEquation;
  12218. }
  12219. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  12220. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  12221. _oldBlendSrc = blendSrc;
  12222. _oldBlendDst = blendDst;
  12223. }
  12224. } else {
  12225. _oldBlendEquation = null;
  12226. _oldBlendSrc = null;
  12227. _oldBlendDst = null;
  12228. }
  12229. };
  12230. // Shaders
  12231. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, parameters ) {
  12232. var p, pl, program, code;
  12233. var chunks = [];
  12234. // Generate code
  12235. if ( shaderID ) {
  12236. chunks.push( shaderID );
  12237. } else {
  12238. chunks.push( fragmentShader );
  12239. chunks.push( vertexShader );
  12240. }
  12241. for ( p in parameters ) {
  12242. chunks.push( p );
  12243. chunks.push( parameters[ p ] );
  12244. }
  12245. code = chunks.join();
  12246. // Check if code has been already compiled
  12247. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  12248. var programInfo = _programs[ p ];
  12249. if ( programInfo.code === code ) {
  12250. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  12251. programInfo.usedTimes ++;
  12252. return programInfo.program;
  12253. }
  12254. }
  12255. //console.log( "building new program " );
  12256. //
  12257. program = _gl.createProgram();
  12258. var prefix_vertex = [
  12259. "precision " + _precision + " float;",
  12260. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  12261. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  12262. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  12263. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  12264. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  12265. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  12266. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  12267. "#define MAX_SHADOWS " + parameters.maxShadows,
  12268. "#define MAX_BONES " + parameters.maxBones,
  12269. parameters.map ? "#define USE_MAP" : "",
  12270. parameters.envMap ? "#define USE_ENVMAP" : "",
  12271. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  12272. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  12273. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  12274. parameters.vertexColors ? "#define USE_COLOR" : "",
  12275. parameters.skinning ? "#define USE_SKINNING" : "",
  12276. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  12277. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  12278. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  12279. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  12280. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  12281. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  12282. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  12283. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  12284. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  12285. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  12286. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  12287. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  12288. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  12289. "uniform mat4 modelMatrix;",
  12290. "uniform mat4 modelViewMatrix;",
  12291. "uniform mat4 projectionMatrix;",
  12292. "uniform mat4 viewMatrix;",
  12293. "uniform mat3 normalMatrix;",
  12294. "uniform vec3 cameraPosition;",
  12295. "attribute vec3 position;",
  12296. "attribute vec3 normal;",
  12297. "attribute vec2 uv;",
  12298. "attribute vec2 uv2;",
  12299. "#ifdef USE_COLOR",
  12300. "attribute vec3 color;",
  12301. "#endif",
  12302. "#ifdef USE_MORPHTARGETS",
  12303. "attribute vec3 morphTarget0;",
  12304. "attribute vec3 morphTarget1;",
  12305. "attribute vec3 morphTarget2;",
  12306. "attribute vec3 morphTarget3;",
  12307. "#ifdef USE_MORPHNORMALS",
  12308. "attribute vec3 morphNormal0;",
  12309. "attribute vec3 morphNormal1;",
  12310. "attribute vec3 morphNormal2;",
  12311. "attribute vec3 morphNormal3;",
  12312. "#else",
  12313. "attribute vec3 morphTarget4;",
  12314. "attribute vec3 morphTarget5;",
  12315. "attribute vec3 morphTarget6;",
  12316. "attribute vec3 morphTarget7;",
  12317. "#endif",
  12318. "#endif",
  12319. "#ifdef USE_SKINNING",
  12320. "attribute vec4 skinIndex;",
  12321. "attribute vec4 skinWeight;",
  12322. "#endif",
  12323. ""
  12324. ].join("\n");
  12325. var prefix_fragment = [
  12326. "precision " + _precision + " float;",
  12327. parameters.bumpMap ? "#extension GL_OES_standard_derivatives : enable" : "",
  12328. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  12329. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  12330. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  12331. "#define MAX_SHADOWS " + parameters.maxShadows,
  12332. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  12333. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  12334. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  12335. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  12336. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  12337. ( parameters.useFog && parameters.fog instanceof THREE.FogExp2 ) ? "#define FOG_EXP2" : "",
  12338. parameters.map ? "#define USE_MAP" : "",
  12339. parameters.envMap ? "#define USE_ENVMAP" : "",
  12340. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  12341. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  12342. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  12343. parameters.vertexColors ? "#define USE_COLOR" : "",
  12344. parameters.metal ? "#define METAL" : "",
  12345. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  12346. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  12347. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  12348. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  12349. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  12350. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  12351. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  12352. "uniform mat4 viewMatrix;",
  12353. "uniform vec3 cameraPosition;",
  12354. ""
  12355. ].join("\n");
  12356. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  12357. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  12358. _gl.attachShader( program, glVertexShader );
  12359. _gl.attachShader( program, glFragmentShader );
  12360. _gl.linkProgram( program );
  12361. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  12362. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  12363. }
  12364. // clean up
  12365. _gl.deleteShader( glFragmentShader );
  12366. _gl.deleteShader( glVertexShader );
  12367. //console.log( prefix_fragment + fragmentShader );
  12368. //console.log( prefix_vertex + vertexShader );
  12369. program.uniforms = {};
  12370. program.attributes = {};
  12371. var identifiers, u, a, i;
  12372. // cache uniform locations
  12373. identifiers = [
  12374. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  12375. 'morphTargetInfluences'
  12376. ];
  12377. if ( parameters.useVertexTexture ) {
  12378. identifiers.push( 'boneTexture' );
  12379. } else {
  12380. identifiers.push( 'boneGlobalMatrices' );
  12381. }
  12382. for ( u in uniforms ) {
  12383. identifiers.push( u );
  12384. }
  12385. cacheUniformLocations( program, identifiers );
  12386. // cache attributes locations
  12387. identifiers = [
  12388. "position", "normal", "uv", "uv2", "tangent", "color",
  12389. "skinIndex", "skinWeight"
  12390. ];
  12391. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  12392. identifiers.push( "morphTarget" + i );
  12393. }
  12394. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  12395. identifiers.push( "morphNormal" + i );
  12396. }
  12397. for ( a in attributes ) {
  12398. identifiers.push( a );
  12399. }
  12400. cacheAttributeLocations( program, identifiers );
  12401. program.id = _programs_counter ++;
  12402. _programs.push( { program: program, code: code, usedTimes: 1 } );
  12403. _this.info.memory.programs = _programs.length;
  12404. return program;
  12405. };
  12406. // Shader parameters cache
  12407. function cacheUniformLocations ( program, identifiers ) {
  12408. var i, l, id;
  12409. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  12410. id = identifiers[ i ];
  12411. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  12412. }
  12413. };
  12414. function cacheAttributeLocations ( program, identifiers ) {
  12415. var i, l, id;
  12416. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  12417. id = identifiers[ i ];
  12418. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  12419. }
  12420. };
  12421. function addLineNumbers ( string ) {
  12422. var chunks = string.split( "\n" );
  12423. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  12424. // Chrome reports shader errors on lines
  12425. // starting counting from 1
  12426. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  12427. }
  12428. return chunks.join( "\n" );
  12429. };
  12430. function getShader ( type, string ) {
  12431. var shader;
  12432. if ( type === "fragment" ) {
  12433. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  12434. } else if ( type === "vertex" ) {
  12435. shader = _gl.createShader( _gl.VERTEX_SHADER );
  12436. }
  12437. _gl.shaderSource( shader, string );
  12438. _gl.compileShader( shader );
  12439. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  12440. console.error( _gl.getShaderInfoLog( shader ) );
  12441. console.error( addLineNumbers( string ) );
  12442. return null;
  12443. }
  12444. return shader;
  12445. };
  12446. // Textures
  12447. function isPowerOfTwo ( value ) {
  12448. return ( value & ( value - 1 ) ) === 0;
  12449. };
  12450. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  12451. if ( isImagePowerOfTwo ) {
  12452. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  12453. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  12454. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  12455. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  12456. } else {
  12457. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  12458. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  12459. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  12460. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  12461. }
  12462. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  12463. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  12464. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  12465. texture.__oldAnisotropy = texture.anisotropy;
  12466. }
  12467. }
  12468. };
  12469. this.setTexture = function ( texture, slot ) {
  12470. if ( texture.needsUpdate ) {
  12471. if ( ! texture.__webglInit ) {
  12472. texture.__webglInit = true;
  12473. texture.__webglTexture = _gl.createTexture();
  12474. _this.info.memory.textures ++;
  12475. }
  12476. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12477. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  12478. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  12479. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  12480. var image = texture.image,
  12481. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  12482. glFormat = paramThreeToGL( texture.format ),
  12483. glType = paramThreeToGL( texture.type );
  12484. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  12485. if ( texture instanceof THREE.DataTexture ) {
  12486. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  12487. } else {
  12488. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  12489. }
  12490. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  12491. texture.needsUpdate = false;
  12492. if ( texture.onUpdate ) texture.onUpdate();
  12493. } else {
  12494. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12495. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  12496. }
  12497. };
  12498. function clampToMaxSize ( image, maxSize ) {
  12499. if ( image.width <= maxSize && image.height <= maxSize ) {
  12500. return image;
  12501. }
  12502. // Warning: Scaling through the canvas will only work with images that use
  12503. // premultiplied alpha.
  12504. var maxDimension = Math.max( image.width, image.height );
  12505. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  12506. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  12507. var canvas = document.createElement( 'canvas' );
  12508. canvas.width = newWidth;
  12509. canvas.height = newHeight;
  12510. var ctx = canvas.getContext( "2d" );
  12511. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  12512. return canvas;
  12513. }
  12514. function setCubeTexture ( texture, slot ) {
  12515. if ( texture.image.length === 6 ) {
  12516. if ( texture.needsUpdate ) {
  12517. if ( ! texture.image.__webglTextureCube ) {
  12518. texture.image.__webglTextureCube = _gl.createTexture();
  12519. }
  12520. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12521. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  12522. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  12523. var cubeImage = [];
  12524. for ( var i = 0; i < 6; i ++ ) {
  12525. if ( _this.autoScaleCubemaps ) {
  12526. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  12527. } else {
  12528. cubeImage[ i ] = texture.image[ i ];
  12529. }
  12530. }
  12531. var image = cubeImage[ 0 ],
  12532. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  12533. glFormat = paramThreeToGL( texture.format ),
  12534. glType = paramThreeToGL( texture.type );
  12535. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  12536. for ( var i = 0; i < 6; i ++ ) {
  12537. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  12538. }
  12539. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  12540. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  12541. }
  12542. texture.needsUpdate = false;
  12543. if ( texture.onUpdate ) texture.onUpdate();
  12544. } else {
  12545. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12546. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  12547. }
  12548. }
  12549. };
  12550. function setCubeTextureDynamic ( texture, slot ) {
  12551. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12552. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  12553. };
  12554. // Render targets
  12555. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  12556. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12557. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  12558. };
  12559. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  12560. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  12561. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  12562. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  12563. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  12564. /* For some reason this is not working. Defaulting to RGBA4.
  12565. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  12566. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  12567. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  12568. */
  12569. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  12570. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  12571. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  12572. } else {
  12573. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  12574. }
  12575. };
  12576. this.setRenderTarget = function ( renderTarget ) {
  12577. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  12578. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  12579. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  12580. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  12581. renderTarget.__webglTexture = _gl.createTexture();
  12582. // Setup texture, create render and frame buffers
  12583. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  12584. glFormat = paramThreeToGL( renderTarget.format ),
  12585. glType = paramThreeToGL( renderTarget.type );
  12586. if ( isCube ) {
  12587. renderTarget.__webglFramebuffer = [];
  12588. renderTarget.__webglRenderbuffer = [];
  12589. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  12590. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  12591. for ( var i = 0; i < 6; i ++ ) {
  12592. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  12593. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  12594. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  12595. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  12596. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  12597. }
  12598. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  12599. } else {
  12600. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  12601. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  12602. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  12603. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  12604. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  12605. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  12606. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  12607. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  12608. }
  12609. // Release everything
  12610. if ( isCube ) {
  12611. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  12612. } else {
  12613. _gl.bindTexture( _gl.TEXTURE_2D, null );
  12614. }
  12615. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  12616. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  12617. }
  12618. var framebuffer, width, height, vx, vy;
  12619. if ( renderTarget ) {
  12620. if ( isCube ) {
  12621. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  12622. } else {
  12623. framebuffer = renderTarget.__webglFramebuffer;
  12624. }
  12625. width = renderTarget.width;
  12626. height = renderTarget.height;
  12627. vx = 0;
  12628. vy = 0;
  12629. } else {
  12630. framebuffer = null;
  12631. width = _viewportWidth;
  12632. height = _viewportHeight;
  12633. vx = _viewportX;
  12634. vy = _viewportY;
  12635. }
  12636. if ( framebuffer !== _currentFramebuffer ) {
  12637. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12638. _gl.viewport( vx, vy, width, height );
  12639. _currentFramebuffer = framebuffer;
  12640. }
  12641. _currentWidth = width;
  12642. _currentHeight = height;
  12643. };
  12644. function updateRenderTargetMipmap ( renderTarget ) {
  12645. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12646. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  12647. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  12648. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  12649. } else {
  12650. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  12651. _gl.generateMipmap( _gl.TEXTURE_2D );
  12652. _gl.bindTexture( _gl.TEXTURE_2D, null );
  12653. }
  12654. };
  12655. // Fallback filters for non-power-of-2 textures
  12656. function filterFallback ( f ) {
  12657. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  12658. return _gl.NEAREST;
  12659. }
  12660. return _gl.LINEAR;
  12661. };
  12662. // Map three.js constants to WebGL constants
  12663. function paramThreeToGL ( p ) {
  12664. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  12665. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  12666. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  12667. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  12668. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  12669. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  12670. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  12671. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  12672. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  12673. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  12674. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  12675. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  12676. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  12677. if ( p === THREE.ByteType ) return _gl.BYTE;
  12678. if ( p === THREE.ShortType ) return _gl.SHORT;
  12679. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  12680. if ( p === THREE.IntType ) return _gl.INT;
  12681. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  12682. if ( p === THREE.FloatType ) return _gl.FLOAT;
  12683. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  12684. if ( p === THREE.RGBFormat ) return _gl.RGB;
  12685. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  12686. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  12687. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  12688. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  12689. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  12690. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  12691. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  12692. if ( p === THREE.OneFactor ) return _gl.ONE;
  12693. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  12694. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  12695. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  12696. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  12697. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  12698. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  12699. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  12700. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  12701. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  12702. return 0;
  12703. };
  12704. // Allocations
  12705. function allocateBones ( object ) {
  12706. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  12707. return 1024;
  12708. } else {
  12709. // default for when object is not specified
  12710. // ( for example when prebuilding shader
  12711. // to be used with multiple objects )
  12712. //
  12713. // - leave some extra space for other uniforms
  12714. // - limit here is ANGLE's 254 max uniform vectors
  12715. // (up to 54 should be safe)
  12716. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  12717. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  12718. var maxBones = nVertexMatrices;
  12719. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  12720. maxBones = Math.min( object.bones.length, maxBones );
  12721. if ( maxBones < object.bones.length ) {
  12722. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  12723. }
  12724. }
  12725. return maxBones;
  12726. }
  12727. };
  12728. function allocateLights ( lights ) {
  12729. var l, ll, light, dirLights, pointLights, spotLights, maxDirLights, maxPointLights, maxSpotLights;
  12730. dirLights = pointLights = spotLights = maxDirLights = maxPointLights = maxSpotLights = 0;
  12731. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12732. light = lights[ l ];
  12733. if ( light.onlyShadow ) continue;
  12734. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  12735. if ( light instanceof THREE.PointLight ) pointLights ++;
  12736. if ( light instanceof THREE.SpotLight ) spotLights ++;
  12737. }
  12738. if ( ( pointLights + spotLights + dirLights ) <= _maxLights ) {
  12739. maxDirLights = dirLights;
  12740. maxPointLights = pointLights;
  12741. maxSpotLights = spotLights;
  12742. } else {
  12743. maxDirLights = Math.ceil( _maxLights * dirLights / ( pointLights + dirLights ) );
  12744. maxPointLights = _maxLights - maxDirLights;
  12745. maxSpotLights = maxPointLights; // this is not really correct
  12746. }
  12747. return { 'directional' : maxDirLights, 'point' : maxPointLights, 'spot': maxSpotLights };
  12748. };
  12749. function allocateShadows ( lights ) {
  12750. var l, ll, light, maxShadows = 0;
  12751. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  12752. light = lights[ l ];
  12753. if ( ! light.castShadow ) continue;
  12754. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  12755. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  12756. }
  12757. return maxShadows;
  12758. };
  12759. // Initialization
  12760. function initGL () {
  12761. try {
  12762. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  12763. throw 'Error creating WebGL context.';
  12764. }
  12765. } catch ( error ) {
  12766. console.error( error );
  12767. }
  12768. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  12769. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  12770. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  12771. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  12772. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  12773. if ( ! _glExtensionTextureFloat ) {
  12774. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  12775. }
  12776. if ( ! _glExtensionStandardDerivatives ) {
  12777. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  12778. }
  12779. if ( ! _glExtensionTextureFilterAnisotropic ) {
  12780. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  12781. }
  12782. };
  12783. function setDefaultGLState () {
  12784. _gl.clearColor( 0, 0, 0, 1 );
  12785. _gl.clearDepth( 1 );
  12786. _gl.clearStencil( 0 );
  12787. _gl.enable( _gl.DEPTH_TEST );
  12788. _gl.depthFunc( _gl.LEQUAL );
  12789. _gl.frontFace( _gl.CCW );
  12790. _gl.cullFace( _gl.BACK );
  12791. _gl.enable( _gl.CULL_FACE );
  12792. _gl.enable( _gl.BLEND );
  12793. _gl.blendEquation( _gl.FUNC_ADD );
  12794. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  12795. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12796. };
  12797. // default plugins (order is important)
  12798. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  12799. this.addPrePlugin( this.shadowMapPlugin );
  12800. this.addPostPlugin( new THREE.SpritePlugin() );
  12801. this.addPostPlugin( new THREE.LensFlarePlugin() );
  12802. };
  12803. /**
  12804. * @author szimek / https://github.com/szimek/
  12805. * @author alteredq / http://alteredqualia.com/
  12806. */
  12807. THREE.WebGLRenderTarget = function ( width, height, options ) {
  12808. this.width = width;
  12809. this.height = height;
  12810. options = options || {};
  12811. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  12812. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  12813. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  12814. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  12815. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  12816. this.offset = new THREE.Vector2( 0, 0 );
  12817. this.repeat = new THREE.Vector2( 1, 1 );
  12818. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  12819. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  12820. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  12821. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  12822. this.generateMipmaps = true;
  12823. };
  12824. THREE.WebGLRenderTarget.prototype.clone = function() {
  12825. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  12826. tmp.wrapS = this.wrapS;
  12827. tmp.wrapT = this.wrapT;
  12828. tmp.magFilter = this.magFilter;
  12829. tmp.anisotropy = this.anisotropy;
  12830. tmp.minFilter = this.minFilter;
  12831. tmp.offset.copy( this.offset );
  12832. tmp.repeat.copy( this.repeat );
  12833. tmp.format = this.format;
  12834. tmp.type = this.type;
  12835. tmp.depthBuffer = this.depthBuffer;
  12836. tmp.stencilBuffer = this.stencilBuffer;
  12837. tmp.generateMipmaps = this.generateMipmaps;
  12838. return tmp;
  12839. };
  12840. /**
  12841. * @author alteredq / http://alteredqualia.com
  12842. */
  12843. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  12844. THREE.WebGLRenderTarget.call( this, width, height, options );
  12845. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  12846. };
  12847. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  12848. /**
  12849. * @author mrdoob / http://mrdoob.com/
  12850. */
  12851. THREE.RenderableVertex = function () {
  12852. this.positionWorld = new THREE.Vector3();
  12853. this.positionScreen = new THREE.Vector4();
  12854. this.visible = true;
  12855. };
  12856. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  12857. this.positionWorld.copy( vertex.positionWorld );
  12858. this.positionScreen.copy( vertex.positionScreen );
  12859. }
  12860. /**
  12861. * @author mrdoob / http://mrdoob.com/
  12862. */
  12863. THREE.RenderableFace3 = function () {
  12864. this.v1 = new THREE.RenderableVertex();
  12865. this.v2 = new THREE.RenderableVertex();
  12866. this.v3 = new THREE.RenderableVertex();
  12867. this.centroidWorld = new THREE.Vector3();
  12868. this.centroidScreen = new THREE.Vector3();
  12869. this.normalWorld = new THREE.Vector3();
  12870. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  12871. this.vertexNormalsLength = 0;
  12872. this.material = null;
  12873. this.uvs = [[]];
  12874. this.z = null;
  12875. };
  12876. /**
  12877. * @author mrdoob / http://mrdoob.com/
  12878. */
  12879. THREE.RenderableFace4 = function () {
  12880. this.v1 = new THREE.RenderableVertex();
  12881. this.v2 = new THREE.RenderableVertex();
  12882. this.v3 = new THREE.RenderableVertex();
  12883. this.v4 = new THREE.RenderableVertex();
  12884. this.centroidWorld = new THREE.Vector3();
  12885. this.centroidScreen = new THREE.Vector3();
  12886. this.normalWorld = new THREE.Vector3();
  12887. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  12888. this.vertexNormalsLength = 0;
  12889. this.material = null;
  12890. this.uvs = [[]];
  12891. this.z = null;
  12892. };
  12893. /**
  12894. * @author mrdoob / http://mrdoob.com/
  12895. */
  12896. THREE.RenderableObject = function () {
  12897. this.object = null;
  12898. this.z = null;
  12899. };
  12900. /**
  12901. * @author mrdoob / http://mrdoob.com/
  12902. */
  12903. THREE.RenderableParticle = function () {
  12904. this.object = null;
  12905. this.x = null;
  12906. this.y = null;
  12907. this.z = null;
  12908. this.rotation = null;
  12909. this.scale = new THREE.Vector2();
  12910. this.material = null;
  12911. };
  12912. /**
  12913. * @author mrdoob / http://mrdoob.com/
  12914. */
  12915. THREE.RenderableLine = function () {
  12916. this.z = null;
  12917. this.v1 = new THREE.RenderableVertex();
  12918. this.v2 = new THREE.RenderableVertex();
  12919. this.material = null;
  12920. };
  12921. /**
  12922. * @author alteredq / http://alteredqualia.com/
  12923. */
  12924. THREE.ColorUtils = {
  12925. adjustHSV : function ( color, h, s, v ) {
  12926. var hsv = THREE.ColorUtils.__hsv;
  12927. THREE.ColorUtils.rgbToHsv( color, hsv );
  12928. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  12929. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  12930. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  12931. color.setHSV( hsv.h, hsv.s, hsv.v );
  12932. },
  12933. // based on MochiKit implementation by Bob Ippolito
  12934. rgbToHsv : function ( color, hsv ) {
  12935. var r = color.r;
  12936. var g = color.g;
  12937. var b = color.b;
  12938. var max = Math.max( Math.max( r, g ), b );
  12939. var min = Math.min( Math.min( r, g ), b );
  12940. var hue;
  12941. var saturation;
  12942. var value = max;
  12943. if ( min === max ) {
  12944. hue = 0;
  12945. saturation = 0;
  12946. } else {
  12947. var delta = ( max - min );
  12948. saturation = delta / max;
  12949. if ( r === max ) {
  12950. hue = ( g - b ) / delta;
  12951. } else if ( g === max ) {
  12952. hue = 2 + ( ( b - r ) / delta );
  12953. } else {
  12954. hue = 4 + ( ( r - g ) / delta );
  12955. }
  12956. hue /= 6;
  12957. if ( hue < 0 ) {
  12958. hue += 1;
  12959. }
  12960. if ( hue > 1 ) {
  12961. hue -= 1;
  12962. }
  12963. }
  12964. if ( hsv === undefined ) {
  12965. hsv = { h: 0, s: 0, v: 0 };
  12966. }
  12967. hsv.h = hue;
  12968. hsv.s = saturation;
  12969. hsv.v = value;
  12970. return hsv;
  12971. }
  12972. };
  12973. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  12974. * @author mrdoob / http://mrdoob.com/
  12975. * @author alteredq / http://alteredqualia.com/
  12976. */
  12977. THREE.GeometryUtils = {
  12978. // Merge two geometries or geometry and geometry from object (using object's transform)
  12979. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  12980. var matrix, matrixRotation,
  12981. vertexOffset = geometry1.vertices.length,
  12982. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  12983. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  12984. vertices1 = geometry1.vertices,
  12985. vertices2 = geometry2.vertices,
  12986. faces1 = geometry1.faces,
  12987. faces2 = geometry2.faces,
  12988. uvs1 = geometry1.faceVertexUvs[ 0 ],
  12989. uvs2 = geometry2.faceVertexUvs[ 0 ];
  12990. var geo1MaterialsMap = {};
  12991. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  12992. var id = geometry1.materials[ i ].id;
  12993. geo1MaterialsMap[ id ] = i;
  12994. }
  12995. if ( object2 instanceof THREE.Mesh ) {
  12996. object2.matrixAutoUpdate && object2.updateMatrix();
  12997. matrix = object2.matrix;
  12998. matrixRotation = new THREE.Matrix4();
  12999. matrixRotation.extractRotation( matrix, object2.scale );
  13000. }
  13001. // vertices
  13002. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  13003. var vertex = vertices2[ i ];
  13004. var vertexCopy = vertex.clone();
  13005. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  13006. vertices1.push( vertexCopy );
  13007. }
  13008. // faces
  13009. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  13010. var face = faces2[ i ], faceCopy, normal, color,
  13011. faceVertexNormals = face.vertexNormals,
  13012. faceVertexColors = face.vertexColors;
  13013. if ( face instanceof THREE.Face3 ) {
  13014. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  13015. } else if ( face instanceof THREE.Face4 ) {
  13016. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  13017. }
  13018. faceCopy.normal.copy( face.normal );
  13019. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  13020. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  13021. normal = faceVertexNormals[ j ].clone();
  13022. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  13023. faceCopy.vertexNormals.push( normal );
  13024. }
  13025. faceCopy.color.copy( face.color );
  13026. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  13027. color = faceVertexColors[ j ];
  13028. faceCopy.vertexColors.push( color.clone() );
  13029. }
  13030. if ( face.materialIndex !== undefined ) {
  13031. var material2 = geometry2.materials[ face.materialIndex ];
  13032. var materialId2 = material2.id;
  13033. var materialIndex = geo1MaterialsMap[ materialId2 ];
  13034. if ( materialIndex === undefined ) {
  13035. materialIndex = geometry1.materials.length;
  13036. geo1MaterialsMap[ materialId2 ] = materialIndex;
  13037. geometry1.materials.push( material2 );
  13038. }
  13039. faceCopy.materialIndex = materialIndex;
  13040. }
  13041. faceCopy.centroid.copy( face.centroid );
  13042. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  13043. faces1.push( faceCopy );
  13044. }
  13045. // uvs
  13046. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  13047. var uv = uvs2[ i ], uvCopy = [];
  13048. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13049. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13050. }
  13051. uvs1.push( uvCopy );
  13052. }
  13053. },
  13054. clone: function ( geometry ) {
  13055. var cloneGeo = new THREE.Geometry();
  13056. var i, il;
  13057. var vertices = geometry.vertices,
  13058. faces = geometry.faces,
  13059. uvs = geometry.faceVertexUvs[ 0 ];
  13060. // materials
  13061. if ( geometry.materials ) {
  13062. cloneGeo.materials = geometry.materials.slice();
  13063. }
  13064. // vertices
  13065. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  13066. var vertex = vertices[ i ];
  13067. cloneGeo.vertices.push( vertex.clone() );
  13068. }
  13069. // faces
  13070. for ( i = 0, il = faces.length; i < il; i ++ ) {
  13071. var face = faces[ i ];
  13072. cloneGeo.faces.push( face.clone() );
  13073. }
  13074. // uvs
  13075. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  13076. var uv = uvs[ i ], uvCopy = [];
  13077. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13078. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13079. }
  13080. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  13081. }
  13082. return cloneGeo;
  13083. },
  13084. // Get random point in triangle (via barycentric coordinates)
  13085. // (uniform distribution)
  13086. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  13087. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  13088. var a, b, c,
  13089. point = new THREE.Vector3(),
  13090. tmp = THREE.GeometryUtils.__v1;
  13091. a = THREE.GeometryUtils.random();
  13092. b = THREE.GeometryUtils.random();
  13093. if ( ( a + b ) > 1 ) {
  13094. a = 1 - a;
  13095. b = 1 - b;
  13096. }
  13097. c = 1 - a - b;
  13098. point.copy( vectorA );
  13099. point.multiplyScalar( a );
  13100. tmp.copy( vectorB );
  13101. tmp.multiplyScalar( b );
  13102. point.addSelf( tmp );
  13103. tmp.copy( vectorC );
  13104. tmp.multiplyScalar( c );
  13105. point.addSelf( tmp );
  13106. return point;
  13107. },
  13108. // Get random point in face (triangle / quad)
  13109. // (uniform distribution)
  13110. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  13111. var vA, vB, vC, vD;
  13112. if ( face instanceof THREE.Face3 ) {
  13113. vA = geometry.vertices[ face.a ];
  13114. vB = geometry.vertices[ face.b ];
  13115. vC = geometry.vertices[ face.c ];
  13116. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  13117. } else if ( face instanceof THREE.Face4 ) {
  13118. vA = geometry.vertices[ face.a ];
  13119. vB = geometry.vertices[ face.b ];
  13120. vC = geometry.vertices[ face.c ];
  13121. vD = geometry.vertices[ face.d ];
  13122. var area1, area2;
  13123. if ( useCachedAreas ) {
  13124. if ( face._area1 && face._area2 ) {
  13125. area1 = face._area1;
  13126. area2 = face._area2;
  13127. } else {
  13128. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13129. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13130. face._area1 = area1;
  13131. face._area2 = area2;
  13132. }
  13133. } else {
  13134. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  13135. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13136. }
  13137. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  13138. if ( r < area1 ) {
  13139. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  13140. } else {
  13141. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  13142. }
  13143. }
  13144. },
  13145. // Get uniformly distributed random points in mesh
  13146. // - create array with cumulative sums of face areas
  13147. // - pick random number from 0 to total area
  13148. // - find corresponding place in area array by binary search
  13149. // - get random point in face
  13150. randomPointsInGeometry: function ( geometry, n ) {
  13151. var face, i,
  13152. faces = geometry.faces,
  13153. vertices = geometry.vertices,
  13154. il = faces.length,
  13155. totalArea = 0,
  13156. cumulativeAreas = [],
  13157. vA, vB, vC, vD;
  13158. // precompute face areas
  13159. for ( i = 0; i < il; i ++ ) {
  13160. face = faces[ i ];
  13161. if ( face instanceof THREE.Face3 ) {
  13162. vA = vertices[ face.a ];
  13163. vB = vertices[ face.b ];
  13164. vC = vertices[ face.c ];
  13165. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  13166. } else if ( face instanceof THREE.Face4 ) {
  13167. vA = vertices[ face.a ];
  13168. vB = vertices[ face.b ];
  13169. vC = vertices[ face.c ];
  13170. vD = vertices[ face.d ];
  13171. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13172. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13173. face._area = face._area1 + face._area2;
  13174. }
  13175. totalArea += face._area;
  13176. cumulativeAreas[ i ] = totalArea;
  13177. }
  13178. // binary search cumulative areas array
  13179. function binarySearchIndices( value ) {
  13180. function binarySearch( start, end ) {
  13181. // return closest larger index
  13182. // if exact number is not found
  13183. if ( end < start )
  13184. return start;
  13185. var mid = start + Math.floor( ( end - start ) / 2 );
  13186. if ( cumulativeAreas[ mid ] > value ) {
  13187. return binarySearch( start, mid - 1 );
  13188. } else if ( cumulativeAreas[ mid ] < value ) {
  13189. return binarySearch( mid + 1, end );
  13190. } else {
  13191. return mid;
  13192. }
  13193. }
  13194. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  13195. return result;
  13196. }
  13197. // pick random face weighted by face area
  13198. var r, index,
  13199. result = [];
  13200. var stats = {};
  13201. for ( i = 0; i < n; i ++ ) {
  13202. r = THREE.GeometryUtils.random() * totalArea;
  13203. index = binarySearchIndices( r );
  13204. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  13205. if ( ! stats[ index ] ) {
  13206. stats[ index ] = 1;
  13207. } else {
  13208. stats[ index ] += 1;
  13209. }
  13210. }
  13211. return result;
  13212. },
  13213. // Get triangle area (by Heron's formula)
  13214. // http://en.wikipedia.org/wiki/Heron%27s_formula
  13215. triangleArea: function ( vectorA, vectorB, vectorC ) {
  13216. var s, a, b, c,
  13217. tmp = THREE.GeometryUtils.__v1;
  13218. tmp.sub( vectorA, vectorB );
  13219. a = tmp.length();
  13220. tmp.sub( vectorA, vectorC );
  13221. b = tmp.length();
  13222. tmp.sub( vectorB, vectorC );
  13223. c = tmp.length();
  13224. s = 0.5 * ( a + b + c );
  13225. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  13226. },
  13227. // Center geometry so that 0,0,0 is in center of bounding box
  13228. center: function ( geometry ) {
  13229. geometry.computeBoundingBox();
  13230. var bb = geometry.boundingBox;
  13231. var offset = new THREE.Vector3();
  13232. offset.add( bb.min, bb.max );
  13233. offset.multiplyScalar( -0.5 );
  13234. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  13235. geometry.computeBoundingBox();
  13236. return offset;
  13237. },
  13238. // Normalize UVs to be from <0,1>
  13239. // (for now just the first set of UVs)
  13240. normalizeUVs: function ( geometry ) {
  13241. var uvSet = geometry.faceVertexUvs[ 0 ];
  13242. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  13243. var uvs = uvSet[ i ];
  13244. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  13245. // texture repeat
  13246. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  13247. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  13248. }
  13249. }
  13250. },
  13251. triangulateQuads: function ( geometry ) {
  13252. var i, il, j, jl;
  13253. var faces = [];
  13254. var faceUvs = [];
  13255. var faceVertexUvs = [];
  13256. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  13257. faceUvs[ i ] = [];
  13258. }
  13259. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13260. faceVertexUvs[ i ] = [];
  13261. }
  13262. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13263. var face = geometry.faces[ i ];
  13264. if ( face instanceof THREE.Face4 ) {
  13265. var a = face.a;
  13266. var b = face.b;
  13267. var c = face.c;
  13268. var d = face.d;
  13269. var triA = new THREE.Face3();
  13270. var triB = new THREE.Face3();
  13271. triA.color.copy( face.color );
  13272. triB.color.copy( face.color );
  13273. triA.materialIndex = face.materialIndex;
  13274. triB.materialIndex = face.materialIndex;
  13275. triA.a = a;
  13276. triA.b = b;
  13277. triA.c = d;
  13278. triB.a = b;
  13279. triB.b = c;
  13280. triB.c = d;
  13281. if ( face.vertexColors.length === 4 ) {
  13282. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  13283. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  13284. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13285. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  13286. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  13287. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13288. }
  13289. faces.push( triA, triB );
  13290. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13291. if ( geometry.faceVertexUvs[ j ].length ) {
  13292. var uvs = geometry.faceVertexUvs[ j ][ i ];
  13293. var uvA = uvs[ 0 ];
  13294. var uvB = uvs[ 1 ];
  13295. var uvC = uvs[ 2 ];
  13296. var uvD = uvs[ 3 ];
  13297. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  13298. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  13299. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  13300. }
  13301. }
  13302. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13303. if ( geometry.faceUvs[ j ].length ) {
  13304. var faceUv = geometry.faceUvs[ j ][ i ];
  13305. faceUvs[ j ].push( faceUv, faceUv );
  13306. }
  13307. }
  13308. } else {
  13309. faces.push( face );
  13310. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13311. faceUvs[ j ].push( geometry.faceUvs[ j ] );
  13312. }
  13313. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13314. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  13315. }
  13316. }
  13317. }
  13318. geometry.faces = faces;
  13319. geometry.faceUvs = faceUvs;
  13320. geometry.faceVertexUvs = faceVertexUvs;
  13321. geometry.computeCentroids();
  13322. geometry.computeFaceNormals();
  13323. geometry.computeVertexNormals();
  13324. if ( geometry.hasTangents ) geometry.computeTangents();
  13325. },
  13326. // Make all faces use unique vertices
  13327. // so that each face can be separated from others
  13328. explode: function( geometry ) {
  13329. var vertices = [];
  13330. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13331. var n = vertices.length;
  13332. var face = geometry.faces[ i ];
  13333. if ( face instanceof THREE.Face4 ) {
  13334. var a = face.a;
  13335. var b = face.b;
  13336. var c = face.c;
  13337. var d = face.d;
  13338. var va = geometry.vertices[ a ];
  13339. var vb = geometry.vertices[ b ];
  13340. var vc = geometry.vertices[ c ];
  13341. var vd = geometry.vertices[ d ];
  13342. vertices.push( va.clone() );
  13343. vertices.push( vb.clone() );
  13344. vertices.push( vc.clone() );
  13345. vertices.push( vd.clone() );
  13346. face.a = n;
  13347. face.b = n + 1;
  13348. face.c = n + 2;
  13349. face.d = n + 3;
  13350. } else {
  13351. var a = face.a;
  13352. var b = face.b;
  13353. var c = face.c;
  13354. var va = geometry.vertices[ a ];
  13355. var vb = geometry.vertices[ b ];
  13356. var vc = geometry.vertices[ c ];
  13357. vertices.push( va.clone() );
  13358. vertices.push( vb.clone() );
  13359. vertices.push( vc.clone() );
  13360. face.a = n;
  13361. face.b = n + 1;
  13362. face.c = n + 2;
  13363. }
  13364. }
  13365. geometry.vertices = vertices;
  13366. delete geometry.__tmpVertices;
  13367. },
  13368. // Break faces with edges longer than maxEdgeLength
  13369. // - not recursive
  13370. tessellate: function ( geometry, maxEdgeLength ) {
  13371. var i, il, face,
  13372. a, b, c, d,
  13373. va, vb, vc, vd,
  13374. dab, dbc, dac, dcd, dad,
  13375. m, m1, m2,
  13376. vm, vm1, vm2,
  13377. vnm, vnm1, vnm2,
  13378. vcm, vcm1, vcm2,
  13379. triA, triB,
  13380. quadA, quadB,
  13381. edge;
  13382. var faces = [];
  13383. var faceVertexUvs = [];
  13384. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13385. faceVertexUvs[ i ] = [];
  13386. }
  13387. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13388. face = geometry.faces[ i ];
  13389. if ( face instanceof THREE.Face3 ) {
  13390. a = face.a;
  13391. b = face.b;
  13392. c = face.c;
  13393. va = geometry.vertices[ a ];
  13394. vb = geometry.vertices[ b ];
  13395. vc = geometry.vertices[ c ];
  13396. dab = va.distanceTo( vb );
  13397. dbc = vb.distanceTo( vc );
  13398. dac = va.distanceTo( vc );
  13399. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  13400. m = geometry.vertices.length;
  13401. triA = face.clone();
  13402. triB = face.clone();
  13403. if ( dab >= dbc && dab >= dac ) {
  13404. vm = va.clone();
  13405. vm.lerpSelf( vb, 0.5 );
  13406. triA.a = a;
  13407. triA.b = m;
  13408. triA.c = c;
  13409. triB.a = m;
  13410. triB.b = b;
  13411. triB.c = c;
  13412. if ( face.vertexNormals.length === 3 ) {
  13413. vnm = face.vertexNormals[ 0 ].clone();
  13414. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  13415. triA.vertexNormals[ 1 ].copy( vnm );
  13416. triB.vertexNormals[ 0 ].copy( vnm );
  13417. }
  13418. if ( face.vertexColors.length === 3 ) {
  13419. vcm = face.vertexColors[ 0 ].clone();
  13420. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  13421. triA.vertexColors[ 1 ].copy( vcm );
  13422. triB.vertexColors[ 0 ].copy( vcm );
  13423. }
  13424. edge = 0;
  13425. } else if ( dbc >= dab && dbc >= dac ) {
  13426. vm = vb.clone();
  13427. vm.lerpSelf( vc, 0.5 );
  13428. triA.a = a;
  13429. triA.b = b;
  13430. triA.c = m;
  13431. triB.a = m;
  13432. triB.b = c;
  13433. triB.c = a;
  13434. if ( face.vertexNormals.length === 3 ) {
  13435. vnm = face.vertexNormals[ 1 ].clone();
  13436. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  13437. triA.vertexNormals[ 2 ].copy( vnm );
  13438. triB.vertexNormals[ 0 ].copy( vnm );
  13439. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  13440. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  13441. }
  13442. if ( face.vertexColors.length === 3 ) {
  13443. vcm = face.vertexColors[ 1 ].clone();
  13444. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  13445. triA.vertexColors[ 2 ].copy( vcm );
  13446. triB.vertexColors[ 0 ].copy( vcm );
  13447. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  13448. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  13449. }
  13450. edge = 1;
  13451. } else {
  13452. vm = va.clone();
  13453. vm.lerpSelf( vc, 0.5 );
  13454. triA.a = a;
  13455. triA.b = b;
  13456. triA.c = m;
  13457. triB.a = m;
  13458. triB.b = b;
  13459. triB.c = c;
  13460. if ( face.vertexNormals.length === 3 ) {
  13461. vnm = face.vertexNormals[ 0 ].clone();
  13462. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  13463. triA.vertexNormals[ 2 ].copy( vnm );
  13464. triB.vertexNormals[ 0 ].copy( vnm );
  13465. }
  13466. if ( face.vertexColors.length === 3 ) {
  13467. vcm = face.vertexColors[ 0 ].clone();
  13468. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  13469. triA.vertexColors[ 2 ].copy( vcm );
  13470. triB.vertexColors[ 0 ].copy( vcm );
  13471. }
  13472. edge = 2;
  13473. }
  13474. faces.push( triA, triB );
  13475. geometry.vertices.push( vm );
  13476. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  13477. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13478. if ( geometry.faceVertexUvs[ j ].length ) {
  13479. uvs = geometry.faceVertexUvs[ j ][ i ];
  13480. uvA = uvs[ 0 ];
  13481. uvB = uvs[ 1 ];
  13482. uvC = uvs[ 2 ];
  13483. // AB
  13484. if ( edge === 0 ) {
  13485. uvM = uvA.clone();
  13486. uvM.lerpSelf( uvB, 0.5 );
  13487. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  13488. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  13489. // BC
  13490. } else if ( edge === 1 ) {
  13491. uvM = uvB.clone();
  13492. uvM.lerpSelf( uvC, 0.5 );
  13493. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  13494. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  13495. // AC
  13496. } else {
  13497. uvM = uvA.clone();
  13498. uvM.lerpSelf( uvC, 0.5 );
  13499. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  13500. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  13501. }
  13502. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  13503. }
  13504. }
  13505. } else {
  13506. faces.push( face );
  13507. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13508. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  13509. }
  13510. }
  13511. } else {
  13512. a = face.a;
  13513. b = face.b;
  13514. c = face.c;
  13515. d = face.d;
  13516. va = geometry.vertices[ a ];
  13517. vb = geometry.vertices[ b ];
  13518. vc = geometry.vertices[ c ];
  13519. vd = geometry.vertices[ d ];
  13520. dab = va.distanceTo( vb );
  13521. dbc = vb.distanceTo( vc );
  13522. dcd = vc.distanceTo( vd );
  13523. dad = va.distanceTo( vd );
  13524. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  13525. m1 = geometry.vertices.length;
  13526. m2 = geometry.vertices.length + 1;
  13527. quadA = face.clone();
  13528. quadB = face.clone();
  13529. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  13530. vm1 = va.clone();
  13531. vm1.lerpSelf( vb, 0.5 );
  13532. vm2 = vc.clone();
  13533. vm2.lerpSelf( vd, 0.5 );
  13534. quadA.a = a;
  13535. quadA.b = m1;
  13536. quadA.c = m2;
  13537. quadA.d = d;
  13538. quadB.a = m1;
  13539. quadB.b = b;
  13540. quadB.c = c;
  13541. quadB.d = m2;
  13542. if ( face.vertexNormals.length === 4 ) {
  13543. vnm1 = face.vertexNormals[ 0 ].clone();
  13544. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  13545. vnm2 = face.vertexNormals[ 2 ].clone();
  13546. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  13547. quadA.vertexNormals[ 1 ].copy( vnm1 );
  13548. quadA.vertexNormals[ 2 ].copy( vnm2 );
  13549. quadB.vertexNormals[ 0 ].copy( vnm1 );
  13550. quadB.vertexNormals[ 3 ].copy( vnm2 );
  13551. }
  13552. if ( face.vertexColors.length === 4 ) {
  13553. vcm1 = face.vertexColors[ 0 ].clone();
  13554. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  13555. vcm2 = face.vertexColors[ 2 ].clone();
  13556. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  13557. quadA.vertexColors[ 1 ].copy( vcm1 );
  13558. quadA.vertexColors[ 2 ].copy( vcm2 );
  13559. quadB.vertexColors[ 0 ].copy( vcm1 );
  13560. quadB.vertexColors[ 3 ].copy( vcm2 );
  13561. }
  13562. edge = 0;
  13563. } else {
  13564. vm1 = vb.clone();
  13565. vm1.lerpSelf( vc, 0.5 );
  13566. vm2 = vd.clone();
  13567. vm2.lerpSelf( va, 0.5 );
  13568. quadA.a = a;
  13569. quadA.b = b;
  13570. quadA.c = m1;
  13571. quadA.d = m2;
  13572. quadB.a = m2;
  13573. quadB.b = m1;
  13574. quadB.c = c;
  13575. quadB.d = d;
  13576. if ( face.vertexNormals.length === 4 ) {
  13577. vnm1 = face.vertexNormals[ 1 ].clone();
  13578. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  13579. vnm2 = face.vertexNormals[ 3 ].clone();
  13580. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  13581. quadA.vertexNormals[ 2 ].copy( vnm1 );
  13582. quadA.vertexNormals[ 3 ].copy( vnm2 );
  13583. quadB.vertexNormals[ 0 ].copy( vnm2 );
  13584. quadB.vertexNormals[ 1 ].copy( vnm1 );
  13585. }
  13586. if ( face.vertexColors.length === 4 ) {
  13587. vcm1 = face.vertexColors[ 1 ].clone();
  13588. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  13589. vcm2 = face.vertexColors[ 3 ].clone();
  13590. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  13591. quadA.vertexColors[ 2 ].copy( vcm1 );
  13592. quadA.vertexColors[ 3 ].copy( vcm2 );
  13593. quadB.vertexColors[ 0 ].copy( vcm2 );
  13594. quadB.vertexColors[ 1 ].copy( vcm1 );
  13595. }
  13596. edge = 1;
  13597. }
  13598. faces.push( quadA, quadB );
  13599. geometry.vertices.push( vm1, vm2 );
  13600. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  13601. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13602. if ( geometry.faceVertexUvs[ j ].length ) {
  13603. uvs = geometry.faceVertexUvs[ j ][ i ];
  13604. uvA = uvs[ 0 ];
  13605. uvB = uvs[ 1 ];
  13606. uvC = uvs[ 2 ];
  13607. uvD = uvs[ 3 ];
  13608. // AB + CD
  13609. if ( edge === 0 ) {
  13610. uvM1 = uvA.clone();
  13611. uvM1.lerpSelf( uvB, 0.5 );
  13612. uvM2 = uvC.clone();
  13613. uvM2.lerpSelf( uvD, 0.5 );
  13614. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  13615. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  13616. // BC + AD
  13617. } else {
  13618. uvM1 = uvB.clone();
  13619. uvM1.lerpSelf( uvC, 0.5 );
  13620. uvM2 = uvD.clone();
  13621. uvM2.lerpSelf( uvA, 0.5 );
  13622. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  13623. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  13624. }
  13625. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  13626. }
  13627. }
  13628. } else {
  13629. faces.push( face );
  13630. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13631. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  13632. }
  13633. }
  13634. }
  13635. }
  13636. geometry.faces = faces;
  13637. geometry.faceVertexUvs = faceVertexUvs;
  13638. }
  13639. };
  13640. THREE.GeometryUtils.random = THREE.Math.random16;
  13641. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  13642. /**
  13643. * @author alteredq / http://alteredqualia.com/
  13644. * @author mrdoob / http://mrdoob.com/
  13645. */
  13646. THREE.ImageUtils = {
  13647. crossOrigin: 'anonymous',
  13648. loadTexture: function ( url, mapping, onLoad, onError ) {
  13649. var image = new Image();
  13650. var texture = new THREE.Texture( image, mapping );
  13651. var loader = new THREE.ImageLoader();
  13652. loader.addEventListener( 'load', function ( event ) {
  13653. texture.image = event.content;
  13654. texture.needsUpdate = true;
  13655. if ( onLoad ) onLoad( texture );
  13656. } );
  13657. loader.addEventListener( 'error', function ( event ) {
  13658. if ( onError ) onError( event.message );
  13659. } );
  13660. loader.crossOrigin = this.crossOrigin;
  13661. loader.load( url, image );
  13662. return texture;
  13663. },
  13664. loadTextureCube: function ( array, mapping, onLoad ) {
  13665. var i, l, images = [];
  13666. var texture = new THREE.Texture( images, mapping );
  13667. texture.flipY = false;
  13668. images.loadCount = 0;
  13669. for ( i = 0, l = array.length; i < l; ++ i ) {
  13670. images[ i ] = new Image();
  13671. images[ i ].onload = function () {
  13672. images.loadCount += 1;
  13673. if ( images.loadCount === 6 ) {
  13674. texture.needsUpdate = true;
  13675. if ( onLoad ) onLoad();
  13676. }
  13677. };
  13678. images[ i ].crossOrigin = this.crossOrigin;
  13679. images[ i ].src = array[ i ];
  13680. }
  13681. return texture;
  13682. },
  13683. getNormalMap: function ( image, depth ) {
  13684. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  13685. var cross = function ( a, b ) {
  13686. 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 ] ];
  13687. }
  13688. var subtract = function ( a, b ) {
  13689. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  13690. }
  13691. var normalize = function ( a ) {
  13692. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  13693. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  13694. }
  13695. depth = depth | 1;
  13696. var width = image.width;
  13697. var height = image.height;
  13698. var canvas = document.createElement( 'canvas' );
  13699. canvas.width = width;
  13700. canvas.height = height;
  13701. var context = canvas.getContext( '2d' );
  13702. context.drawImage( image, 0, 0 );
  13703. var data = context.getImageData( 0, 0, width, height ).data;
  13704. var imageData = context.createImageData( width, height );
  13705. var output = imageData.data;
  13706. for ( var x = 0; x < width; x ++ ) {
  13707. for ( var y = 0; y < height; y ++ ) {
  13708. var ly = y - 1 < 0 ? 0 : y - 1;
  13709. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  13710. var lx = x - 1 < 0 ? 0 : x - 1;
  13711. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  13712. var points = [];
  13713. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  13714. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  13715. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  13716. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  13717. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  13718. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  13719. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  13720. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  13721. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  13722. var normals = [];
  13723. var num_points = points.length;
  13724. for ( var i = 0; i < num_points; i ++ ) {
  13725. var v1 = points[ i ];
  13726. var v2 = points[ ( i + 1 ) % num_points ];
  13727. v1 = subtract( v1, origin );
  13728. v2 = subtract( v2, origin );
  13729. normals.push( normalize( cross( v1, v2 ) ) );
  13730. }
  13731. var normal = [ 0, 0, 0 ];
  13732. for ( var i = 0; i < normals.length; i ++ ) {
  13733. normal[ 0 ] += normals[ i ][ 0 ];
  13734. normal[ 1 ] += normals[ i ][ 1 ];
  13735. normal[ 2 ] += normals[ i ][ 2 ];
  13736. }
  13737. normal[ 0 ] /= normals.length;
  13738. normal[ 1 ] /= normals.length;
  13739. normal[ 2 ] /= normals.length;
  13740. var idx = ( y * width + x ) * 4;
  13741. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  13742. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  13743. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  13744. output[ idx + 3 ] = 255;
  13745. }
  13746. }
  13747. context.putImageData( imageData, 0, 0 );
  13748. return canvas;
  13749. },
  13750. generateDataTexture: function ( width, height, color ) {
  13751. var size = width * height;
  13752. var data = new Uint8Array( 3 * size );
  13753. var r = Math.floor( color.r * 255 );
  13754. var g = Math.floor( color.g * 255 );
  13755. var b = Math.floor( color.b * 255 );
  13756. for ( var i = 0; i < size; i ++ ) {
  13757. data[ i * 3 ] = r;
  13758. data[ i * 3 + 1 ] = g;
  13759. data[ i * 3 + 2 ] = b;
  13760. }
  13761. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  13762. texture.needsUpdate = true;
  13763. return texture;
  13764. }
  13765. };
  13766. /**
  13767. * @author alteredq / http://alteredqualia.com/
  13768. */
  13769. THREE.SceneUtils = {
  13770. showHierarchy : function ( root, visible ) {
  13771. THREE.SceneUtils.traverseHierarchy( root, function( node ) { node.visible = visible; } );
  13772. },
  13773. traverseHierarchy : function ( root, callback ) {
  13774. var n, i, l = root.children.length;
  13775. for ( i = 0; i < l; i ++ ) {
  13776. n = root.children[ i ];
  13777. callback( n );
  13778. THREE.SceneUtils.traverseHierarchy( n, callback );
  13779. }
  13780. },
  13781. createMultiMaterialObject : function ( geometry, materials ) {
  13782. var i, il = materials.length,
  13783. group = new THREE.Object3D();
  13784. for ( i = 0; i < il; i ++ ) {
  13785. var object = new THREE.Mesh( geometry, materials[ i ] );
  13786. group.add( object );
  13787. }
  13788. return group;
  13789. },
  13790. cloneObject: function ( source ) {
  13791. var object;
  13792. // subclass specific properties
  13793. // (must process in order from more specific subclasses to more abstract classes)
  13794. if ( source instanceof THREE.MorphAnimMesh ) {
  13795. object = new THREE.MorphAnimMesh( source.geometry, source.material );
  13796. object.duration = source.duration;
  13797. object.mirroredLoop = source.mirroredLoop;
  13798. object.time = source.time;
  13799. object.lastKeyframe = source.lastKeyframe;
  13800. object.currentKeyframe = source.currentKeyframe;
  13801. object.direction = source.direction;
  13802. object.directionBackwards = source.directionBackwards;
  13803. } else if ( source instanceof THREE.SkinnedMesh ) {
  13804. object = new THREE.SkinnedMesh( source.geometry, source.material );
  13805. } else if ( source instanceof THREE.Mesh ) {
  13806. object = new THREE.Mesh( source.geometry, source.material );
  13807. } else if ( source instanceof THREE.Line ) {
  13808. object = new THREE.Line( source.geometry, source.material, source.type );
  13809. } else if ( source instanceof THREE.Ribbon ) {
  13810. object = new THREE.Ribbon( source.geometry, source.material );
  13811. } else if ( source instanceof THREE.ParticleSystem ) {
  13812. object = new THREE.ParticleSystem( source.geometry, source.material );
  13813. object.sortParticles = source.sortParticles;
  13814. } else if ( source instanceof THREE.Particle ) {
  13815. object = new THREE.Particle( source.material );
  13816. } else if ( source instanceof THREE.Sprite ) {
  13817. object = new THREE.Sprite( {} );
  13818. object.color.copy( source.color );
  13819. object.map = source.map;
  13820. object.blending = source.blending;
  13821. object.useScreenCoordinates = source.useScreenCoordinates;
  13822. object.mergeWith3D = source.mergeWith3D;
  13823. object.affectedByDistance = source.affectedByDistance;
  13824. object.scaleByViewport = source.scaleByViewport;
  13825. object.alignment = source.alignment;
  13826. object.rotation3d.copy( source.rotation3d );
  13827. object.rotation = source.rotation;
  13828. object.opacity = source.opacity;
  13829. object.uvOffset.copy( source.uvOffset );
  13830. object.uvScale.copy( source.uvScale);
  13831. } else if ( source instanceof THREE.LOD ) {
  13832. object = new THREE.LOD();
  13833. /*
  13834. } else if ( source instanceof THREE.MarchingCubes ) {
  13835. object = new THREE.MarchingCubes( source.resolution, source.material );
  13836. object.field.set( source.field );
  13837. object.isolation = source.isolation;
  13838. */
  13839. } else if ( source instanceof THREE.Object3D ) {
  13840. object = new THREE.Object3D();
  13841. }
  13842. // base class properties
  13843. object.name = source.name;
  13844. object.parent = source.parent;
  13845. object.up.copy( source.up );
  13846. object.position.copy( source.position );
  13847. // because of Sprite madness
  13848. if ( object.rotation instanceof THREE.Vector3 )
  13849. object.rotation.copy( source.rotation );
  13850. object.eulerOrder = source.eulerOrder;
  13851. object.scale.copy( source.scale );
  13852. object.dynamic = source.dynamic;
  13853. object.renderDepth = source.renderDepth;
  13854. object.rotationAutoUpdate = source.rotationAutoUpdate;
  13855. object.matrix.copy( source.matrix );
  13856. object.matrixWorld.copy( source.matrixWorld );
  13857. object.matrixRotationWorld.copy( source.matrixRotationWorld );
  13858. object.matrixAutoUpdate = source.matrixAutoUpdate;
  13859. object.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  13860. object.quaternion.copy( source.quaternion );
  13861. object.useQuaternion = source.useQuaternion;
  13862. object.boundRadius = source.boundRadius;
  13863. object.boundRadiusScale = source.boundRadiusScale;
  13864. object.visible = source.visible;
  13865. object.castShadow = source.castShadow;
  13866. object.receiveShadow = source.receiveShadow;
  13867. object.frustumCulled = source.frustumCulled;
  13868. // children
  13869. for ( var i = 0; i < source.children.length; i ++ ) {
  13870. var child = THREE.SceneUtils.cloneObject( source.children[ i ] );
  13871. object.children[ i ] = child;
  13872. child.parent = object;
  13873. }
  13874. // LODs need to be patched separately to use cloned children
  13875. if ( source instanceof THREE.LOD ) {
  13876. for ( var i = 0; i < source.LODs.length; i ++ ) {
  13877. var lod = source.LODs[ i ];
  13878. object.LODs[ i ] = { visibleAtDistance: lod.visibleAtDistance, object3D: object.children[ i ] };
  13879. }
  13880. }
  13881. return object;
  13882. },
  13883. detach : function ( child, parent, scene ) {
  13884. child.applyMatrix( parent.matrixWorld );
  13885. parent.remove( child );
  13886. scene.add( child );
  13887. },
  13888. attach: function ( child, scene, parent ) {
  13889. var matrixWorldInverse = new THREE.Matrix4();
  13890. matrixWorldInverse.getInverse( parent.matrixWorld );
  13891. child.applyMatrix( matrixWorldInverse );
  13892. scene.remove( child );
  13893. parent.add( child );
  13894. }
  13895. };
  13896. /**
  13897. * @author alteredq / http://alteredqualia.com/
  13898. * @author mrdoob / http://mrdoob.com/
  13899. *
  13900. * ShaderUtils currently contains:
  13901. *
  13902. * fresnel
  13903. * normal
  13904. * cube
  13905. *
  13906. */
  13907. if ( THREE.WebGLRenderer ) {
  13908. THREE.ShaderUtils = {
  13909. lib: {
  13910. /* -------------------------------------------------------------------------
  13911. // Fresnel shader
  13912. // - based on Nvidia Cg tutorial
  13913. ------------------------------------------------------------------------- */
  13914. 'fresnel': {
  13915. uniforms: {
  13916. "mRefractionRatio": { type: "f", value: 1.02 },
  13917. "mFresnelBias": { type: "f", value: 0.1 },
  13918. "mFresnelPower": { type: "f", value: 2.0 },
  13919. "mFresnelScale": { type: "f", value: 1.0 },
  13920. "tCube": { type: "t", value: 1, texture: null }
  13921. },
  13922. fragmentShader: [
  13923. "uniform samplerCube tCube;",
  13924. "varying vec3 vReflect;",
  13925. "varying vec3 vRefract[3];",
  13926. "varying float vReflectionFactor;",
  13927. "void main() {",
  13928. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  13929. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  13930. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  13931. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  13932. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  13933. "refractedColor.a = 1.0;",
  13934. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  13935. "}"
  13936. ].join("\n"),
  13937. vertexShader: [
  13938. "uniform float mRefractionRatio;",
  13939. "uniform float mFresnelBias;",
  13940. "uniform float mFresnelScale;",
  13941. "uniform float mFresnelPower;",
  13942. "varying vec3 vReflect;",
  13943. "varying vec3 vRefract[3];",
  13944. "varying float vReflectionFactor;",
  13945. "void main() {",
  13946. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  13947. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  13948. "vec3 nWorld = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  13949. "vec3 I = mPosition.xyz - cameraPosition;",
  13950. "vReflect = reflect( I, nWorld );",
  13951. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  13952. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  13953. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  13954. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  13955. "gl_Position = projectionMatrix * mvPosition;",
  13956. "}"
  13957. ].join("\n")
  13958. },
  13959. /* -------------------------------------------------------------------------
  13960. // Normal map shader
  13961. // - Blinn-Phong
  13962. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  13963. // - point and directional lights (use with "lights: true" material option)
  13964. ------------------------------------------------------------------------- */
  13965. 'normal' : {
  13966. uniforms: THREE.UniformsUtils.merge( [
  13967. THREE.UniformsLib[ "fog" ],
  13968. THREE.UniformsLib[ "lights" ],
  13969. THREE.UniformsLib[ "shadowmap" ],
  13970. {
  13971. "enableAO" : { type: "i", value: 0 },
  13972. "enableDiffuse" : { type: "i", value: 0 },
  13973. "enableSpecular" : { type: "i", value: 0 },
  13974. "enableReflection": { type: "i", value: 0 },
  13975. "enableDisplacement": { type: "i", value: 0 },
  13976. "tDiffuse" : { type: "t", value: 0, texture: null },
  13977. "tCube" : { type: "t", value: 1, texture: null },
  13978. "tNormal" : { type: "t", value: 2, texture: null },
  13979. "tSpecular" : { type: "t", value: 3, texture: null },
  13980. "tAO" : { type: "t", value: 4, texture: null },
  13981. "tDisplacement": { type: "t", value: 5, texture: null },
  13982. "uNormalScale": { type: "f", value: 1.0 },
  13983. "uDisplacementBias": { type: "f", value: 0.0 },
  13984. "uDisplacementScale": { type: "f", value: 1.0 },
  13985. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  13986. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  13987. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  13988. "uShininess": { type: "f", value: 30 },
  13989. "uOpacity": { type: "f", value: 1 },
  13990. "useRefract": { type: "i", value: 0 },
  13991. "uRefractionRatio": { type: "f", value: 0.98 },
  13992. "uReflectivity": { type: "f", value: 0.5 },
  13993. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  13994. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  13995. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  13996. }
  13997. ] ),
  13998. fragmentShader: [
  13999. "uniform vec3 uAmbientColor;",
  14000. "uniform vec3 uDiffuseColor;",
  14001. "uniform vec3 uSpecularColor;",
  14002. "uniform float uShininess;",
  14003. "uniform float uOpacity;",
  14004. "uniform bool enableDiffuse;",
  14005. "uniform bool enableSpecular;",
  14006. "uniform bool enableAO;",
  14007. "uniform bool enableReflection;",
  14008. "uniform sampler2D tDiffuse;",
  14009. "uniform sampler2D tNormal;",
  14010. "uniform sampler2D tSpecular;",
  14011. "uniform sampler2D tAO;",
  14012. "uniform samplerCube tCube;",
  14013. "uniform float uNormalScale;",
  14014. "uniform bool useRefract;",
  14015. "uniform float uRefractionRatio;",
  14016. "uniform float uReflectivity;",
  14017. "varying vec3 vTangent;",
  14018. "varying vec3 vBinormal;",
  14019. "varying vec3 vNormal;",
  14020. "varying vec2 vUv;",
  14021. "uniform vec3 ambientLightColor;",
  14022. "#if MAX_DIR_LIGHTS > 0",
  14023. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  14024. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  14025. "#endif",
  14026. "#if MAX_POINT_LIGHTS > 0",
  14027. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  14028. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  14029. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  14030. "#endif",
  14031. "#if MAX_SPOT_LIGHTS > 0",
  14032. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  14033. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  14034. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  14035. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  14036. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  14037. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  14038. "#endif",
  14039. "#ifdef WRAP_AROUND",
  14040. "uniform vec3 wrapRGB;",
  14041. "#endif",
  14042. "varying vec3 vWorldPosition;",
  14043. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14044. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14045. "void main() {",
  14046. "vec3 vViewPosition = cameraPosition - vWorldPosition;",
  14047. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  14048. "vec3 specularTex = vec3( 1.0 );",
  14049. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  14050. "normalTex.xy *= uNormalScale;",
  14051. "normalTex = normalize( normalTex );",
  14052. "if( enableDiffuse ) {",
  14053. "#ifdef GAMMA_INPUT",
  14054. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  14055. "texelColor.xyz *= texelColor.xyz;",
  14056. "gl_FragColor = gl_FragColor * texelColor;",
  14057. "#else",
  14058. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  14059. "#endif",
  14060. "}",
  14061. "if( enableAO ) {",
  14062. "#ifdef GAMMA_INPUT",
  14063. "vec4 aoColor = texture2D( tAO, vUv );",
  14064. "aoColor.xyz *= aoColor.xyz;",
  14065. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  14066. "#else",
  14067. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  14068. "#endif",
  14069. "}",
  14070. "if( enableSpecular )",
  14071. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  14072. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  14073. "vec3 finalNormal = tsb * normalTex;",
  14074. "vec3 normal = normalize( finalNormal );",
  14075. "vec3 viewPosition = normalize( vViewPosition );",
  14076. // point lights
  14077. "#if MAX_POINT_LIGHTS > 0",
  14078. "vec3 pointDiffuse = vec3( 0.0 );",
  14079. "vec3 pointSpecular = vec3( 0.0 );",
  14080. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  14081. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  14082. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  14083. "float pointDistance = 1.0;",
  14084. "if ( pointLightDistance[ i ] > 0.0 )",
  14085. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  14086. "pointVector = normalize( pointVector );",
  14087. // diffuse
  14088. "#ifdef WRAP_AROUND",
  14089. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  14090. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  14091. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  14092. "#else",
  14093. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  14094. "#endif",
  14095. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  14096. // specular
  14097. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  14098. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  14099. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  14100. "#ifdef PHYSICALLY_BASED_SHADING",
  14101. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14102. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14103. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  14104. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  14105. "#else",
  14106. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  14107. "#endif",
  14108. "}",
  14109. "#endif",
  14110. // spot lights
  14111. "#if MAX_SPOT_LIGHTS > 0",
  14112. "vec3 spotDiffuse = vec3( 0.0 );",
  14113. "vec3 spotSpecular = vec3( 0.0 );",
  14114. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  14115. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  14116. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  14117. "float spotDistance = 1.0;",
  14118. "if ( spotLightDistance[ i ] > 0.0 )",
  14119. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  14120. "spotVector = normalize( spotVector );",
  14121. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  14122. "if ( spotEffect > spotLightAngle[ i ] ) {",
  14123. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  14124. // diffuse
  14125. "#ifdef WRAP_AROUND",
  14126. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  14127. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  14128. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  14129. "#else",
  14130. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  14131. "#endif",
  14132. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  14133. // specular
  14134. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  14135. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  14136. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  14137. "#ifdef PHYSICALLY_BASED_SHADING",
  14138. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14139. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14140. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  14141. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  14142. "#else",
  14143. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  14144. "#endif",
  14145. "}",
  14146. "}",
  14147. "#endif",
  14148. // directional lights
  14149. "#if MAX_DIR_LIGHTS > 0",
  14150. "vec3 dirDiffuse = vec3( 0.0 );",
  14151. "vec3 dirSpecular = vec3( 0.0 );",
  14152. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  14153. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  14154. "vec3 dirVector = normalize( lDirection.xyz );",
  14155. // diffuse
  14156. "#ifdef WRAP_AROUND",
  14157. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  14158. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  14159. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  14160. "#else",
  14161. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  14162. "#endif",
  14163. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  14164. // specular
  14165. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  14166. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  14167. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  14168. "#ifdef PHYSICALLY_BASED_SHADING",
  14169. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14170. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14171. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  14172. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  14173. "#else",
  14174. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  14175. "#endif",
  14176. "}",
  14177. "#endif",
  14178. // all lights contribution summation
  14179. "vec3 totalDiffuse = vec3( 0.0 );",
  14180. "vec3 totalSpecular = vec3( 0.0 );",
  14181. "#if MAX_DIR_LIGHTS > 0",
  14182. "totalDiffuse += dirDiffuse;",
  14183. "totalSpecular += dirSpecular;",
  14184. "#endif",
  14185. "#if MAX_POINT_LIGHTS > 0",
  14186. "totalDiffuse += pointDiffuse;",
  14187. "totalSpecular += pointSpecular;",
  14188. "#endif",
  14189. "#if MAX_SPOT_LIGHTS > 0",
  14190. "totalDiffuse += spotDiffuse;",
  14191. "totalSpecular += spotSpecular;",
  14192. "#endif",
  14193. "#ifdef METAL",
  14194. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  14195. "#else",
  14196. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  14197. "#endif",
  14198. "if ( enableReflection ) {",
  14199. "vec3 vReflect;",
  14200. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  14201. "if ( useRefract ) {",
  14202. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  14203. "} else {",
  14204. "vReflect = reflect( cameraToVertex, normal );",
  14205. "}",
  14206. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14207. "#ifdef GAMMA_INPUT",
  14208. "cubeColor.xyz *= cubeColor.xyz;",
  14209. "#endif",
  14210. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  14211. "}",
  14212. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14213. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14214. THREE.ShaderChunk[ "fog_fragment" ],
  14215. "}"
  14216. ].join("\n"),
  14217. vertexShader: [
  14218. "attribute vec4 tangent;",
  14219. "uniform vec2 uOffset;",
  14220. "uniform vec2 uRepeat;",
  14221. "uniform bool enableDisplacement;",
  14222. "#ifdef VERTEX_TEXTURES",
  14223. "uniform sampler2D tDisplacement;",
  14224. "uniform float uDisplacementScale;",
  14225. "uniform float uDisplacementBias;",
  14226. "#endif",
  14227. "varying vec3 vTangent;",
  14228. "varying vec3 vBinormal;",
  14229. "varying vec3 vNormal;",
  14230. "varying vec2 vUv;",
  14231. "varying vec3 vWorldPosition;",
  14232. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14233. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14234. "void main() {",
  14235. THREE.ShaderChunk[ "skinbase_vertex" ],
  14236. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14237. // normal, tangent and binormal vectors
  14238. "#ifdef USE_SKINNING",
  14239. "vNormal = normalMatrix * skinnedNormal.xyz;",
  14240. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  14241. "vTangent = normalMatrix * skinnedTangent.xyz;",
  14242. "#else",
  14243. "vNormal = normalMatrix * normal;",
  14244. "vTangent = normalMatrix * tangent.xyz;",
  14245. "#endif",
  14246. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  14247. "vUv = uv * uRepeat + uOffset;",
  14248. // displacement mapping
  14249. "vec3 displacedPosition;",
  14250. "#ifdef VERTEX_TEXTURES",
  14251. "if ( enableDisplacement ) {",
  14252. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  14253. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  14254. "displacedPosition = position + normalize( normal ) * df;",
  14255. "} else {",
  14256. "#ifdef USE_SKINNING",
  14257. "vec4 skinVertex = vec4( position, 1.0 );",
  14258. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  14259. "skinned += boneMatY * skinVertex * skinWeight.y;",
  14260. "displacedPosition = skinned.xyz;",
  14261. "#else",
  14262. "displacedPosition = position;",
  14263. "#endif",
  14264. "}",
  14265. "#else",
  14266. "#ifdef USE_SKINNING",
  14267. "vec4 skinVertex = vec4( position, 1.0 );",
  14268. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  14269. "skinned += boneMatY * skinVertex * skinWeight.y;",
  14270. "displacedPosition = skinned.xyz;",
  14271. "#else",
  14272. "displacedPosition = position;",
  14273. "#endif",
  14274. "#endif",
  14275. //
  14276. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  14277. "vec4 wPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  14278. "gl_Position = projectionMatrix * mvPosition;",
  14279. //
  14280. "vWorldPosition = wPosition.xyz;",
  14281. // shadows
  14282. "#ifdef USE_SHADOWMAP",
  14283. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  14284. "vShadowCoord[ i ] = shadowMatrix[ i ] * wPosition;",
  14285. "}",
  14286. "#endif",
  14287. "}"
  14288. ].join("\n")
  14289. },
  14290. /* -------------------------------------------------------------------------
  14291. // Cube map shader
  14292. ------------------------------------------------------------------------- */
  14293. 'cube': {
  14294. uniforms: { "tCube": { type: "t", value: 1, texture: null },
  14295. "tFlip": { type: "f", value: -1 } },
  14296. vertexShader: [
  14297. "varying vec3 vViewPosition;",
  14298. "void main() {",
  14299. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  14300. "vViewPosition = cameraPosition - mPosition.xyz;",
  14301. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  14302. "}"
  14303. ].join("\n"),
  14304. fragmentShader: [
  14305. "uniform samplerCube tCube;",
  14306. "uniform float tFlip;",
  14307. "varying vec3 vViewPosition;",
  14308. "void main() {",
  14309. "vec3 wPos = cameraPosition - vViewPosition;",
  14310. "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
  14311. "}"
  14312. ].join("\n")
  14313. }
  14314. }
  14315. };
  14316. };
  14317. /**
  14318. * @author zz85 / http://www.lab4games.net/zz85/blog
  14319. * @author alteredq / http://alteredqualia.com/
  14320. *
  14321. * For Text operations in three.js (See TextGeometry)
  14322. *
  14323. * It uses techniques used in:
  14324. *
  14325. * typeface.js and canvastext
  14326. * For converting fonts and rendering with javascript
  14327. * http://typeface.neocracy.org
  14328. *
  14329. * Triangulation ported from AS3
  14330. * Simple Polygon Triangulation
  14331. * http://actionsnippet.com/?p=1462
  14332. *
  14333. * A Method to triangulate shapes with holes
  14334. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  14335. *
  14336. */
  14337. THREE.FontUtils = {
  14338. faces : {},
  14339. // Just for now. face[weight][style]
  14340. face : "helvetiker",
  14341. weight: "normal",
  14342. style : "normal",
  14343. size : 150,
  14344. divisions : 10,
  14345. getFace : function() {
  14346. return this.faces[ this.face ][ this.weight ][ this.style ];
  14347. },
  14348. loadFace : function( data ) {
  14349. var family = data.familyName.toLowerCase();
  14350. var ThreeFont = this;
  14351. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  14352. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  14353. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  14354. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  14355. return data;
  14356. },
  14357. drawText : function( text ) {
  14358. var characterPts = [], allPts = [];
  14359. // RenderText
  14360. var i, p,
  14361. face = this.getFace(),
  14362. scale = this.size / face.resolution,
  14363. offset = 0,
  14364. chars = String( text ).split( '' ),
  14365. length = chars.length;
  14366. var fontPaths = [];
  14367. for ( i = 0; i < length; i ++ ) {
  14368. var path = new THREE.Path();
  14369. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  14370. offset += ret.offset;
  14371. fontPaths.push( ret.path );
  14372. }
  14373. // get the width
  14374. var width = offset / 2;
  14375. //
  14376. // for ( p = 0; p < allPts.length; p++ ) {
  14377. //
  14378. // allPts[ p ].x -= width;
  14379. //
  14380. // }
  14381. //var extract = this.extractPoints( allPts, characterPts );
  14382. //extract.contour = allPts;
  14383. //extract.paths = fontPaths;
  14384. //extract.offset = width;
  14385. return { paths : fontPaths, offset : width };
  14386. },
  14387. extractGlyphPoints : function( c, face, scale, offset, path ) {
  14388. var pts = [];
  14389. var i, i2, divisions,
  14390. outline, action, length,
  14391. scaleX, scaleY,
  14392. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  14393. laste,
  14394. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  14395. if ( !glyph ) return;
  14396. if ( glyph.o ) {
  14397. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  14398. length = outline.length;
  14399. scaleX = scale;
  14400. scaleY = scale;
  14401. for ( i = 0; i < length; ) {
  14402. action = outline[ i ++ ];
  14403. //console.log( action );
  14404. switch( action ) {
  14405. case 'm':
  14406. // Move To
  14407. x = outline[ i++ ] * scaleX + offset;
  14408. y = outline[ i++ ] * scaleY;
  14409. path.moveTo( x, y );
  14410. break;
  14411. case 'l':
  14412. // Line To
  14413. x = outline[ i++ ] * scaleX + offset;
  14414. y = outline[ i++ ] * scaleY;
  14415. path.lineTo(x,y);
  14416. break;
  14417. case 'q':
  14418. // QuadraticCurveTo
  14419. cpx = outline[ i++ ] * scaleX + offset;
  14420. cpy = outline[ i++ ] * scaleY;
  14421. cpx1 = outline[ i++ ] * scaleX + offset;
  14422. cpy1 = outline[ i++ ] * scaleY;
  14423. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  14424. laste = pts[ pts.length - 1 ];
  14425. if ( laste ) {
  14426. cpx0 = laste.x;
  14427. cpy0 = laste.y;
  14428. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  14429. var t = i2 / divisions;
  14430. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  14431. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  14432. }
  14433. }
  14434. break;
  14435. case 'b':
  14436. // Cubic Bezier Curve
  14437. cpx = outline[ i++ ] * scaleX + offset;
  14438. cpy = outline[ i++ ] * scaleY;
  14439. cpx1 = outline[ i++ ] * scaleX + offset;
  14440. cpy1 = outline[ i++ ] * -scaleY;
  14441. cpx2 = outline[ i++ ] * scaleX + offset;
  14442. cpy2 = outline[ i++ ] * -scaleY;
  14443. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  14444. laste = pts[ pts.length - 1 ];
  14445. if ( laste ) {
  14446. cpx0 = laste.x;
  14447. cpy0 = laste.y;
  14448. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  14449. var t = i2 / divisions;
  14450. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  14451. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  14452. }
  14453. }
  14454. break;
  14455. }
  14456. }
  14457. }
  14458. return { offset: glyph.ha*scale, path:path};
  14459. }
  14460. };
  14461. THREE.FontUtils.generateShapes = function( text, parameters ) {
  14462. // Parameters
  14463. parameters = parameters || {};
  14464. var size = parameters.size !== undefined ? parameters.size : 100;
  14465. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  14466. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  14467. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  14468. var style = parameters.style !== undefined ? parameters.style : "normal";
  14469. THREE.FontUtils.size = size;
  14470. THREE.FontUtils.divisions = curveSegments;
  14471. THREE.FontUtils.face = font;
  14472. THREE.FontUtils.weight = weight;
  14473. THREE.FontUtils.style = style;
  14474. // Get a Font data json object
  14475. var data = THREE.FontUtils.drawText( text );
  14476. var paths = data.paths;
  14477. var shapes = [];
  14478. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  14479. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  14480. }
  14481. return shapes;
  14482. };
  14483. /**
  14484. * This code is a quick port of code written in C++ which was submitted to
  14485. * flipcode.com by John W. Ratcliff // July 22, 2000
  14486. * See original code and more information here:
  14487. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  14488. *
  14489. * ported to actionscript by Zevan Rosser
  14490. * www.actionsnippet.com
  14491. *
  14492. * ported to javascript by Joshua Koo
  14493. * http://www.lab4games.net/zz85/blog
  14494. *
  14495. */
  14496. ( function( namespace ) {
  14497. var EPSILON = 0.0000000001;
  14498. // takes in an contour array and returns
  14499. var process = function( contour, indices ) {
  14500. var n = contour.length;
  14501. if ( n < 3 ) return null;
  14502. var result = [],
  14503. verts = [],
  14504. vertIndices = [];
  14505. /* we want a counter-clockwise polygon in verts */
  14506. var u, v, w;
  14507. if ( area( contour ) > 0.0 ) {
  14508. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  14509. } else {
  14510. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  14511. }
  14512. var nv = n;
  14513. /* remove nv - 2 vertices, creating 1 triangle every time */
  14514. var count = 2 * nv; /* error detection */
  14515. for( v = nv - 1; nv > 2; ) {
  14516. /* if we loop, it is probably a non-simple polygon */
  14517. if ( ( count-- ) <= 0 ) {
  14518. //** Triangulate: ERROR - probable bad polygon!
  14519. //throw ( "Warning, unable to triangulate polygon!" );
  14520. //return null;
  14521. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  14522. console.log( "Warning, unable to triangulate polygon!" );
  14523. if ( indices ) return vertIndices;
  14524. return result;
  14525. }
  14526. /* three consecutive vertices in current polygon, <u,v,w> */
  14527. u = v; if ( nv <= u ) u = 0; /* previous */
  14528. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  14529. w = v + 1; if ( nv <= w ) w = 0; /* next */
  14530. if ( snip( contour, u, v, w, nv, verts ) ) {
  14531. var a, b, c, s, t;
  14532. /* true names of the vertices */
  14533. a = verts[ u ];
  14534. b = verts[ v ];
  14535. c = verts[ w ];
  14536. /* output Triangle */
  14537. /*
  14538. result.push( contour[ a ] );
  14539. result.push( contour[ b ] );
  14540. result.push( contour[ c ] );
  14541. */
  14542. result.push( [ contour[ a ],
  14543. contour[ b ],
  14544. contour[ c ] ] );
  14545. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  14546. /* remove v from the remaining polygon */
  14547. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  14548. verts[ s ] = verts[ t ];
  14549. }
  14550. nv--;
  14551. /* reset error detection counter */
  14552. count = 2 * nv;
  14553. }
  14554. }
  14555. if ( indices ) return vertIndices;
  14556. return result;
  14557. };
  14558. // calculate area of the contour polygon
  14559. var area = function ( contour ) {
  14560. var n = contour.length;
  14561. var a = 0.0;
  14562. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  14563. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  14564. }
  14565. return a * 0.5;
  14566. };
  14567. // see if p is inside triangle abc
  14568. var insideTriangle = function( ax, ay,
  14569. bx, by,
  14570. cx, cy,
  14571. px, py ) {
  14572. var aX, aY, bX, bY;
  14573. var cX, cY, apx, apy;
  14574. var bpx, bpy, cpx, cpy;
  14575. var cCROSSap, bCROSScp, aCROSSbp;
  14576. aX = cx - bx; aY = cy - by;
  14577. bX = ax - cx; bY = ay - cy;
  14578. cX = bx - ax; cY = by - ay;
  14579. apx= px -ax; apy= py - ay;
  14580. bpx= px - bx; bpy= py - by;
  14581. cpx= px - cx; cpy= py - cy;
  14582. aCROSSbp = aX*bpy - aY*bpx;
  14583. cCROSSap = cX*apy - cY*apx;
  14584. bCROSScp = bX*cpy - bY*cpx;
  14585. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  14586. };
  14587. var snip = function ( contour, u, v, w, n, verts ) {
  14588. var p;
  14589. var ax, ay, bx, by;
  14590. var cx, cy, px, py;
  14591. ax = contour[ verts[ u ] ].x;
  14592. ay = contour[ verts[ u ] ].y;
  14593. bx = contour[ verts[ v ] ].x;
  14594. by = contour[ verts[ v ] ].y;
  14595. cx = contour[ verts[ w ] ].x;
  14596. cy = contour[ verts[ w ] ].y;
  14597. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  14598. for ( p = 0; p < n; p++ ) {
  14599. if( (p == u) || (p == v) || (p == w) ) continue;
  14600. px = contour[ verts[ p ] ].x
  14601. py = contour[ verts[ p ] ].y
  14602. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  14603. }
  14604. return true;
  14605. };
  14606. namespace.Triangulate = process;
  14607. namespace.Triangulate.area = area;
  14608. return namespace;
  14609. })(THREE.FontUtils);
  14610. // To use the typeface.js face files, hook up the API
  14611. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  14612. * @author zz85 / http://www.lab4games.net/zz85/blog
  14613. * Extensible curve object
  14614. *
  14615. * Some common of Curve methods
  14616. * .getPoint(t), getTangent(t)
  14617. * .getPointAt(u), getTagentAt(u)
  14618. * .getPoints(), .getSpacedPoints()
  14619. * .getLength()
  14620. * .updateArcLengths()
  14621. *
  14622. * This file contains following classes:
  14623. *
  14624. * -- 2d classes --
  14625. * THREE.Curve
  14626. * THREE.LineCurve
  14627. * THREE.QuadraticBezierCurve
  14628. * THREE.CubicBezierCurve
  14629. * THREE.SplineCurve
  14630. * THREE.ArcCurve
  14631. * THREE.EllipseCurve
  14632. *
  14633. * -- 3d classes --
  14634. * THREE.LineCurve3
  14635. * THREE.QuadraticBezierCurve3
  14636. * THREE.CubicBezierCurve3
  14637. * THREE.SplineCurve3
  14638. * THREE.ClosedSplineCurve3
  14639. *
  14640. * A series of curves can be represented as a THREE.CurvePath
  14641. *
  14642. **/
  14643. /**************************************************************
  14644. * Abstract Curve base class
  14645. **************************************************************/
  14646. THREE.Curve = function () {
  14647. };
  14648. // Virtual base class method to overwrite and implement in subclasses
  14649. // - t [0 .. 1]
  14650. THREE.Curve.prototype.getPoint = function ( t ) {
  14651. console.log( "Warning, getPoint() not implemented!" );
  14652. return null;
  14653. };
  14654. // Get point at relative position in curve according to arc length
  14655. // - u [0 .. 1]
  14656. THREE.Curve.prototype.getPointAt = function ( u ) {
  14657. var t = this.getUtoTmapping( u );
  14658. return this.getPoint( t );
  14659. };
  14660. // Get sequence of points using getPoint( t )
  14661. THREE.Curve.prototype.getPoints = function ( divisions ) {
  14662. if ( !divisions ) divisions = 5;
  14663. var d, pts = [];
  14664. for ( d = 0; d <= divisions; d ++ ) {
  14665. pts.push( this.getPoint( d / divisions ) );
  14666. }
  14667. return pts;
  14668. };
  14669. // Get sequence of points using getPointAt( u )
  14670. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  14671. if ( !divisions ) divisions = 5;
  14672. var d, pts = [];
  14673. for ( d = 0; d <= divisions; d ++ ) {
  14674. pts.push( this.getPointAt( d / divisions ) );
  14675. }
  14676. return pts;
  14677. };
  14678. // Get total curve arc length
  14679. THREE.Curve.prototype.getLength = function () {
  14680. var lengths = this.getLengths();
  14681. return lengths[ lengths.length - 1 ];
  14682. };
  14683. // Get list of cumulative segment lengths
  14684. THREE.Curve.prototype.getLengths = function ( divisions ) {
  14685. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  14686. if ( this.cacheArcLengths
  14687. && ( this.cacheArcLengths.length == divisions + 1 )
  14688. && !this.needsUpdate) {
  14689. //console.log( "cached", this.cacheArcLengths );
  14690. return this.cacheArcLengths;
  14691. }
  14692. this.needsUpdate = false;
  14693. var cache = [];
  14694. var current, last = this.getPoint( 0 );
  14695. var p, sum = 0;
  14696. cache.push( 0 );
  14697. for ( p = 1; p <= divisions; p ++ ) {
  14698. current = this.getPoint ( p / divisions );
  14699. sum += current.distanceTo( last );
  14700. cache.push( sum );
  14701. last = current;
  14702. }
  14703. this.cacheArcLengths = cache;
  14704. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  14705. };
  14706. THREE.Curve.prototype.updateArcLengths = function() {
  14707. this.needsUpdate = true;
  14708. this.getLengths();
  14709. };
  14710. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  14711. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  14712. var arcLengths = this.getLengths();
  14713. var i = 0, il = arcLengths.length;
  14714. var targetArcLength; // The targeted u distance value to get
  14715. if ( distance ) {
  14716. targetArcLength = distance;
  14717. } else {
  14718. targetArcLength = u * arcLengths[ il - 1 ];
  14719. }
  14720. //var time = Date.now();
  14721. // binary search for the index with largest value smaller than target u distance
  14722. var low = 0, high = il - 1, comparison;
  14723. while ( low <= high ) {
  14724. 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
  14725. comparison = arcLengths[ i ] - targetArcLength;
  14726. if ( comparison < 0 ) {
  14727. low = i + 1;
  14728. continue;
  14729. } else if ( comparison > 0 ) {
  14730. high = i - 1;
  14731. continue;
  14732. } else {
  14733. high = i;
  14734. break;
  14735. // DONE
  14736. }
  14737. }
  14738. i = high;
  14739. //console.log('b' , i, low, high, Date.now()- time);
  14740. if ( arcLengths[ i ] == targetArcLength ) {
  14741. var t = i / ( il - 1 );
  14742. return t;
  14743. }
  14744. // we could get finer grain at lengths, or use simple interpolatation between two points
  14745. var lengthBefore = arcLengths[ i ];
  14746. var lengthAfter = arcLengths[ i + 1 ];
  14747. var segmentLength = lengthAfter - lengthBefore;
  14748. // determine where we are between the 'before' and 'after' points
  14749. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  14750. // add that fractional amount to t
  14751. var t = ( i + segmentFraction ) / ( il -1 );
  14752. return t;
  14753. };
  14754. // In 2D space, there are actually 2 normal vectors,
  14755. // and in 3D space, infinte
  14756. // TODO this should be depreciated.
  14757. THREE.Curve.prototype.getNormalVector = function( t ) {
  14758. var vec = this.getTangent( t );
  14759. return new THREE.Vector2( -vec.y , vec.x );
  14760. };
  14761. // Returns a unit vector tangent at t
  14762. // In case any sub curve does not implement its tangent / normal finding,
  14763. // we get 2 points with a small delta and find a gradient of the 2 points
  14764. // which seems to make a reasonable approximation
  14765. THREE.Curve.prototype.getTangent = function( t ) {
  14766. var delta = 0.0001;
  14767. var t1 = t - delta;
  14768. var t2 = t + delta;
  14769. // Capping in case of danger
  14770. if ( t1 < 0 ) t1 = 0;
  14771. if ( t2 > 1 ) t2 = 1;
  14772. var pt1 = this.getPoint( t1 );
  14773. var pt2 = this.getPoint( t2 );
  14774. var vec = pt2.clone().subSelf(pt1);
  14775. return vec.normalize();
  14776. };
  14777. THREE.Curve.prototype.getTangentAt = function ( u ) {
  14778. var t = this.getUtoTmapping( u );
  14779. return this.getTangent( t );
  14780. };
  14781. /**************************************************************
  14782. * Line
  14783. **************************************************************/
  14784. THREE.LineCurve = function ( v1, v2 ) {
  14785. this.v1 = v1;
  14786. this.v2 = v2;
  14787. };
  14788. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  14789. THREE.LineCurve.prototype.getPoint = function ( t ) {
  14790. var point = this.v2.clone().subSelf(this.v1);
  14791. point.multiplyScalar( t ).addSelf( this.v1 );
  14792. return point;
  14793. };
  14794. // Line curve is linear, so we can overwrite default getPointAt
  14795. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  14796. return this.getPoint( u );
  14797. };
  14798. THREE.LineCurve.prototype.getTangent = function( t ) {
  14799. var tangent = this.v2.clone().subSelf(this.v1);
  14800. return tangent.normalize();
  14801. };
  14802. /**************************************************************
  14803. * Quadratic Bezier curve
  14804. **************************************************************/
  14805. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  14806. this.v0 = v0;
  14807. this.v1 = v1;
  14808. this.v2 = v2;
  14809. };
  14810. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  14811. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  14812. var tx, ty;
  14813. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  14814. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  14815. return new THREE.Vector2( tx, ty );
  14816. };
  14817. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  14818. var tx, ty;
  14819. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  14820. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  14821. // returns unit vector
  14822. var tangent = new THREE.Vector2( tx, ty );
  14823. tangent.normalize();
  14824. return tangent;
  14825. };
  14826. /**************************************************************
  14827. * Cubic Bezier curve
  14828. **************************************************************/
  14829. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  14830. this.v0 = v0;
  14831. this.v1 = v1;
  14832. this.v2 = v2;
  14833. this.v3 = v3;
  14834. };
  14835. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  14836. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  14837. var tx, ty;
  14838. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  14839. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  14840. return new THREE.Vector2( tx, ty );
  14841. };
  14842. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  14843. var tx, ty;
  14844. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  14845. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  14846. var tangent = new THREE.Vector2( tx, ty );
  14847. tangent.normalize();
  14848. return tangent;
  14849. };
  14850. /**************************************************************
  14851. * Spline curve
  14852. **************************************************************/
  14853. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  14854. this.points = (points == undefined) ? [] : points;
  14855. };
  14856. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  14857. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  14858. var v = new THREE.Vector2();
  14859. var c = [];
  14860. var points = this.points, point, intPoint, weight;
  14861. point = ( points.length - 1 ) * t;
  14862. intPoint = Math.floor( point );
  14863. weight = point - intPoint;
  14864. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  14865. c[ 1 ] = intPoint;
  14866. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  14867. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  14868. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  14869. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  14870. return v;
  14871. };
  14872. /**************************************************************
  14873. * Ellipse curve
  14874. **************************************************************/
  14875. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  14876. aStartAngle, aEndAngle,
  14877. aClockwise ) {
  14878. this.aX = aX;
  14879. this.aY = aY;
  14880. this.xRadius = xRadius;
  14881. this.yRadius = yRadius;
  14882. this.aStartAngle = aStartAngle;
  14883. this.aEndAngle = aEndAngle;
  14884. this.aClockwise = aClockwise;
  14885. };
  14886. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  14887. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  14888. var deltaAngle = this.aEndAngle - this.aStartAngle;
  14889. if ( !this.aClockwise ) {
  14890. t = 1 - t;
  14891. }
  14892. var angle = this.aStartAngle + t * deltaAngle;
  14893. var tx = this.aX + this.xRadius * Math.cos( angle );
  14894. var ty = this.aY + this.yRadius * Math.sin( angle );
  14895. return new THREE.Vector2( tx, ty );
  14896. };
  14897. /**************************************************************
  14898. * Arc curve
  14899. **************************************************************/
  14900. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  14901. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  14902. };
  14903. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  14904. /**************************************************************
  14905. * Utils
  14906. **************************************************************/
  14907. THREE.Curve.Utils = {
  14908. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  14909. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  14910. },
  14911. // Puay Bing, thanks for helping with this derivative!
  14912. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  14913. return -3 * p0 * (1 - t) * (1 - t) +
  14914. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  14915. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  14916. 3 * t * t * p3;
  14917. },
  14918. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  14919. // To check if my formulas are correct
  14920. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  14921. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  14922. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  14923. var h11 = 3 * t * t - 2 * t; // t3 − t2
  14924. return h00 + h10 + h01 + h11;
  14925. },
  14926. // Catmull-Rom
  14927. interpolate: function( p0, p1, p2, p3, t ) {
  14928. var v0 = ( p2 - p0 ) * 0.5;
  14929. var v1 = ( p3 - p1 ) * 0.5;
  14930. var t2 = t * t;
  14931. var t3 = t * t2;
  14932. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  14933. }
  14934. };
  14935. // TODO: Transformation for Curves?
  14936. /**************************************************************
  14937. * 3D Curves
  14938. **************************************************************/
  14939. // A Factory method for creating new curve subclasses
  14940. THREE.Curve.create = function ( constructor, getPointFunc ) {
  14941. constructor.prototype = Object.create( THREE.Curve.prototype );
  14942. constructor.prototype.getPoint = getPointFunc;
  14943. return constructor;
  14944. };
  14945. /**************************************************************
  14946. * Line3D
  14947. **************************************************************/
  14948. THREE.LineCurve3 = THREE.Curve.create(
  14949. function ( v1, v2 ) {
  14950. this.v1 = v1;
  14951. this.v2 = v2;
  14952. },
  14953. function ( t ) {
  14954. var r = new THREE.Vector3();
  14955. r.sub( this.v2, this.v1 ); // diff
  14956. r.multiplyScalar( t );
  14957. r.addSelf( this.v1 );
  14958. return r;
  14959. }
  14960. );
  14961. /**************************************************************
  14962. * Quadratic Bezier 3D curve
  14963. **************************************************************/
  14964. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  14965. function ( v0, v1, v2 ) {
  14966. this.v0 = v0;
  14967. this.v1 = v1;
  14968. this.v2 = v2;
  14969. },
  14970. function ( t ) {
  14971. var tx, ty, tz;
  14972. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  14973. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  14974. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  14975. return new THREE.Vector3( tx, ty, tz );
  14976. }
  14977. );
  14978. /**************************************************************
  14979. * Cubic Bezier 3D curve
  14980. **************************************************************/
  14981. THREE.CubicBezierCurve3 = THREE.Curve.create(
  14982. function ( v0, v1, v2, v3 ) {
  14983. this.v0 = v0;
  14984. this.v1 = v1;
  14985. this.v2 = v2;
  14986. this.v3 = v3;
  14987. },
  14988. function ( t ) {
  14989. var tx, ty, tz;
  14990. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  14991. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  14992. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  14993. return new THREE.Vector3( tx, ty, tz );
  14994. }
  14995. );
  14996. /**************************************************************
  14997. * Spline 3D curve
  14998. **************************************************************/
  14999. THREE.SplineCurve3 = THREE.Curve.create(
  15000. function ( points /* array of Vector3 */) {
  15001. this.points = (points == undefined) ? [] : points;
  15002. },
  15003. function ( t ) {
  15004. var v = new THREE.Vector3();
  15005. var c = [];
  15006. var points = this.points, point, intPoint, weight;
  15007. point = ( points.length - 1 ) * t;
  15008. intPoint = Math.floor( point );
  15009. weight = point - intPoint;
  15010. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15011. c[ 1 ] = intPoint;
  15012. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15013. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15014. var pt0 = points[ c[0] ],
  15015. pt1 = points[ c[1] ],
  15016. pt2 = points[ c[2] ],
  15017. pt3 = points[ c[3] ];
  15018. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  15019. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  15020. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  15021. return v;
  15022. }
  15023. );
  15024. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  15025. // var v = new THREE.Vector3();
  15026. // var c = [];
  15027. // var points = this.points, point, intPoint, weight;
  15028. // point = ( points.length - 1 ) * t;
  15029. // intPoint = Math.floor( point );
  15030. // weight = point - intPoint;
  15031. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15032. // c[ 1 ] = intPoint;
  15033. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15034. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15035. // var pt0 = points[ c[0] ],
  15036. // pt1 = points[ c[1] ],
  15037. // pt2 = points[ c[2] ],
  15038. // pt3 = points[ c[3] ];
  15039. // // t = weight;
  15040. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  15041. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  15042. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  15043. // return v;
  15044. // }
  15045. /**************************************************************
  15046. * Closed Spline 3D curve
  15047. **************************************************************/
  15048. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  15049. function ( points /* array of Vector3 */) {
  15050. this.points = (points == undefined) ? [] : points;
  15051. },
  15052. function ( t ) {
  15053. var v = new THREE.Vector3();
  15054. var c = [];
  15055. var points = this.points, point, intPoint, weight;
  15056. point = ( points.length - 0 ) * t;
  15057. // This needs to be from 0-length +1
  15058. intPoint = Math.floor( point );
  15059. weight = point - intPoint;
  15060. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  15061. c[ 0 ] = ( intPoint - 1 ) % points.length;
  15062. c[ 1 ] = ( intPoint ) % points.length;
  15063. c[ 2 ] = ( intPoint + 1 ) % points.length;
  15064. c[ 3 ] = ( intPoint + 2 ) % points.length;
  15065. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15066. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15067. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  15068. return v;
  15069. }
  15070. );
  15071. /**
  15072. * @author zz85 / http://www.lab4games.net/zz85/blog
  15073. *
  15074. **/
  15075. /**************************************************************
  15076. * Curved Path - a curve path is simply a array of connected
  15077. * curves, but retains the api of a curve
  15078. **************************************************************/
  15079. THREE.CurvePath = function () {
  15080. this.curves = [];
  15081. this.bends = [];
  15082. this.autoClose = false; // Automatically closes the path
  15083. };
  15084. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  15085. THREE.CurvePath.prototype.add = function ( curve ) {
  15086. this.curves.push( curve );
  15087. };
  15088. THREE.CurvePath.prototype.checkConnection = function() {
  15089. // TODO
  15090. // If the ending of curve is not connected to the starting
  15091. // or the next curve, then, this is not a real path
  15092. };
  15093. THREE.CurvePath.prototype.closePath = function() {
  15094. // TODO Test
  15095. // and verify for vector3 (needs to implement equals)
  15096. // Add a line curve if start and end of lines are not connected
  15097. var startPoint = this.curves[0].getPoint(0);
  15098. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  15099. if (!startPoint.equals(endPoint)) {
  15100. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  15101. }
  15102. };
  15103. // To get accurate point with reference to
  15104. // entire path distance at time t,
  15105. // following has to be done:
  15106. // 1. Length of each sub path have to be known
  15107. // 2. Locate and identify type of curve
  15108. // 3. Get t for the curve
  15109. // 4. Return curve.getPointAt(t')
  15110. THREE.CurvePath.prototype.getPoint = function( t ) {
  15111. var d = t * this.getLength();
  15112. var curveLengths = this.getCurveLengths();
  15113. var i = 0, diff, curve;
  15114. // To think about boundaries points.
  15115. while ( i < curveLengths.length ) {
  15116. if ( curveLengths[ i ] >= d ) {
  15117. diff = curveLengths[ i ] - d;
  15118. curve = this.curves[ i ];
  15119. var u = 1 - diff / curve.getLength();
  15120. return curve.getPointAt( u );
  15121. break;
  15122. }
  15123. i ++;
  15124. }
  15125. return null;
  15126. // loop where sum != 0, sum > d , sum+1 <d
  15127. };
  15128. /*
  15129. THREE.CurvePath.prototype.getTangent = function( t ) {
  15130. };*/
  15131. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  15132. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  15133. // getPoint() depends on getLength
  15134. THREE.CurvePath.prototype.getLength = function() {
  15135. var lens = this.getCurveLengths();
  15136. return lens[ lens.length - 1 ];
  15137. };
  15138. // Compute lengths and cache them
  15139. // We cannot overwrite getLengths() because UtoT mapping uses it.
  15140. THREE.CurvePath.prototype.getCurveLengths = function() {
  15141. // We use cache values if curves and cache array are same length
  15142. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  15143. return this.cacheLengths;
  15144. };
  15145. // Get length of subsurve
  15146. // Push sums into cached array
  15147. var lengths = [], sums = 0;
  15148. var i, il = this.curves.length;
  15149. for ( i = 0; i < il; i ++ ) {
  15150. sums += this.curves[ i ].getLength();
  15151. lengths.push( sums );
  15152. }
  15153. this.cacheLengths = lengths;
  15154. return lengths;
  15155. };
  15156. // Returns min and max coordinates, as well as centroid
  15157. THREE.CurvePath.prototype.getBoundingBox = function () {
  15158. var points = this.getPoints();
  15159. var maxX, maxY, maxZ;
  15160. var minX, minY, minZ;
  15161. maxX = maxY = Number.NEGATIVE_INFINITY;
  15162. minX = minY = Number.POSITIVE_INFINITY;
  15163. var p, i, il, sum;
  15164. var v3 = points[0] instanceof THREE.Vector3;
  15165. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  15166. for ( i = 0, il = points.length; i < il; i ++ ) {
  15167. p = points[ i ];
  15168. if ( p.x > maxX ) maxX = p.x;
  15169. else if ( p.x < minX ) minX = p.x;
  15170. if ( p.y > maxY ) maxY = p.y;
  15171. else if ( p.y < minY ) minY = p.y;
  15172. if (v3) {
  15173. if ( p.z > maxZ ) maxZ = p.z;
  15174. else if ( p.z < minZ ) minZ = p.z;
  15175. }
  15176. sum.addSelf( p );
  15177. }
  15178. var ret = {
  15179. minX: minX,
  15180. minY: minY,
  15181. maxX: maxX,
  15182. maxY: maxY,
  15183. centroid: sum.divideScalar( il )
  15184. };
  15185. if (v3) {
  15186. ret.maxZ = maxZ;
  15187. ret.minZ = minZ;
  15188. }
  15189. return ret;
  15190. };
  15191. /**************************************************************
  15192. * Create Geometries Helpers
  15193. **************************************************************/
  15194. /// Generate geometry from path points (for Line or ParticleSystem objects)
  15195. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  15196. var pts = this.getPoints( divisions, true );
  15197. return this.createGeometry( pts );
  15198. };
  15199. // Generate geometry from equidistance sampling along the path
  15200. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  15201. var pts = this.getSpacedPoints( divisions, true );
  15202. return this.createGeometry( pts );
  15203. };
  15204. THREE.CurvePath.prototype.createGeometry = function( points ) {
  15205. var geometry = new THREE.Geometry();
  15206. for ( var i = 0; i < points.length; i ++ ) {
  15207. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  15208. }
  15209. return geometry;
  15210. };
  15211. /**************************************************************
  15212. * Bend / Wrap Helper Methods
  15213. **************************************************************/
  15214. // Wrap path / Bend modifiers?
  15215. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  15216. this.bends.push( bendpath );
  15217. };
  15218. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  15219. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  15220. var i, il;
  15221. if ( !bends ) {
  15222. bends = this.bends;
  15223. }
  15224. for ( i = 0, il = bends.length; i < il; i ++ ) {
  15225. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  15226. }
  15227. return oldPts;
  15228. };
  15229. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  15230. var oldPts = this.getSpacedPoints( segments );
  15231. var i, il;
  15232. if ( !bends ) {
  15233. bends = this.bends;
  15234. }
  15235. for ( i = 0, il = bends.length; i < il; i ++ ) {
  15236. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  15237. }
  15238. return oldPts;
  15239. };
  15240. // This returns getPoints() bend/wrapped around the contour of a path.
  15241. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  15242. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  15243. var bounds = this.getBoundingBox();
  15244. var i, il, p, oldX, oldY, xNorm;
  15245. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  15246. p = oldPts[ i ];
  15247. oldX = p.x;
  15248. oldY = p.y;
  15249. xNorm = oldX / bounds.maxX;
  15250. // If using actual distance, for length > path, requires line extrusions
  15251. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  15252. xNorm = path.getUtoTmapping( xNorm, oldX );
  15253. // check for out of bounds?
  15254. var pathPt = path.getPoint( xNorm );
  15255. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  15256. p.x = pathPt.x + normal.x;
  15257. p.y = pathPt.y + normal.y;
  15258. }
  15259. return oldPts;
  15260. };
  15261. /**
  15262. * @author alteredq / http://alteredqualia.com/
  15263. */
  15264. THREE.Gyroscope = function () {
  15265. THREE.Object3D.call( this );
  15266. };
  15267. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  15268. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  15269. this.matrixAutoUpdate && this.updateMatrix();
  15270. // update matrixWorld
  15271. if ( this.matrixWorldNeedsUpdate || force ) {
  15272. if ( this.parent ) {
  15273. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  15274. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  15275. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  15276. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  15277. } else {
  15278. this.matrixWorld.copy( this.matrix );
  15279. }
  15280. this.matrixWorldNeedsUpdate = false;
  15281. force = true;
  15282. }
  15283. // update children
  15284. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  15285. this.children[ i ].updateMatrixWorld( force );
  15286. }
  15287. };
  15288. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  15289. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  15290. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  15291. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  15292. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  15293. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  15294. /**
  15295. * @author zz85 / http://www.lab4games.net/zz85/blog
  15296. * Creates free form 2d path using series of points, lines or curves.
  15297. *
  15298. **/
  15299. THREE.Path = function ( points ) {
  15300. THREE.CurvePath.call(this);
  15301. this.actions = [];
  15302. if ( points ) {
  15303. this.fromPoints( points );
  15304. }
  15305. };
  15306. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  15307. THREE.PathActions = {
  15308. MOVE_TO: 'moveTo',
  15309. LINE_TO: 'lineTo',
  15310. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  15311. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  15312. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  15313. ARC: 'arc', // Circle
  15314. ELLIPSE: 'ellipse'
  15315. };
  15316. // TODO Clean up PATH API
  15317. // Create path using straight lines to connect all points
  15318. // - vectors: array of Vector2
  15319. THREE.Path.prototype.fromPoints = function ( vectors ) {
  15320. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  15321. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  15322. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  15323. };
  15324. };
  15325. // startPath() endPath()?
  15326. THREE.Path.prototype.moveTo = function ( x, y ) {
  15327. var args = Array.prototype.slice.call( arguments );
  15328. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  15329. };
  15330. THREE.Path.prototype.lineTo = function ( x, y ) {
  15331. var args = Array.prototype.slice.call( arguments );
  15332. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15333. var x0 = lastargs[ lastargs.length - 2 ];
  15334. var y0 = lastargs[ lastargs.length - 1 ];
  15335. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  15336. this.curves.push( curve );
  15337. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  15338. };
  15339. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  15340. var args = Array.prototype.slice.call( arguments );
  15341. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15342. var x0 = lastargs[ lastargs.length - 2 ];
  15343. var y0 = lastargs[ lastargs.length - 1 ];
  15344. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  15345. new THREE.Vector2( aCPx, aCPy ),
  15346. new THREE.Vector2( aX, aY ) );
  15347. this.curves.push( curve );
  15348. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  15349. };
  15350. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  15351. aCP2x, aCP2y,
  15352. aX, aY ) {
  15353. var args = Array.prototype.slice.call( arguments );
  15354. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15355. var x0 = lastargs[ lastargs.length - 2 ];
  15356. var y0 = lastargs[ lastargs.length - 1 ];
  15357. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  15358. new THREE.Vector2( aCP1x, aCP1y ),
  15359. new THREE.Vector2( aCP2x, aCP2y ),
  15360. new THREE.Vector2( aX, aY ) );
  15361. this.curves.push( curve );
  15362. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  15363. };
  15364. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  15365. var args = Array.prototype.slice.call( arguments );
  15366. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15367. var x0 = lastargs[ lastargs.length - 2 ];
  15368. var y0 = lastargs[ lastargs.length - 1 ];
  15369. //---
  15370. var npts = [ new THREE.Vector2( x0, y0 ) ];
  15371. Array.prototype.push.apply( npts, pts );
  15372. var curve = new THREE.SplineCurve( npts );
  15373. this.curves.push( curve );
  15374. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  15375. };
  15376. // FUTURE: Change the API or follow canvas API?
  15377. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  15378. aStartAngle, aEndAngle, aClockwise ) {
  15379. var lastargs = this.actions[ this.actions.length - 1].args;
  15380. var x0 = lastargs[ lastargs.length - 2 ];
  15381. var y0 = lastargs[ lastargs.length - 1 ];
  15382. this.absarc(aX + x0, aY + y0, aRadius,
  15383. aStartAngle, aEndAngle, aClockwise );
  15384. };
  15385. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  15386. aStartAngle, aEndAngle, aClockwise ) {
  15387. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  15388. };
  15389. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  15390. aStartAngle, aEndAngle, aClockwise ) {
  15391. var lastargs = this.actions[ this.actions.length - 1].args;
  15392. var x0 = lastargs[ lastargs.length - 2 ];
  15393. var y0 = lastargs[ lastargs.length - 1 ];
  15394. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  15395. aStartAngle, aEndAngle, aClockwise );
  15396. };
  15397. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  15398. aStartAngle, aEndAngle, aClockwise ) {
  15399. var args = Array.prototype.slice.call( arguments );
  15400. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  15401. aStartAngle, aEndAngle, aClockwise );
  15402. this.curves.push( curve );
  15403. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  15404. args.push(lastPoint.x);
  15405. args.push(lastPoint.y);
  15406. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  15407. };
  15408. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  15409. if ( ! divisions ) divisions = 40;
  15410. var points = [];
  15411. for ( var i = 0; i < divisions; i ++ ) {
  15412. points.push( this.getPoint( i / divisions ) );
  15413. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  15414. }
  15415. // if ( closedPath ) {
  15416. //
  15417. // points.push( points[ 0 ] );
  15418. //
  15419. // }
  15420. return points;
  15421. };
  15422. /* Return an array of vectors based on contour of the path */
  15423. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  15424. if (this.useSpacedPoints) {
  15425. console.log('tata');
  15426. return this.getSpacedPoints( divisions, closedPath );
  15427. }
  15428. divisions = divisions || 12;
  15429. var points = [];
  15430. var i, il, item, action, args;
  15431. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  15432. laste, j,
  15433. t, tx, ty;
  15434. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  15435. item = this.actions[ i ];
  15436. action = item.action;
  15437. args = item.args;
  15438. switch( action ) {
  15439. case THREE.PathActions.MOVE_TO:
  15440. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  15441. break;
  15442. case THREE.PathActions.LINE_TO:
  15443. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  15444. break;
  15445. case THREE.PathActions.QUADRATIC_CURVE_TO:
  15446. cpx = args[ 2 ];
  15447. cpy = args[ 3 ];
  15448. cpx1 = args[ 0 ];
  15449. cpy1 = args[ 1 ];
  15450. if ( points.length > 0 ) {
  15451. laste = points[ points.length - 1 ];
  15452. cpx0 = laste.x;
  15453. cpy0 = laste.y;
  15454. } else {
  15455. laste = this.actions[ i - 1 ].args;
  15456. cpx0 = laste[ laste.length - 2 ];
  15457. cpy0 = laste[ laste.length - 1 ];
  15458. }
  15459. for ( j = 1; j <= divisions; j ++ ) {
  15460. t = j / divisions;
  15461. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15462. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15463. points.push( new THREE.Vector2( tx, ty ) );
  15464. }
  15465. break;
  15466. case THREE.PathActions.BEZIER_CURVE_TO:
  15467. cpx = args[ 4 ];
  15468. cpy = args[ 5 ];
  15469. cpx1 = args[ 0 ];
  15470. cpy1 = args[ 1 ];
  15471. cpx2 = args[ 2 ];
  15472. cpy2 = args[ 3 ];
  15473. if ( points.length > 0 ) {
  15474. laste = points[ points.length - 1 ];
  15475. cpx0 = laste.x;
  15476. cpy0 = laste.y;
  15477. } else {
  15478. laste = this.actions[ i - 1 ].args;
  15479. cpx0 = laste[ laste.length - 2 ];
  15480. cpy0 = laste[ laste.length - 1 ];
  15481. }
  15482. for ( j = 1; j <= divisions; j ++ ) {
  15483. t = j / divisions;
  15484. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15485. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15486. points.push( new THREE.Vector2( tx, ty ) );
  15487. }
  15488. break;
  15489. case THREE.PathActions.CSPLINE_THRU:
  15490. laste = this.actions[ i - 1 ].args;
  15491. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  15492. var spts = [ last ];
  15493. var n = divisions * args[ 0 ].length;
  15494. spts = spts.concat( args[ 0 ] );
  15495. var spline = new THREE.SplineCurve( spts );
  15496. for ( j = 1; j <= n; j ++ ) {
  15497. points.push( spline.getPointAt( j / n ) ) ;
  15498. }
  15499. break;
  15500. case THREE.PathActions.ARC:
  15501. var aX = args[ 0 ], aY = args[ 1 ],
  15502. aRadius = args[ 2 ],
  15503. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  15504. aClockwise = !!args[ 5 ];
  15505. var deltaAngle = aEndAngle - aStartAngle;
  15506. var angle;
  15507. var tdivisions = divisions * 2;
  15508. for ( j = 1; j <= tdivisions; j ++ ) {
  15509. t = j / tdivisions;
  15510. if ( ! aClockwise ) {
  15511. t = 1 - t;
  15512. }
  15513. angle = aStartAngle + t * deltaAngle;
  15514. tx = aX + aRadius * Math.cos( angle );
  15515. ty = aY + aRadius * Math.sin( angle );
  15516. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  15517. points.push( new THREE.Vector2( tx, ty ) );
  15518. }
  15519. //console.log(points);
  15520. break;
  15521. case THREE.PathActions.ELLIPSE:
  15522. var aX = args[ 0 ], aY = args[ 1 ],
  15523. xRadius = args[ 2 ],
  15524. yRadius = args[ 3 ],
  15525. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  15526. aClockwise = !!args[ 6 ];
  15527. var deltaAngle = aEndAngle - aStartAngle;
  15528. var angle;
  15529. var tdivisions = divisions * 2;
  15530. for ( j = 1; j <= tdivisions; j ++ ) {
  15531. t = j / tdivisions;
  15532. if ( ! aClockwise ) {
  15533. t = 1 - t;
  15534. }
  15535. angle = aStartAngle + t * deltaAngle;
  15536. tx = aX + xRadius * Math.cos( angle );
  15537. ty = aY + yRadius * Math.sin( angle );
  15538. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  15539. points.push( new THREE.Vector2( tx, ty ) );
  15540. }
  15541. //console.log(points);
  15542. break;
  15543. } // end switch
  15544. }
  15545. // Normalize to remove the closing point by default.
  15546. var lastPoint = points[ points.length - 1];
  15547. var EPSILON = 0.0000000001;
  15548. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  15549. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  15550. points.splice( points.length - 1, 1);
  15551. if ( closedPath ) {
  15552. points.push( points[ 0 ] );
  15553. }
  15554. return points;
  15555. };
  15556. // Breaks path into shapes
  15557. THREE.Path.prototype.toShapes = function() {
  15558. var i, il, item, action, args;
  15559. var subPaths = [], lastPath = new THREE.Path();
  15560. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  15561. item = this.actions[ i ];
  15562. args = item.args;
  15563. action = item.action;
  15564. if ( action == THREE.PathActions.MOVE_TO ) {
  15565. if ( lastPath.actions.length != 0 ) {
  15566. subPaths.push( lastPath );
  15567. lastPath = new THREE.Path();
  15568. }
  15569. }
  15570. lastPath[ action ].apply( lastPath, args );
  15571. }
  15572. if ( lastPath.actions.length != 0 ) {
  15573. subPaths.push( lastPath );
  15574. }
  15575. // console.log(subPaths);
  15576. if ( subPaths.length == 0 ) return [];
  15577. var tmpPath, tmpShape, shapes = [];
  15578. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  15579. // console.log("Holes first", holesFirst);
  15580. if ( subPaths.length == 1) {
  15581. tmpPath = subPaths[0];
  15582. tmpShape = new THREE.Shape();
  15583. tmpShape.actions = tmpPath.actions;
  15584. tmpShape.curves = tmpPath.curves;
  15585. shapes.push( tmpShape );
  15586. return shapes;
  15587. };
  15588. if ( holesFirst ) {
  15589. tmpShape = new THREE.Shape();
  15590. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  15591. tmpPath = subPaths[ i ];
  15592. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  15593. tmpShape.actions = tmpPath.actions;
  15594. tmpShape.curves = tmpPath.curves;
  15595. shapes.push( tmpShape );
  15596. tmpShape = new THREE.Shape();
  15597. //console.log('cw', i);
  15598. } else {
  15599. tmpShape.holes.push( tmpPath );
  15600. //console.log('ccw', i);
  15601. }
  15602. }
  15603. } else {
  15604. // Shapes first
  15605. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  15606. tmpPath = subPaths[ i ];
  15607. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  15608. if ( tmpShape ) shapes.push( tmpShape );
  15609. tmpShape = new THREE.Shape();
  15610. tmpShape.actions = tmpPath.actions;
  15611. tmpShape.curves = tmpPath.curves;
  15612. } else {
  15613. tmpShape.holes.push( tmpPath );
  15614. }
  15615. }
  15616. shapes.push( tmpShape );
  15617. }
  15618. //console.log("shape", shapes);
  15619. return shapes;
  15620. };
  15621. /**
  15622. * @author zz85 / http://www.lab4games.net/zz85/blog
  15623. * Defines a 2d shape plane using paths.
  15624. **/
  15625. // STEP 1 Create a path.
  15626. // STEP 2 Turn path into shape.
  15627. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  15628. // STEP 3a - Extract points from each shape, turn to vertices
  15629. // STEP 3b - Triangulate each shape, add faces.
  15630. THREE.Shape = function ( ) {
  15631. THREE.Path.apply( this, arguments );
  15632. this.holes = [];
  15633. };
  15634. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  15635. // Convenience method to return ExtrudeGeometry
  15636. THREE.Shape.prototype.extrude = function ( options ) {
  15637. var extruded = new THREE.ExtrudeGeometry( this, options );
  15638. return extruded;
  15639. };
  15640. // Get points of holes
  15641. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  15642. var i, il = this.holes.length, holesPts = [];
  15643. for ( i = 0; i < il; i ++ ) {
  15644. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  15645. }
  15646. return holesPts;
  15647. };
  15648. // Get points of holes (spaced by regular distance)
  15649. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  15650. var i, il = this.holes.length, holesPts = [];
  15651. for ( i = 0; i < il; i ++ ) {
  15652. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  15653. }
  15654. return holesPts;
  15655. };
  15656. // Get points of shape and holes (keypoints based on segments parameter)
  15657. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  15658. return {
  15659. shape: this.getTransformedPoints( divisions ),
  15660. holes: this.getPointsHoles( divisions )
  15661. };
  15662. };
  15663. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  15664. if (this.useSpacedPoints) {
  15665. return this.extractAllSpacedPoints(divisions);
  15666. }
  15667. return this.extractAllPoints(divisions);
  15668. };
  15669. //
  15670. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  15671. //
  15672. // return {
  15673. //
  15674. // shape: this.transform( bend, divisions ),
  15675. // holes: this.getPointsHoles( divisions, bend )
  15676. //
  15677. // };
  15678. //
  15679. // };
  15680. // Get points of shape and holes (spaced by regular distance)
  15681. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  15682. return {
  15683. shape: this.getTransformedSpacedPoints( divisions ),
  15684. holes: this.getSpacedPointsHoles( divisions )
  15685. };
  15686. };
  15687. /**************************************************************
  15688. * Utils
  15689. **************************************************************/
  15690. THREE.Shape.Utils = {
  15691. /*
  15692. contour - array of vector2 for contour
  15693. holes - array of array of vector2
  15694. */
  15695. removeHoles: function ( contour, holes ) {
  15696. var shape = contour.concat(); // work on this shape
  15697. var allpoints = shape.concat();
  15698. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  15699. var prevShapeVert, nextShapeVert,
  15700. prevHoleVert, nextHoleVert,
  15701. holeIndex, shapeIndex,
  15702. shapeId, shapeGroup,
  15703. h, h2,
  15704. hole, shortest, d,
  15705. p, pts1, pts2,
  15706. tmpShape1, tmpShape2,
  15707. tmpHole1, tmpHole2,
  15708. verts = [];
  15709. for ( h = 0; h < holes.length; h ++ ) {
  15710. hole = holes[ h ];
  15711. /*
  15712. shapeholes[ h ].concat(); // preserves original
  15713. holes.push( hole );
  15714. */
  15715. Array.prototype.push.apply( allpoints, hole );
  15716. shortest = Number.POSITIVE_INFINITY;
  15717. // Find the shortest pair of pts between shape and hole
  15718. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  15719. // Using distanceToSquared() intead of distanceTo() should speed a little
  15720. // since running square roots operations are reduced.
  15721. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  15722. pts1 = hole[ h2 ];
  15723. var dist = [];
  15724. for ( p = 0; p < shape.length; p++ ) {
  15725. pts2 = shape[ p ];
  15726. d = pts1.distanceToSquared( pts2 );
  15727. dist.push( d );
  15728. if ( d < shortest ) {
  15729. shortest = d;
  15730. holeIndex = h2;
  15731. shapeIndex = p;
  15732. }
  15733. }
  15734. }
  15735. //console.log("shortest", shortest, dist);
  15736. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  15737. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  15738. var areaapts = [
  15739. hole[ holeIndex ],
  15740. shape[ shapeIndex ],
  15741. shape[ prevShapeVert ]
  15742. ];
  15743. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  15744. var areabpts = [
  15745. hole[ holeIndex ],
  15746. hole[ prevHoleVert ],
  15747. shape[ shapeIndex ]
  15748. ];
  15749. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  15750. var shapeOffset = 1;
  15751. var holeOffset = -1;
  15752. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  15753. shapeIndex += shapeOffset;
  15754. holeIndex += holeOffset;
  15755. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  15756. shapeIndex %= shape.length;
  15757. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  15758. holeIndex %= hole.length;
  15759. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  15760. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  15761. areaapts = [
  15762. hole[ holeIndex ],
  15763. shape[ shapeIndex ],
  15764. shape[ prevShapeVert ]
  15765. ];
  15766. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  15767. areabpts = [
  15768. hole[ holeIndex ],
  15769. hole[ prevHoleVert ],
  15770. shape[ shapeIndex ]
  15771. ];
  15772. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  15773. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  15774. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  15775. // In case areas are not correct.
  15776. //console.log("USE THIS");
  15777. shapeIndex = oldShapeIndex;
  15778. holeIndex = oldHoleIndex ;
  15779. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  15780. shapeIndex %= shape.length;
  15781. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  15782. holeIndex %= hole.length;
  15783. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  15784. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  15785. } else {
  15786. //console.log("USE THAT ")
  15787. }
  15788. tmpShape1 = shape.slice( 0, shapeIndex );
  15789. tmpShape2 = shape.slice( shapeIndex );
  15790. tmpHole1 = hole.slice( holeIndex );
  15791. tmpHole2 = hole.slice( 0, holeIndex );
  15792. // Should check orders here again?
  15793. var trianglea = [
  15794. hole[ holeIndex ],
  15795. shape[ shapeIndex ],
  15796. shape[ prevShapeVert ]
  15797. ];
  15798. var triangleb = [
  15799. hole[ holeIndex ] ,
  15800. hole[ prevHoleVert ],
  15801. shape[ shapeIndex ]
  15802. ];
  15803. verts.push( trianglea );
  15804. verts.push( triangleb );
  15805. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15806. }
  15807. return {
  15808. shape:shape, /* shape with no holes */
  15809. isolatedPts: verts, /* isolated faces */
  15810. allpoints: allpoints
  15811. }
  15812. },
  15813. triangulateShape: function ( contour, holes ) {
  15814. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  15815. var shape = shapeWithoutHoles.shape,
  15816. allpoints = shapeWithoutHoles.allpoints,
  15817. isolatedPts = shapeWithoutHoles.isolatedPts;
  15818. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  15819. // 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.
  15820. //console.log( "triangles",triangles, triangles.length );
  15821. //console.log( "allpoints",allpoints, allpoints.length );
  15822. var i, il, f, face,
  15823. key, index,
  15824. allPointsMap = {},
  15825. isolatedPointsMap = {};
  15826. // prepare all points map
  15827. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15828. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  15829. if ( allPointsMap[ key ] !== undefined ) {
  15830. console.log( "Duplicate point", key );
  15831. }
  15832. allPointsMap[ key ] = i;
  15833. }
  15834. // check all face vertices against all points map
  15835. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15836. face = triangles[ i ];
  15837. for ( f = 0; f < 3; f ++ ) {
  15838. key = face[ f ].x + ":" + face[ f ].y;
  15839. index = allPointsMap[ key ];
  15840. if ( index !== undefined ) {
  15841. face[ f ] = index;
  15842. }
  15843. }
  15844. }
  15845. // check isolated points vertices against all points map
  15846. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  15847. face = isolatedPts[ i ];
  15848. for ( f = 0; f < 3; f ++ ) {
  15849. key = face[ f ].x + ":" + face[ f ].y;
  15850. index = allPointsMap[ key ];
  15851. if ( index !== undefined ) {
  15852. face[ f ] = index;
  15853. }
  15854. }
  15855. }
  15856. return triangles.concat( isolatedPts );
  15857. }, // end triangulate shapes
  15858. /*
  15859. triangulate2 : function( pts, holes ) {
  15860. // For use with Poly2Tri.js
  15861. var allpts = pts.concat();
  15862. var shape = [];
  15863. for (var p in pts) {
  15864. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  15865. }
  15866. var swctx = new js.poly2tri.SweepContext(shape);
  15867. for (var h in holes) {
  15868. var aHole = holes[h];
  15869. var newHole = []
  15870. for (i in aHole) {
  15871. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  15872. allpts.push(aHole[i]);
  15873. }
  15874. swctx.AddHole(newHole);
  15875. }
  15876. var find;
  15877. var findIndexForPt = function (pt) {
  15878. find = new THREE.Vector2(pt.x, pt.y);
  15879. var p;
  15880. for (p=0, pl = allpts.length; p<pl; p++) {
  15881. if (allpts[p].equals(find)) return p;
  15882. }
  15883. return -1;
  15884. };
  15885. // triangulate
  15886. js.poly2tri.sweep.Triangulate(swctx);
  15887. var triangles = swctx.GetTriangles();
  15888. var tr ;
  15889. var facesPts = [];
  15890. for (var t in triangles) {
  15891. tr = triangles[t];
  15892. facesPts.push([
  15893. findIndexForPt(tr.GetPoint(0)),
  15894. findIndexForPt(tr.GetPoint(1)),
  15895. findIndexForPt(tr.GetPoint(2))
  15896. ]);
  15897. }
  15898. // console.log(facesPts);
  15899. // console.log("triangles", triangles.length, triangles);
  15900. // Returns array of faces with 3 element each
  15901. return facesPts;
  15902. },
  15903. */
  15904. isClockWise: function ( pts ) {
  15905. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  15906. },
  15907. // Bezier Curves formulas obtained from
  15908. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  15909. // Quad Bezier Functions
  15910. b2p0: function ( t, p ) {
  15911. var k = 1 - t;
  15912. return k * k * p;
  15913. },
  15914. b2p1: function ( t, p ) {
  15915. return 2 * ( 1 - t ) * t * p;
  15916. },
  15917. b2p2: function ( t, p ) {
  15918. return t * t * p;
  15919. },
  15920. b2: function ( t, p0, p1, p2 ) {
  15921. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  15922. },
  15923. // Cubic Bezier Functions
  15924. b3p0: function ( t, p ) {
  15925. var k = 1 - t;
  15926. return k * k * k * p;
  15927. },
  15928. b3p1: function ( t, p ) {
  15929. var k = 1 - t;
  15930. return 3 * k * k * t * p;
  15931. },
  15932. b3p2: function ( t, p ) {
  15933. var k = 1 - t;
  15934. return 3 * k * t * t * p;
  15935. },
  15936. b3p3: function ( t, p ) {
  15937. return t * t * t * p;
  15938. },
  15939. b3: function ( t, p0, p1, p2, p3 ) {
  15940. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  15941. }
  15942. };
  15943. /**
  15944. * @author mikael emtinger / http://gomo.se/
  15945. */
  15946. THREE.AnimationHandler = (function() {
  15947. var playing = [];
  15948. var library = {};
  15949. var that = {};
  15950. //--- update ---
  15951. that.update = function( deltaTimeMS ) {
  15952. for( var i = 0; i < playing.length; i ++ )
  15953. playing[ i ].update( deltaTimeMS );
  15954. };
  15955. //--- add ---
  15956. that.addToUpdate = function( animation ) {
  15957. if ( playing.indexOf( animation ) === -1 )
  15958. playing.push( animation );
  15959. };
  15960. //--- remove ---
  15961. that.removeFromUpdate = function( animation ) {
  15962. var index = playing.indexOf( animation );
  15963. if( index !== -1 )
  15964. playing.splice( index, 1 );
  15965. };
  15966. //--- add ---
  15967. that.add = function( data ) {
  15968. if ( library[ data.name ] !== undefined )
  15969. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  15970. library[ data.name ] = data;
  15971. initData( data );
  15972. };
  15973. //--- get ---
  15974. that.get = function( name ) {
  15975. if ( typeof name === "string" ) {
  15976. if ( library[ name ] ) {
  15977. return library[ name ];
  15978. } else {
  15979. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  15980. return null;
  15981. }
  15982. } else {
  15983. // todo: add simple tween library
  15984. }
  15985. };
  15986. //--- parse ---
  15987. that.parse = function( root ) {
  15988. // setup hierarchy
  15989. var hierarchy = [];
  15990. if ( root instanceof THREE.SkinnedMesh ) {
  15991. for( var b = 0; b < root.bones.length; b++ ) {
  15992. hierarchy.push( root.bones[ b ] );
  15993. }
  15994. } else {
  15995. parseRecurseHierarchy( root, hierarchy );
  15996. }
  15997. return hierarchy;
  15998. };
  15999. var parseRecurseHierarchy = function( root, hierarchy ) {
  16000. hierarchy.push( root );
  16001. for( var c = 0; c < root.children.length; c++ )
  16002. parseRecurseHierarchy( root.children[ c ], hierarchy );
  16003. }
  16004. //--- init data ---
  16005. var initData = function( data ) {
  16006. if( data.initialized === true )
  16007. return;
  16008. // loop through all keys
  16009. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  16010. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16011. // remove minus times
  16012. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  16013. data.hierarchy[ h ].keys[ k ].time = 0;
  16014. // create quaternions
  16015. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  16016. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  16017. var quat = data.hierarchy[ h ].keys[ k ].rot;
  16018. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  16019. }
  16020. }
  16021. // prepare morph target keys
  16022. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  16023. // get all used
  16024. var usedMorphTargets = {};
  16025. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16026. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16027. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  16028. usedMorphTargets[ morphTargetName ] = -1;
  16029. }
  16030. }
  16031. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  16032. // set all used on all frames
  16033. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16034. var influences = {};
  16035. for ( var morphTargetName in usedMorphTargets ) {
  16036. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16037. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  16038. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  16039. break;
  16040. }
  16041. }
  16042. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  16043. influences[ morphTargetName ] = 0;
  16044. }
  16045. }
  16046. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  16047. }
  16048. }
  16049. // remove all keys that are on the same time
  16050. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16051. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  16052. data.hierarchy[ h ].keys.splice( k, 1 );
  16053. k --;
  16054. }
  16055. }
  16056. // set index
  16057. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16058. data.hierarchy[ h ].keys[ k ].index = k;
  16059. }
  16060. }
  16061. // JIT
  16062. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  16063. data.JIT = {};
  16064. data.JIT.hierarchy = [];
  16065. for( var h = 0; h < data.hierarchy.length; h ++ )
  16066. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  16067. // done
  16068. data.initialized = true;
  16069. };
  16070. // interpolation types
  16071. that.LINEAR = 0;
  16072. that.CATMULLROM = 1;
  16073. that.CATMULLROM_FORWARD = 2;
  16074. return that;
  16075. }());
  16076. /**
  16077. * @author mikael emtinger / http://gomo.se/
  16078. * @author mrdoob / http://mrdoob.com/
  16079. * @author alteredq / http://alteredqualia.com/
  16080. */
  16081. THREE.Animation = function ( root, name, interpolationType ) {
  16082. this.root = root;
  16083. this.data = THREE.AnimationHandler.get( name );
  16084. this.hierarchy = THREE.AnimationHandler.parse( root );
  16085. this.currentTime = 0;
  16086. this.timeScale = 1;
  16087. this.isPlaying = false;
  16088. this.isPaused = true;
  16089. this.loop = true;
  16090. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  16091. this.points = [];
  16092. this.target = new THREE.Vector3();
  16093. };
  16094. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  16095. if ( this.isPlaying === false ) {
  16096. this.isPlaying = true;
  16097. this.loop = loop !== undefined ? loop : true;
  16098. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  16099. // reset key cache
  16100. var h, hl = this.hierarchy.length,
  16101. object;
  16102. for ( h = 0; h < hl; h ++ ) {
  16103. object = this.hierarchy[ h ];
  16104. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16105. object.useQuaternion = true;
  16106. }
  16107. object.matrixAutoUpdate = true;
  16108. if ( object.animationCache === undefined ) {
  16109. object.animationCache = {};
  16110. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  16111. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  16112. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  16113. }
  16114. var prevKey = object.animationCache.prevKey;
  16115. var nextKey = object.animationCache.nextKey;
  16116. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  16117. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  16118. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  16119. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  16120. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  16121. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  16122. }
  16123. this.update( 0 );
  16124. }
  16125. this.isPaused = false;
  16126. THREE.AnimationHandler.addToUpdate( this );
  16127. };
  16128. THREE.Animation.prototype.pause = function() {
  16129. if ( this.isPaused === true ) {
  16130. THREE.AnimationHandler.addToUpdate( this );
  16131. } else {
  16132. THREE.AnimationHandler.removeFromUpdate( this );
  16133. }
  16134. this.isPaused = !this.isPaused;
  16135. };
  16136. THREE.Animation.prototype.stop = function() {
  16137. this.isPlaying = false;
  16138. this.isPaused = false;
  16139. THREE.AnimationHandler.removeFromUpdate( this );
  16140. };
  16141. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  16142. // early out
  16143. if ( this.isPlaying === false ) return;
  16144. // vars
  16145. var types = [ "pos", "rot", "scl" ];
  16146. var type;
  16147. var scale;
  16148. var vector;
  16149. var prevXYZ, nextXYZ;
  16150. var prevKey, nextKey;
  16151. var object;
  16152. var animationCache;
  16153. var frame;
  16154. var JIThierarchy = this.data.JIT.hierarchy;
  16155. var currentTime, unloopedCurrentTime;
  16156. var currentPoint, forwardPoint, angle;
  16157. this.currentTime += deltaTimeMS * this.timeScale;
  16158. unloopedCurrentTime = this.currentTime;
  16159. currentTime = this.currentTime = this.currentTime % this.data.length;
  16160. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  16161. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  16162. object = this.hierarchy[ h ];
  16163. animationCache = object.animationCache;
  16164. // loop through pos/rot/scl
  16165. for ( var t = 0; t < 3; t ++ ) {
  16166. // get keys
  16167. type = types[ t ];
  16168. prevKey = animationCache.prevKey[ type ];
  16169. nextKey = animationCache.nextKey[ type ];
  16170. // switch keys?
  16171. if ( nextKey.time <= unloopedCurrentTime ) {
  16172. // did we loop?
  16173. if ( currentTime < unloopedCurrentTime ) {
  16174. if ( this.loop ) {
  16175. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  16176. nextKey = this.getNextKeyWith( type, h, 1 );
  16177. while( nextKey.time < currentTime ) {
  16178. prevKey = nextKey;
  16179. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16180. }
  16181. } else {
  16182. this.stop();
  16183. return;
  16184. }
  16185. } else {
  16186. do {
  16187. prevKey = nextKey;
  16188. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16189. } while( nextKey.time < currentTime )
  16190. }
  16191. animationCache.prevKey[ type ] = prevKey;
  16192. animationCache.nextKey[ type ] = nextKey;
  16193. }
  16194. object.matrixAutoUpdate = true;
  16195. object.matrixWorldNeedsUpdate = true;
  16196. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  16197. prevXYZ = prevKey[ type ];
  16198. nextXYZ = nextKey[ type ];
  16199. // check scale error
  16200. if ( scale < 0 || scale > 1 ) {
  16201. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  16202. scale = scale < 0 ? 0 : 1;
  16203. }
  16204. // interpolate
  16205. if ( type === "pos" ) {
  16206. vector = object.position;
  16207. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  16208. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  16209. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  16210. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  16211. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16212. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16213. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  16214. this.points[ 1 ] = prevXYZ;
  16215. this.points[ 2 ] = nextXYZ;
  16216. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  16217. scale = scale * 0.33 + 0.33;
  16218. currentPoint = this.interpolateCatmullRom( this.points, scale );
  16219. vector.x = currentPoint[ 0 ];
  16220. vector.y = currentPoint[ 1 ];
  16221. vector.z = currentPoint[ 2 ];
  16222. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16223. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  16224. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  16225. this.target.subSelf( vector );
  16226. this.target.y = 0;
  16227. this.target.normalize();
  16228. angle = Math.atan2( this.target.x, this.target.z );
  16229. object.rotation.set( 0, angle, 0 );
  16230. }
  16231. }
  16232. } else if ( type === "rot" ) {
  16233. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  16234. } else if ( type === "scl" ) {
  16235. vector = object.scale;
  16236. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  16237. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  16238. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  16239. }
  16240. }
  16241. }
  16242. };
  16243. // Catmull-Rom spline
  16244. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  16245. var c = [], v3 = [],
  16246. point, intPoint, weight, w2, w3,
  16247. pa, pb, pc, pd;
  16248. point = ( points.length - 1 ) * scale;
  16249. intPoint = Math.floor( point );
  16250. weight = point - intPoint;
  16251. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  16252. c[ 1 ] = intPoint;
  16253. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  16254. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  16255. pa = points[ c[ 0 ] ];
  16256. pb = points[ c[ 1 ] ];
  16257. pc = points[ c[ 2 ] ];
  16258. pd = points[ c[ 3 ] ];
  16259. w2 = weight * weight;
  16260. w3 = weight * w2;
  16261. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  16262. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  16263. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  16264. return v3;
  16265. };
  16266. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  16267. var v0 = ( p2 - p0 ) * 0.5,
  16268. v1 = ( p3 - p1 ) * 0.5;
  16269. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16270. };
  16271. // Get next key with
  16272. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  16273. var keys = this.data.hierarchy[ h ].keys;
  16274. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16275. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16276. key = key < keys.length - 1 ? key : keys.length - 1;
  16277. } else {
  16278. key = key % keys.length;
  16279. }
  16280. for ( ; key < keys.length; key++ ) {
  16281. if ( keys[ key ][ type ] !== undefined ) {
  16282. return keys[ key ];
  16283. }
  16284. }
  16285. return this.data.hierarchy[ h ].keys[ 0 ];
  16286. };
  16287. // Get previous key with
  16288. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  16289. var keys = this.data.hierarchy[ h ].keys;
  16290. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16291. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16292. key = key > 0 ? key : 0;
  16293. } else {
  16294. key = key >= 0 ? key : key + keys.length;
  16295. }
  16296. for ( ; key >= 0; key -- ) {
  16297. if ( keys[ key ][ type ] !== undefined ) {
  16298. return keys[ key ];
  16299. }
  16300. }
  16301. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  16302. };
  16303. /**
  16304. * @author mikael emtinger / http://gomo.se/
  16305. * @author mrdoob / http://mrdoob.com/
  16306. * @author alteredq / http://alteredqualia.com/
  16307. * @author khang duong
  16308. * @author erik kitson
  16309. */
  16310. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  16311. this.root = root;
  16312. this.data = THREE.AnimationHandler.get( data );
  16313. this.hierarchy = THREE.AnimationHandler.parse( root );
  16314. this.currentTime = 0;
  16315. this.timeScale = 0.001;
  16316. this.isPlaying = false;
  16317. this.isPaused = true;
  16318. this.loop = true;
  16319. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  16320. // initialize to first keyframes
  16321. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  16322. var keys = this.data.hierarchy[h].keys,
  16323. sids = this.data.hierarchy[h].sids,
  16324. obj = this.hierarchy[h];
  16325. if ( keys.length && sids ) {
  16326. for ( var s = 0; s < sids.length; s++ ) {
  16327. var sid = sids[ s ],
  16328. next = this.getNextKeyWith( sid, h, 0 );
  16329. if ( next ) {
  16330. next.apply( sid );
  16331. }
  16332. }
  16333. obj.matrixAutoUpdate = false;
  16334. this.data.hierarchy[h].node.updateMatrix();
  16335. obj.matrixWorldNeedsUpdate = true;
  16336. }
  16337. }
  16338. };
  16339. // Play
  16340. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  16341. if( !this.isPlaying ) {
  16342. this.isPlaying = true;
  16343. this.loop = loop !== undefined ? loop : true;
  16344. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  16345. this.startTimeMs = startTimeMS;
  16346. this.startTime = 10000000;
  16347. this.endTime = -this.startTime;
  16348. // reset key cache
  16349. var h, hl = this.hierarchy.length,
  16350. object,
  16351. node;
  16352. for ( h = 0; h < hl; h++ ) {
  16353. object = this.hierarchy[ h ];
  16354. node = this.data.hierarchy[ h ];
  16355. object.useQuaternion = true;
  16356. if ( node.animationCache === undefined ) {
  16357. node.animationCache = {};
  16358. node.animationCache.prevKey = null;
  16359. node.animationCache.nextKey = null;
  16360. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  16361. }
  16362. var keys = this.data.hierarchy[h].keys;
  16363. if (keys.length) {
  16364. node.animationCache.prevKey = keys[ 0 ];
  16365. node.animationCache.nextKey = keys[ 1 ];
  16366. this.startTime = Math.min( keys[0].time, this.startTime );
  16367. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  16368. }
  16369. }
  16370. this.update( 0 );
  16371. }
  16372. this.isPaused = false;
  16373. THREE.AnimationHandler.addToUpdate( this );
  16374. };
  16375. // Pause
  16376. THREE.KeyFrameAnimation.prototype.pause = function() {
  16377. if( this.isPaused ) {
  16378. THREE.AnimationHandler.addToUpdate( this );
  16379. } else {
  16380. THREE.AnimationHandler.removeFromUpdate( this );
  16381. }
  16382. this.isPaused = !this.isPaused;
  16383. };
  16384. // Stop
  16385. THREE.KeyFrameAnimation.prototype.stop = function() {
  16386. this.isPlaying = false;
  16387. this.isPaused = false;
  16388. THREE.AnimationHandler.removeFromUpdate( this );
  16389. // reset JIT matrix and remove cache
  16390. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  16391. var obj = this.hierarchy[ h ];
  16392. var node = this.data.hierarchy[ h ];
  16393. if ( node.animationCache !== undefined ) {
  16394. var original = node.animationCache.originalMatrix;
  16395. if( obj instanceof THREE.Bone ) {
  16396. original.copy( obj.skinMatrix );
  16397. obj.skinMatrix = original;
  16398. } else {
  16399. original.copy( obj.matrix );
  16400. obj.matrix = original;
  16401. }
  16402. delete node.animationCache;
  16403. }
  16404. }
  16405. };
  16406. // Update
  16407. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  16408. // early out
  16409. if( !this.isPlaying ) return;
  16410. // vars
  16411. var prevKey, nextKey;
  16412. var object;
  16413. var node;
  16414. var frame;
  16415. var JIThierarchy = this.data.JIT.hierarchy;
  16416. var currentTime, unloopedCurrentTime;
  16417. var looped;
  16418. // update
  16419. this.currentTime += deltaTimeMS * this.timeScale;
  16420. unloopedCurrentTime = this.currentTime;
  16421. currentTime = this.currentTime = this.currentTime % this.data.length;
  16422. // if looped around, the current time should be based on the startTime
  16423. if ( currentTime < this.startTimeMs ) {
  16424. currentTime = this.currentTime = this.startTimeMs + currentTime;
  16425. }
  16426. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  16427. looped = currentTime < unloopedCurrentTime;
  16428. if ( looped && !this.loop ) {
  16429. // Set the animation to the last keyframes and stop
  16430. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  16431. var keys = this.data.hierarchy[h].keys,
  16432. sids = this.data.hierarchy[h].sids,
  16433. end = keys.length-1,
  16434. obj = this.hierarchy[h];
  16435. if ( keys.length ) {
  16436. for ( var s = 0; s < sids.length; s++ ) {
  16437. var sid = sids[ s ],
  16438. prev = this.getPrevKeyWith( sid, h, end );
  16439. if ( prev ) {
  16440. prev.apply( sid );
  16441. }
  16442. }
  16443. this.data.hierarchy[h].node.updateMatrix();
  16444. obj.matrixWorldNeedsUpdate = true;
  16445. }
  16446. }
  16447. this.stop();
  16448. return;
  16449. }
  16450. // check pre-infinity
  16451. if ( currentTime < this.startTime ) {
  16452. return;
  16453. }
  16454. // update
  16455. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  16456. object = this.hierarchy[ h ];
  16457. node = this.data.hierarchy[ h ];
  16458. var keys = node.keys,
  16459. animationCache = node.animationCache;
  16460. // use JIT?
  16461. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  16462. if( object instanceof THREE.Bone ) {
  16463. object.skinMatrix = JIThierarchy[ h ][ frame ];
  16464. object.matrixWorldNeedsUpdate = false;
  16465. } else {
  16466. object.matrix = JIThierarchy[ h ][ frame ];
  16467. object.matrixWorldNeedsUpdate = true;
  16468. }
  16469. // use interpolation
  16470. } else if ( keys.length ) {
  16471. // make sure so original matrix and not JIT matrix is set
  16472. if ( this.JITCompile && animationCache ) {
  16473. if( object instanceof THREE.Bone ) {
  16474. object.skinMatrix = animationCache.originalMatrix;
  16475. } else {
  16476. object.matrix = animationCache.originalMatrix;
  16477. }
  16478. }
  16479. prevKey = animationCache.prevKey;
  16480. nextKey = animationCache.nextKey;
  16481. if ( prevKey && nextKey ) {
  16482. // switch keys?
  16483. if ( nextKey.time <= unloopedCurrentTime ) {
  16484. // did we loop?
  16485. if ( looped && this.loop ) {
  16486. prevKey = keys[ 0 ];
  16487. nextKey = keys[ 1 ];
  16488. while ( nextKey.time < currentTime ) {
  16489. prevKey = nextKey;
  16490. nextKey = keys[ prevKey.index + 1 ];
  16491. }
  16492. } else if ( !looped ) {
  16493. var lastIndex = keys.length - 1;
  16494. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  16495. prevKey = nextKey;
  16496. nextKey = keys[ prevKey.index + 1 ];
  16497. }
  16498. }
  16499. animationCache.prevKey = prevKey;
  16500. animationCache.nextKey = nextKey;
  16501. }
  16502. if(nextKey.time >= currentTime)
  16503. prevKey.interpolate( nextKey, currentTime );
  16504. else
  16505. prevKey.interpolate( nextKey, nextKey.time);
  16506. }
  16507. this.data.hierarchy[h].node.updateMatrix();
  16508. object.matrixWorldNeedsUpdate = true;
  16509. }
  16510. }
  16511. // update JIT?
  16512. if ( this.JITCompile ) {
  16513. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  16514. this.hierarchy[ 0 ].updateMatrixWorld( true );
  16515. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  16516. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  16517. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  16518. } else {
  16519. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  16520. }
  16521. }
  16522. }
  16523. }
  16524. };
  16525. // Get next key with
  16526. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  16527. var keys = this.data.hierarchy[ h ].keys;
  16528. key = key % keys.length;
  16529. for ( ; key < keys.length; key++ ) {
  16530. if ( keys[ key ].hasTarget( sid ) ) {
  16531. return keys[ key ];
  16532. }
  16533. }
  16534. return keys[ 0 ];
  16535. };
  16536. // Get previous key with
  16537. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  16538. var keys = this.data.hierarchy[ h ].keys;
  16539. key = key >= 0 ? key : key + keys.length;
  16540. for ( ; key >= 0; key-- ) {
  16541. if ( keys[ key ].hasTarget( sid ) ) {
  16542. return keys[ key ];
  16543. }
  16544. }
  16545. return keys[ keys.length - 1 ];
  16546. };
  16547. /**
  16548. * Camera for rendering cube maps
  16549. * - renders scene into axis-aligned cube
  16550. *
  16551. * @author alteredq / http://alteredqualia.com/
  16552. */
  16553. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  16554. THREE.Object3D.call( this );
  16555. var fov = 90, aspect = 1;
  16556. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16557. cameraPX.up.set( 0, -1, 0 );
  16558. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  16559. this.add( cameraPX );
  16560. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16561. cameraNX.up.set( 0, -1, 0 );
  16562. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  16563. this.add( cameraNX );
  16564. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16565. cameraPY.up.set( 0, 0, 1 );
  16566. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  16567. this.add( cameraPY );
  16568. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16569. cameraNY.up.set( 0, 0, -1 );
  16570. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  16571. this.add( cameraNY );
  16572. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16573. cameraPZ.up.set( 0, -1, 0 );
  16574. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  16575. this.add( cameraPZ );
  16576. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16577. cameraNZ.up.set( 0, -1, 0 );
  16578. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  16579. this.add( cameraNZ );
  16580. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  16581. this.updateCubeMap = function ( renderer, scene ) {
  16582. var renderTarget = this.renderTarget;
  16583. var generateMipmaps = renderTarget.generateMipmaps;
  16584. renderTarget.generateMipmaps = false;
  16585. renderTarget.activeCubeFace = 0;
  16586. renderer.render( scene, cameraPX, renderTarget );
  16587. renderTarget.activeCubeFace = 1;
  16588. renderer.render( scene, cameraNX, renderTarget );
  16589. renderTarget.activeCubeFace = 2;
  16590. renderer.render( scene, cameraPY, renderTarget );
  16591. renderTarget.activeCubeFace = 3;
  16592. renderer.render( scene, cameraNY, renderTarget );
  16593. renderTarget.activeCubeFace = 4;
  16594. renderer.render( scene, cameraPZ, renderTarget );
  16595. renderTarget.generateMipmaps = generateMipmaps;
  16596. renderTarget.activeCubeFace = 5;
  16597. renderer.render( scene, cameraNZ, renderTarget );
  16598. };
  16599. };
  16600. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  16601. /*
  16602. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  16603. *
  16604. * A general perpose camera, for setting FOV, Lens Focal Length,
  16605. * and switching between perspective and orthographic views easily.
  16606. * Use this only if you do not wish to manage
  16607. * both a Orthographic and Perspective Camera
  16608. *
  16609. */
  16610. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  16611. THREE.Camera.call( this );
  16612. this.fov = fov;
  16613. this.left = -width / 2;
  16614. this.right = width / 2
  16615. this.top = height / 2;
  16616. this.bottom = -height / 2;
  16617. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  16618. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  16619. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  16620. this.zoom = 1;
  16621. this.toPerspective();
  16622. var aspect = width/height;
  16623. };
  16624. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  16625. THREE.CombinedCamera.prototype.toPerspective = function () {
  16626. // Switches to the Perspective Camera
  16627. this.near = this.cameraP.near;
  16628. this.far = this.cameraP.far;
  16629. this.cameraP.fov = this.fov / this.zoom ;
  16630. this.cameraP.updateProjectionMatrix();
  16631. this.projectionMatrix = this.cameraP.projectionMatrix;
  16632. this.inPerspectiveMode = true;
  16633. this.inOrthographicMode = false;
  16634. };
  16635. THREE.CombinedCamera.prototype.toOrthographic = function () {
  16636. // Switches to the Orthographic camera estimating viewport from Perspective
  16637. var fov = this.fov;
  16638. var aspect = this.cameraP.aspect;
  16639. var near = this.cameraP.near;
  16640. var far = this.cameraP.far;
  16641. // The size that we set is the mid plane of the viewing frustum
  16642. var hyperfocus = ( near + far ) / 2;
  16643. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  16644. var planeHeight = 2 * halfHeight;
  16645. var planeWidth = planeHeight * aspect;
  16646. var halfWidth = planeWidth / 2;
  16647. halfHeight /= this.zoom;
  16648. halfWidth /= this.zoom;
  16649. this.cameraO.left = -halfWidth;
  16650. this.cameraO.right = halfWidth;
  16651. this.cameraO.top = halfHeight;
  16652. this.cameraO.bottom = -halfHeight;
  16653. // this.cameraO.left = -farHalfWidth;
  16654. // this.cameraO.right = farHalfWidth;
  16655. // this.cameraO.top = farHalfHeight;
  16656. // this.cameraO.bottom = -farHalfHeight;
  16657. // this.cameraO.left = this.left / this.zoom;
  16658. // this.cameraO.right = this.right / this.zoom;
  16659. // this.cameraO.top = this.top / this.zoom;
  16660. // this.cameraO.bottom = this.bottom / this.zoom;
  16661. this.cameraO.updateProjectionMatrix();
  16662. this.near = this.cameraO.near;
  16663. this.far = this.cameraO.far;
  16664. this.projectionMatrix = this.cameraO.projectionMatrix;
  16665. this.inPerspectiveMode = false;
  16666. this.inOrthographicMode = true;
  16667. };
  16668. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  16669. this.cameraP.aspect = width / height;
  16670. this.left = -width / 2;
  16671. this.right = width / 2
  16672. this.top = height / 2;
  16673. this.bottom = -height / 2;
  16674. };
  16675. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  16676. this.fov = fov;
  16677. if ( this.inPerspectiveMode ) {
  16678. this.toPerspective();
  16679. } else {
  16680. this.toOrthographic();
  16681. }
  16682. };
  16683. // For mantaining similar API with PerspectiveCamera
  16684. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  16685. if ( this.inPerspectiveMode ) {
  16686. this.toPerspective();
  16687. } else {
  16688. this.toPerspective();
  16689. this.toOrthographic();
  16690. }
  16691. };
  16692. /*
  16693. * Uses Focal Length (in mm) to estimate and set FOV
  16694. * 35mm (fullframe) camera is used if frame size is not specified;
  16695. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  16696. */
  16697. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  16698. if ( frameHeight === undefined ) frameHeight = 24;
  16699. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  16700. this.setFov( fov );
  16701. return fov;
  16702. };
  16703. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  16704. this.zoom = zoom;
  16705. if ( this.inPerspectiveMode ) {
  16706. this.toPerspective();
  16707. } else {
  16708. this.toOrthographic();
  16709. }
  16710. };
  16711. THREE.CombinedCamera.prototype.toFrontView = function() {
  16712. this.rotation.x = 0;
  16713. this.rotation.y = 0;
  16714. this.rotation.z = 0;
  16715. // should we be modifing the matrix instead?
  16716. this.rotationAutoUpdate = false;
  16717. };
  16718. THREE.CombinedCamera.prototype.toBackView = function() {
  16719. this.rotation.x = 0;
  16720. this.rotation.y = Math.PI;
  16721. this.rotation.z = 0;
  16722. this.rotationAutoUpdate = false;
  16723. };
  16724. THREE.CombinedCamera.prototype.toLeftView = function() {
  16725. this.rotation.x = 0;
  16726. this.rotation.y = - Math.PI / 2;
  16727. this.rotation.z = 0;
  16728. this.rotationAutoUpdate = false;
  16729. };
  16730. THREE.CombinedCamera.prototype.toRightView = function() {
  16731. this.rotation.x = 0;
  16732. this.rotation.y = Math.PI / 2;
  16733. this.rotation.z = 0;
  16734. this.rotationAutoUpdate = false;
  16735. };
  16736. THREE.CombinedCamera.prototype.toTopView = function() {
  16737. this.rotation.x = - Math.PI / 2;
  16738. this.rotation.y = 0;
  16739. this.rotation.z = 0;
  16740. this.rotationAutoUpdate = false;
  16741. };
  16742. THREE.CombinedCamera.prototype.toBottomView = function() {
  16743. this.rotation.x = Math.PI / 2;
  16744. this.rotation.y = 0;
  16745. this.rotation.z = 0;
  16746. this.rotationAutoUpdate = false;
  16747. };
  16748. /**
  16749. * @author mrdoob / http://mrdoob.com/
  16750. * @author alteredq / http://alteredqualia.com/
  16751. * @author paulirish / http://paulirish.com/
  16752. */
  16753. THREE.FirstPersonControls = function ( object, domElement ) {
  16754. this.object = object;
  16755. this.target = new THREE.Vector3( 0, 0, 0 );
  16756. this.domElement = ( domElement !== undefined ) ? domElement : document;
  16757. this.movementSpeed = 1.0;
  16758. this.lookSpeed = 0.005;
  16759. this.lookVertical = true;
  16760. this.autoForward = false;
  16761. // this.invertVertical = false;
  16762. this.activeLook = true;
  16763. this.heightSpeed = false;
  16764. this.heightCoef = 1.0;
  16765. this.heightMin = 0.0;
  16766. this.heightMax = 1.0;
  16767. this.constrainVertical = false;
  16768. this.verticalMin = 0;
  16769. this.verticalMax = Math.PI;
  16770. this.autoSpeedFactor = 0.0;
  16771. this.mouseX = 0;
  16772. this.mouseY = 0;
  16773. this.lat = 0;
  16774. this.lon = 0;
  16775. this.phi = 0;
  16776. this.theta = 0;
  16777. this.moveForward = false;
  16778. this.moveBackward = false;
  16779. this.moveLeft = false;
  16780. this.moveRight = false;
  16781. this.freeze = false;
  16782. this.mouseDragOn = false;
  16783. this.viewHalfX = 0;
  16784. this.viewHalfY = 0;
  16785. if ( this.domElement !== document ) {
  16786. this.domElement.setAttribute( 'tabindex', -1 );
  16787. }
  16788. //
  16789. this.handleResize = function () {
  16790. if ( this.domElement === document ) {
  16791. this.viewHalfX = window.innerWidth / 2;
  16792. this.viewHalfY = window.innerHeight / 2;
  16793. } else {
  16794. this.viewHalfX = this.domElement.offsetWidth / 2;
  16795. this.viewHalfY = this.domElement.offsetHeight / 2;
  16796. }
  16797. };
  16798. this.onMouseDown = function ( event ) {
  16799. if ( this.domElement !== document ) {
  16800. this.domElement.focus();
  16801. }
  16802. event.preventDefault();
  16803. event.stopPropagation();
  16804. if ( this.activeLook ) {
  16805. switch ( event.button ) {
  16806. case 0: this.moveForward = true; break;
  16807. case 2: this.moveBackward = true; break;
  16808. }
  16809. }
  16810. this.mouseDragOn = true;
  16811. };
  16812. this.onMouseUp = function ( event ) {
  16813. event.preventDefault();
  16814. event.stopPropagation();
  16815. if ( this.activeLook ) {
  16816. switch ( event.button ) {
  16817. case 0: this.moveForward = false; break;
  16818. case 2: this.moveBackward = false; break;
  16819. }
  16820. }
  16821. this.mouseDragOn = false;
  16822. };
  16823. this.onMouseMove = function ( event ) {
  16824. if ( this.domElement === document ) {
  16825. this.mouseX = event.pageX - this.viewHalfX;
  16826. this.mouseY = event.pageY - this.viewHalfY;
  16827. } else {
  16828. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  16829. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  16830. }
  16831. };
  16832. this.onKeyDown = function ( event ) {
  16833. //event.preventDefault();
  16834. switch ( event.keyCode ) {
  16835. case 38: /*up*/
  16836. case 87: /*W*/ this.moveForward = true; break;
  16837. case 37: /*left*/
  16838. case 65: /*A*/ this.moveLeft = true; break;
  16839. case 40: /*down*/
  16840. case 83: /*S*/ this.moveBackward = true; break;
  16841. case 39: /*right*/
  16842. case 68: /*D*/ this.moveRight = true; break;
  16843. case 82: /*R*/ this.moveUp = true; break;
  16844. case 70: /*F*/ this.moveDown = true; break;
  16845. case 81: /*Q*/ this.freeze = !this.freeze; break;
  16846. }
  16847. };
  16848. this.onKeyUp = function ( event ) {
  16849. switch( event.keyCode ) {
  16850. case 38: /*up*/
  16851. case 87: /*W*/ this.moveForward = false; break;
  16852. case 37: /*left*/
  16853. case 65: /*A*/ this.moveLeft = false; break;
  16854. case 40: /*down*/
  16855. case 83: /*S*/ this.moveBackward = false; break;
  16856. case 39: /*right*/
  16857. case 68: /*D*/ this.moveRight = false; break;
  16858. case 82: /*R*/ this.moveUp = false; break;
  16859. case 70: /*F*/ this.moveDown = false; break;
  16860. }
  16861. };
  16862. this.update = function( delta ) {
  16863. var actualMoveSpeed = 0;
  16864. if ( this.freeze ) {
  16865. return;
  16866. } else {
  16867. if ( this.heightSpeed ) {
  16868. var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
  16869. var heightDelta = y - this.heightMin;
  16870. this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );
  16871. } else {
  16872. this.autoSpeedFactor = 0.0;
  16873. }
  16874. actualMoveSpeed = delta * this.movementSpeed;
  16875. if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
  16876. if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed );
  16877. if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed );
  16878. if ( this.moveRight ) this.object.translateX( actualMoveSpeed );
  16879. if ( this.moveUp ) this.object.translateY( actualMoveSpeed );
  16880. if ( this.moveDown ) this.object.translateY( - actualMoveSpeed );
  16881. var actualLookSpeed = delta * this.lookSpeed;
  16882. if ( !this.activeLook ) {
  16883. actualLookSpeed = 0;
  16884. }
  16885. this.lon += this.mouseX * actualLookSpeed;
  16886. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed; // * this.invertVertical?-1:1;
  16887. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  16888. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  16889. this.theta = this.lon * Math.PI / 180;
  16890. var targetPosition = this.target,
  16891. position = this.object.position;
  16892. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  16893. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  16894. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  16895. }
  16896. var verticalLookRatio = 1;
  16897. if ( this.constrainVertical ) {
  16898. verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );
  16899. }
  16900. this.lon += this.mouseX * actualLookSpeed;
  16901. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;
  16902. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  16903. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  16904. this.theta = this.lon * Math.PI / 180;
  16905. if ( this.constrainVertical ) {
  16906. this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );
  16907. }
  16908. var targetPosition = this.target,
  16909. position = this.object.position;
  16910. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  16911. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  16912. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  16913. this.object.lookAt( targetPosition );
  16914. };
  16915. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  16916. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  16917. this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
  16918. this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
  16919. this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
  16920. this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
  16921. function bind( scope, fn ) {
  16922. return function () {
  16923. fn.apply( scope, arguments );
  16924. };
  16925. };
  16926. this.handleResize();
  16927. };
  16928. /**
  16929. * @author alteredq / http://alteredqualia.com/
  16930. */
  16931. THREE.PathControls = function ( object, domElement ) {
  16932. this.object = object;
  16933. this.domElement = ( domElement !== undefined ) ? domElement : document;
  16934. this.id = "PathControls" + THREE.PathControlsIdCounter ++;
  16935. // API
  16936. this.duration = 10 * 1000; // milliseconds
  16937. this.waypoints = [];
  16938. this.useConstantSpeed = true;
  16939. this.resamplingCoef = 50;
  16940. this.debugPath = new THREE.Object3D();
  16941. this.debugDummy = new THREE.Object3D();
  16942. this.animationParent = new THREE.Object3D();
  16943. this.lookSpeed = 0.005;
  16944. this.lookVertical = true;
  16945. this.lookHorizontal = true;
  16946. this.verticalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  16947. this.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  16948. // internals
  16949. this.target = new THREE.Object3D();
  16950. this.mouseX = 0;
  16951. this.mouseY = 0;
  16952. this.lat = 0;
  16953. this.lon = 0;
  16954. this.phi = 0;
  16955. this.theta = 0;
  16956. var PI2 = Math.PI * 2,
  16957. PI180 = Math.PI / 180;
  16958. this.viewHalfX = 0;
  16959. this.viewHalfY = 0;
  16960. if ( this.domElement !== document ) {
  16961. this.domElement.setAttribute( 'tabindex', -1 );
  16962. }
  16963. // methods
  16964. this.handleResize = function () {
  16965. if ( this.domElement === document ) {
  16966. this.viewHalfX = window.innerWidth / 2;
  16967. this.viewHalfY = window.innerHeight / 2;
  16968. } else {
  16969. this.viewHalfX = this.domElement.offsetWidth / 2;
  16970. this.viewHalfY = this.domElement.offsetHeight / 2;
  16971. }
  16972. };
  16973. this.update = function ( delta ) {
  16974. var srcRange, dstRange;
  16975. if( this.lookHorizontal ) this.lon += this.mouseX * this.lookSpeed * delta;
  16976. if( this.lookVertical ) this.lat -= this.mouseY * this.lookSpeed * delta;
  16977. this.lon = Math.max( 0, Math.min( 360, this.lon ) );
  16978. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  16979. this.phi = ( 90 - this.lat ) * PI180;
  16980. this.theta = this.lon * PI180;
  16981. this.phi = normalize_angle_rad( this.phi );
  16982. // constrain vertical look angle
  16983. srcRange = this.verticalAngleMap.srcRange;
  16984. dstRange = this.verticalAngleMap.dstRange;
  16985. var tmpPhi = THREE.Math.mapLinear( this.phi, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  16986. var tmpPhiFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  16987. var tmpPhiNormalized = ( tmpPhi - dstRange[ 0 ] ) / tmpPhiFullRange;
  16988. this.phi = QuadraticEaseInOut( tmpPhiNormalized ) * tmpPhiFullRange + dstRange[ 0 ];
  16989. // constrain horizontal look angle
  16990. srcRange = this.horizontalAngleMap.srcRange;
  16991. dstRange = this.horizontalAngleMap.dstRange;
  16992. var tmpTheta = THREE.Math.mapLinear( this.theta, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  16993. var tmpThetaFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  16994. var tmpThetaNormalized = ( tmpTheta - dstRange[ 0 ] ) / tmpThetaFullRange;
  16995. this.theta = QuadraticEaseInOut( tmpThetaNormalized ) * tmpThetaFullRange + dstRange[ 0 ];
  16996. var targetPosition = this.target.position,
  16997. position = this.object.position;
  16998. targetPosition.x = 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  16999. targetPosition.y = 100 * Math.cos( this.phi );
  17000. targetPosition.z = 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  17001. this.object.lookAt( this.target.position );
  17002. };
  17003. this.onMouseMove = function ( event ) {
  17004. if ( this.domElement === document ) {
  17005. this.mouseX = event.pageX - this.viewHalfX;
  17006. this.mouseY = event.pageY - this.viewHalfY;
  17007. } else {
  17008. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  17009. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  17010. }
  17011. };
  17012. // utils
  17013. function normalize_angle_rad( a ) {
  17014. var b = a % PI2;
  17015. return b >= 0 ? b : b + PI2;
  17016. };
  17017. function distance( a, b ) {
  17018. var dx = a[ 0 ] - b[ 0 ],
  17019. dy = a[ 1 ] - b[ 1 ],
  17020. dz = a[ 2 ] - b[ 2 ];
  17021. return Math.sqrt( dx * dx + dy * dy + dz * dz );
  17022. };
  17023. function QuadraticEaseInOut ( k ) {
  17024. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  17025. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  17026. };
  17027. function bind( scope, fn ) {
  17028. return function () {
  17029. fn.apply( scope, arguments );
  17030. };
  17031. };
  17032. function initAnimationPath( parent, spline, name, duration ) {
  17033. var animationData = {
  17034. name: name,
  17035. fps: 0.6,
  17036. length: duration,
  17037. hierarchy: []
  17038. };
  17039. var i,
  17040. parentAnimation, childAnimation,
  17041. path = spline.getControlPointsArray(),
  17042. sl = spline.getLength(),
  17043. pl = path.length,
  17044. t = 0,
  17045. first = 0,
  17046. last = pl - 1;
  17047. parentAnimation = { parent: -1, keys: [] };
  17048. parentAnimation.keys[ first ] = { time: 0, pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  17049. parentAnimation.keys[ last ] = { time: duration, pos: path[ last ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  17050. for ( i = 1; i < pl - 1; i++ ) {
  17051. // real distance (approximation via linear segments)
  17052. t = duration * sl.chunks[ i ] / sl.total;
  17053. // equal distance
  17054. //t = duration * ( i / pl );
  17055. // linear distance
  17056. //t += duration * distance( path[ i ], path[ i - 1 ] ) / sl.total;
  17057. parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };
  17058. }
  17059. animationData.hierarchy[ 0 ] = parentAnimation;
  17060. THREE.AnimationHandler.add( animationData );
  17061. return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );
  17062. };
  17063. function createSplineGeometry( spline, n_sub ) {
  17064. var i, index, position,
  17065. geometry = new THREE.Geometry();
  17066. for ( i = 0; i < spline.points.length * n_sub; i ++ ) {
  17067. index = i / ( spline.points.length * n_sub );
  17068. position = spline.getPoint( index );
  17069. geometry.vertices[ i ] = new THREE.Vector3( position.x, position.y, position.z );
  17070. }
  17071. return geometry;
  17072. };
  17073. function createPath( parent, spline ) {
  17074. var lineGeo = createSplineGeometry( spline, 10 ),
  17075. particleGeo = createSplineGeometry( spline, 10 ),
  17076. lineMat = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 3 } ),
  17077. lineObj = new THREE.Line( lineGeo, lineMat ),
  17078. particleObj = new THREE.ParticleSystem( particleGeo, new THREE.ParticleBasicMaterial( { color: 0xffaa00, size: 3 } ) );
  17079. lineObj.scale.set( 1, 1, 1 );
  17080. parent.add( lineObj );
  17081. particleObj.scale.set( 1, 1, 1 );
  17082. parent.add( particleObj );
  17083. var waypoint,
  17084. geo = new THREE.SphereGeometry( 1, 16, 8 ),
  17085. mat = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  17086. for ( var i = 0; i < spline.points.length; i ++ ) {
  17087. waypoint = new THREE.Mesh( geo, mat );
  17088. waypoint.position.copy( spline.points[ i ] );
  17089. parent.add( waypoint );
  17090. }
  17091. };
  17092. this.init = function ( ) {
  17093. // constructor
  17094. this.spline = new THREE.Spline();
  17095. this.spline.initFromArray( this.waypoints );
  17096. if ( this.useConstantSpeed ) {
  17097. this.spline.reparametrizeByArcLength( this.resamplingCoef );
  17098. }
  17099. if ( this.createDebugDummy ) {
  17100. var dummyParentMaterial = new THREE.MeshLambertMaterial( { color: 0x0077ff } ),
  17101. dummyChildMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ),
  17102. dummyParentGeo = new THREE.CubeGeometry( 10, 10, 20 ),
  17103. dummyChildGeo = new THREE.CubeGeometry( 2, 2, 10 );
  17104. this.animationParent = new THREE.Mesh( dummyParentGeo, dummyParentMaterial );
  17105. var dummyChild = new THREE.Mesh( dummyChildGeo, dummyChildMaterial );
  17106. dummyChild.position.set( 0, 10, 0 );
  17107. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  17108. this.animationParent.add( this.object );
  17109. this.animationParent.add( this.target );
  17110. this.animationParent.add( dummyChild );
  17111. } else {
  17112. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  17113. this.animationParent.add( this.target );
  17114. this.animationParent.add( this.object );
  17115. }
  17116. if ( this.createDebugPath ) {
  17117. createPath( this.debugPath, this.spline );
  17118. }
  17119. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  17120. };
  17121. this.handleResize();
  17122. };
  17123. THREE.PathControlsIdCounter = 0;
  17124. /**
  17125. * @author James Baicoianu / http://www.baicoianu.com/
  17126. */
  17127. THREE.FlyControls = function ( object, domElement ) {
  17128. this.object = object;
  17129. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17130. if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );
  17131. // API
  17132. this.movementSpeed = 1.0;
  17133. this.rollSpeed = 0.005;
  17134. this.dragToLook = false;
  17135. this.autoForward = false;
  17136. // disable default target object behavior
  17137. this.object.useQuaternion = true;
  17138. // internals
  17139. this.tmpQuaternion = new THREE.Quaternion();
  17140. this.mouseStatus = 0;
  17141. this.moveState = { up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0 };
  17142. this.moveVector = new THREE.Vector3( 0, 0, 0 );
  17143. this.rotationVector = new THREE.Vector3( 0, 0, 0 );
  17144. this.handleEvent = function ( event ) {
  17145. if ( typeof this[ event.type ] == 'function' ) {
  17146. this[ event.type ]( event );
  17147. }
  17148. };
  17149. this.keydown = function( event ) {
  17150. if ( event.altKey ) {
  17151. return;
  17152. }
  17153. //event.preventDefault();
  17154. switch ( event.keyCode ) {
  17155. case 16: /* shift */ this.movementSpeedMultiplier = .1; break;
  17156. case 87: /*W*/ this.moveState.forward = 1; break;
  17157. case 83: /*S*/ this.moveState.back = 1; break;
  17158. case 65: /*A*/ this.moveState.left = 1; break;
  17159. case 68: /*D*/ this.moveState.right = 1; break;
  17160. case 82: /*R*/ this.moveState.up = 1; break;
  17161. case 70: /*F*/ this.moveState.down = 1; break;
  17162. case 38: /*up*/ this.moveState.pitchUp = 1; break;
  17163. case 40: /*down*/ this.moveState.pitchDown = 1; break;
  17164. case 37: /*left*/ this.moveState.yawLeft = 1; break;
  17165. case 39: /*right*/ this.moveState.yawRight = 1; break;
  17166. case 81: /*Q*/ this.moveState.rollLeft = 1; break;
  17167. case 69: /*E*/ this.moveState.rollRight = 1; break;
  17168. }
  17169. this.updateMovementVector();
  17170. this.updateRotationVector();
  17171. };
  17172. this.keyup = function( event ) {
  17173. switch( event.keyCode ) {
  17174. case 16: /* shift */ this.movementSpeedMultiplier = 1; break;
  17175. case 87: /*W*/ this.moveState.forward = 0; break;
  17176. case 83: /*S*/ this.moveState.back = 0; break;
  17177. case 65: /*A*/ this.moveState.left = 0; break;
  17178. case 68: /*D*/ this.moveState.right = 0; break;
  17179. case 82: /*R*/ this.moveState.up = 0; break;
  17180. case 70: /*F*/ this.moveState.down = 0; break;
  17181. case 38: /*up*/ this.moveState.pitchUp = 0; break;
  17182. case 40: /*down*/ this.moveState.pitchDown = 0; break;
  17183. case 37: /*left*/ this.moveState.yawLeft = 0; break;
  17184. case 39: /*right*/ this.moveState.yawRight = 0; break;
  17185. case 81: /*Q*/ this.moveState.rollLeft = 0; break;
  17186. case 69: /*E*/ this.moveState.rollRight = 0; break;
  17187. }
  17188. this.updateMovementVector();
  17189. this.updateRotationVector();
  17190. };
  17191. this.mousedown = function( event ) {
  17192. if ( this.domElement !== document ) {
  17193. this.domElement.focus();
  17194. }
  17195. event.preventDefault();
  17196. event.stopPropagation();
  17197. if ( this.dragToLook ) {
  17198. this.mouseStatus ++;
  17199. } else {
  17200. switch ( event.button ) {
  17201. case 0: this.object.moveForward = true; break;
  17202. case 2: this.object.moveBackward = true; break;
  17203. }
  17204. }
  17205. };
  17206. this.mousemove = function( event ) {
  17207. if ( !this.dragToLook || this.mouseStatus > 0 ) {
  17208. var container = this.getContainerDimensions();
  17209. var halfWidth = container.size[ 0 ] / 2;
  17210. var halfHeight = container.size[ 1 ] / 2;
  17211. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  17212. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  17213. this.updateRotationVector();
  17214. }
  17215. };
  17216. this.mouseup = function( event ) {
  17217. event.preventDefault();
  17218. event.stopPropagation();
  17219. if ( this.dragToLook ) {
  17220. this.mouseStatus --;
  17221. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  17222. } else {
  17223. switch ( event.button ) {
  17224. case 0: this.moveForward = false; break;
  17225. case 2: this.moveBackward = false; break;
  17226. }
  17227. }
  17228. this.updateRotationVector();
  17229. };
  17230. this.update = function( delta ) {
  17231. var moveMult = delta * this.movementSpeed;
  17232. var rotMult = delta * this.rollSpeed;
  17233. this.object.translateX( this.moveVector.x * moveMult );
  17234. this.object.translateY( this.moveVector.y * moveMult );
  17235. this.object.translateZ( this.moveVector.z * moveMult );
  17236. this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
  17237. this.object.quaternion.multiplySelf( this.tmpQuaternion );
  17238. this.object.matrix.setPosition( this.object.position );
  17239. this.object.matrix.setRotationFromQuaternion( this.object.quaternion );
  17240. this.object.matrixWorldNeedsUpdate = true;
  17241. };
  17242. this.updateMovementVector = function() {
  17243. var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;
  17244. this.moveVector.x = ( -this.moveState.left + this.moveState.right );
  17245. this.moveVector.y = ( -this.moveState.down + this.moveState.up );
  17246. this.moveVector.z = ( -forward + this.moveState.back );
  17247. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  17248. };
  17249. this.updateRotationVector = function() {
  17250. this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
  17251. this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
  17252. this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
  17253. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  17254. };
  17255. this.getContainerDimensions = function() {
  17256. if ( this.domElement != document ) {
  17257. return {
  17258. size : [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  17259. offset : [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  17260. };
  17261. } else {
  17262. return {
  17263. size : [ window.innerWidth, window.innerHeight ],
  17264. offset : [ 0, 0 ]
  17265. };
  17266. }
  17267. };
  17268. function bind( scope, fn ) {
  17269. return function () {
  17270. fn.apply( scope, arguments );
  17271. };
  17272. };
  17273. this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
  17274. this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
  17275. this.domElement.addEventListener( 'mouseup', bind( this, this.mouseup ), false );
  17276. this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
  17277. this.domElement.addEventListener( 'keyup', bind( this, this.keyup ), false );
  17278. this.updateMovementVector();
  17279. this.updateRotationVector();
  17280. };
  17281. /**
  17282. * @author mikael emtinger / http://gomo.se/
  17283. * @author alteredq / http://alteredqualia.com/
  17284. */
  17285. THREE.RollControls = function ( object, domElement ) {
  17286. this.object = object;
  17287. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17288. // API
  17289. this.mouseLook = true;
  17290. this.autoForward = false;
  17291. this.lookSpeed = 1;
  17292. this.movementSpeed = 1;
  17293. this.rollSpeed = 1;
  17294. this.constrainVertical = [ -0.9, 0.9 ];
  17295. // disable default target object behavior
  17296. this.object.matrixAutoUpdate = false;
  17297. // internals
  17298. this.forward = new THREE.Vector3( 0, 0, 1 );
  17299. this.roll = 0;
  17300. var xTemp = new THREE.Vector3();
  17301. var yTemp = new THREE.Vector3();
  17302. var zTemp = new THREE.Vector3();
  17303. var rollMatrix = new THREE.Matrix4();
  17304. var doRoll = false, rollDirection = 1, forwardSpeed = 0, sideSpeed = 0, upSpeed = 0;
  17305. var mouseX = 0, mouseY = 0;
  17306. var windowHalfX = 0;
  17307. var windowHalfY = 0;
  17308. //
  17309. this.handleResize = function () {
  17310. windowHalfX = window.innerWidth / 2;
  17311. windowHalfY = window.innerHeight / 2;
  17312. };
  17313. // custom update
  17314. this.update = function ( delta ) {
  17315. if ( this.mouseLook ) {
  17316. var actualLookSpeed = delta * this.lookSpeed;
  17317. this.rotateHorizontally( actualLookSpeed * mouseX );
  17318. this.rotateVertically( actualLookSpeed * mouseY );
  17319. }
  17320. var actualSpeed = delta * this.movementSpeed;
  17321. var forwardOrAuto = ( forwardSpeed > 0 || ( this.autoForward && ! ( forwardSpeed < 0 ) ) ) ? 1 : forwardSpeed;
  17322. this.object.translateZ( -actualSpeed * forwardOrAuto );
  17323. this.object.translateX( actualSpeed * sideSpeed );
  17324. this.object.translateY( actualSpeed * upSpeed );
  17325. if( doRoll ) {
  17326. this.roll += this.rollSpeed * delta * rollDirection;
  17327. }
  17328. // cap forward up / down
  17329. if( this.forward.y > this.constrainVertical[ 1 ] ) {
  17330. this.forward.y = this.constrainVertical[ 1 ];
  17331. this.forward.normalize();
  17332. } else if( this.forward.y < this.constrainVertical[ 0 ] ) {
  17333. this.forward.y = this.constrainVertical[ 0 ];
  17334. this.forward.normalize();
  17335. }
  17336. // construct unrolled camera matrix
  17337. zTemp.copy( this.forward );
  17338. yTemp.set( 0, 1, 0 );
  17339. xTemp.cross( yTemp, zTemp ).normalize();
  17340. yTemp.cross( zTemp, xTemp ).normalize();
  17341. this.object.matrix.elements[0] = xTemp.x; this.object.matrix.elements[4] = yTemp.x; this.object.matrix.elements[8] = zTemp.x;
  17342. this.object.matrix.elements[1] = xTemp.y; this.object.matrix.elements[5] = yTemp.y; this.object.matrix.elements[9] = zTemp.y;
  17343. this.object.matrix.elements[2] = xTemp.z; this.object.matrix.elements[6] = yTemp.z; this.object.matrix.elements[10] = zTemp.z;
  17344. // calculate roll matrix
  17345. rollMatrix.identity();
  17346. rollMatrix.elements[0] = Math.cos( this.roll ); rollMatrix.elements[4] = -Math.sin( this.roll );
  17347. rollMatrix.elements[1] = Math.sin( this.roll ); rollMatrix.elements[5] = Math.cos( this.roll );
  17348. // multiply camera with roll
  17349. this.object.matrix.multiplySelf( rollMatrix );
  17350. this.object.matrixWorldNeedsUpdate = true;
  17351. // set position
  17352. this.object.matrix.elements[12] = this.object.position.x;
  17353. this.object.matrix.elements[13] = this.object.position.y;
  17354. this.object.matrix.elements[14] = this.object.position.z;
  17355. };
  17356. this.translateX = function ( distance ) {
  17357. this.object.position.x += this.object.matrix.elements[0] * distance;
  17358. this.object.position.y += this.object.matrix.elements[1] * distance;
  17359. this.object.position.z += this.object.matrix.elements[2] * distance;
  17360. };
  17361. this.translateY = function ( distance ) {
  17362. this.object.position.x += this.object.matrix.elements[4] * distance;
  17363. this.object.position.y += this.object.matrix.elements[5] * distance;
  17364. this.object.position.z += this.object.matrix.elements[6] * distance;
  17365. };
  17366. this.translateZ = function ( distance ) {
  17367. this.object.position.x -= this.object.matrix.elements[8] * distance;
  17368. this.object.position.y -= this.object.matrix.elements[9] * distance;
  17369. this.object.position.z -= this.object.matrix.elements[10] * distance;
  17370. };
  17371. this.rotateHorizontally = function ( amount ) {
  17372. // please note that the amount is NOT degrees, but a scale value
  17373. xTemp.set( this.object.matrix.elements[0], this.object.matrix.elements[1], this.object.matrix.elements[2] );
  17374. xTemp.multiplyScalar( amount );
  17375. this.forward.subSelf( xTemp );
  17376. this.forward.normalize();
  17377. };
  17378. this.rotateVertically = function ( amount ) {
  17379. // please note that the amount is NOT degrees, but a scale value
  17380. yTemp.set( this.object.matrix.elements[4], this.object.matrix.elements[5], this.object.matrix.elements[6] );
  17381. yTemp.multiplyScalar( amount );
  17382. this.forward.addSelf( yTemp );
  17383. this.forward.normalize();
  17384. };
  17385. function onKeyDown( event ) {
  17386. //event.preventDefault();
  17387. switch ( event.keyCode ) {
  17388. case 38: /*up*/
  17389. case 87: /*W*/ forwardSpeed = 1; break;
  17390. case 37: /*left*/
  17391. case 65: /*A*/ sideSpeed = -1; break;
  17392. case 40: /*down*/
  17393. case 83: /*S*/ forwardSpeed = -1; break;
  17394. case 39: /*right*/
  17395. case 68: /*D*/ sideSpeed = 1; break;
  17396. case 81: /*Q*/ doRoll = true; rollDirection = 1; break;
  17397. case 69: /*E*/ doRoll = true; rollDirection = -1; break;
  17398. case 82: /*R*/ upSpeed = 1; break;
  17399. case 70: /*F*/ upSpeed = -1; break;
  17400. }
  17401. };
  17402. function onKeyUp( event ) {
  17403. switch( event.keyCode ) {
  17404. case 38: /*up*/
  17405. case 87: /*W*/ forwardSpeed = 0; break;
  17406. case 37: /*left*/
  17407. case 65: /*A*/ sideSpeed = 0; break;
  17408. case 40: /*down*/
  17409. case 83: /*S*/ forwardSpeed = 0; break;
  17410. case 39: /*right*/
  17411. case 68: /*D*/ sideSpeed = 0; break;
  17412. case 81: /*Q*/ doRoll = false; break;
  17413. case 69: /*E*/ doRoll = false; break;
  17414. case 82: /*R*/ upSpeed = 0; break;
  17415. case 70: /*F*/ upSpeed = 0; break;
  17416. }
  17417. };
  17418. function onMouseMove( event ) {
  17419. mouseX = ( event.clientX - windowHalfX ) / window.innerWidth;
  17420. mouseY = ( event.clientY - windowHalfY ) / window.innerHeight;
  17421. };
  17422. function onMouseDown ( event ) {
  17423. event.preventDefault();
  17424. event.stopPropagation();
  17425. switch ( event.button ) {
  17426. case 0: forwardSpeed = 1; break;
  17427. case 2: forwardSpeed = -1; break;
  17428. }
  17429. };
  17430. function onMouseUp ( event ) {
  17431. event.preventDefault();
  17432. event.stopPropagation();
  17433. switch ( event.button ) {
  17434. case 0: forwardSpeed = 0; break;
  17435. case 2: forwardSpeed = 0; break;
  17436. }
  17437. };
  17438. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17439. this.domElement.addEventListener( 'mousemove', onMouseMove, false );
  17440. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  17441. this.domElement.addEventListener( 'mouseup', onMouseUp, false );
  17442. this.domElement.addEventListener( 'keydown', onKeyDown, false );
  17443. this.domElement.addEventListener( 'keyup', onKeyUp, false );
  17444. this.handleResize();
  17445. };
  17446. /**
  17447. * @author Eberhard Graether / http://egraether.com/
  17448. */
  17449. THREE.TrackballControls = function ( object, domElement ) {
  17450. THREE.EventTarget.call( this );
  17451. var _this = this,
  17452. STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };
  17453. this.object = object;
  17454. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17455. // API
  17456. this.enabled = true;
  17457. this.screen = { width: 0, height: 0, offsetLeft: 0, offsetTop: 0 };
  17458. this.radius = ( this.screen.width + this.screen.height ) / 4;
  17459. this.rotateSpeed = 1.0;
  17460. this.zoomSpeed = 1.2;
  17461. this.panSpeed = 0.3;
  17462. this.noRotate = false;
  17463. this.noZoom = false;
  17464. this.noPan = false;
  17465. this.staticMoving = false;
  17466. this.dynamicDampingFactor = 0.2;
  17467. this.minDistance = 0;
  17468. this.maxDistance = Infinity;
  17469. this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
  17470. // internals
  17471. this.target = new THREE.Vector3();
  17472. var lastPosition = new THREE.Vector3();
  17473. var _keyPressed = false,
  17474. _state = STATE.NONE,
  17475. _eye = new THREE.Vector3(),
  17476. _rotateStart = new THREE.Vector3(),
  17477. _rotateEnd = new THREE.Vector3(),
  17478. _zoomStart = new THREE.Vector2(),
  17479. _zoomEnd = new THREE.Vector2(),
  17480. _panStart = new THREE.Vector2(),
  17481. _panEnd = new THREE.Vector2();
  17482. // events
  17483. var changeEvent = { type: 'change' };
  17484. // methods
  17485. this.handleResize = function () {
  17486. this.screen.width = window.innerWidth;
  17487. this.screen.height = window.innerHeight;
  17488. this.screen.offsetLeft = 0;
  17489. this.screen.offsetTop = 0;
  17490. this.radius = ( this.screen.width + this.screen.height ) / 4;
  17491. };
  17492. this.handleEvent = function ( event ) {
  17493. if ( typeof this[ event.type ] == 'function' ) {
  17494. this[ event.type ]( event );
  17495. }
  17496. };
  17497. this.getMouseOnScreen = function ( clientX, clientY ) {
  17498. return new THREE.Vector2(
  17499. ( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
  17500. ( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
  17501. );
  17502. };
  17503. this.getMouseProjectionOnBall = function ( clientX, clientY ) {
  17504. var mouseOnBall = new THREE.Vector3(
  17505. ( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
  17506. ( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
  17507. 0.0
  17508. );
  17509. var length = mouseOnBall.length();
  17510. if ( length > 1.0 ) {
  17511. mouseOnBall.normalize();
  17512. } else {
  17513. mouseOnBall.z = Math.sqrt( 1.0 - length * length );
  17514. }
  17515. _eye.copy( _this.object.position ).subSelf( _this.target );
  17516. var projection = _this.object.up.clone().setLength( mouseOnBall.y );
  17517. projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
  17518. projection.addSelf( _eye.setLength( mouseOnBall.z ) );
  17519. return projection;
  17520. };
  17521. this.rotateCamera = function () {
  17522. var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
  17523. if ( angle ) {
  17524. var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
  17525. quaternion = new THREE.Quaternion();
  17526. angle *= _this.rotateSpeed;
  17527. quaternion.setFromAxisAngle( axis, -angle );
  17528. quaternion.multiplyVector3( _eye );
  17529. quaternion.multiplyVector3( _this.object.up );
  17530. quaternion.multiplyVector3( _rotateEnd );
  17531. if ( _this.staticMoving ) {
  17532. _rotateStart = _rotateEnd;
  17533. } else {
  17534. quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
  17535. quaternion.multiplyVector3( _rotateStart );
  17536. }
  17537. }
  17538. };
  17539. this.zoomCamera = function () {
  17540. var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
  17541. if ( factor !== 1.0 && factor > 0.0 ) {
  17542. _eye.multiplyScalar( factor );
  17543. if ( _this.staticMoving ) {
  17544. _zoomStart = _zoomEnd;
  17545. } else {
  17546. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  17547. }
  17548. }
  17549. };
  17550. this.panCamera = function () {
  17551. var mouseChange = _panEnd.clone().subSelf( _panStart );
  17552. if ( mouseChange.lengthSq() ) {
  17553. mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
  17554. var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
  17555. pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );
  17556. _this.object.position.addSelf( pan );
  17557. _this.target.addSelf( pan );
  17558. if ( _this.staticMoving ) {
  17559. _panStart = _panEnd;
  17560. } else {
  17561. _panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
  17562. }
  17563. }
  17564. };
  17565. this.checkDistances = function () {
  17566. if ( !_this.noZoom || !_this.noPan ) {
  17567. if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {
  17568. _this.object.position.setLength( _this.maxDistance );
  17569. }
  17570. if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
  17571. _this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );
  17572. }
  17573. }
  17574. };
  17575. this.update = function () {
  17576. _eye.copy( _this.object.position ).subSelf( _this.target );
  17577. if ( !_this.noRotate ) {
  17578. _this.rotateCamera();
  17579. }
  17580. if ( !_this.noZoom ) {
  17581. _this.zoomCamera();
  17582. }
  17583. if ( !_this.noPan ) {
  17584. _this.panCamera();
  17585. }
  17586. _this.object.position.add( _this.target, _eye );
  17587. _this.checkDistances();
  17588. _this.object.lookAt( _this.target );
  17589. if ( lastPosition.distanceToSquared( _this.object.position ) > 0 ) {
  17590. _this.dispatchEvent( changeEvent );
  17591. lastPosition.copy( _this.object.position );
  17592. }
  17593. };
  17594. // listeners
  17595. function keydown( event ) {
  17596. if ( ! _this.enabled ) return;
  17597. //event.preventDefault();
  17598. if ( _state !== STATE.NONE ) {
  17599. return;
  17600. } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
  17601. _state = STATE.ROTATE;
  17602. } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
  17603. _state = STATE.ZOOM;
  17604. } else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
  17605. _state = STATE.PAN;
  17606. }
  17607. if ( _state !== STATE.NONE ) {
  17608. _keyPressed = true;
  17609. }
  17610. }
  17611. function keyup( event ) {
  17612. if ( ! _this.enabled ) return;
  17613. if ( _state !== STATE.NONE ) {
  17614. _state = STATE.NONE;
  17615. }
  17616. }
  17617. function mousedown( event ) {
  17618. if ( ! _this.enabled ) return;
  17619. event.preventDefault();
  17620. event.stopPropagation();
  17621. if ( _state === STATE.NONE ) {
  17622. _state = event.button;
  17623. if ( _state === STATE.ROTATE && !_this.noRotate ) {
  17624. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  17625. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  17626. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17627. } else if ( !this.noPan ) {
  17628. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17629. }
  17630. }
  17631. }
  17632. function mousemove( event ) {
  17633. if ( ! _this.enabled ) return;
  17634. if ( _keyPressed ) {
  17635. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  17636. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17637. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17638. _keyPressed = false;
  17639. }
  17640. if ( _state === STATE.NONE ) {
  17641. return;
  17642. } else if ( _state === STATE.ROTATE && !_this.noRotate ) {
  17643. _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  17644. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  17645. _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17646. } else if ( _state === STATE.PAN && !_this.noPan ) {
  17647. _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17648. }
  17649. }
  17650. function mouseup( event ) {
  17651. if ( ! _this.enabled ) return;
  17652. event.preventDefault();
  17653. event.stopPropagation();
  17654. _state = STATE.NONE;
  17655. }
  17656. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17657. this.domElement.addEventListener( 'mousemove', mousemove, false );
  17658. this.domElement.addEventListener( 'mousedown', mousedown, false );
  17659. this.domElement.addEventListener( 'mouseup', mouseup, false );
  17660. // this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false );
  17661. // this.domElement.addEventListener( 'mousewheel', mousewheel, false );
  17662. window.addEventListener( 'keydown', keydown, false );
  17663. window.addEventListener( 'keyup', keyup, false );
  17664. this.handleResize();
  17665. };
  17666. /**
  17667. * @author qiao / https://github.com/qiao
  17668. * @author mrdoob / http://mrdoob.com
  17669. * @author alteredq / http://alteredqualia.com/
  17670. */
  17671. THREE.OrbitControls = function ( object, domElement ) {
  17672. THREE.EventTarget.call( this );
  17673. this.object = object;
  17674. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17675. // API
  17676. this.center = new THREE.Vector3();
  17677. this.userZoom = true;
  17678. this.userZoomSpeed = 1.0;
  17679. this.userRotate = true;
  17680. this.userRotateSpeed = 1.0;
  17681. this.autoRotate = false;
  17682. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  17683. // internals
  17684. var scope = this;
  17685. var EPS = 0.000001;
  17686. var PIXELS_PER_ROUND = 1800;
  17687. var rotateStart = new THREE.Vector2();
  17688. var rotateEnd = new THREE.Vector2();
  17689. var rotateDelta = new THREE.Vector2();
  17690. var zoomStart = new THREE.Vector2();
  17691. var zoomEnd = new THREE.Vector2();
  17692. var zoomDelta = new THREE.Vector2();
  17693. var phiDelta = 0;
  17694. var thetaDelta = 0;
  17695. var scale = 1;
  17696. var lastPosition = new THREE.Vector3();
  17697. var STATE = { NONE : -1, ROTATE : 0, ZOOM : 1 };
  17698. var state = STATE.NONE;
  17699. // events
  17700. var changeEvent = { type: 'change' };
  17701. this.rotateLeft = function ( angle ) {
  17702. if ( angle === undefined ) {
  17703. angle = getAutoRotationAngle();
  17704. }
  17705. thetaDelta -= angle;
  17706. };
  17707. this.rotateRight = function ( angle ) {
  17708. if ( angle === undefined ) {
  17709. angle = getAutoRotationAngle();
  17710. }
  17711. thetaDelta += angle;
  17712. };
  17713. this.rotateUp = function ( angle ) {
  17714. if ( angle === undefined ) {
  17715. angle = getAutoRotationAngle();
  17716. }
  17717. phiDelta -= angle;
  17718. };
  17719. this.rotateDown = function ( angle ) {
  17720. if ( angle === undefined ) {
  17721. angle = getAutoRotationAngle();
  17722. }
  17723. phiDelta += angle;
  17724. };
  17725. this.zoomIn = function ( zoomScale ) {
  17726. if ( zoomScale === undefined ) {
  17727. zoomScale = getZoomScale();
  17728. }
  17729. scale /= zoomScale;
  17730. };
  17731. this.zoomOut = function ( zoomScale ) {
  17732. if ( zoomScale === undefined ) {
  17733. zoomScale = getZoomScale();
  17734. }
  17735. scale *= zoomScale;
  17736. };
  17737. this.update = function () {
  17738. var position = this.object.position;
  17739. var offset = position.clone().subSelf( this.center )
  17740. // angle from z-axis around y-axis
  17741. var theta = Math.atan2( offset.x, offset.z );
  17742. // angle from y-axis
  17743. var phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y );
  17744. if ( this.autoRotate ) {
  17745. this.rotateLeft( getAutoRotationAngle() );
  17746. }
  17747. theta += thetaDelta;
  17748. phi += phiDelta;
  17749. // restrict phi to be betwee EPS and PI-EPS
  17750. phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) );
  17751. var radius = offset.length();
  17752. offset.x = radius * Math.sin( phi ) * Math.sin( theta );
  17753. offset.y = radius * Math.cos( phi );
  17754. offset.z = radius * Math.sin( phi ) * Math.cos( theta );
  17755. offset.multiplyScalar( scale );
  17756. position.copy( this.center ).addSelf( offset );
  17757. this.object.lookAt( this.center );
  17758. thetaDelta = 0;
  17759. phiDelta = 0;
  17760. scale = 1;
  17761. if ( lastPosition.distanceTo( this.object.position ) > 0 ) {
  17762. this.dispatchEvent( changeEvent );
  17763. lastPosition.copy( this.object.position );
  17764. }
  17765. };
  17766. function getAutoRotationAngle() {
  17767. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  17768. }
  17769. function getZoomScale() {
  17770. return Math.pow( 0.95, scope.userZoomSpeed );
  17771. }
  17772. function onMouseDown( event ) {
  17773. if ( !scope.userRotate ) return;
  17774. event.preventDefault();
  17775. if ( event.button === 0 || event.button === 2 ) {
  17776. state = STATE.ROTATE;
  17777. rotateStart.set( event.clientX, event.clientY );
  17778. } else if ( event.button === 1 ) {
  17779. state = STATE.ZOOM;
  17780. zoomStart.set( event.clientX, event.clientY );
  17781. }
  17782. document.addEventListener( 'mousemove', onMouseMove, false );
  17783. document.addEventListener( 'mouseup', onMouseUp, false );
  17784. }
  17785. function onMouseMove( event ) {
  17786. event.preventDefault();
  17787. if ( state === STATE.ROTATE ) {
  17788. rotateEnd.set( event.clientX, event.clientY );
  17789. rotateDelta.sub( rotateEnd, rotateStart );
  17790. scope.rotateLeft( 2 * Math.PI * rotateDelta.x / PIXELS_PER_ROUND * scope.userRotateSpeed );
  17791. scope.rotateUp( 2 * Math.PI * rotateDelta.y / PIXELS_PER_ROUND * scope.userRotateSpeed );
  17792. rotateStart.copy( rotateEnd );
  17793. } else if ( state === STATE.ZOOM ) {
  17794. zoomEnd.set( event.clientX, event.clientY );
  17795. zoomDelta.sub( zoomEnd, zoomStart );
  17796. if ( zoomDelta.y > 0 ) {
  17797. scope.zoomIn();
  17798. } else {
  17799. scope.zoomOut();
  17800. }
  17801. zoomStart.copy( zoomEnd );
  17802. }
  17803. }
  17804. function onMouseUp( event ) {
  17805. if ( ! scope.userRotate ) return;
  17806. document.removeEventListener( 'mousemove', onMouseMove, false );
  17807. document.removeEventListener( 'mouseup', onMouseUp, false );
  17808. state = STATE.NONE;
  17809. }
  17810. function onMouseWheel( event ) {
  17811. if ( ! scope.userZoom ) return;
  17812. if ( event.wheelDelta > 0 ) {
  17813. scope.zoomOut();
  17814. } else {
  17815. scope.zoomIn();
  17816. }
  17817. }
  17818. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17819. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  17820. this.domElement.addEventListener( 'mousewheel', onMouseWheel, false );
  17821. };
  17822. /**
  17823. * @author hughes
  17824. */
  17825. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  17826. THREE.Geometry.call( this );
  17827. radius = radius || 50;
  17828. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17829. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17830. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17831. var i, uvs = [],
  17832. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  17833. this.vertices.push(center);
  17834. uvs.push( centerUV );
  17835. for ( i = 0; i <= segments; i ++ ) {
  17836. var vertex = new THREE.Vector3();
  17837. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  17838. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  17839. this.vertices.push( vertex );
  17840. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  17841. }
  17842. var n = new THREE.Vector3( 0, 0, -1 );
  17843. for ( i = 1; i <= segments; i ++ ) {
  17844. var v1 = i;
  17845. var v2 = i + 1 ;
  17846. var v3 = 0;
  17847. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  17848. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  17849. }
  17850. this.computeCentroids();
  17851. this.computeFaceNormals();
  17852. this.boundingSphere = { radius: radius };
  17853. };
  17854. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17855. /**
  17856. * @author mrdoob / http://mrdoob.com/
  17857. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  17858. */
  17859. THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
  17860. THREE.Geometry.call( this );
  17861. var scope = this,
  17862. width_half = width / 2,
  17863. height_half = height / 2,
  17864. depth_half = depth / 2;
  17865. var mpx, mpy, mpz, mnx, mny, mnz;
  17866. if ( materials !== undefined ) {
  17867. if ( materials instanceof Array ) {
  17868. this.materials = materials;
  17869. } else {
  17870. this.materials = [];
  17871. for ( var i = 0; i < 6; i ++ ) {
  17872. this.materials.push( materials );
  17873. }
  17874. }
  17875. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  17876. } else {
  17877. this.materials = [];
  17878. }
  17879. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  17880. if ( sides != undefined ) {
  17881. for ( var s in sides ) {
  17882. if ( this.sides[ s ] !== undefined ) {
  17883. this.sides[ s ] = sides[ s ];
  17884. }
  17885. }
  17886. }
  17887. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
  17888. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, mnx ); // nx
  17889. this.sides.py && buildPlane( 'x', 'z', 1, 1, width, depth, height_half, mpy ); // py
  17890. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, mny ); // ny
  17891. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, mpz ); // pz
  17892. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz
  17893. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  17894. var w, ix, iy,
  17895. gridX = segmentsWidth || 1,
  17896. gridY = segmentsHeight || 1,
  17897. width_half = width / 2,
  17898. height_half = height / 2,
  17899. offset = scope.vertices.length;
  17900. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  17901. w = 'z';
  17902. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  17903. w = 'y';
  17904. gridY = segmentsDepth || 1;
  17905. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  17906. w = 'x';
  17907. gridX = segmentsDepth || 1;
  17908. }
  17909. var gridX1 = gridX + 1,
  17910. gridY1 = gridY + 1,
  17911. segment_width = width / gridX,
  17912. segment_height = height / gridY,
  17913. normal = new THREE.Vector3();
  17914. normal[ w ] = depth > 0 ? 1 : - 1;
  17915. for ( iy = 0; iy < gridY1; iy ++ ) {
  17916. for ( ix = 0; ix < gridX1; ix ++ ) {
  17917. var vector = new THREE.Vector3();
  17918. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  17919. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  17920. vector[ w ] = depth;
  17921. scope.vertices.push( vector );
  17922. }
  17923. }
  17924. for ( iy = 0; iy < gridY; iy++ ) {
  17925. for ( ix = 0; ix < gridX; ix++ ) {
  17926. var a = ix + gridX1 * iy;
  17927. var b = ix + gridX1 * ( iy + 1 );
  17928. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  17929. var d = ( ix + 1 ) + gridX1 * iy;
  17930. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  17931. face.normal.copy( normal );
  17932. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  17933. face.materialIndex = material;
  17934. scope.faces.push( face );
  17935. scope.faceVertexUvs[ 0 ].push( [
  17936. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  17937. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  17938. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  17939. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  17940. ] );
  17941. }
  17942. }
  17943. }
  17944. this.computeCentroids();
  17945. this.mergeVertices();
  17946. };
  17947. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17948. /**
  17949. * @author mrdoob / http://mrdoob.com/
  17950. */
  17951. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded ) {
  17952. THREE.Geometry.call( this );
  17953. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  17954. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  17955. height = height !== undefined ? height : 100;
  17956. var heightHalf = height / 2;
  17957. var segmentsX = segmentsRadius || 8;
  17958. var segmentsY = segmentsHeight || 1;
  17959. var x, y, vertices = [], uvs = [];
  17960. for ( y = 0; y <= segmentsY; y ++ ) {
  17961. var verticesRow = [];
  17962. var uvsRow = [];
  17963. var v = y / segmentsY;
  17964. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17965. for ( x = 0; x <= segmentsX; x ++ ) {
  17966. var u = x / segmentsX;
  17967. var vertex = new THREE.Vector3();
  17968. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  17969. vertex.y = - v * height + heightHalf;
  17970. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  17971. this.vertices.push( vertex );
  17972. verticesRow.push( this.vertices.length - 1 );
  17973. uvsRow.push( new THREE.UV( u, 1 - v ) );
  17974. }
  17975. vertices.push( verticesRow );
  17976. uvs.push( uvsRow );
  17977. }
  17978. var tanTheta = ( radiusBottom - radiusTop ) / height;
  17979. var na, nb;
  17980. for ( x = 0; x < segmentsX; x ++ ) {
  17981. if ( radiusTop !== 0 ) {
  17982. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  17983. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  17984. } else {
  17985. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  17986. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  17987. }
  17988. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  17989. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  17990. for ( y = 0; y < segmentsY; y ++ ) {
  17991. var v1 = vertices[ y ][ x ];
  17992. var v2 = vertices[ y + 1 ][ x ];
  17993. var v3 = vertices[ y + 1 ][ x + 1 ];
  17994. var v4 = vertices[ y ][ x + 1 ];
  17995. var n1 = na.clone();
  17996. var n2 = na.clone();
  17997. var n3 = nb.clone();
  17998. var n4 = nb.clone();
  17999. var uv1 = uvs[ y ][ x ].clone();
  18000. var uv2 = uvs[ y + 1 ][ x ].clone();
  18001. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18002. var uv4 = uvs[ y ][ x + 1 ].clone();
  18003. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18004. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18005. }
  18006. }
  18007. // top cap
  18008. if ( !openEnded && radiusTop > 0 ) {
  18009. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18010. for ( x = 0; x < segmentsX; x ++ ) {
  18011. var v1 = vertices[ 0 ][ x ];
  18012. var v2 = vertices[ 0 ][ x + 1 ];
  18013. var v3 = this.vertices.length - 1;
  18014. var n1 = new THREE.Vector3( 0, 1, 0 );
  18015. var n2 = new THREE.Vector3( 0, 1, 0 );
  18016. var n3 = new THREE.Vector3( 0, 1, 0 );
  18017. var uv1 = uvs[ 0 ][ x ].clone();
  18018. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18019. var uv3 = new THREE.UV( uv2.u, 0 );
  18020. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18021. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18022. }
  18023. }
  18024. // bottom cap
  18025. if ( !openEnded && radiusBottom > 0 ) {
  18026. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18027. for ( x = 0; x < segmentsX; x ++ ) {
  18028. var v1 = vertices[ y ][ x + 1 ];
  18029. var v2 = vertices[ y ][ x ];
  18030. var v3 = this.vertices.length - 1;
  18031. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18032. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18033. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18034. var uv1 = uvs[ y ][ x + 1 ].clone();
  18035. var uv2 = uvs[ y ][ x ].clone();
  18036. var uv3 = new THREE.UV( uv2.u, 1 );
  18037. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18038. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18039. }
  18040. }
  18041. this.computeCentroids();
  18042. this.computeFaceNormals();
  18043. }
  18044. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18045. /**
  18046. * @author zz85 / http://www.lab4games.net/zz85/blog
  18047. *
  18048. * Creates extruded geometry from a path shape.
  18049. *
  18050. * parameters = {
  18051. *
  18052. * size: <float>, // size of the text
  18053. * height: <float>, // thickness to extrude text
  18054. * curveSegments: <int>, // number of points on the curves
  18055. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18056. amount: <int>, // Amount
  18057. *
  18058. * bevelEnabled: <bool>, // turn on bevel
  18059. * bevelThickness: <float>, // how deep into text bevel goes
  18060. * bevelSize: <float>, // how far from text outline is bevel
  18061. * bevelSegments: <int>, // number of bevel layers
  18062. *
  18063. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18064. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18065. * bendPath: <THREE.CurvePath> // 2d path for bend the shape around x/y plane
  18066. *
  18067. * material: <int> // material index for front and back faces
  18068. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18069. * uvGenerator: <Object> // object that provides UV generator functions
  18070. *
  18071. * }
  18072. **/
  18073. THREE.ExtrudeGeometry = function( shapes, options ) {
  18074. if ( typeof( shapes ) === "undefined" ) {
  18075. shapes = [];
  18076. return;
  18077. }
  18078. THREE.Geometry.call( this );
  18079. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18080. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18081. this.addShapeList( shapes, options );
  18082. this.computeCentroids();
  18083. this.computeFaceNormals();
  18084. // can't really use automatic vertex normals
  18085. // as then front and back sides get smoothed too
  18086. // should do separate smoothing just for sides
  18087. //this.computeVertexNormals();
  18088. //console.log( "took", ( Date.now() - startTime ) );
  18089. };
  18090. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18091. THREE.ExtrudeGeometry.prototype.addShapeList = function(shapes, options) {
  18092. var sl = shapes.length;
  18093. for ( var s = 0; s < sl; s ++ ) {
  18094. var shape = shapes[ s ];
  18095. this.addShape( shape, options );
  18096. }
  18097. };
  18098. THREE.ExtrudeGeometry.prototype.addShape = function( shape, options ) {
  18099. var amount = options.amount !== undefined ? options.amount : 100;
  18100. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18101. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18102. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18103. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18104. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18105. var steps = options.steps !== undefined ? options.steps : 1;
  18106. var bendPath = options.bendPath;
  18107. var extrudePath = options.extrudePath;
  18108. var extrudePts, extrudeByPath = false;
  18109. var material = options.material;
  18110. var extrudeMaterial = options.extrudeMaterial;
  18111. // Use default WorldUVGenerator if no UV generators are specified.
  18112. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18113. var shapebb = this.shapebb;
  18114. //shapebb = shape.getBoundingBox();
  18115. var splineTube, binormal, normal, position2;
  18116. if ( extrudePath ) {
  18117. extrudePts = extrudePath.getSpacedPoints( steps );
  18118. extrudeByPath = true;
  18119. bevelEnabled = false; // bevels not supported for path extrusion
  18120. // SETUP TNB variables
  18121. // Reuse TNB from TubeGeomtry for now.
  18122. // TODO1 - have a .isClosed in spline?
  18123. splineTube = options.frames !== undefined ?
  18124. options.frames :
  18125. new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18126. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18127. binormal = new THREE.Vector3();
  18128. normal = new THREE.Vector3();
  18129. position2 = new THREE.Vector3();
  18130. }
  18131. // Safeguards if bevels are not enabled
  18132. if ( ! bevelEnabled ) {
  18133. bevelSegments = 0;
  18134. bevelThickness = 0;
  18135. bevelSize = 0;
  18136. }
  18137. // Variables initalization
  18138. var ahole, h, hl; // looping of holes
  18139. var scope = this;
  18140. var bevelPoints = [];
  18141. var shapesOffset = this.vertices.length;
  18142. if ( bendPath ) {
  18143. shape.addWrapPath( bendPath );
  18144. }
  18145. var shapePoints = shape.extractPoints();
  18146. var vertices = shapePoints.shape;
  18147. var holes = shapePoints.holes;
  18148. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18149. if ( reverse ) {
  18150. vertices = vertices.reverse();
  18151. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18152. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18153. ahole = holes[ h ];
  18154. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18155. holes[ h ] = ahole.reverse();
  18156. }
  18157. }
  18158. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18159. }
  18160. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18161. //var faces = THREE.Shape.Utils.triangulate2( vertices, holes );
  18162. // Would it be better to move points after triangulation?
  18163. // shapePoints = shape.extractAllPointsWithBend( curveSegments, bendPath );
  18164. // vertices = shapePoints.shape;
  18165. // holes = shapePoints.holes;
  18166. //console.log(faces);
  18167. ////
  18168. /// Handle Vertices
  18169. ////
  18170. var contour = vertices; // vertices has all points but contour has only points of circumference
  18171. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18172. ahole = holes[ h ];
  18173. vertices = vertices.concat( ahole );
  18174. }
  18175. function scalePt2 ( pt, vec, size ) {
  18176. if ( !vec ) console.log( "die" );
  18177. return vec.clone().multiplyScalar( size ).addSelf( pt );
  18178. }
  18179. var b, bs, t, z,
  18180. vert, vlen = vertices.length,
  18181. face, flen = faces.length,
  18182. cont, clen = contour.length;
  18183. //------
  18184. // Find directions for point movement
  18185. //
  18186. var RAD_TO_DEGREES = 180 / Math.PI;
  18187. function getBevelVec( pt_i, pt_j, pt_k ) {
  18188. // Algorithm 2
  18189. return getBevelVec2( pt_i, pt_j, pt_k );
  18190. }
  18191. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18192. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18193. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18194. if ( anglea > angleb ) {
  18195. angleb += Math.PI * 2;
  18196. }
  18197. var anglec = ( anglea + angleb ) / 2;
  18198. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18199. var x = - Math.cos( anglec );
  18200. var y = - Math.sin( anglec );
  18201. var vec = new THREE.Vector2( x, y ); //.normalize();
  18202. return vec;
  18203. }
  18204. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18205. var a = THREE.ExtrudeGeometry.__v1,
  18206. b = THREE.ExtrudeGeometry.__v2,
  18207. v_hat = THREE.ExtrudeGeometry.__v3,
  18208. w_hat = THREE.ExtrudeGeometry.__v4,
  18209. p = THREE.ExtrudeGeometry.__v5,
  18210. q = THREE.ExtrudeGeometry.__v6,
  18211. v, w,
  18212. v_dot_w_hat, q_sub_p_dot_w_hat,
  18213. s, intersection;
  18214. // good reading for line-line intersection
  18215. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18216. // define a as vector j->i
  18217. // define b as vectot k->i
  18218. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18219. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18220. // get unit vectors
  18221. v = a.normalize();
  18222. w = b.normalize();
  18223. // normals from pt i
  18224. v_hat.set( -v.y, v.x );
  18225. w_hat.set( w.y, -w.x );
  18226. // pts from i
  18227. p.copy( pt_i ).addSelf( v_hat );
  18228. q.copy( pt_i ).addSelf( w_hat );
  18229. if ( p.equals( q ) ) {
  18230. //console.log("Warning: lines are straight");
  18231. return w_hat.clone();
  18232. }
  18233. // Points from j, k. helps prevents points cross overover most of the time
  18234. p.copy( pt_j ).addSelf( v_hat );
  18235. q.copy( pt_k ).addSelf( w_hat );
  18236. v_dot_w_hat = v.dot( w_hat );
  18237. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18238. // We should not reach these conditions
  18239. if ( v_dot_w_hat === 0 ) {
  18240. console.log( "Either infinite or no solutions!" );
  18241. if ( q_sub_p_dot_w_hat === 0 ) {
  18242. console.log( "Its finite solutions." );
  18243. } else {
  18244. console.log( "Too bad, no solutions." );
  18245. }
  18246. }
  18247. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18248. if ( s < 0 ) {
  18249. // in case of emergecy, revert to algorithm 1.
  18250. return getBevelVec1( pt_i, pt_j, pt_k );
  18251. }
  18252. intersection = v.multiplyScalar( s ).addSelf( p );
  18253. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18254. }
  18255. var contourMovements = [];
  18256. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18257. if ( j === il ) j = 0;
  18258. if ( k === il ) k = 0;
  18259. // (j)---(i)---(k)
  18260. // console.log('i,j,k', i, j , k)
  18261. var pt_i = contour[ i ];
  18262. var pt_j = contour[ j ];
  18263. var pt_k = contour[ k ];
  18264. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18265. }
  18266. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18267. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18268. ahole = holes[ h ];
  18269. oneHoleMovements = [];
  18270. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18271. if ( j === il ) j = 0;
  18272. if ( k === il ) k = 0;
  18273. // (j)---(i)---(k)
  18274. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18275. }
  18276. holesMovements.push( oneHoleMovements );
  18277. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18278. }
  18279. // Loop bevelSegments, 1 for the front, 1 for the back
  18280. for ( b = 0; b < bevelSegments; b ++ ) {
  18281. //for ( b = bevelSegments; b > 0; b -- ) {
  18282. t = b / bevelSegments;
  18283. z = bevelThickness * ( 1 - t );
  18284. //z = bevelThickness * t;
  18285. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18286. //bs = bevelSize * t ; // linear
  18287. // contract shape
  18288. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18289. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18290. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18291. v( vert.x, vert.y, - z );
  18292. }
  18293. // expand holes
  18294. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18295. ahole = holes[ h ];
  18296. oneHoleMovements = holesMovements[ h ];
  18297. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18298. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18299. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18300. v( vert.x, vert.y, -z );
  18301. }
  18302. }
  18303. }
  18304. bs = bevelSize;
  18305. // Back facing vertices
  18306. for ( i = 0; i < vlen; i ++ ) {
  18307. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18308. if ( !extrudeByPath ) {
  18309. v( vert.x, vert.y, 0 );
  18310. } else {
  18311. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18312. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18313. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18314. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  18315. v( position2.x, position2.y, position2.z );
  18316. }
  18317. }
  18318. // Add stepped vertices...
  18319. // Including front facing vertices
  18320. var s;
  18321. for ( s = 1; s <= steps; s ++ ) {
  18322. for ( i = 0; i < vlen; i ++ ) {
  18323. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18324. if ( !extrudeByPath ) {
  18325. v( vert.x, vert.y, amount / steps * s );
  18326. } else {
  18327. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18328. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18329. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18330. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  18331. v( position2.x, position2.y, position2.z );
  18332. }
  18333. }
  18334. }
  18335. // Add bevel segments planes
  18336. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18337. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18338. t = b / bevelSegments;
  18339. z = bevelThickness * ( 1 - t );
  18340. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18341. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18342. // contract shape
  18343. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18344. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18345. v( vert.x, vert.y, amount + z );
  18346. }
  18347. // expand holes
  18348. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18349. ahole = holes[ h ];
  18350. oneHoleMovements = holesMovements[ h ];
  18351. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18352. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18353. if ( !extrudeByPath ) {
  18354. v( vert.x, vert.y, amount + z );
  18355. } else {
  18356. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18357. }
  18358. }
  18359. }
  18360. }
  18361. ////
  18362. /// Handle Faces
  18363. ////
  18364. // Top and bottom faces
  18365. buildLidFaces();
  18366. // Sides faces
  18367. buildSideFaces();
  18368. ///// Internal functions
  18369. function buildLidFaces() {
  18370. if ( bevelEnabled ) {
  18371. var layer = 0 ; // steps + 1
  18372. var offset = vlen * layer;
  18373. // Bottom faces
  18374. for ( i = 0; i < flen; i ++ ) {
  18375. face = faces[ i ];
  18376. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18377. }
  18378. layer = steps + bevelSegments * 2;
  18379. offset = vlen * layer;
  18380. // Top faces
  18381. for ( i = 0; i < flen; i ++ ) {
  18382. face = faces[ i ];
  18383. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18384. }
  18385. } else {
  18386. // Bottom faces
  18387. for ( i = 0; i < flen; i++ ) {
  18388. face = faces[ i ];
  18389. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18390. }
  18391. // Top faces
  18392. for ( i = 0; i < flen; i ++ ) {
  18393. face = faces[ i ];
  18394. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18395. }
  18396. }
  18397. }
  18398. // Create faces for the z-sides of the shape
  18399. function buildSideFaces() {
  18400. var layeroffset = 0;
  18401. sidewalls( contour, layeroffset );
  18402. layeroffset += contour.length;
  18403. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18404. ahole = holes[ h ];
  18405. sidewalls( ahole, layeroffset );
  18406. //, true
  18407. layeroffset += ahole.length;
  18408. }
  18409. }
  18410. function sidewalls( contour, layeroffset ) {
  18411. var j, k;
  18412. i = contour.length;
  18413. while ( --i >= 0 ) {
  18414. j = i;
  18415. k = i - 1;
  18416. if ( k < 0 ) k = contour.length - 1;
  18417. //console.log('b', i,j, i-1, k,vertices.length);
  18418. var s = 0, sl = steps + bevelSegments * 2;
  18419. for ( s = 0; s < sl; s ++ ) {
  18420. var slen1 = vlen * s;
  18421. var slen2 = vlen * ( s + 1 );
  18422. var a = layeroffset + j + slen1,
  18423. b = layeroffset + k + slen1,
  18424. c = layeroffset + k + slen2,
  18425. d = layeroffset + j + slen2;
  18426. f4( a, b, c, d, contour, s, sl, j, k );
  18427. }
  18428. }
  18429. }
  18430. function v( x, y, z ) {
  18431. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18432. }
  18433. function f3( a, b, c, isBottom ) {
  18434. a += shapesOffset;
  18435. b += shapesOffset;
  18436. c += shapesOffset;
  18437. // normal, color, material
  18438. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18439. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c )
  18440. : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18441. scope.faceVertexUvs[ 0 ].push( uvs );
  18442. }
  18443. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18444. a += shapesOffset;
  18445. b += shapesOffset;
  18446. c += shapesOffset;
  18447. d += shapesOffset;
  18448. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18449. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18450. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18451. scope.faceVertexUvs[ 0 ].push( uvs );
  18452. }
  18453. };
  18454. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18455. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18456. var ax = geometry.vertices[ indexA ].x,
  18457. ay = geometry.vertices[ indexA ].y,
  18458. bx = geometry.vertices[ indexB ].x,
  18459. by = geometry.vertices[ indexB ].y,
  18460. cx = geometry.vertices[ indexC ].x,
  18461. cy = geometry.vertices[ indexC ].y;
  18462. return [
  18463. new THREE.UV( ax, ay ),
  18464. new THREE.UV( bx, by ),
  18465. new THREE.UV( cx, cy )
  18466. ];
  18467. },
  18468. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18469. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18470. },
  18471. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18472. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18473. contourIndex1, contourIndex2 ) {
  18474. var ax = geometry.vertices[ indexA ].x,
  18475. ay = geometry.vertices[ indexA ].y,
  18476. az = geometry.vertices[ indexA ].z,
  18477. bx = geometry.vertices[ indexB ].x,
  18478. by = geometry.vertices[ indexB ].y,
  18479. bz = geometry.vertices[ indexB ].z,
  18480. cx = geometry.vertices[ indexC ].x,
  18481. cy = geometry.vertices[ indexC ].y,
  18482. cz = geometry.vertices[ indexC ].z,
  18483. dx = geometry.vertices[ indexD ].x,
  18484. dy = geometry.vertices[ indexD ].y,
  18485. dz = geometry.vertices[ indexD ].z;
  18486. if ( Math.abs( ay - by ) < 0.01 ) {
  18487. return [
  18488. new THREE.UV( ax, 1 - az ),
  18489. new THREE.UV( bx, 1 - bz ),
  18490. new THREE.UV( cx, 1 - cz ),
  18491. new THREE.UV( dx, 1 - dz )
  18492. ];
  18493. } else {
  18494. return [
  18495. new THREE.UV( ay, 1 - az ),
  18496. new THREE.UV( by, 1 - bz ),
  18497. new THREE.UV( cy, 1 - cz ),
  18498. new THREE.UV( dy, 1 - dz )
  18499. ];
  18500. }
  18501. }
  18502. };
  18503. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18504. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18505. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18506. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18507. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18508. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18509. /**
  18510. * @author astrodud / http://astrodud.isgreat.org/
  18511. * @author zz85 / https://github.com/zz85
  18512. */
  18513. THREE.LatheGeometry = function ( points, steps, angle ) {
  18514. THREE.Geometry.call( this );
  18515. var _steps = steps || 12;
  18516. var _angle = angle || 2 * Math.PI;
  18517. var _newV = [];
  18518. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  18519. for ( var j = 0; j < points.length; j ++ ) {
  18520. _newV[ j ] = points[ j ].clone();
  18521. this.vertices.push( _newV[ j ] );
  18522. }
  18523. var i, il = _steps + 1;
  18524. for ( i = 0; i < il; i ++ ) {
  18525. for ( var j = 0; j < _newV.length; j ++ ) {
  18526. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  18527. this.vertices.push( _newV[ j ] );
  18528. }
  18529. }
  18530. for ( i = 0; i < _steps; i ++ ) {
  18531. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  18532. var a = i * kl + k;
  18533. var b = ( ( i + 1 ) % il ) * kl + k;
  18534. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  18535. var d = i * kl + ( k + 1 ) % kl;
  18536. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18537. this.faceVertexUvs[ 0 ].push( [
  18538. new THREE.UV( 1 - i / _steps, k / kl ),
  18539. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  18540. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  18541. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  18542. ] );
  18543. }
  18544. }
  18545. this.computeCentroids();
  18546. this.computeFaceNormals();
  18547. this.computeVertexNormals();
  18548. };
  18549. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18550. /**
  18551. * @author mrdoob / http://mrdoob.com/
  18552. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18553. */
  18554. THREE.PlaneGeometry = function ( width, height, segmentsWidth, segmentsheight ) {
  18555. THREE.Geometry.call( this );
  18556. var ix, iz,
  18557. width_half = width / 2,
  18558. height_half = height / 2,
  18559. gridX = segmentsWidth || 1,
  18560. gridZ = segmentsheight || 1,
  18561. gridX1 = gridX + 1,
  18562. gridZ1 = gridZ + 1,
  18563. segment_width = width / gridX,
  18564. segment_height = height / gridZ,
  18565. normal = new THREE.Vector3( 0, 0, 1 );
  18566. for ( iz = 0; iz < gridZ1; iz ++ ) {
  18567. for ( ix = 0; ix < gridX1; ix ++ ) {
  18568. var x = ix * segment_width - width_half;
  18569. var y = iz * segment_height - height_half;
  18570. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  18571. }
  18572. }
  18573. for ( iz = 0; iz < gridZ; iz ++ ) {
  18574. for ( ix = 0; ix < gridX; ix ++ ) {
  18575. var a = ix + gridX1 * iz;
  18576. var b = ix + gridX1 * ( iz + 1 );
  18577. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  18578. var d = ( ix + 1 ) + gridX1 * iz;
  18579. var face = new THREE.Face4( a, b, c, d );
  18580. face.normal.copy( normal );
  18581. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18582. this.faces.push( face );
  18583. this.faceVertexUvs[ 0 ].push( [
  18584. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  18585. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  18586. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  18587. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  18588. ] );
  18589. }
  18590. }
  18591. this.computeCentroids();
  18592. };
  18593. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18594. /**
  18595. * @author mrdoob / http://mrdoob.com/
  18596. */
  18597. THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength ) {
  18598. THREE.Geometry.call( this );
  18599. radius = radius || 50;
  18600. phiStart = phiStart !== undefined ? phiStart : 0;
  18601. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18602. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18603. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18604. var segmentsX = Math.max( 3, Math.floor( segmentsWidth ) || 8 );
  18605. var segmentsY = Math.max( 2, Math.floor( segmentsHeight ) || 6 );
  18606. var x, y, vertices = [], uvs = [];
  18607. for ( y = 0; y <= segmentsY; y ++ ) {
  18608. var verticesRow = [];
  18609. var uvsRow = [];
  18610. for ( x = 0; x <= segmentsX; x ++ ) {
  18611. var u = x / segmentsX;
  18612. var v = y / segmentsY;
  18613. var vertex = new THREE.Vector3();
  18614. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18615. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  18616. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18617. this.vertices.push( vertex );
  18618. verticesRow.push( this.vertices.length - 1 );
  18619. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18620. }
  18621. vertices.push( verticesRow );
  18622. uvs.push( uvsRow );
  18623. }
  18624. for ( y = 0; y < segmentsY; y ++ ) {
  18625. for ( x = 0; x < segmentsX; x ++ ) {
  18626. var v1 = vertices[ y ][ x + 1 ];
  18627. var v2 = vertices[ y ][ x ];
  18628. var v3 = vertices[ y + 1 ][ x ];
  18629. var v4 = vertices[ y + 1 ][ x + 1 ];
  18630. var n1 = this.vertices[ v1 ].clone().normalize();
  18631. var n2 = this.vertices[ v2 ].clone().normalize();
  18632. var n3 = this.vertices[ v3 ].clone().normalize();
  18633. var n4 = this.vertices[ v4 ].clone().normalize();
  18634. var uv1 = uvs[ y ][ x + 1 ].clone();
  18635. var uv2 = uvs[ y ][ x ].clone();
  18636. var uv3 = uvs[ y + 1 ][ x ].clone();
  18637. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  18638. if ( Math.abs( this.vertices[ v1 ].y ) == radius ) {
  18639. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  18640. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  18641. } else if ( Math.abs( this.vertices[ v3 ].y ) == radius ) {
  18642. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18643. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18644. } else {
  18645. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18646. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18647. }
  18648. }
  18649. }
  18650. this.computeCentroids();
  18651. this.computeFaceNormals();
  18652. this.boundingSphere = { radius: radius };
  18653. };
  18654. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18655. /**
  18656. * @author zz85 / http://www.lab4games.net/zz85/blog
  18657. * @author alteredq / http://alteredqualia.com/
  18658. *
  18659. * For creating 3D text geometry in three.js
  18660. *
  18661. * Text = 3D Text
  18662. *
  18663. * parameters = {
  18664. * size: <float>, // size of the text
  18665. * height: <float>, // thickness to extrude text
  18666. * curveSegments: <int>, // number of points on the curves
  18667. *
  18668. * font: <string>, // font name
  18669. * weight: <string>, // font weight (normal, bold)
  18670. * style: <string>, // font style (normal, italics)
  18671. *
  18672. * bevelEnabled: <bool>, // turn on bevel
  18673. * bevelThickness: <float>, // how deep into text bevel goes
  18674. * bevelSize: <float>, // how far from text outline is bevel
  18675. *
  18676. * bend: <bool> // bend according to hardcoded curve (generates bendPath)
  18677. * bendPath: <curve> // wraps text according to bend Path
  18678. * }
  18679. *
  18680. */
  18681. /* Usage Examples
  18682. // TextGeometry wrapper
  18683. var text3d = new TextGeometry( text, options );
  18684. // Complete manner
  18685. var textShapes = THREE.FontUtils.generateShapes( text, options );
  18686. var text3d = new ExtrudeGeometry( textShapes, options );
  18687. */
  18688. THREE.TextGeometry = function ( text, parameters ) {
  18689. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  18690. // translate parameters to ExtrudeGeometry API
  18691. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  18692. // defaults
  18693. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18694. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18695. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18696. if ( parameters.bend ) {
  18697. var b = textShapes[ textShapes.length - 1 ].getBoundingBox();
  18698. var max = b.maxX;
  18699. parameters.bendPath = new THREE.QuadraticBezierCurve(
  18700. new THREE.Vector2( 0, 0 ),
  18701. new THREE.Vector2( max / 2, 120 ),
  18702. new THREE.Vector2( max, 0 )
  18703. );
  18704. }
  18705. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  18706. };
  18707. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  18708. /**
  18709. * @author oosmoxiecode
  18710. * @author mrdoob / http://mrdoob.com/
  18711. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  18712. */
  18713. THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {
  18714. THREE.Geometry.call( this );
  18715. var scope = this;
  18716. this.radius = radius || 100;
  18717. this.tube = tube || 40;
  18718. this.segmentsR = segmentsR || 8;
  18719. this.segmentsT = segmentsT || 6;
  18720. this.arc = arc || Math.PI * 2;
  18721. var center = new THREE.Vector3(), uvs = [], normals = [];
  18722. for ( var j = 0; j <= this.segmentsR; j ++ ) {
  18723. for ( var i = 0; i <= this.segmentsT; i ++ ) {
  18724. var u = i / this.segmentsT * this.arc;
  18725. var v = j / this.segmentsR * Math.PI * 2;
  18726. center.x = this.radius * Math.cos( u );
  18727. center.y = this.radius * Math.sin( u );
  18728. var vertex = new THREE.Vector3();
  18729. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  18730. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  18731. vertex.z = this.tube * Math.sin( v );
  18732. this.vertices.push( vertex );
  18733. uvs.push( new THREE.UV( i / this.segmentsT, j / this.segmentsR ) );
  18734. normals.push( vertex.clone().subSelf( center ).normalize() );
  18735. }
  18736. }
  18737. for ( var j = 1; j <= this.segmentsR; j ++ ) {
  18738. for ( var i = 1; i <= this.segmentsT; i ++ ) {
  18739. var a = ( this.segmentsT + 1 ) * j + i - 1;
  18740. var b = ( this.segmentsT + 1 ) * ( j - 1 ) + i - 1;
  18741. var c = ( this.segmentsT + 1 ) * ( j - 1 ) + i;
  18742. var d = ( this.segmentsT + 1 ) * j + i;
  18743. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  18744. face.normal.addSelf( normals[ a ] );
  18745. face.normal.addSelf( normals[ b ] );
  18746. face.normal.addSelf( normals[ c ] );
  18747. face.normal.addSelf( normals[ d ] );
  18748. face.normal.normalize();
  18749. this.faces.push( face );
  18750. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  18751. }
  18752. }
  18753. this.computeCentroids();
  18754. };
  18755. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18756. /**
  18757. * @author oosmoxiecode
  18758. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  18759. */
  18760. THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {
  18761. THREE.Geometry.call( this );
  18762. var scope = this;
  18763. this.radius = radius || 200;
  18764. this.tube = tube || 40;
  18765. this.segmentsR = segmentsR || 64;
  18766. this.segmentsT = segmentsT || 8;
  18767. this.p = p || 2;
  18768. this.q = q || 3;
  18769. this.heightScale = heightScale || 1;
  18770. this.grid = new Array(this.segmentsR);
  18771. var tang = new THREE.Vector3();
  18772. var n = new THREE.Vector3();
  18773. var bitan = new THREE.Vector3();
  18774. for ( var i = 0; i < this.segmentsR; ++ i ) {
  18775. this.grid[ i ] = new Array( this.segmentsT );
  18776. for ( var j = 0; j < this.segmentsT; ++ j ) {
  18777. var u = i / this.segmentsR * 2 * this.p * Math.PI;
  18778. var v = j / this.segmentsT * 2 * Math.PI;
  18779. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  18780. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  18781. var cx, cy;
  18782. tang.sub( p2, p1 );
  18783. n.add( p2, p1 );
  18784. bitan.cross( tang, n );
  18785. n.cross( bitan, tang );
  18786. bitan.normalize();
  18787. n.normalize();
  18788. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18789. cy = this.tube * Math.sin( v );
  18790. p1.x += cx * n.x + cy * bitan.x;
  18791. p1.y += cx * n.y + cy * bitan.y;
  18792. p1.z += cx * n.z + cy * bitan.z;
  18793. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  18794. }
  18795. }
  18796. for ( var i = 0; i < this.segmentsR; ++ i ) {
  18797. for ( var j = 0; j < this.segmentsT; ++ j ) {
  18798. var ip = ( i + 1 ) % this.segmentsR;
  18799. var jp = ( j + 1 ) % this.segmentsT;
  18800. var a = this.grid[ i ][ j ];
  18801. var b = this.grid[ ip ][ j ];
  18802. var c = this.grid[ ip ][ jp ];
  18803. var d = this.grid[ i ][ jp ];
  18804. var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
  18805. var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
  18806. var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
  18807. var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );
  18808. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18809. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  18810. }
  18811. }
  18812. this.computeCentroids();
  18813. this.computeFaceNormals();
  18814. this.computeVertexNormals();
  18815. function vert( x, y, z ) {
  18816. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18817. }
  18818. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  18819. var cu = Math.cos( u );
  18820. var cv = Math.cos( v );
  18821. var su = Math.sin( u );
  18822. var quOverP = in_q / in_p * u;
  18823. var cs = Math.cos( quOverP );
  18824. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  18825. var ty = radius * ( 2 + cs ) * su * 0.5;
  18826. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  18827. return new THREE.Vector3( tx, ty, tz );
  18828. }
  18829. };
  18830. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18831. /**
  18832. * @author WestLangley / https://github.com/WestLangley
  18833. * @author zz85 / https://github.com/zz85
  18834. * @author miningold / https://github.com/miningold
  18835. *
  18836. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18837. *
  18838. * Creates a tube which extrudes along a 3d spline
  18839. *
  18840. * Uses parallel transport frames as described in
  18841. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18842. */
  18843. THREE.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {
  18844. THREE.Geometry.call( this );
  18845. this.path = path;
  18846. this.segments = segments || 64;
  18847. this.radius = radius || 1;
  18848. this.segmentsRadius = segmentsRadius || 8;
  18849. this.closed = closed || false;
  18850. if ( debug ) this.debug = new THREE.Object3D();
  18851. this.grid = [];
  18852. var scope = this,
  18853. tangent,
  18854. normal,
  18855. binormal,
  18856. numpoints = this.segments + 1,
  18857. x, y, z,
  18858. tx, ty, tz,
  18859. u, v,
  18860. cx, cy,
  18861. pos, pos2 = new THREE.Vector3(),
  18862. i, j,
  18863. ip, jp,
  18864. a, b, c, d,
  18865. uva, uvb, uvc, uvd;
  18866. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  18867. tangents = frames.tangents,
  18868. normals = frames.normals,
  18869. binormals = frames.binormals;
  18870. // proxy internals
  18871. this.tangents = tangents;
  18872. this.normals = normals;
  18873. this.binormals = binormals;
  18874. function vert( x, y, z ) {
  18875. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18876. }
  18877. // consruct the grid
  18878. for ( i = 0; i < numpoints; i++ ) {
  18879. this.grid[ i ] = [];
  18880. u = i / ( numpoints - 1 );
  18881. pos = path.getPointAt( u );
  18882. tangent = tangents[ i ];
  18883. normal = normals[ i ];
  18884. binormal = binormals[ i ];
  18885. if ( this.debug ) {
  18886. this.debug.add(new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff));
  18887. this.debug.add(new THREE.ArrowHelper(normal, pos, radius, 0xff0000));
  18888. this.debug.add(new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00));
  18889. }
  18890. for ( j = 0; j < this.segmentsRadius; j++ ) {
  18891. v = j / this.segmentsRadius * 2 * Math.PI;
  18892. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18893. cy = this.radius * Math.sin( v );
  18894. pos2.copy( pos );
  18895. pos2.x += cx * normal.x + cy * binormal.x;
  18896. pos2.y += cx * normal.y + cy * binormal.y;
  18897. pos2.z += cx * normal.z + cy * binormal.z;
  18898. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18899. }
  18900. }
  18901. // construct the mesh
  18902. for ( i = 0; i < this.segments; i++ ) {
  18903. for ( j = 0; j < this.segmentsRadius; j++ ) {
  18904. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  18905. jp = (j + 1) % this.segmentsRadius;
  18906. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18907. b = this.grid[ ip ][ j ];
  18908. c = this.grid[ ip ][ jp ];
  18909. d = this.grid[ i ][ jp ];
  18910. uva = new THREE.UV( i / this.segments, j / this.segmentsRadius );
  18911. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.segmentsRadius );
  18912. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.segmentsRadius );
  18913. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.segmentsRadius );
  18914. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18915. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  18916. }
  18917. }
  18918. this.computeCentroids();
  18919. this.computeFaceNormals();
  18920. this.computeVertexNormals();
  18921. };
  18922. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18923. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  18924. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  18925. var
  18926. tangent = new THREE.Vector3(),
  18927. normal = new THREE.Vector3(),
  18928. binormal = new THREE.Vector3(),
  18929. tangents = [],
  18930. normals = [],
  18931. binormals = [],
  18932. vec = new THREE.Vector3(),
  18933. mat = new THREE.Matrix4(),
  18934. numpoints = segments + 1,
  18935. theta,
  18936. epsilon = 0.0001,
  18937. smallest,
  18938. tx, ty, tz,
  18939. i, u, v;
  18940. // expose internals
  18941. this.tangents = tangents;
  18942. this.normals = normals;
  18943. this.binormals = binormals;
  18944. // compute the tangent vectors for each segment on the path
  18945. for ( i = 0; i < numpoints; i++ ) {
  18946. u = i / ( numpoints - 1 );
  18947. tangents[ i ] = path.getTangentAt( u );
  18948. tangents[ i ].normalize();
  18949. }
  18950. initialNormal3();
  18951. function initialNormal1(lastBinormal) {
  18952. // fixed start binormal. Has dangers of 0 vectors
  18953. normals[ 0 ] = new THREE.Vector3();
  18954. binormals[ 0 ] = new THREE.Vector3();
  18955. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  18956. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  18957. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18958. }
  18959. function initialNormal2() {
  18960. // This uses the Frenet-Serret formula for deriving binormal
  18961. var t2 = path.getTangentAt( epsilon );
  18962. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  18963. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  18964. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  18965. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18966. }
  18967. function initialNormal3() {
  18968. // select an initial normal vector perpenicular to the first tangent vector,
  18969. // and in the direction of the smallest tangent xyz component
  18970. normals[ 0 ] = new THREE.Vector3();
  18971. binormals[ 0 ] = new THREE.Vector3();
  18972. smallest = Number.MAX_VALUE;
  18973. tx = Math.abs( tangents[ 0 ].x );
  18974. ty = Math.abs( tangents[ 0 ].y );
  18975. tz = Math.abs( tangents[ 0 ].z );
  18976. if ( tx <= smallest ) {
  18977. smallest = tx;
  18978. normal.set( 1, 0, 0 );
  18979. }
  18980. if ( ty <= smallest ) {
  18981. smallest = ty;
  18982. normal.set( 0, 1, 0 );
  18983. }
  18984. if ( tz <= smallest ) {
  18985. normal.set( 0, 0, 1 );
  18986. }
  18987. vec.cross( tangents[ 0 ], normal ).normalize();
  18988. normals[ 0 ].cross( tangents[ 0 ], vec );
  18989. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  18990. }
  18991. // compute the slowly-varying normal and binormal vectors for each segment on the path
  18992. for ( i = 1; i < numpoints; i++ ) {
  18993. normals[ i ] = normals[ i-1 ].clone();
  18994. binormals[ i ] = binormals[ i-1 ].clone();
  18995. vec.cross( tangents[ i-1 ], tangents[ i ] );
  18996. if ( vec.length() > epsilon ) {
  18997. vec.normalize();
  18998. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  18999. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  19000. }
  19001. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19002. }
  19003. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19004. if ( closed ) {
  19005. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19006. theta /= ( numpoints - 1 );
  19007. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19008. theta = -theta;
  19009. }
  19010. for ( i = 1; i < numpoints; i++ ) {
  19011. // twist a little...
  19012. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  19013. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19014. }
  19015. }
  19016. };
  19017. /**
  19018. * @author clockworkgeek / https://github.com/clockworkgeek
  19019. * @author timothypratley / https://github.com/timothypratley
  19020. */
  19021. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19022. THREE.Geometry.call( this );
  19023. radius = radius || 1;
  19024. detail = detail || 0;
  19025. var that = this;
  19026. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19027. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19028. }
  19029. var midpoints = [], p = this.vertices;
  19030. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19031. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19032. }
  19033. this.mergeVertices();
  19034. // Apply radius
  19035. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19036. this.vertices[ i ].multiplyScalar( radius );
  19037. }
  19038. // Project vector onto sphere's surface
  19039. function prepare( vector ) {
  19040. var vertex = vector.normalize().clone();
  19041. vertex.index = that.vertices.push( vertex ) - 1;
  19042. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19043. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19044. var v = inclination( vector ) / Math.PI + 0.5;
  19045. vertex.uv = new THREE.UV( u, 1 - v );
  19046. return vertex;
  19047. }
  19048. // Approximate a curved face with recursively sub-divided triangles.
  19049. function make( v1, v2, v3, detail ) {
  19050. if ( detail < 1 ) {
  19051. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19052. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  19053. face.normal = face.centroid.clone().normalize();
  19054. that.faces.push( face );
  19055. var azi = azimuth( face.centroid );
  19056. that.faceVertexUvs[ 0 ].push( [
  19057. correctUV( v1.uv, v1, azi ),
  19058. correctUV( v2.uv, v2, azi ),
  19059. correctUV( v3.uv, v3, azi )
  19060. ] );
  19061. } else {
  19062. detail -= 1;
  19063. // split triangle into 4 smaller triangles
  19064. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19065. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19066. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19067. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19068. }
  19069. }
  19070. function midpoint( v1, v2 ) {
  19071. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19072. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19073. var mid = midpoints[ v1.index ][ v2.index ];
  19074. if ( mid === undefined ) {
  19075. // generate mean point and project to surface with prepare()
  19076. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19077. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  19078. );
  19079. }
  19080. return mid;
  19081. }
  19082. // Angle around the Y axis, counter-clockwise when looking from above.
  19083. function azimuth( vector ) {
  19084. return Math.atan2( vector.z, -vector.x );
  19085. }
  19086. // Angle above the XZ plane.
  19087. function inclination( vector ) {
  19088. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19089. }
  19090. // Texture fixing helper. Spheres have some odd behaviours.
  19091. function correctUV( uv, vector, azimuth ) {
  19092. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  19093. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  19094. return uv;
  19095. }
  19096. this.computeCentroids();
  19097. this.boundingSphere = { radius: radius };
  19098. };
  19099. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19100. /**
  19101. * @author timothypratley / https://github.com/timothypratley
  19102. */
  19103. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19104. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19105. var vertices = [
  19106. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19107. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19108. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19109. ];
  19110. var faces = [
  19111. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19112. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19113. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19114. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19115. ];
  19116. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19117. };
  19118. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19119. /**
  19120. * @author timothypratley / https://github.com/timothypratley
  19121. */
  19122. THREE.OctahedronGeometry = function ( radius, detail ) {
  19123. var vertices = [
  19124. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19125. ];
  19126. var faces = [
  19127. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19128. ];
  19129. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19130. };
  19131. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19132. /**
  19133. * @author timothypratley / https://github.com/timothypratley
  19134. */
  19135. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19136. var vertices = [
  19137. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19138. ];
  19139. var faces = [
  19140. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19141. ];
  19142. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19143. };
  19144. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19145. /**
  19146. * @author zz85 / https://github.com/zz85
  19147. * Parametric Surfaces Geometry
  19148. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19149. *
  19150. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19151. *
  19152. */
  19153. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19154. THREE.Geometry.call( this );
  19155. var verts = this.vertices;
  19156. var faces = this.faces;
  19157. var uvs = this.faceVertexUvs[ 0 ];
  19158. useTris = (useTris === undefined) ? false : useTris;
  19159. var i, il, j, p;
  19160. var u, v;
  19161. var stackCount = stacks + 1;
  19162. var sliceCount = slices + 1;
  19163. for ( i = 0; i <= stacks; i ++ ) {
  19164. v = i / stacks;
  19165. for ( j = 0; j <= slices; j ++ ) {
  19166. u = j / slices;
  19167. p = func( u, v );
  19168. verts.push( p );
  19169. }
  19170. }
  19171. var a, b, c, d;
  19172. var uva, uvb, uvc, uvd;
  19173. for ( i = 0; i < stacks; i ++ ) {
  19174. for ( j = 0; j < slices; j ++ ) {
  19175. a = i * sliceCount + j;
  19176. b = i * sliceCount + j + 1;
  19177. c = (i + 1) * sliceCount + j;
  19178. d = (i + 1) * sliceCount + j + 1;
  19179. uva = new THREE.UV( j / slices, i / stacks );
  19180. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  19181. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  19182. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19183. if ( useTris ) {
  19184. faces.push( new THREE.Face3( a, b, c ) );
  19185. faces.push( new THREE.Face3( b, d, c ) );
  19186. uvs.push( [ uva, uvb, uvc ] );
  19187. uvs.push( [ uvb, uvd, uvc ] );
  19188. } else {
  19189. faces.push( new THREE.Face4( a, b, d, c ) );
  19190. uvs.push( [ uva, uvb, uvd, uvc ] );
  19191. }
  19192. }
  19193. }
  19194. // console.log(this);
  19195. // magic bullet
  19196. // var diff = this.mergeVertices();
  19197. // console.log('removed ', diff, ' vertices by merging');
  19198. this.computeCentroids();
  19199. this.computeFaceNormals();
  19200. this.computeVertexNormals();
  19201. };
  19202. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19203. /**
  19204. * @author qiao / https://github.com/qiao
  19205. * @fileoverview This is a convex hull generator using the incremental method.
  19206. * The complexity is O(n^2) where n is the number of vertices.
  19207. * O(nlogn) algorithms do exist, but they are much more complicated.
  19208. *
  19209. * Benchmark:
  19210. *
  19211. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19212. *
  19213. * Num Vertices Time(ms)
  19214. *
  19215. * 10 1
  19216. * 20 3
  19217. * 30 19
  19218. * 40 48
  19219. * 50 107
  19220. */
  19221. THREE.ConvexGeometry = function( vertices ) {
  19222. THREE.Geometry.call( this );
  19223. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19224. for ( var i = 3; i < vertices.length; i++ ) {
  19225. addPoint( i );
  19226. }
  19227. function addPoint( vertexId ) {
  19228. var vertex = vertices[ vertexId ].clone();
  19229. var mag = vertex.length();
  19230. vertex.x += mag * randomOffset();
  19231. vertex.y += mag * randomOffset();
  19232. vertex.z += mag * randomOffset();
  19233. var hole = [];
  19234. for ( var f = 0; f < faces.length; ) {
  19235. var face = faces[ f ];
  19236. // for each face, if the vertex can see it,
  19237. // then we try to add the face's edges into the hole.
  19238. if ( visible( face, vertex ) ) {
  19239. for ( var e = 0; e < 3; e++ ) {
  19240. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19241. var boundary = true;
  19242. // remove duplicated edges.
  19243. for ( var h = 0; h < hole.length; h++ ) {
  19244. if ( equalEdge( hole[ h ], edge ) ) {
  19245. hole[ h ] = hole[ hole.length - 1 ];
  19246. hole.pop();
  19247. boundary = false;
  19248. break;
  19249. }
  19250. }
  19251. if ( boundary ) {
  19252. hole.push( edge );
  19253. }
  19254. }
  19255. // remove faces[ f ]
  19256. faces[ f ] = faces[ faces.length - 1 ];
  19257. faces.pop();
  19258. } else { // not visible
  19259. f++;
  19260. }
  19261. }
  19262. // construct the new faces formed by the edges of the hole and the vertex
  19263. for ( var h = 0; h < hole.length; h++ ) {
  19264. faces.push( [
  19265. hole[ h ][ 0 ],
  19266. hole[ h ][ 1 ],
  19267. vertexId
  19268. ] );
  19269. }
  19270. }
  19271. /**
  19272. * Whether the face is visible from the vertex
  19273. */
  19274. function visible( face, vertex ) {
  19275. var va = vertices[ face[ 0 ] ];
  19276. var vb = vertices[ face[ 1 ] ];
  19277. var vc = vertices[ face[ 2 ] ];
  19278. var n = normal( va, vb, vc );
  19279. // distance from face to origin
  19280. var dist = n.dot( va );
  19281. return n.dot( vertex ) >= dist;
  19282. }
  19283. /**
  19284. * Face normal
  19285. */
  19286. function normal( va, vb, vc ) {
  19287. var cb = new THREE.Vector3();
  19288. var ab = new THREE.Vector3();
  19289. cb.sub( vc, vb );
  19290. ab.sub( va, vb );
  19291. cb.crossSelf( ab );
  19292. if ( !cb.isZero() ) {
  19293. cb.normalize();
  19294. }
  19295. return cb;
  19296. }
  19297. /**
  19298. * Detect whether two edges are equal.
  19299. * Note that when constructing the convex hull, two same edges can only
  19300. * be of the negative direction.
  19301. */
  19302. function equalEdge( ea, eb ) {
  19303. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19304. }
  19305. /**
  19306. * Create a random offset between -1e-6 and 1e-6.
  19307. */
  19308. function randomOffset() {
  19309. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19310. }
  19311. /**
  19312. * XXX: Not sure if this is the correct approach. Need someone to review.
  19313. */
  19314. function vertexUv( vertex ) {
  19315. var mag = vertex.length();
  19316. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  19317. }
  19318. // Push vertices into `this.vertices`, skipping those inside the hull
  19319. var id = 0;
  19320. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19321. for ( var i = 0; i < faces.length; i++ ) {
  19322. var face = faces[ i ];
  19323. for ( var j = 0; j < 3; j++ ) {
  19324. if ( newId[ face[ j ] ] === undefined ) {
  19325. newId[ face[ j ] ] = id++;
  19326. this.vertices.push( vertices[ face[ j ] ] );
  19327. }
  19328. face[ j ] = newId[ face[ j ] ];
  19329. }
  19330. }
  19331. // Convert faces into instances of THREE.Face3
  19332. for ( var i = 0; i < faces.length; i++ ) {
  19333. this.faces.push( new THREE.Face3(
  19334. faces[ i ][ 0 ],
  19335. faces[ i ][ 1 ],
  19336. faces[ i ][ 2 ]
  19337. ) );
  19338. }
  19339. // Compute UVs
  19340. for ( var i = 0; i < this.faces.length; i++ ) {
  19341. var face = this.faces[ i ];
  19342. this.faceVertexUvs[ 0 ].push( [
  19343. vertexUv( this.vertices[ face.a ] ),
  19344. vertexUv( this.vertices[ face.b ] ),
  19345. vertexUv( this.vertices[ face.c ])
  19346. ] );
  19347. }
  19348. this.computeCentroids();
  19349. this.computeFaceNormals();
  19350. this.computeVertexNormals();
  19351. };
  19352. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19353. /**
  19354. * @author sroucheray / http://sroucheray.org/
  19355. * @author mrdoob / http://mrdoob.com/
  19356. */
  19357. THREE.AxisHelper = function () {
  19358. THREE.Object3D.call( this );
  19359. var lineGeometry = new THREE.Geometry();
  19360. lineGeometry.vertices.push( new THREE.Vector3() );
  19361. lineGeometry.vertices.push( new THREE.Vector3( 0, 100, 0 ) );
  19362. var coneGeometry = new THREE.CylinderGeometry( 0, 5, 25, 5, 1 );
  19363. var line, cone;
  19364. // x
  19365. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
  19366. line.rotation.z = - Math.PI / 2;
  19367. this.add( line );
  19368. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0xff0000 } ) );
  19369. cone.position.x = 100;
  19370. cone.rotation.z = - Math.PI / 2;
  19371. this.add( cone );
  19372. // y
  19373. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x00ff00 } ) );
  19374. this.add( line );
  19375. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x00ff00 } ) );
  19376. cone.position.y = 100;
  19377. this.add( cone );
  19378. // z
  19379. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
  19380. line.rotation.x = Math.PI / 2;
  19381. this.add( line );
  19382. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x0000ff } ) );
  19383. cone.position.z = 100;
  19384. cone.rotation.x = Math.PI / 2;
  19385. this.add( cone );
  19386. };
  19387. THREE.AxisHelper.prototype = Object.create( THREE.Object3D.prototype );
  19388. /**
  19389. * @author WestLangley / http://github.com/WestLangley
  19390. * @author zz85 / https://github.com/zz85
  19391. *
  19392. * Creates an arrow for visualizing directions
  19393. *
  19394. * Parameters:
  19395. * dir - Vector3
  19396. * origin - Vector3
  19397. * length - Number
  19398. * hex - color in hex value
  19399. */
  19400. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19401. THREE.Object3D.call( this );
  19402. if ( hex === undefined ) hex = 0xffff00;
  19403. if ( length === undefined ) length = 20;
  19404. var lineGeometry = new THREE.Geometry();
  19405. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19406. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19407. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19408. this.add( this.line );
  19409. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19410. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19411. this.cone.position.set( 0, 1, 0 );
  19412. this.add( this.cone );
  19413. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19414. this.setDirection( dir );
  19415. this.setLength( length );
  19416. };
  19417. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19418. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19419. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  19420. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  19421. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  19422. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  19423. };
  19424. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19425. this.scale.set( length, length, length );
  19426. };
  19427. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19428. this.line.material.color.setHex( hex );
  19429. this.cone.material.color.setHex( hex );
  19430. };
  19431. /**
  19432. * @author alteredq / http://alteredqualia.com/
  19433. *
  19434. * - shows frustum, line of sight and up of the camera
  19435. * - suitable for fast updates
  19436. * - based on frustum visualization in lightgl.js shadowmap example
  19437. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19438. */
  19439. THREE.CameraHelper = function ( camera ) {
  19440. THREE.Object3D.call( this );
  19441. var _this = this;
  19442. this.lineGeometry = new THREE.Geometry();
  19443. this.lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19444. this.pointMap = {};
  19445. // colors
  19446. var hexFrustum = 0xffaa00,
  19447. hexCone = 0xff0000,
  19448. hexUp = 0x00aaff,
  19449. hexTarget = 0xffffff,
  19450. hexCross = 0x333333;
  19451. // near
  19452. addLine( "n1", "n2", hexFrustum );
  19453. addLine( "n2", "n4", hexFrustum );
  19454. addLine( "n4", "n3", hexFrustum );
  19455. addLine( "n3", "n1", hexFrustum );
  19456. // far
  19457. addLine( "f1", "f2", hexFrustum );
  19458. addLine( "f2", "f4", hexFrustum );
  19459. addLine( "f4", "f3", hexFrustum );
  19460. addLine( "f3", "f1", hexFrustum );
  19461. // sides
  19462. addLine( "n1", "f1", hexFrustum );
  19463. addLine( "n2", "f2", hexFrustum );
  19464. addLine( "n3", "f3", hexFrustum );
  19465. addLine( "n4", "f4", hexFrustum );
  19466. // cone
  19467. addLine( "p", "n1", hexCone );
  19468. addLine( "p", "n2", hexCone );
  19469. addLine( "p", "n3", hexCone );
  19470. addLine( "p", "n4", hexCone );
  19471. // up
  19472. addLine( "u1", "u2", hexUp );
  19473. addLine( "u2", "u3", hexUp );
  19474. addLine( "u3", "u1", hexUp );
  19475. // target
  19476. addLine( "c", "t", hexTarget );
  19477. addLine( "p", "c", hexCross );
  19478. // cross
  19479. addLine( "cn1", "cn2", hexCross );
  19480. addLine( "cn3", "cn4", hexCross );
  19481. addLine( "cf1", "cf2", hexCross );
  19482. addLine( "cf3", "cf4", hexCross );
  19483. this.camera = camera;
  19484. function addLine( a, b, hex ) {
  19485. addPoint( a, hex );
  19486. addPoint( b, hex );
  19487. }
  19488. function addPoint( id, hex ) {
  19489. _this.lineGeometry.vertices.push( new THREE.Vector3() );
  19490. _this.lineGeometry.colors.push( new THREE.Color( hex ) );
  19491. if ( _this.pointMap[ id ] === undefined ) _this.pointMap[ id ] = [];
  19492. _this.pointMap[ id ].push( _this.lineGeometry.vertices.length - 1 );
  19493. }
  19494. this.update( camera );
  19495. this.lines = new THREE.Line( this.lineGeometry, this.lineMaterial, THREE.LinePieces );
  19496. this.add( this.lines );
  19497. };
  19498. THREE.CameraHelper.prototype = Object.create( THREE.Object3D.prototype );
  19499. THREE.CameraHelper.prototype.update = function () {
  19500. var camera = this.camera;
  19501. var w = 1;
  19502. var h = 1;
  19503. var _this = this;
  19504. // we need just camera projection matrix
  19505. // world matrix must be identity
  19506. THREE.CameraHelper.__c.projectionMatrix.copy( camera.projectionMatrix );
  19507. // center / target
  19508. setPoint( "c", 0, 0, -1 );
  19509. setPoint( "t", 0, 0, 1 );
  19510. // near
  19511. setPoint( "n1", -w, -h, -1 );
  19512. setPoint( "n2", w, -h, -1 );
  19513. setPoint( "n3", -w, h, -1 );
  19514. setPoint( "n4", w, h, -1 );
  19515. // far
  19516. setPoint( "f1", -w, -h, 1 );
  19517. setPoint( "f2", w, -h, 1 );
  19518. setPoint( "f3", -w, h, 1 );
  19519. setPoint( "f4", w, h, 1 );
  19520. // up
  19521. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19522. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19523. setPoint( "u3", 0, h * 2, -1 );
  19524. // cross
  19525. setPoint( "cf1", -w, 0, 1 );
  19526. setPoint( "cf2", w, 0, 1 );
  19527. setPoint( "cf3", 0, -h, 1 );
  19528. setPoint( "cf4", 0, h, 1 );
  19529. setPoint( "cn1", -w, 0, -1 );
  19530. setPoint( "cn2", w, 0, -1 );
  19531. setPoint( "cn3", 0, -h, -1 );
  19532. setPoint( "cn4", 0, h, -1 );
  19533. function setPoint( point, x, y, z ) {
  19534. THREE.CameraHelper.__v.set( x, y, z );
  19535. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19536. var points = _this.pointMap[ point ];
  19537. if ( points !== undefined ) {
  19538. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19539. var j = points[ i ];
  19540. _this.lineGeometry.vertices[ j ].copy( THREE.CameraHelper.__v );
  19541. }
  19542. }
  19543. }
  19544. this.lineGeometry.verticesNeedUpdate = true;
  19545. };
  19546. THREE.CameraHelper.__projector = new THREE.Projector();
  19547. THREE.CameraHelper.__v = new THREE.Vector3();
  19548. THREE.CameraHelper.__c = new THREE.Camera();
  19549. /*
  19550. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19551. *
  19552. * Subdivision Geometry Modifier
  19553. * using Catmull-Clark Subdivision Surfaces
  19554. * for creating smooth geometry meshes
  19555. *
  19556. * Note: a modifier modifies vertices and faces of geometry,
  19557. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  19558. *
  19559. * Readings:
  19560. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19561. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  19562. * http://xrt.wikidot.com/blog:31
  19563. * "Subdivision Surfaces in Character Animation"
  19564. *
  19565. * Supports:
  19566. * Closed and Open geometries.
  19567. *
  19568. * TODO:
  19569. * crease vertex and "semi-sharp" features
  19570. * selective subdivision
  19571. */
  19572. THREE.SubdivisionModifier = function( subdivisions ) {
  19573. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  19574. // Settings
  19575. this.useOldVertexColors = false;
  19576. this.supportUVs = true;
  19577. this.debug = false;
  19578. };
  19579. // Applies the "modify" pattern
  19580. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  19581. var repeats = this.subdivisions;
  19582. while ( repeats-- > 0 ) {
  19583. this.smooth( geometry );
  19584. }
  19585. };
  19586. // Performs an iteration of Catmull-Clark Subdivision
  19587. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  19588. //debug( 'running smooth' );
  19589. // New set of vertices, faces and uvs
  19590. var newVertices = [], newFaces = [], newUVs = [];
  19591. function v( x, y, z ) {
  19592. newVertices.push( new THREE.Vector3( x, y, z ) );
  19593. }
  19594. var scope = this;
  19595. function debug() {
  19596. if (scope.debug) console.log.apply(console, arguments);
  19597. }
  19598. function warn() {
  19599. if (console)
  19600. console.log.apply(console, arguments);
  19601. }
  19602. function f4( a, b, c, d, oldFace, orders, facei ) {
  19603. // TODO move vertex selection over here!
  19604. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  19605. if (scope.useOldVertexColors) {
  19606. newFace.vertexColors = [];
  19607. var color, tmpColor, order;
  19608. for (var i=0;i<4;i++) {
  19609. order = orders[i];
  19610. color = new THREE.Color(),
  19611. color.setRGB(0,0,0);
  19612. for (var j=0, jl=0; j<order.length;j++) {
  19613. tmpColor = oldFace.vertexColors[order[j]-1];
  19614. color.r += tmpColor.r;
  19615. color.g += tmpColor.g;
  19616. color.b += tmpColor.b;
  19617. }
  19618. color.r /= order.length;
  19619. color.g /= order.length;
  19620. color.b /= order.length;
  19621. newFace.vertexColors[i] = color;
  19622. }
  19623. }
  19624. newFaces.push( newFace );
  19625. if (scope.supportUVs) {
  19626. var aUv = [
  19627. getUV(a, ''),
  19628. getUV(b, facei),
  19629. getUV(c, facei),
  19630. getUV(d, facei)
  19631. ];
  19632. if (!aUv[0]) debug('a :( ', a+':'+facei);
  19633. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  19634. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  19635. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  19636. else
  19637. newUVs.push( aUv );
  19638. }
  19639. }
  19640. function edge_hash( a, b ) {
  19641. return Math.min( a, b ) + "_" + Math.max( a, b );
  19642. }
  19643. function computeEdgeFaces( geometry ) {
  19644. var i, il, v1, v2, j, k,
  19645. face, faceIndices, faceIndex,
  19646. edge,
  19647. hash,
  19648. edgeFaceMap = {};
  19649. function mapEdgeHash( hash, i ) {
  19650. if ( edgeFaceMap[ hash ] === undefined ) {
  19651. edgeFaceMap[ hash ] = [];
  19652. }
  19653. edgeFaceMap[ hash ].push( i );
  19654. }
  19655. // construct vertex -> face map
  19656. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  19657. face = geometry.faces[ i ];
  19658. if ( face instanceof THREE.Face3 ) {
  19659. hash = edge_hash( face.a, face.b );
  19660. mapEdgeHash( hash, i );
  19661. hash = edge_hash( face.b, face.c );
  19662. mapEdgeHash( hash, i );
  19663. hash = edge_hash( face.c, face.a );
  19664. mapEdgeHash( hash, i );
  19665. } else if ( face instanceof THREE.Face4 ) {
  19666. hash = edge_hash( face.a, face.b );
  19667. mapEdgeHash( hash, i );
  19668. hash = edge_hash( face.b, face.c );
  19669. mapEdgeHash( hash, i );
  19670. hash = edge_hash( face.c, face.d );
  19671. mapEdgeHash( hash, i );
  19672. hash = edge_hash( face.d, face.a );
  19673. mapEdgeHash( hash, i );
  19674. }
  19675. }
  19676. // extract faces
  19677. // var edges = [];
  19678. //
  19679. // var numOfEdges = 0;
  19680. // for (i in edgeFaceMap) {
  19681. // numOfEdges++;
  19682. //
  19683. // edge = edgeFaceMap[i];
  19684. // edges.push(edge);
  19685. //
  19686. // }
  19687. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  19688. return edgeFaceMap;
  19689. }
  19690. var originalPoints = oldGeometry.vertices;
  19691. var originalFaces = oldGeometry.faces;
  19692. var newPoints = originalPoints.concat(); // Vertices
  19693. var facePoints = [], edgePoints = {};
  19694. var sharpEdges = {}, sharpVertices = [], sharpFaces = [];
  19695. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  19696. var originalVerticesLength = originalPoints.length;
  19697. function getUV(vertexNo, oldFaceNo) {
  19698. var j,jl;
  19699. var key = vertexNo+':'+oldFaceNo;
  19700. var theUV = uvForVertices[key];
  19701. if (!theUV) {
  19702. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  19703. debug('face pt');
  19704. } else {
  19705. debug('edge pt');
  19706. }
  19707. warn('warning, UV not found for', key);
  19708. return null;
  19709. }
  19710. return theUV;
  19711. // Original faces -> Vertex Nos.
  19712. // new Facepoint -> Vertex Nos.
  19713. // edge Points
  19714. }
  19715. function addUV(vertexNo, oldFaceNo, value) {
  19716. var key = vertexNo+':'+oldFaceNo;
  19717. if (!(key in uvForVertices)) {
  19718. uvForVertices[key] = value;
  19719. } else {
  19720. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  19721. }
  19722. }
  19723. // Step 1
  19724. // For each face, add a face point
  19725. // Set each face point to be the centroid of all original points for the respective face.
  19726. // debug(oldGeometry);
  19727. var i, il, j, jl, face;
  19728. // For Uvs
  19729. var uvs = oldGeometry.faceVertexUvs[0];
  19730. var abcd = 'abcd', vertice;
  19731. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  19732. if (scope.supportUVs)
  19733. for (i=0, il = uvs.length; i<il; i++ ) {
  19734. for (j=0,jl=uvs[i].length;j<jl;j++) {
  19735. vertice = originalFaces[i][abcd.charAt(j)];
  19736. addUV(vertice, i, uvs[i][j]);
  19737. }
  19738. }
  19739. if (uvs.length == 0) scope.supportUVs = false;
  19740. // Additional UVs check, if we index original
  19741. var uvCount = 0;
  19742. for (var u in uvForVertices) {
  19743. uvCount++;
  19744. }
  19745. if (!uvCount) {
  19746. scope.supportUVs = false;
  19747. debug('no uvs');
  19748. }
  19749. debug('-- Original Faces + Vertices UVs completed', uvForVertices, 'vs', uvs.length);
  19750. var avgUv ;
  19751. for (i=0, il = originalFaces.length; i<il ;i++) {
  19752. face = originalFaces[ i ];
  19753. facePoints.push( face.centroid );
  19754. newPoints.push( face.centroid );
  19755. if (!scope.supportUVs) continue;
  19756. // Prepare subdivided uv
  19757. avgUv = new THREE.UV();
  19758. if ( face instanceof THREE.Face3 ) {
  19759. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  19760. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  19761. avgUv.u /= 3;
  19762. avgUv.v /= 3;
  19763. } else if ( face instanceof THREE.Face4 ) {
  19764. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  19765. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  19766. avgUv.u /= 4;
  19767. avgUv.v /= 4;
  19768. }
  19769. addUV(originalVerticesLength + i, '', avgUv);
  19770. }
  19771. debug('-- added UVs for new Faces', uvForVertices);
  19772. // Step 2
  19773. // For each edge, add an edge point.
  19774. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  19775. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index
  19776. var edge, faceIndexA, faceIndexB, avg;
  19777. // debug('edgeFaceMap', edgeFaceMap);
  19778. var edgeCount = 0;
  19779. var edgeVertex, edgeVertexA, edgeVertexB;
  19780. ////
  19781. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  19782. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  19783. function addVertexEdgeMap(vertex, edge) {
  19784. if (vertexEdgeMap[vertex]===undefined) {
  19785. vertexEdgeMap[vertex] = [];
  19786. }
  19787. vertexEdgeMap[vertex].push(edge);
  19788. }
  19789. function addVertexFaceMap(vertex, face, edge) {
  19790. if (vertexFaceMap[vertex]===undefined) {
  19791. vertexFaceMap[vertex] = {};
  19792. }
  19793. vertexFaceMap[vertex][face] = edge;
  19794. // vertexFaceMap[vertex][face] = null;
  19795. }
  19796. // Prepares vertexEdgeMap and vertexFaceMap
  19797. for (i in edgeFaceMap) { // This is for every edge
  19798. edge = edgeFaceMap[i];
  19799. edgeVertex = i.split('_');
  19800. edgeVertexA = edgeVertex[0];
  19801. edgeVertexB = edgeVertex[1];
  19802. // Maps an edgeVertex to connecting edges
  19803. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  19804. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  19805. for (j=0,jl=edge.length;j<jl;j++) {
  19806. face = edge[j];
  19807. addVertexFaceMap(edgeVertexA, face, i);
  19808. addVertexFaceMap(edgeVertexB, face, i);
  19809. }
  19810. if (edge.length < 2) {
  19811. // edge is "sharp";
  19812. sharpEdges[i] = true;
  19813. sharpVertices[edgeVertexA] = true;
  19814. sharpVertices[edgeVertexB] = true;
  19815. }
  19816. }
  19817. debug('vertexEdgeMap',vertexEdgeMap, 'vertexFaceMap', vertexFaceMap);
  19818. for (i in edgeFaceMap) {
  19819. edge = edgeFaceMap[i];
  19820. faceIndexA = edge[0]; // face index a
  19821. faceIndexB = edge[1]; // face index b
  19822. edgeVertex = i.split('_');
  19823. edgeVertexA = edgeVertex[0];
  19824. edgeVertexB = edgeVertex[1];
  19825. avg = new THREE.Vector3();
  19826. //debug(i, faceIndexB,facePoints[faceIndexB]);
  19827. if (sharpEdges[i]) {
  19828. //debug('warning, ', i, 'edge has only 1 connecting face', edge);
  19829. // For a sharp edge, average the edge end points.
  19830. avg.addSelf(originalPoints[edgeVertexA]);
  19831. avg.addSelf(originalPoints[edgeVertexB]);
  19832. avg.multiplyScalar(0.5);
  19833. sharpVertices[newPoints.length] = true;
  19834. } else {
  19835. avg.addSelf(facePoints[faceIndexA]);
  19836. avg.addSelf(facePoints[faceIndexB]);
  19837. avg.addSelf(originalPoints[edgeVertexA]);
  19838. avg.addSelf(originalPoints[edgeVertexB]);
  19839. avg.multiplyScalar(0.25);
  19840. }
  19841. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  19842. newPoints.push( avg );
  19843. edgeCount ++;
  19844. if (!scope.supportUVs) {
  19845. continue;
  19846. }
  19847. // debug('faceIndexAB', faceIndexA, faceIndexB, sharpEdges[i]);
  19848. // Prepare subdivided uv
  19849. avgUv = new THREE.UV();
  19850. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  19851. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  19852. avgUv.u /= 2;
  19853. avgUv.v /= 2;
  19854. addUV(edgePoints[i], faceIndexA, avgUv);
  19855. if (!sharpEdges[i]) {
  19856. avgUv = new THREE.UV();
  19857. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  19858. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  19859. avgUv.u /= 2;
  19860. avgUv.v /= 2;
  19861. addUV(edgePoints[i], faceIndexB, avgUv);
  19862. }
  19863. }
  19864. debug('-- Step 2 done');
  19865. // Step 3
  19866. // For each face point, add an edge for every edge of the face,
  19867. // connecting the face point to each edge point for the face.
  19868. var facePt, currentVerticeIndex;
  19869. var hashAB, hashBC, hashCD, hashDA, hashCA;
  19870. var abc123 = ['123', '12', '2', '23'];
  19871. var bca123 = ['123', '23', '3', '31'];
  19872. var cab123 = ['123', '31', '1', '12'];
  19873. var abc1234 = ['1234', '12', '2', '23'];
  19874. var bcd1234 = ['1234', '23', '3', '34'];
  19875. var cda1234 = ['1234', '34', '4', '41'];
  19876. var dab1234 = ['1234', '41', '1', '12'];
  19877. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  19878. facePt = facePoints[i];
  19879. face = originalFaces[i];
  19880. currentVerticeIndex = originalVerticesLength+ i;
  19881. if ( face instanceof THREE.Face3 ) {
  19882. // create 3 face4s
  19883. hashAB = edge_hash( face.a, face.b );
  19884. hashBC = edge_hash( face.b, face.c );
  19885. hashCA = edge_hash( face.c, face.a );
  19886. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  19887. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  19888. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  19889. } else if ( face instanceof THREE.Face4 ) {
  19890. // create 4 face4s
  19891. hashAB = edge_hash( face.a, face.b );
  19892. hashBC = edge_hash( face.b, face.c );
  19893. hashCD = edge_hash( face.c, face.d );
  19894. hashDA = edge_hash( face.d, face.a );
  19895. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  19896. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  19897. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  19898. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  19899. } else {
  19900. debug('face should be a face!', face);
  19901. }
  19902. }
  19903. newVertices = newPoints;
  19904. // debug('original ', oldGeometry.vertices.length, oldGeometry.faces.length );
  19905. // debug('new points', newPoints.length, 'faces', newFaces.length );
  19906. // Step 4
  19907. // For each original point P,
  19908. // take the average F of all n face points for faces touching P,
  19909. // and take the average R of all n edge midpoints for edges touching P,
  19910. // where each edge midpoint is the average of its two endpoint vertices.
  19911. // Move each original point to the point
  19912. var F = new THREE.Vector3();
  19913. var R = new THREE.Vector3();
  19914. var n;
  19915. for (i=0, il = originalPoints.length; i<il; i++) {
  19916. // (F + 2R + (n-3)P) / n
  19917. if (vertexEdgeMap[i]===undefined) continue;
  19918. F.set(0,0,0);
  19919. R.set(0,0,0);
  19920. var newPos = new THREE.Vector3(0,0,0);
  19921. var f =0;
  19922. for (j in vertexFaceMap[i]) {
  19923. F.addSelf(facePoints[j]);
  19924. f++;
  19925. }
  19926. var sharpEdgeCount = 0;
  19927. n = vertexEdgeMap[i].length;
  19928. for (j=0;j<n;j++) {
  19929. if (
  19930. sharpEdges[
  19931. edge_hash(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  19932. ]) {
  19933. sharpEdgeCount++;
  19934. }
  19935. }
  19936. if ( sharpEdgeCount==2 ) {
  19937. continue;
  19938. // Do not move vertex if there's 2 connecting sharp edges.
  19939. }
  19940. /*
  19941. if (sharpEdgeCount>2) {
  19942. // TODO
  19943. }
  19944. */
  19945. F.divideScalar(f);
  19946. for (j=0; j<n;j++) {
  19947. edge = vertexEdgeMap[i][j];
  19948. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  19949. R.addSelf(midPt);
  19950. // R.addSelf(originalPoints[edge[0]]);
  19951. // R.addSelf(originalPoints[edge[1]]);
  19952. }
  19953. R.divideScalar(n);
  19954. newPos.addSelf(originalPoints[i]);
  19955. newPos.multiplyScalar(n - 3);
  19956. newPos.addSelf(F);
  19957. newPos.addSelf(R.multiplyScalar(2));
  19958. newPos.divideScalar(n);
  19959. newVertices[i] = newPos;
  19960. }
  19961. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  19962. newGeometry.vertices = newVertices;
  19963. newGeometry.faces = newFaces;
  19964. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  19965. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  19966. newGeometry.computeCentroids();
  19967. newGeometry.computeFaceNormals();
  19968. newGeometry.computeVertexNormals();
  19969. };
  19970. /**
  19971. * @author alteredq / http://alteredqualia.com/
  19972. */
  19973. THREE.ImmediateRenderObject = function ( ) {
  19974. THREE.Object3D.call( this );
  19975. this.render = function ( renderCallback ) { };
  19976. };
  19977. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  19978. /**
  19979. * @author mikael emtinger / http://gomo.se/
  19980. * @author alteredq / http://alteredqualia.com/
  19981. */
  19982. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  19983. THREE.Object3D.call( this );
  19984. this.lensFlares = [];
  19985. this.positionScreen = new THREE.Vector3();
  19986. this.customUpdateCallback = undefined;
  19987. if( texture !== undefined ) {
  19988. this.add( texture, size, distance, blending, color );
  19989. }
  19990. };
  19991. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  19992. /*
  19993. * Add: adds another flare
  19994. */
  19995. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  19996. if( size === undefined ) size = -1;
  19997. if( distance === undefined ) distance = 0;
  19998. if( opacity === undefined ) opacity = 1;
  19999. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20000. if( blending === undefined ) blending = THREE.NormalBlending;
  20001. distance = Math.min( distance, Math.max( 0, distance ) );
  20002. this.lensFlares.push( { texture: texture, // THREE.Texture
  20003. size: size, // size in pixels (-1 = use texture.width)
  20004. distance: distance, // distance (0-1) from light source (0=at light source)
  20005. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20006. scale: 1, // scale
  20007. rotation: 1, // rotation
  20008. opacity: opacity, // opacity
  20009. color: color, // color
  20010. blending: blending } ); // blending
  20011. };
  20012. /*
  20013. * Update lens flares update positions on all flares based on the screen position
  20014. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20015. */
  20016. THREE.LensFlare.prototype.updateLensFlares = function () {
  20017. var f, fl = this.lensFlares.length;
  20018. var flare;
  20019. var vecX = -this.positionScreen.x * 2;
  20020. var vecY = -this.positionScreen.y * 2;
  20021. for( f = 0; f < fl; f ++ ) {
  20022. flare = this.lensFlares[ f ];
  20023. flare.x = this.positionScreen.x + vecX * flare.distance;
  20024. flare.y = this.positionScreen.y + vecY * flare.distance;
  20025. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20026. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20027. }
  20028. };
  20029. /**
  20030. * @author alteredq / http://alteredqualia.com/
  20031. */
  20032. THREE.MorphBlendMesh = function( geometry, material ) {
  20033. THREE.Mesh.call( this, geometry, material );
  20034. this.animationsMap = {};
  20035. this.animationsList = [];
  20036. // prepare default animation
  20037. // (all frames played together in 1 second)
  20038. var numFrames = this.geometry.morphTargets.length;
  20039. var name = "__default";
  20040. var startFrame = 0;
  20041. var endFrame = numFrames - 1;
  20042. var fps = numFrames / 1;
  20043. this.createAnimation( name, startFrame, endFrame, fps );
  20044. this.setAnimationWeight( name, 1 );
  20045. };
  20046. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20047. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20048. var animation = {
  20049. startFrame: start,
  20050. endFrame: end,
  20051. length: end - start + 1,
  20052. fps: fps,
  20053. duration: ( end - start ) / fps,
  20054. lastFrame: 0,
  20055. currentFrame: 0,
  20056. active: false,
  20057. time: 0,
  20058. direction: 1,
  20059. weight: 1,
  20060. directionBackwards: false,
  20061. mirroredLoop: false
  20062. };
  20063. this.animationsMap[ name ] = animation;
  20064. this.animationsList.push( animation );
  20065. };
  20066. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20067. var pattern = /([a-z]+)(\d+)/;
  20068. var firstAnimation, frameRanges = {};
  20069. var geometry = this.geometry;
  20070. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20071. var morph = geometry.morphTargets[ i ];
  20072. var chunks = morph.name.match( pattern );
  20073. if ( chunks && chunks.length > 1 ) {
  20074. var name = chunks[ 1 ];
  20075. var num = chunks[ 2 ];
  20076. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20077. var range = frameRanges[ name ];
  20078. if ( i < range.start ) range.start = i;
  20079. if ( i > range.end ) range.end = i;
  20080. if ( ! firstAnimation ) firstAnimation = name;
  20081. }
  20082. }
  20083. for ( var name in frameRanges ) {
  20084. var range = frameRanges[ name ];
  20085. this.createAnimation( name, range.start, range.end, fps );
  20086. }
  20087. this.firstAnimation = firstAnimation;
  20088. };
  20089. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20090. var animation = this.animationsMap[ name ];
  20091. if ( animation ) {
  20092. animation.direction = 1;
  20093. animation.directionBackwards = false;
  20094. }
  20095. };
  20096. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20097. var animation = this.animationsMap[ name ];
  20098. if ( animation ) {
  20099. animation.direction = -1;
  20100. animation.directionBackwards = true;
  20101. }
  20102. };
  20103. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20104. var animation = this.animationsMap[ name ];
  20105. if ( animation ) {
  20106. animation.fps = fps;
  20107. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20108. }
  20109. };
  20110. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20111. var animation = this.animationsMap[ name ];
  20112. if ( animation ) {
  20113. animation.duration = duration;
  20114. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20115. }
  20116. };
  20117. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20118. var animation = this.animationsMap[ name ];
  20119. if ( animation ) {
  20120. animation.weight = weight;
  20121. }
  20122. };
  20123. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20124. var animation = this.animationsMap[ name ];
  20125. if ( animation ) {
  20126. animation.time = time;
  20127. }
  20128. };
  20129. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20130. var time = 0;
  20131. var animation = this.animationsMap[ name ];
  20132. if ( animation ) {
  20133. time = animation.time;
  20134. }
  20135. return time;
  20136. };
  20137. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20138. var duration = -1;
  20139. var animation = this.animationsMap[ name ];
  20140. if ( animation ) {
  20141. duration = animation.duration;
  20142. }
  20143. return duration;
  20144. };
  20145. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20146. var animation = this.animationsMap[ name ];
  20147. if ( animation ) {
  20148. animation.time = 0;
  20149. animation.active = true;
  20150. } else {
  20151. console.warn( "animation[" + name + "] undefined" );
  20152. }
  20153. };
  20154. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20155. var animation = this.animationsMap[ name ];
  20156. if ( animation ) {
  20157. animation.active = false;
  20158. }
  20159. };
  20160. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20161. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20162. var animation = this.animationsList[ i ];
  20163. if ( ! animation.active ) continue;
  20164. var frameTime = animation.duration / animation.length;
  20165. animation.time += animation.direction * delta;
  20166. if ( animation.mirroredLoop ) {
  20167. if ( animation.time > animation.duration || animation.time < 0 ) {
  20168. animation.direction *= -1;
  20169. if ( animation.time > animation.duration ) {
  20170. animation.time = animation.duration;
  20171. animation.directionBackwards = true;
  20172. }
  20173. if ( animation.time < 0 ) {
  20174. animation.time = 0;
  20175. animation.directionBackwards = false;
  20176. }
  20177. }
  20178. } else {
  20179. animation.time = animation.time % animation.duration;
  20180. if ( animation.time < 0 ) animation.time += animation.duration;
  20181. }
  20182. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20183. var weight = animation.weight;
  20184. if ( keyframe !== animation.currentFrame ) {
  20185. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20186. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20187. this.morphTargetInfluences[ keyframe ] = 0;
  20188. animation.lastFrame = animation.currentFrame;
  20189. animation.currentFrame = keyframe;
  20190. }
  20191. var mix = ( animation.time % frameTime ) / frameTime;
  20192. if ( animation.directionBackwards ) mix = 1 - mix;
  20193. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20194. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20195. }
  20196. };
  20197. /**
  20198. * @author mikael emtinger / http://gomo.se/
  20199. * @author alteredq / http://alteredqualia.com/
  20200. */
  20201. THREE.LensFlarePlugin = function ( ) {
  20202. var _gl, _renderer, _lensFlare = {};
  20203. this.init = function ( renderer ) {
  20204. _gl = renderer.context;
  20205. _renderer = renderer;
  20206. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20207. _lensFlare.faces = new Uint16Array( 6 );
  20208. var i = 0;
  20209. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20210. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20211. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20212. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20213. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20214. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20215. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20216. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20217. i = 0;
  20218. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20219. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20220. // buffers
  20221. _lensFlare.vertexBuffer = _gl.createBuffer();
  20222. _lensFlare.elementBuffer = _gl.createBuffer();
  20223. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20224. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20225. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20226. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20227. // textures
  20228. _lensFlare.tempTexture = _gl.createTexture();
  20229. _lensFlare.occlusionTexture = _gl.createTexture();
  20230. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20231. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20232. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20233. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20234. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20235. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20236. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20237. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20238. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20239. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20240. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20241. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20242. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20243. _lensFlare.hasVertexTexture = false;
  20244. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20245. } else {
  20246. _lensFlare.hasVertexTexture = true;
  20247. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20248. }
  20249. _lensFlare.attributes = {};
  20250. _lensFlare.uniforms = {};
  20251. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20252. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20253. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20254. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20255. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20256. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20257. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20258. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20259. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20260. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20261. _lensFlare.attributesEnabled = false;
  20262. };
  20263. /*
  20264. * Render lens flares
  20265. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20266. * reads these back and calculates occlusion.
  20267. * Then _lensFlare.update_lensFlares() is called to re-position and
  20268. * update transparency of flares. Then they are rendered.
  20269. *
  20270. */
  20271. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20272. var flares = scene.__webglFlares,
  20273. nFlares = flares.length;
  20274. if ( ! nFlares ) return;
  20275. var tempPosition = new THREE.Vector3();
  20276. var invAspect = viewportHeight / viewportWidth,
  20277. halfViewportWidth = viewportWidth * 0.5,
  20278. halfViewportHeight = viewportHeight * 0.5;
  20279. var size = 16 / viewportHeight,
  20280. scale = new THREE.Vector2( size * invAspect, size );
  20281. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20282. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20283. var uniforms = _lensFlare.uniforms,
  20284. attributes = _lensFlare.attributes;
  20285. // set _lensFlare program and reset blending
  20286. _gl.useProgram( _lensFlare.program );
  20287. if ( ! _lensFlare.attributesEnabled ) {
  20288. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20289. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20290. _lensFlare.attributesEnabled = true;
  20291. }
  20292. // loop through all lens flares to update their occlusion and positions
  20293. // setup gl and common used attribs/unforms
  20294. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20295. _gl.uniform1i( uniforms.map, 1 );
  20296. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20297. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20298. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20299. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20300. _gl.disable( _gl.CULL_FACE );
  20301. _gl.depthMask( false );
  20302. var i, j, jl, flare, sprite;
  20303. for ( i = 0; i < nFlares; i ++ ) {
  20304. size = 16 / viewportHeight;
  20305. scale.set( size * invAspect, size );
  20306. // calc object screen position
  20307. flare = flares[ i ];
  20308. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20309. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  20310. camera.projectionMatrix.multiplyVector3( tempPosition );
  20311. // setup arrays for gl programs
  20312. screenPosition.copy( tempPosition )
  20313. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20314. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20315. // screen cull
  20316. if ( _lensFlare.hasVertexTexture || (
  20317. screenPositionPixels.x > 0 &&
  20318. screenPositionPixels.x < viewportWidth &&
  20319. screenPositionPixels.y > 0 &&
  20320. screenPositionPixels.y < viewportHeight ) ) {
  20321. // save current RGB to temp texture
  20322. _gl.activeTexture( _gl.TEXTURE1 );
  20323. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20324. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20325. // render pink quad
  20326. _gl.uniform1i( uniforms.renderType, 0 );
  20327. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20328. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20329. _gl.disable( _gl.BLEND );
  20330. _gl.enable( _gl.DEPTH_TEST );
  20331. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20332. // copy result to occlusionMap
  20333. _gl.activeTexture( _gl.TEXTURE0 );
  20334. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20335. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20336. // restore graphics
  20337. _gl.uniform1i( uniforms.renderType, 1 );
  20338. _gl.disable( _gl.DEPTH_TEST );
  20339. _gl.activeTexture( _gl.TEXTURE1 );
  20340. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20341. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20342. // update object positions
  20343. flare.positionScreen.copy( screenPosition )
  20344. if ( flare.customUpdateCallback ) {
  20345. flare.customUpdateCallback( flare );
  20346. } else {
  20347. flare.updateLensFlares();
  20348. }
  20349. // render flares
  20350. _gl.uniform1i( uniforms.renderType, 2 );
  20351. _gl.enable( _gl.BLEND );
  20352. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20353. sprite = flare.lensFlares[ j ];
  20354. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20355. screenPosition.x = sprite.x;
  20356. screenPosition.y = sprite.y;
  20357. screenPosition.z = sprite.z;
  20358. size = sprite.size * sprite.scale / viewportHeight;
  20359. scale.x = size * invAspect;
  20360. scale.y = size;
  20361. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20362. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20363. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20364. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20365. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20366. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20367. _renderer.setTexture( sprite.texture, 1 );
  20368. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20369. }
  20370. }
  20371. }
  20372. }
  20373. // restore gl
  20374. _gl.enable( _gl.CULL_FACE );
  20375. _gl.enable( _gl.DEPTH_TEST );
  20376. _gl.depthMask( true );
  20377. };
  20378. function createProgram ( shader ) {
  20379. var program = _gl.createProgram();
  20380. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20381. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20382. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20383. _gl.shaderSource( vertexShader, shader.vertexShader );
  20384. _gl.compileShader( fragmentShader );
  20385. _gl.compileShader( vertexShader );
  20386. _gl.attachShader( program, fragmentShader );
  20387. _gl.attachShader( program, vertexShader );
  20388. _gl.linkProgram( program );
  20389. return program;
  20390. };
  20391. };/**
  20392. * @author alteredq / http://alteredqualia.com/
  20393. */
  20394. THREE.ShadowMapPlugin = function ( ) {
  20395. var _gl,
  20396. _renderer,
  20397. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20398. _frustum = new THREE.Frustum(),
  20399. _projScreenMatrix = new THREE.Matrix4(),
  20400. _min = new THREE.Vector3(),
  20401. _max = new THREE.Vector3();
  20402. this.init = function ( renderer ) {
  20403. _gl = renderer.context;
  20404. _renderer = renderer;
  20405. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20406. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20407. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20408. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20409. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20410. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20411. _depthMaterial._shadowPass = true;
  20412. _depthMaterialMorph._shadowPass = true;
  20413. _depthMaterialSkin._shadowPass = true;
  20414. _depthMaterialMorphSkin._shadowPass = true;
  20415. };
  20416. this.render = function ( scene, camera ) {
  20417. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20418. this.update( scene, camera );
  20419. };
  20420. this.update = function ( scene, camera ) {
  20421. var i, il, j, jl, n,
  20422. shadowMap, shadowMatrix, shadowCamera,
  20423. program, buffer, material,
  20424. webglObject, object, light,
  20425. renderList,
  20426. lights = [],
  20427. k = 0,
  20428. fog = null;
  20429. // set GL state for depth map
  20430. _gl.clearColor( 1, 1, 1, 1 );
  20431. _gl.disable( _gl.BLEND );
  20432. _gl.enable( _gl.CULL_FACE );
  20433. if ( _renderer.shadowMapCullFrontFaces ) {
  20434. _gl.cullFace( _gl.FRONT );
  20435. } else {
  20436. _gl.cullFace( _gl.BACK );
  20437. }
  20438. _renderer.setDepthTest( true );
  20439. // preprocess lights
  20440. // - skip lights that are not casting shadows
  20441. // - create virtual lights for cascaded shadow maps
  20442. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20443. light = scene.__lights[ i ];
  20444. if ( ! light.castShadow ) continue;
  20445. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20446. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20447. var virtualLight;
  20448. if ( ! light.shadowCascadeArray[ n ] ) {
  20449. virtualLight = createVirtualLight( light, n );
  20450. virtualLight.originalCamera = camera;
  20451. var gyro = new THREE.Gyroscope();
  20452. gyro.position = light.shadowCascadeOffset;
  20453. gyro.add( virtualLight );
  20454. gyro.add( virtualLight.target );
  20455. camera.add( gyro );
  20456. light.shadowCascadeArray[ n ] = virtualLight;
  20457. console.log( "Created virtualLight", virtualLight );
  20458. } else {
  20459. virtualLight = light.shadowCascadeArray[ n ];
  20460. }
  20461. updateVirtualLight( light, n );
  20462. lights[ k ] = virtualLight;
  20463. k ++;
  20464. }
  20465. } else {
  20466. lights[ k ] = light;
  20467. k ++;
  20468. }
  20469. }
  20470. // render depth map
  20471. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20472. light = lights[ i ];
  20473. if ( ! light.shadowMap ) {
  20474. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  20475. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20476. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20477. light.shadowMatrix = new THREE.Matrix4();
  20478. }
  20479. if ( ! light.shadowCamera ) {
  20480. if ( light instanceof THREE.SpotLight ) {
  20481. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20482. } else if ( light instanceof THREE.DirectionalLight ) {
  20483. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20484. } else {
  20485. console.error( "Unsupported light type for shadow" );
  20486. continue;
  20487. }
  20488. scene.add( light.shadowCamera );
  20489. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20490. }
  20491. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20492. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20493. light.shadowCamera.add( light.cameraHelper );
  20494. }
  20495. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20496. updateShadowCamera( camera, light );
  20497. }
  20498. shadowMap = light.shadowMap;
  20499. shadowMatrix = light.shadowMatrix;
  20500. shadowCamera = light.shadowCamera;
  20501. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20502. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20503. shadowCamera.updateMatrixWorld();
  20504. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20505. if ( light.cameraHelper ) light.cameraHelper.lines.visible = light.shadowCameraVisible;
  20506. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20507. // compute shadow matrix
  20508. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20509. 0.0, 0.5, 0.0, 0.5,
  20510. 0.0, 0.0, 0.5, 0.5,
  20511. 0.0, 0.0, 0.0, 1.0 );
  20512. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  20513. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  20514. // update camera matrices and frustum
  20515. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  20516. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  20517. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  20518. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  20519. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20520. _frustum.setFromMatrix( _projScreenMatrix );
  20521. // render shadow map
  20522. _renderer.setRenderTarget( shadowMap );
  20523. _renderer.clear();
  20524. // set object matrices & frustum culling
  20525. renderList = scene.__webglObjects;
  20526. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20527. webglObject = renderList[ j ];
  20528. object = webglObject.object;
  20529. webglObject.render = false;
  20530. if ( object.visible && object.castShadow ) {
  20531. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20532. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20533. webglObject.render = true;
  20534. }
  20535. }
  20536. }
  20537. // render regular objects
  20538. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20539. webglObject = renderList[ j ];
  20540. if ( webglObject.render ) {
  20541. object = webglObject.object;
  20542. buffer = webglObject.buffer;
  20543. // culling is overriden globally for all objects
  20544. // while rendering depth map
  20545. if ( object.customDepthMaterial ) {
  20546. material = object.customDepthMaterial;
  20547. } else if ( object instanceof THREE.SkinnedMesh ) {
  20548. material = object.geometry.morphTargets.length ?
  20549. _depthMaterialMorphSkin : _depthMaterialSkin;
  20550. } else if ( object.geometry.morphTargets.length ) {
  20551. material = _depthMaterialMorph;
  20552. } else {
  20553. material = _depthMaterial;
  20554. }
  20555. if ( buffer instanceof THREE.BufferGeometry ) {
  20556. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20557. } else {
  20558. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20559. }
  20560. }
  20561. }
  20562. // set matrices and render immediate objects
  20563. renderList = scene.__webglObjectsImmediate;
  20564. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20565. webglObject = renderList[ j ];
  20566. object = webglObject.object;
  20567. if ( object.visible && object.castShadow ) {
  20568. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20569. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20570. }
  20571. }
  20572. }
  20573. // restore GL state
  20574. var clearColor = _renderer.getClearColor(),
  20575. clearAlpha = _renderer.getClearAlpha();
  20576. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20577. _gl.enable( _gl.BLEND );
  20578. if ( _renderer.shadowMapCullFrontFaces ) {
  20579. _gl.cullFace( _gl.BACK );
  20580. }
  20581. };
  20582. function createVirtualLight( light, cascade ) {
  20583. var virtualLight = new THREE.DirectionalLight();
  20584. virtualLight.isVirtual = true;
  20585. virtualLight.onlyShadow = true;
  20586. virtualLight.castShadow = true;
  20587. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20588. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20589. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20590. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20591. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20592. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20593. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20594. virtualLight.shadowDarkness = light.shadowDarkness;
  20595. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20596. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20597. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20598. virtualLight.pointsWorld = [];
  20599. virtualLight.pointsFrustum = [];
  20600. var pointsWorld = virtualLight.pointsWorld,
  20601. pointsFrustum = virtualLight.pointsFrustum;
  20602. for ( var i = 0; i < 8; i ++ ) {
  20603. pointsWorld[ i ] = new THREE.Vector3();
  20604. pointsFrustum[ i ] = new THREE.Vector3();
  20605. }
  20606. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20607. var farZ = light.shadowCascadeFarZ[ cascade ];
  20608. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20609. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20610. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20611. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20612. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20613. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20614. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20615. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20616. return virtualLight;
  20617. }
  20618. // Synchronize virtual light with the original light
  20619. function updateVirtualLight( light, cascade ) {
  20620. var virtualLight = light.shadowCascadeArray[ cascade ];
  20621. virtualLight.position.copy( light.position );
  20622. virtualLight.target.position.copy( light.target.position );
  20623. virtualLight.lookAt( virtualLight.target );
  20624. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20625. virtualLight.shadowDarkness = light.shadowDarkness;
  20626. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20627. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20628. var farZ = light.shadowCascadeFarZ[ cascade ];
  20629. var pointsFrustum = virtualLight.pointsFrustum;
  20630. pointsFrustum[ 0 ].z = nearZ;
  20631. pointsFrustum[ 1 ].z = nearZ;
  20632. pointsFrustum[ 2 ].z = nearZ;
  20633. pointsFrustum[ 3 ].z = nearZ;
  20634. pointsFrustum[ 4 ].z = farZ;
  20635. pointsFrustum[ 5 ].z = farZ;
  20636. pointsFrustum[ 6 ].z = farZ;
  20637. pointsFrustum[ 7 ].z = farZ;
  20638. }
  20639. // Fit shadow camera's ortho frustum to camera frustum
  20640. function updateShadowCamera( camera, light ) {
  20641. var shadowCamera = light.shadowCamera,
  20642. pointsFrustum = light.pointsFrustum,
  20643. pointsWorld = light.pointsWorld;
  20644. _min.set( Infinity, Infinity, Infinity );
  20645. _max.set( -Infinity, -Infinity, -Infinity );
  20646. for ( var i = 0; i < 8; i ++ ) {
  20647. var p = pointsWorld[ i ];
  20648. p.copy( pointsFrustum[ i ] );
  20649. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  20650. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  20651. if ( p.x < _min.x ) _min.x = p.x;
  20652. if ( p.x > _max.x ) _max.x = p.x;
  20653. if ( p.y < _min.y ) _min.y = p.y;
  20654. if ( p.y > _max.y ) _max.y = p.y;
  20655. if ( p.z < _min.z ) _min.z = p.z;
  20656. if ( p.z > _max.z ) _max.z = p.z;
  20657. }
  20658. shadowCamera.left = _min.x;
  20659. shadowCamera.right = _max.x;
  20660. shadowCamera.top = _max.y;
  20661. shadowCamera.bottom = _min.y;
  20662. // can't really fit near/far
  20663. //shadowCamera.near = _min.z;
  20664. //shadowCamera.far = _max.z;
  20665. shadowCamera.updateProjectionMatrix();
  20666. }
  20667. };
  20668. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  20669. /**
  20670. * @author mikael emtinger / http://gomo.se/
  20671. * @author alteredq / http://alteredqualia.com/
  20672. */
  20673. THREE.SpritePlugin = function ( ) {
  20674. var _gl, _renderer, _sprite = {};
  20675. this.init = function ( renderer ) {
  20676. _gl = renderer.context;
  20677. _renderer = renderer;
  20678. _sprite.vertices = new Float32Array( 8 + 8 );
  20679. _sprite.faces = new Uint16Array( 6 );
  20680. var i = 0;
  20681. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  20682. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  20683. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  20684. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  20685. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  20686. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  20687. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  20688. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  20689. i = 0;
  20690. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  20691. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  20692. _sprite.vertexBuffer = _gl.createBuffer();
  20693. _sprite.elementBuffer = _gl.createBuffer();
  20694. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20695. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  20696. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20697. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  20698. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  20699. _sprite.attributes = {};
  20700. _sprite.uniforms = {};
  20701. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  20702. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  20703. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  20704. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  20705. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  20706. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  20707. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  20708. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  20709. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  20710. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  20711. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  20712. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  20713. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  20714. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  20715. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  20716. _sprite.attributesEnabled = false;
  20717. };
  20718. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20719. var sprites = scene.__webglSprites,
  20720. nSprites = sprites.length;
  20721. if ( ! nSprites ) return;
  20722. var attributes = _sprite.attributes,
  20723. uniforms = _sprite.uniforms;
  20724. var invAspect = viewportHeight / viewportWidth;
  20725. var halfViewportWidth = viewportWidth * 0.5,
  20726. halfViewportHeight = viewportHeight * 0.5;
  20727. var mergeWith3D = true;
  20728. // setup gl
  20729. _gl.useProgram( _sprite.program );
  20730. if ( ! _sprite.attributesEnabled ) {
  20731. _gl.enableVertexAttribArray( attributes.position );
  20732. _gl.enableVertexAttribArray( attributes.uv );
  20733. _sprite.attributesEnabled = true;
  20734. }
  20735. _gl.disable( _gl.CULL_FACE );
  20736. _gl.enable( _gl.BLEND );
  20737. _gl.depthMask( true );
  20738. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20739. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20740. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20741. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20742. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  20743. _gl.activeTexture( _gl.TEXTURE0 );
  20744. _gl.uniform1i( uniforms.map, 0 );
  20745. // update positions and sort
  20746. var i, sprite, screenPosition, size, scale = [];
  20747. for( i = 0; i < nSprites; i ++ ) {
  20748. sprite = sprites[ i ];
  20749. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  20750. if( ! sprite.useScreenCoordinates ) {
  20751. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  20752. sprite.z = - sprite._modelViewMatrix.elements[14];
  20753. } else {
  20754. sprite.z = - sprite.position.z;
  20755. }
  20756. }
  20757. sprites.sort( painterSort );
  20758. // render all sprites
  20759. for( i = 0; i < nSprites; i ++ ) {
  20760. sprite = sprites[ i ];
  20761. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  20762. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  20763. if ( sprite.useScreenCoordinates ) {
  20764. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  20765. _gl.uniform3f( uniforms.screenPosition, ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  20766. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  20767. Math.max( 0, Math.min( 1, sprite.position.z ) ) );
  20768. } else {
  20769. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  20770. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  20771. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  20772. }
  20773. size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
  20774. scale[ 0 ] = size * invAspect * sprite.scale.x;
  20775. scale[ 1 ] = size * sprite.scale.y;
  20776. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  20777. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  20778. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  20779. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20780. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20781. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20782. _gl.uniform2fv( uniforms.scale, scale );
  20783. if ( sprite.mergeWith3D && !mergeWith3D ) {
  20784. _gl.enable( _gl.DEPTH_TEST );
  20785. mergeWith3D = true;
  20786. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  20787. _gl.disable( _gl.DEPTH_TEST );
  20788. mergeWith3D = false;
  20789. }
  20790. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20791. _renderer.setTexture( sprite.map, 0 );
  20792. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20793. }
  20794. }
  20795. // restore gl
  20796. _gl.enable( _gl.CULL_FACE );
  20797. _gl.enable( _gl.DEPTH_TEST );
  20798. _gl.depthMask( true );
  20799. };
  20800. function createProgram ( shader ) {
  20801. var program = _gl.createProgram();
  20802. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20803. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20804. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20805. _gl.shaderSource( vertexShader, shader.vertexShader );
  20806. _gl.compileShader( fragmentShader );
  20807. _gl.compileShader( vertexShader );
  20808. _gl.attachShader( program, fragmentShader );
  20809. _gl.attachShader( program, vertexShader );
  20810. _gl.linkProgram( program );
  20811. return program;
  20812. };
  20813. function painterSort ( a, b ) {
  20814. return b.z - a.z;
  20815. };
  20816. };/**
  20817. * @author alteredq / http://alteredqualia.com/
  20818. */
  20819. THREE.DepthPassPlugin = function ( ) {
  20820. this.enabled = false;
  20821. this.renderTarget = null;
  20822. var _gl,
  20823. _renderer,
  20824. _depthMaterial, _depthMaterialMorph,
  20825. _frustum = new THREE.Frustum(),
  20826. _projScreenMatrix = new THREE.Matrix4();
  20827. this.init = function ( renderer ) {
  20828. _gl = renderer.context;
  20829. _renderer = renderer;
  20830. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20831. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20832. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20833. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20834. _depthMaterial._shadowPass = true;
  20835. _depthMaterialMorph._shadowPass = true;
  20836. };
  20837. this.render = function ( scene, camera ) {
  20838. if ( ! this.enabled ) return;
  20839. this.update( scene, camera );
  20840. };
  20841. this.update = function ( scene, camera ) {
  20842. var i, il, j, jl, n,
  20843. program, buffer, material,
  20844. webglObject, object, light,
  20845. renderList,
  20846. fog = null;
  20847. // set GL state for depth map
  20848. _gl.clearColor( 1, 1, 1, 1 );
  20849. _gl.disable( _gl.BLEND );
  20850. _renderer.setDepthTest( true );
  20851. // update scene
  20852. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20853. // update camera matrices and frustum
  20854. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  20855. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  20856. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  20857. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  20858. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  20859. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  20860. _frustum.setFromMatrix( _projScreenMatrix );
  20861. // render depth map
  20862. _renderer.setRenderTarget( this.renderTarget );
  20863. _renderer.clear();
  20864. // set object matrices & frustum culling
  20865. renderList = scene.__webglObjects;
  20866. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20867. webglObject = renderList[ j ];
  20868. object = webglObject.object;
  20869. webglObject.render = false;
  20870. if ( object.visible ) {
  20871. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20872. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  20873. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  20874. webglObject.render = true;
  20875. }
  20876. }
  20877. }
  20878. // render regular objects
  20879. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20880. webglObject = renderList[ j ];
  20881. if ( webglObject.render ) {
  20882. object = webglObject.object;
  20883. buffer = webglObject.buffer;
  20884. if ( object.material ) _renderer.setMaterialFaces( object.material );
  20885. if ( object.customDepthMaterial ) {
  20886. material = object.customDepthMaterial;
  20887. } else if ( object.geometry.morphTargets.length ) {
  20888. material = _depthMaterialMorph;
  20889. } else {
  20890. material = _depthMaterial;
  20891. }
  20892. if ( buffer instanceof THREE.BufferGeometry ) {
  20893. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  20894. } else {
  20895. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  20896. }
  20897. }
  20898. }
  20899. // set matrices and render immediate objects
  20900. renderList = scene.__webglObjectsImmediate;
  20901. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20902. webglObject = renderList[ j ];
  20903. object = webglObject.object;
  20904. if ( object.visible && object.castShadow ) {
  20905. /*
  20906. if ( object.matrixAutoUpdate ) {
  20907. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  20908. }
  20909. */
  20910. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  20911. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  20912. }
  20913. }
  20914. // restore GL state
  20915. var clearColor = _renderer.getClearColor(),
  20916. clearAlpha = _renderer.getClearAlpha();
  20917. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20918. _gl.enable( _gl.BLEND );
  20919. };
  20920. };
  20921. /**
  20922. * @author mikael emtinger / http://gomo.se/
  20923. *
  20924. */
  20925. THREE.ShaderFlares = {
  20926. 'lensFlareVertexTexture': {
  20927. vertexShader: [
  20928. "uniform vec3 screenPosition;",
  20929. "uniform vec2 scale;",
  20930. "uniform float rotation;",
  20931. "uniform int renderType;",
  20932. "uniform sampler2D occlusionMap;",
  20933. "attribute vec2 position;",
  20934. "attribute vec2 uv;",
  20935. "varying vec2 vUV;",
  20936. "varying float vVisibility;",
  20937. "void main() {",
  20938. "vUV = uv;",
  20939. "vec2 pos = position;",
  20940. "if( renderType == 2 ) {",
  20941. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  20942. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  20943. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  20944. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  20945. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  20946. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  20947. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  20948. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  20949. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  20950. "vVisibility = ( visibility.r / 9.0 ) *",
  20951. "( 1.0 - visibility.g / 9.0 ) *",
  20952. "( visibility.b / 9.0 ) *",
  20953. "( 1.0 - visibility.a / 9.0 );",
  20954. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  20955. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  20956. "}",
  20957. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  20958. "}"
  20959. ].join( "\n" ),
  20960. fragmentShader: [
  20961. "precision mediump float;",
  20962. "uniform sampler2D map;",
  20963. "uniform float opacity;",
  20964. "uniform int renderType;",
  20965. "uniform vec3 color;",
  20966. "varying vec2 vUV;",
  20967. "varying float vVisibility;",
  20968. "void main() {",
  20969. // pink square
  20970. "if( renderType == 0 ) {",
  20971. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  20972. // restore
  20973. "} else if( renderType == 1 ) {",
  20974. "gl_FragColor = texture2D( map, vUV );",
  20975. // flare
  20976. "} else {",
  20977. "vec4 texture = texture2D( map, vUV );",
  20978. "texture.a *= opacity * vVisibility;",
  20979. "gl_FragColor = texture;",
  20980. "gl_FragColor.rgb *= color;",
  20981. "}",
  20982. "}"
  20983. ].join( "\n" )
  20984. },
  20985. 'lensFlare': {
  20986. vertexShader: [
  20987. "uniform vec3 screenPosition;",
  20988. "uniform vec2 scale;",
  20989. "uniform float rotation;",
  20990. "uniform int renderType;",
  20991. "attribute vec2 position;",
  20992. "attribute vec2 uv;",
  20993. "varying vec2 vUV;",
  20994. "void main() {",
  20995. "vUV = uv;",
  20996. "vec2 pos = position;",
  20997. "if( renderType == 2 ) {",
  20998. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  20999. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21000. "}",
  21001. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21002. "}"
  21003. ].join( "\n" ),
  21004. fragmentShader: [
  21005. "precision mediump float;",
  21006. "uniform sampler2D map;",
  21007. "uniform sampler2D occlusionMap;",
  21008. "uniform float opacity;",
  21009. "uniform int renderType;",
  21010. "uniform vec3 color;",
  21011. "varying vec2 vUV;",
  21012. "void main() {",
  21013. // pink square
  21014. "if( renderType == 0 ) {",
  21015. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21016. // restore
  21017. "} else if( renderType == 1 ) {",
  21018. "gl_FragColor = texture2D( map, vUV );",
  21019. // flare
  21020. "} else {",
  21021. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21022. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21023. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21024. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21025. "visibility = ( 1.0 - visibility / 4.0 );",
  21026. "vec4 texture = texture2D( map, vUV );",
  21027. "texture.a *= opacity * visibility;",
  21028. "gl_FragColor = texture;",
  21029. "gl_FragColor.rgb *= color;",
  21030. "}",
  21031. "}"
  21032. ].join( "\n" )
  21033. }
  21034. };
  21035. /**
  21036. * @author mikael emtinger / http://gomo.se/
  21037. *
  21038. */
  21039. THREE.ShaderSprite = {
  21040. 'sprite': {
  21041. vertexShader: [
  21042. "uniform int useScreenCoordinates;",
  21043. "uniform int affectedByDistance;",
  21044. "uniform vec3 screenPosition;",
  21045. "uniform mat4 modelViewMatrix;",
  21046. "uniform mat4 projectionMatrix;",
  21047. "uniform float rotation;",
  21048. "uniform vec2 scale;",
  21049. "uniform vec2 alignment;",
  21050. "uniform vec2 uvOffset;",
  21051. "uniform vec2 uvScale;",
  21052. "attribute vec2 position;",
  21053. "attribute vec2 uv;",
  21054. "varying vec2 vUV;",
  21055. "void main() {",
  21056. "vUV = uvOffset + uv * uvScale;",
  21057. "vec2 alignedPosition = position + alignment;",
  21058. "vec2 rotatedPosition;",
  21059. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21060. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21061. "vec4 finalPosition;",
  21062. "if( useScreenCoordinates != 0 ) {",
  21063. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21064. "} else {",
  21065. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21066. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  21067. "}",
  21068. "gl_Position = finalPosition;",
  21069. "}"
  21070. ].join( "\n" ),
  21071. fragmentShader: [
  21072. "precision mediump float;",
  21073. "uniform vec3 color;",
  21074. "uniform sampler2D map;",
  21075. "uniform float opacity;",
  21076. "varying vec2 vUV;",
  21077. "void main() {",
  21078. "vec4 texture = texture2D( map, vUV );",
  21079. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21080. "}"
  21081. ].join( "\n" )
  21082. }
  21083. };
粤ICP备19079148号