Three.js 798 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212
  1. /**
  2. * @author mr.doob / http://mrdoob.com/
  3. */
  4. var THREE = THREE || { REVISION: '49dev' };
  5. if ( ! self.Int32Array ) {
  6. self.Int32Array = Array;
  7. self.Float32Array = Array;
  8. }
  9. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  10. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  11. // requestAnimationFrame polyfill by Erik Möller
  12. // fixes from Paul Irish and Tino Zijdel
  13. (function() {
  14. var lastTime = 0;
  15. var vendors = ['ms', 'moz', 'webkit', 'o'];
  16. for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
  17. window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
  18. window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
  19. || window[vendors[x]+'CancelRequestAnimationFrame'];
  20. }
  21. if (!window.requestAnimationFrame)
  22. window.requestAnimationFrame = function(callback, element) {
  23. var currTime = new Date().getTime();
  24. var timeToCall = Math.max(0, 16 - (currTime - lastTime));
  25. var id = window.setTimeout(function() { callback(currTime + timeToCall); },
  26. timeToCall);
  27. lastTime = currTime + timeToCall;
  28. return id;
  29. };
  30. if (!window.cancelAnimationFrame)
  31. window.cancelAnimationFrame = function(id) {
  32. clearTimeout(id);
  33. };
  34. }());
  35. /**
  36. * @author alteredq / http://alteredqualia.com/
  37. */
  38. THREE.Clock = function ( autoStart ) {
  39. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  40. this.startTime = 0;
  41. this.oldTime = 0;
  42. this.elapsedTime = 0;
  43. this.running = false;
  44. };
  45. THREE.Clock.prototype.start = function () {
  46. this.startTime = Date.now();
  47. this.oldTime = this.startTime;
  48. this.running = true;
  49. };
  50. THREE.Clock.prototype.stop = function () {
  51. this.getElapsedTime();
  52. this.running = false;
  53. };
  54. THREE.Clock.prototype.getElapsedTime = function () {
  55. this.elapsedTime += this.getDelta();
  56. return this.elapsedTime;
  57. };
  58. THREE.Clock.prototype.getDelta = function () {
  59. var diff = 0;
  60. if ( this.autoStart && ! this.running ) {
  61. this.start();
  62. }
  63. if ( this.running ) {
  64. var newTime = Date.now();
  65. diff = 0.001 * ( newTime - this.oldTime );
  66. this.oldTime = newTime;
  67. this.elapsedTime += diff;
  68. }
  69. return diff;
  70. };/**
  71. * @author mr.doob / http://mrdoob.com/
  72. */
  73. THREE.Color = function ( hex ) {
  74. if ( hex !== undefined ) this.setHex( hex );
  75. return this;
  76. };
  77. THREE.Color.prototype = {
  78. constructor: THREE.Color,
  79. r: 1, g: 1, b: 1,
  80. copy: function ( color ) {
  81. this.r = color.r;
  82. this.g = color.g;
  83. this.b = color.b;
  84. return this;
  85. },
  86. copyGammaToLinear: function ( color ) {
  87. this.r = color.r * color.r;
  88. this.g = color.g * color.g;
  89. this.b = color.b * color.b;
  90. return this;
  91. },
  92. copyLinearToGamma: function ( color ) {
  93. this.r = Math.sqrt( color.r );
  94. this.g = Math.sqrt( color.g );
  95. this.b = Math.sqrt( color.b );
  96. return this;
  97. },
  98. convertGammaToLinear: function () {
  99. var r = this.r, g = this.g, b = this.b;
  100. this.r = r * r;
  101. this.g = g * g;
  102. this.b = b * b;
  103. return this;
  104. },
  105. convertLinearToGamma: function () {
  106. this.r = Math.sqrt( this.r );
  107. this.g = Math.sqrt( this.g );
  108. this.b = Math.sqrt( this.b );
  109. return this;
  110. },
  111. setRGB: function ( r, g, b ) {
  112. this.r = r;
  113. this.g = g;
  114. this.b = b;
  115. return this;
  116. },
  117. setHSV: function ( h, s, v ) {
  118. // based on MochiKit implementation by Bob Ippolito
  119. // h,s,v ranges are < 0.0 - 1.0 >
  120. var i, f, p, q, t;
  121. if ( v === 0 ) {
  122. this.r = this.g = this.b = 0;
  123. } else {
  124. i = Math.floor( h * 6 );
  125. f = ( h * 6 ) - i;
  126. p = v * ( 1 - s );
  127. q = v * ( 1 - ( s * f ) );
  128. t = v * ( 1 - ( s * ( 1 - f ) ) );
  129. switch ( i ) {
  130. case 1: this.r = q; this.g = v; this.b = p; break;
  131. case 2: this.r = p; this.g = v; this.b = t; break;
  132. case 3: this.r = p; this.g = q; this.b = v; break;
  133. case 4: this.r = t; this.g = p; this.b = v; break;
  134. case 5: this.r = v; this.g = p; this.b = q; break;
  135. case 6: // fall through
  136. case 0: this.r = v; this.g = t; this.b = p; break;
  137. }
  138. }
  139. return this;
  140. },
  141. setHex: function ( hex ) {
  142. hex = Math.floor( hex );
  143. this.r = ( hex >> 16 & 255 ) / 255;
  144. this.g = ( hex >> 8 & 255 ) / 255;
  145. this.b = ( hex & 255 ) / 255;
  146. return this;
  147. },
  148. lerpSelf: function ( color, alpha ) {
  149. this.r += ( color.r - this.r ) * alpha;
  150. this.g += ( color.g - this.g ) * alpha;
  151. this.b += ( color.b - this.b ) * alpha;
  152. return this;
  153. },
  154. getHex: function () {
  155. return Math.floor( this.r * 255 ) << 16 ^ Math.floor( this.g * 255 ) << 8 ^ Math.floor( this.b * 255 );
  156. },
  157. getContextStyle: function () {
  158. return 'rgb(' + Math.floor( this.r * 255 ) + ',' + Math.floor( this.g * 255 ) + ',' + Math.floor( this.b * 255 ) + ')';
  159. },
  160. clone: function () {
  161. return new THREE.Color().setRGB( this.r, this.g, this.b );
  162. }
  163. };
  164. /**
  165. * @author mr.doob / http://mrdoob.com/
  166. * @author philogb / http://blog.thejit.org/
  167. * @author egraether / http://egraether.com/
  168. * @author zz85 / http://www.lab4games.net/zz85/blog
  169. */
  170. THREE.Vector2 = function ( x, y ) {
  171. this.x = x || 0;
  172. this.y = y || 0;
  173. };
  174. THREE.Vector2.prototype = {
  175. constructor: THREE.Vector2,
  176. set: function ( x, y ) {
  177. this.x = x;
  178. this.y = y;
  179. return this;
  180. },
  181. copy: function ( v ) {
  182. this.x = v.x;
  183. this.y = v.y;
  184. return this;
  185. },
  186. add: function ( a, b ) {
  187. this.x = a.x + b.x;
  188. this.y = a.y + b.y;
  189. return this;
  190. },
  191. addSelf: function ( v ) {
  192. this.x += v.x;
  193. this.y += v.y;
  194. return this;
  195. },
  196. sub: function ( a, b ) {
  197. this.x = a.x - b.x;
  198. this.y = a.y - b.y;
  199. return this;
  200. },
  201. subSelf: function ( v ) {
  202. this.x -= v.x;
  203. this.y -= v.y;
  204. return this;
  205. },
  206. multiplyScalar: function ( s ) {
  207. this.x *= s;
  208. this.y *= s;
  209. return this;
  210. },
  211. divideScalar: function ( s ) {
  212. if ( s ) {
  213. this.x /= s;
  214. this.y /= s;
  215. } else {
  216. this.set( 0, 0 );
  217. }
  218. return this;
  219. },
  220. negate: function() {
  221. return this.multiplyScalar( - 1 );
  222. },
  223. dot: function ( v ) {
  224. return this.x * v.x + this.y * v.y;
  225. },
  226. lengthSq: function () {
  227. return this.x * this.x + this.y * this.y;
  228. },
  229. length: function () {
  230. return Math.sqrt( this.lengthSq() );
  231. },
  232. normalize: function () {
  233. return this.divideScalar( this.length() );
  234. },
  235. distanceTo: function ( v ) {
  236. return Math.sqrt( this.distanceToSquared( v ) );
  237. },
  238. distanceToSquared: function ( v ) {
  239. var dx = this.x - v.x, dy = this.y - v.y;
  240. return dx * dx + dy * dy;
  241. },
  242. setLength: function ( l ) {
  243. return this.normalize().multiplyScalar( l );
  244. },
  245. lerpSelf: function ( v, alpha ) {
  246. this.x += ( v.x - this.x ) * alpha;
  247. this.y += ( v.y - this.y ) * alpha;
  248. return this;
  249. },
  250. equals: function( v ) {
  251. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  252. },
  253. isZero: function () {
  254. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  255. },
  256. clone: function () {
  257. return new THREE.Vector2( this.x, this.y );
  258. }
  259. };
  260. /**
  261. * @author mr.doob / http://mrdoob.com/
  262. * @author kile / http://kile.stravaganza.org/
  263. * @author philogb / http://blog.thejit.org/
  264. * @author mikael emtinger / http://gomo.se/
  265. * @author egraether / http://egraether.com/
  266. */
  267. THREE.Vector3 = function ( x, y, z ) {
  268. this.x = x || 0;
  269. this.y = y || 0;
  270. this.z = z || 0;
  271. };
  272. THREE.Vector3.prototype = {
  273. constructor: THREE.Vector3,
  274. set: function ( x, y, z ) {
  275. this.x = x;
  276. this.y = y;
  277. this.z = z;
  278. return this;
  279. },
  280. setX: function ( x ) {
  281. this.x = x;
  282. return this;
  283. },
  284. setY: function ( y ) {
  285. this.y = y;
  286. return this;
  287. },
  288. setZ: function ( z ) {
  289. this.z = z;
  290. return this;
  291. },
  292. copy: function ( v ) {
  293. this.x = v.x;
  294. this.y = v.y;
  295. this.z = v.z;
  296. return this;
  297. },
  298. add: function ( a, b ) {
  299. this.x = a.x + b.x;
  300. this.y = a.y + b.y;
  301. this.z = a.z + b.z;
  302. return this;
  303. },
  304. addSelf: function ( v ) {
  305. this.x += v.x;
  306. this.y += v.y;
  307. this.z += v.z;
  308. return this;
  309. },
  310. addScalar: function ( s ) {
  311. this.x += s;
  312. this.y += s;
  313. this.z += s;
  314. return this;
  315. },
  316. sub: function ( a, b ) {
  317. this.x = a.x - b.x;
  318. this.y = a.y - b.y;
  319. this.z = a.z - b.z;
  320. return this;
  321. },
  322. subSelf: function ( v ) {
  323. this.x -= v.x;
  324. this.y -= v.y;
  325. this.z -= v.z;
  326. return this;
  327. },
  328. multiply: function ( a, b ) {
  329. this.x = a.x * b.x;
  330. this.y = a.y * b.y;
  331. this.z = a.z * b.z;
  332. return this;
  333. },
  334. multiplySelf: function ( v ) {
  335. this.x *= v.x;
  336. this.y *= v.y;
  337. this.z *= v.z;
  338. return this;
  339. },
  340. multiplyScalar: function ( s ) {
  341. this.x *= s;
  342. this.y *= s;
  343. this.z *= s;
  344. return this;
  345. },
  346. divideSelf: function ( v ) {
  347. this.x /= v.x;
  348. this.y /= v.y;
  349. this.z /= v.z;
  350. return this;
  351. },
  352. divideScalar: function ( s ) {
  353. if ( s ) {
  354. this.x /= s;
  355. this.y /= s;
  356. this.z /= s;
  357. } else {
  358. this.x = 0;
  359. this.y = 0;
  360. this.z = 0;
  361. }
  362. return this;
  363. },
  364. negate: function() {
  365. return this.multiplyScalar( - 1 );
  366. },
  367. dot: function ( v ) {
  368. return this.x * v.x + this.y * v.y + this.z * v.z;
  369. },
  370. lengthSq: function () {
  371. return this.x * this.x + this.y * this.y + this.z * this.z;
  372. },
  373. length: function () {
  374. return Math.sqrt( this.lengthSq() );
  375. },
  376. lengthManhattan: function () {
  377. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  378. },
  379. normalize: function () {
  380. return this.divideScalar( this.length() );
  381. },
  382. setLength: function ( l ) {
  383. return this.normalize().multiplyScalar( l );
  384. },
  385. lerpSelf: function ( v, alpha ) {
  386. this.x += ( v.x - this.x ) * alpha;
  387. this.y += ( v.y - this.y ) * alpha;
  388. this.z += ( v.z - this.z ) * alpha;
  389. return this;
  390. },
  391. cross: function ( a, b ) {
  392. this.x = a.y * b.z - a.z * b.y;
  393. this.y = a.z * b.x - a.x * b.z;
  394. this.z = a.x * b.y - a.y * b.x;
  395. return this;
  396. },
  397. crossSelf: function ( v ) {
  398. var x = this.x, y = this.y, z = this.z;
  399. this.x = y * v.z - z * v.y;
  400. this.y = z * v.x - x * v.z;
  401. this.z = x * v.y - y * v.x;
  402. return this;
  403. },
  404. distanceTo: function ( v ) {
  405. return Math.sqrt( this.distanceToSquared( v ) );
  406. },
  407. distanceToSquared: function ( v ) {
  408. return new THREE.Vector3().sub( this, v ).lengthSq();
  409. },
  410. getPositionFromMatrix: function ( m ) {
  411. this.x = m.elements[12];
  412. this.y = m.elements[13];
  413. this.z = m.elements[14];
  414. return this;
  415. },
  416. getRotationFromMatrix: function ( m, scale ) {
  417. var sx = scale ? scale.x : 1;
  418. var sy = scale ? scale.y : 1;
  419. var sz = scale ? scale.z : 1;
  420. var m11 = m.elements[0] / sx, m12 = m.elements[4] / sy, m13 = m.elements[8] / sz;
  421. var m21 = m.elements[1] / sx, m22 = m.elements[5] / sy, m23 = m.elements[9] / sz;
  422. var m33 = m.elements[10] / sz;
  423. this.y = Math.asin( m13 );
  424. var cosY = Math.cos( this.y );
  425. if ( Math.abs( cosY ) > 0.00001 ) {
  426. this.x = Math.atan2( - m23 / cosY, m33 / cosY );
  427. this.z = Math.atan2( - m12 / cosY, m11 / cosY );
  428. } else {
  429. this.x = 0;
  430. this.z = Math.atan2( m21, m22 );
  431. }
  432. return this;
  433. },
  434. /*
  435. // from http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  436. // order XYZ
  437. getEulerXYZFromQuaternion: function ( q ) {
  438. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z ) );
  439. this.y = Math.asin( 2 * ( q.x * q.z + q.y * q.w ) );
  440. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z ) );
  441. },
  442. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/index.htm
  443. // order YZX (assuming heading == y, attitude == z, bank == x)
  444. getEulerYZXFromQuaternion: function ( q ) {
  445. var sqw = q.w * q.w;
  446. var sqx = q.x * q.x;
  447. var sqy = q.y * q.y;
  448. var sqz = q.z * q.z;
  449. var unit = sqx + sqy + sqz + sqw; // if normalised is one, otherwise is correction factor
  450. var test = q.x * q.y + q.z * q.w;
  451. if ( test > 0.499 * unit ) { // singularity at north pole
  452. this.y = 2 * Math.atan2( q.x, q.w );
  453. this.z = Math.PI / 2;
  454. this.x = 0;
  455. return;
  456. }
  457. if ( test < -0.499 * unit ) { // singularity at south pole
  458. this.y = -2 * Math.atan2( q.x, q.w );
  459. this.z = -Math.PI / 2;
  460. this.x = 0;
  461. return;
  462. }
  463. this.y = Math.atan2( 2 * q.y * q.w - 2 * q.x * q.z, sqx - sqy - sqz + sqw );
  464. this.z = Math.asin( 2 * test / unit );
  465. this.x = Math.atan2( 2 * q.x * q.w - 2 * q.y * q.z, -sqx + sqy - sqz + sqw );
  466. },
  467. */
  468. getScaleFromMatrix: function ( m ) {
  469. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  470. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  471. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  472. this.x = sx;
  473. this.y = sy;
  474. this.z = sz;
  475. },
  476. equals: function ( v ) {
  477. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  478. },
  479. isZero: function () {
  480. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  481. },
  482. clone: function () {
  483. return new THREE.Vector3( this.x, this.y, this.z );
  484. }
  485. };
  486. /**
  487. * @author supereggbert / http://www.paulbrunt.co.uk/
  488. * @author philogb / http://blog.thejit.org/
  489. * @author mikael emtinger / http://gomo.se/
  490. * @author egraether / http://egraether.com/
  491. */
  492. THREE.Vector4 = function ( x, y, z, w ) {
  493. this.x = x || 0;
  494. this.y = y || 0;
  495. this.z = z || 0;
  496. this.w = ( w !== undefined ) ? w : 1;
  497. };
  498. THREE.Vector4.prototype = {
  499. constructor: THREE.Vector4,
  500. set: function ( x, y, z, w ) {
  501. this.x = x;
  502. this.y = y;
  503. this.z = z;
  504. this.w = w;
  505. return this;
  506. },
  507. copy: function ( v ) {
  508. this.x = v.x;
  509. this.y = v.y;
  510. this.z = v.z;
  511. this.w = ( v.w !== undefined ) ? v.w : 1;
  512. return this;
  513. },
  514. add: function ( a, b ) {
  515. this.x = a.x + b.x;
  516. this.y = a.y + b.y;
  517. this.z = a.z + b.z;
  518. this.w = a.w + b.w;
  519. return this;
  520. },
  521. addSelf: function ( v ) {
  522. this.x += v.x;
  523. this.y += v.y;
  524. this.z += v.z;
  525. this.w += v.w;
  526. return this;
  527. },
  528. sub: function ( a, b ) {
  529. this.x = a.x - b.x;
  530. this.y = a.y - b.y;
  531. this.z = a.z - b.z;
  532. this.w = a.w - b.w;
  533. return this;
  534. },
  535. subSelf: function ( v ) {
  536. this.x -= v.x;
  537. this.y -= v.y;
  538. this.z -= v.z;
  539. this.w -= v.w;
  540. return this;
  541. },
  542. multiplyScalar: function ( s ) {
  543. this.x *= s;
  544. this.y *= s;
  545. this.z *= s;
  546. this.w *= s;
  547. return this;
  548. },
  549. divideScalar: function ( s ) {
  550. if ( s ) {
  551. this.x /= s;
  552. this.y /= s;
  553. this.z /= s;
  554. this.w /= s;
  555. } else {
  556. this.x = 0;
  557. this.y = 0;
  558. this.z = 0;
  559. this.w = 1;
  560. }
  561. return this;
  562. },
  563. negate: function() {
  564. return this.multiplyScalar( -1 );
  565. },
  566. dot: function ( v ) {
  567. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  568. },
  569. lengthSq: function () {
  570. return this.dot( this );
  571. },
  572. length: function () {
  573. return Math.sqrt( this.lengthSq() );
  574. },
  575. normalize: function () {
  576. return this.divideScalar( this.length() );
  577. },
  578. setLength: function ( l ) {
  579. return this.normalize().multiplyScalar( l );
  580. },
  581. lerpSelf: function ( v, alpha ) {
  582. this.x += ( v.x - this.x ) * alpha;
  583. this.y += ( v.y - this.y ) * alpha;
  584. this.z += ( v.z - this.z ) * alpha;
  585. this.w += ( v.w - this.w ) * alpha;
  586. return this;
  587. },
  588. clone: function () {
  589. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  590. }
  591. };
  592. /**
  593. * @author mrdoob / http://mrdoob.com/
  594. * @author alteredq / http://alteredqualia.com/
  595. */
  596. THREE.Frustum = function ( ) {
  597. this.planes = [
  598. new THREE.Vector4(),
  599. new THREE.Vector4(),
  600. new THREE.Vector4(),
  601. new THREE.Vector4(),
  602. new THREE.Vector4(),
  603. new THREE.Vector4()
  604. ];
  605. };
  606. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  607. var i, plane,
  608. planes = this.planes;
  609. planes[ 0 ].set( m.elements[3] - m.elements[0], m.elements[7] - m.elements[4], m.elements[11] - m.elements[8], m.elements[15] - m.elements[12] );
  610. planes[ 1 ].set( m.elements[3] + m.elements[0], m.elements[7] + m.elements[4], m.elements[11] + m.elements[8], m.elements[15] + m.elements[12] );
  611. planes[ 2 ].set( m.elements[3] + m.elements[1], m.elements[7] + m.elements[5], m.elements[11] + m.elements[9], m.elements[15] + m.elements[13] );
  612. planes[ 3 ].set( m.elements[3] - m.elements[1], m.elements[7] - m.elements[5], m.elements[11] - m.elements[9], m.elements[15] - m.elements[13] );
  613. planes[ 4 ].set( m.elements[3] - m.elements[2], m.elements[7] - m.elements[6], m.elements[11] - m.elements[10], m.elements[15] - m.elements[14] );
  614. planes[ 5 ].set( m.elements[3] + m.elements[2], m.elements[7] + m.elements[6], m.elements[11] + m.elements[10], m.elements[15] + m.elements[14] );
  615. for ( i = 0; i < 6; i ++ ) {
  616. plane = planes[ i ];
  617. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  618. }
  619. };
  620. THREE.Frustum.prototype.contains = function ( object ) {
  621. var distance,
  622. planes = this.planes,
  623. matrix = object.matrixWorld,
  624. scale = THREE.Frustum.__v1.set( matrix.getColumnX().length(), matrix.getColumnY().length(), matrix.getColumnZ().length() ),
  625. radius = - object.geometry.boundingSphere.radius * Math.max( scale.x, Math.max( scale.y, scale.z ) );
  626. for ( var i = 0; i < 6; i ++ ) {
  627. distance = planes[ i ].x * matrix.elements[12] + planes[ i ].y * matrix.elements[13] + planes[ i ].z * matrix.elements[14] + planes[ i ].w;
  628. if ( distance <= radius ) return false;
  629. }
  630. return true;
  631. };
  632. THREE.Frustum.__v1 = new THREE.Vector3();
  633. /**
  634. * @author mr.doob / http://mrdoob.com/
  635. */
  636. THREE.Ray = function ( origin, direction ) {
  637. this.origin = origin || new THREE.Vector3();
  638. this.direction = direction || new THREE.Vector3();
  639. var precision = 0.0001;
  640. this.setPrecision = function ( value ) {
  641. precision = value;
  642. };
  643. var a = new THREE.Vector3();
  644. var b = new THREE.Vector3();
  645. var c = new THREE.Vector3();
  646. var d = new THREE.Vector3();
  647. var originCopy = new THREE.Vector3();
  648. var directionCopy = new THREE.Vector3();
  649. var vector = new THREE.Vector3();
  650. var normal = new THREE.Vector3();
  651. var intersectPoint = new THREE.Vector3()
  652. this.intersectObject = function ( object ) {
  653. var intersect, intersects = [];
  654. if ( object instanceof THREE.Particle ) {
  655. var distance = distanceFromIntersection( this.origin, this.direction, object.matrixWorld.getPosition() );
  656. if ( distance > object.scale.x ) {
  657. return [];
  658. }
  659. intersect = {
  660. distance: distance,
  661. point: object.position,
  662. face: null,
  663. object: object
  664. };
  665. intersects.push( intersect );
  666. } else if ( object instanceof THREE.Mesh ) {
  667. // Checking boundingSphere
  668. var distance = distanceFromIntersection( this.origin, this.direction, object.matrixWorld.getPosition() );
  669. var scale = THREE.Frustum.__v1.set( object.matrixWorld.getColumnX().length(), object.matrixWorld.getColumnY().length(), object.matrixWorld.getColumnZ().length() );
  670. if ( distance > object.geometry.boundingSphere.radius * Math.max( scale.x, Math.max( scale.y, scale.z ) ) ) {
  671. return intersects;
  672. }
  673. // Checking faces
  674. var f, fl, face, dot, scalar,
  675. geometry = object.geometry,
  676. vertices = geometry.vertices,
  677. objMatrix;
  678. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  679. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  680. face = geometry.faces[ f ];
  681. originCopy.copy( this.origin );
  682. directionCopy.copy( this.direction );
  683. objMatrix = object.matrixWorld;
  684. // determine if ray intersects the plane of the face
  685. // note: this works regardless of the direction of the face normal
  686. vector = objMatrix.multiplyVector3( vector.copy( face.centroid ) ).subSelf( originCopy );
  687. normal = object.matrixRotationWorld.multiplyVector3( normal.copy( face.normal ) );
  688. dot = directionCopy.dot( normal );
  689. // bail if ray and plane are parallel
  690. if ( Math.abs( dot ) < precision ) continue;
  691. // calc distance to plane
  692. scalar = normal.dot( vector ) / dot;
  693. // if negative distance, then plane is behind ray
  694. if ( scalar < 0 ) continue;
  695. if ( object.doubleSided || ( object.flipSided ? dot > 0 : dot < 0 ) ) {
  696. intersectPoint.add( originCopy, directionCopy.multiplyScalar( scalar ) );
  697. if ( face instanceof THREE.Face3 ) {
  698. a = objMatrix.multiplyVector3( a.copy( vertices[ face.a ].position ) );
  699. b = objMatrix.multiplyVector3( b.copy( vertices[ face.b ].position ) );
  700. c = objMatrix.multiplyVector3( c.copy( vertices[ face.c ].position ) );
  701. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  702. intersect = {
  703. distance: originCopy.distanceTo( intersectPoint ),
  704. point: intersectPoint.clone(),
  705. face: face,
  706. object: object
  707. };
  708. intersects.push( intersect );
  709. }
  710. } else if ( face instanceof THREE.Face4 ) {
  711. a = objMatrix.multiplyVector3( a.copy( vertices[ face.a ].position ) );
  712. b = objMatrix.multiplyVector3( b.copy( vertices[ face.b ].position ) );
  713. c = objMatrix.multiplyVector3( c.copy( vertices[ face.c ].position ) );
  714. d = objMatrix.multiplyVector3( d.copy( vertices[ face.d ].position ) );
  715. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  716. intersect = {
  717. distance: originCopy.distanceTo( intersectPoint ),
  718. point: intersectPoint.clone(),
  719. face: face,
  720. object: object
  721. };
  722. intersects.push( intersect );
  723. }
  724. }
  725. }
  726. }
  727. }
  728. return intersects;
  729. }
  730. this.intersectObjects = function ( objects ) {
  731. var intersects = [];
  732. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  733. Array.prototype.push.apply( intersects, this.intersectObject( objects[ i ] ) );
  734. }
  735. intersects.sort( function ( a, b ) { return a.distance - b.distance; } );
  736. return intersects;
  737. };
  738. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  739. var dot, intersect, distance;
  740. function distanceFromIntersection( origin, direction, position ) {
  741. v0.sub( position, origin );
  742. dot = v0.dot( direction );
  743. intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  744. distance = position.distanceTo( intersect );
  745. return distance;
  746. }
  747. // http://www.blackpawn.com/texts/pointinpoly/default.html
  748. var dot00, dot01, dot02, dot11, dot12, invDenom, u, v;
  749. function pointInFace3( p, a, b, c ) {
  750. v0.sub( c, a );
  751. v1.sub( b, a );
  752. v2.sub( p, a );
  753. dot00 = v0.dot( v0 );
  754. dot01 = v0.dot( v1 );
  755. dot02 = v0.dot( v2 );
  756. dot11 = v1.dot( v1 );
  757. dot12 = v1.dot( v2 );
  758. invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  759. u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  760. v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  761. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  762. }
  763. };/**
  764. * @author mr.doob / http://mrdoob.com/
  765. */
  766. THREE.Rectangle = function () {
  767. var _left, _top, _right, _bottom,
  768. _width, _height, _isEmpty = true;
  769. function resize() {
  770. _width = _right - _left;
  771. _height = _bottom - _top;
  772. }
  773. this.getX = function () {
  774. return _left;
  775. };
  776. this.getY = function () {
  777. return _top;
  778. };
  779. this.getWidth = function () {
  780. return _width;
  781. };
  782. this.getHeight = function () {
  783. return _height;
  784. };
  785. this.getLeft = function() {
  786. return _left;
  787. };
  788. this.getTop = function() {
  789. return _top;
  790. };
  791. this.getRight = function() {
  792. return _right;
  793. };
  794. this.getBottom = function() {
  795. return _bottom;
  796. };
  797. this.set = function ( left, top, right, bottom ) {
  798. _isEmpty = false;
  799. _left = left; _top = top;
  800. _right = right; _bottom = bottom;
  801. resize();
  802. };
  803. this.addPoint = function ( x, y ) {
  804. if ( _isEmpty ) {
  805. _isEmpty = false;
  806. _left = x; _top = y;
  807. _right = x; _bottom = y;
  808. resize();
  809. } else {
  810. _left = _left < x ? _left : x; // Math.min( _left, x );
  811. _top = _top < y ? _top : y; // Math.min( _top, y );
  812. _right = _right > x ? _right : x; // Math.max( _right, x );
  813. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  814. resize();
  815. }
  816. };
  817. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  818. if (_isEmpty) {
  819. _isEmpty = false;
  820. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  821. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  822. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  823. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  824. resize();
  825. } else {
  826. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  827. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  828. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  829. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  830. resize();
  831. };
  832. };
  833. this.addRectangle = function ( r ) {
  834. if ( _isEmpty ) {
  835. _isEmpty = false;
  836. _left = r.getLeft(); _top = r.getTop();
  837. _right = r.getRight(); _bottom = r.getBottom();
  838. resize();
  839. } else {
  840. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  841. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  842. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  843. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  844. resize();
  845. }
  846. };
  847. this.inflate = function ( v ) {
  848. _left -= v; _top -= v;
  849. _right += v; _bottom += v;
  850. resize();
  851. };
  852. this.minSelf = function ( r ) {
  853. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  854. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  855. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  856. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  857. resize();
  858. };
  859. this.intersects = function ( r ) {
  860. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  861. if ( _right < r.getLeft() ) return false;
  862. if ( _left > r.getRight() ) return false;
  863. if ( _bottom < r.getTop() ) return false;
  864. if ( _top > r.getBottom() ) return false;
  865. return true;
  866. };
  867. this.empty = function () {
  868. _isEmpty = true;
  869. _left = 0; _top = 0;
  870. _right = 0; _bottom = 0;
  871. resize();
  872. };
  873. this.isEmpty = function () {
  874. return _isEmpty;
  875. };
  876. };
  877. /**
  878. * @author alteredq / http://alteredqualia.com/
  879. */
  880. THREE.Math = {
  881. // Clamp value to range <a, b>
  882. clamp: function ( x, a, b ) {
  883. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  884. },
  885. // Clamp value to range <a, inf)
  886. clampBottom: function ( x, a ) {
  887. return x < a ? a : x;
  888. },
  889. // Linear mapping from range <a1, a2> to range <b1, b2>
  890. mapLinear: function ( x, a1, a2, b1, b2 ) {
  891. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  892. },
  893. // Random float from <0, 1> with 16 bits of randomness
  894. // (standard Math.random() creates repetitive patterns when applied over larger space)
  895. random16: function () {
  896. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  897. },
  898. // Random integer from <low, high> interval
  899. randInt: function ( low, high ) {
  900. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  901. },
  902. // Random float from <low, high> interval
  903. randFloat: function ( low, high ) {
  904. return low + Math.random() * ( high - low );
  905. },
  906. // Random float from <-range/2, range/2> interval
  907. randFloatSpread: function ( range ) {
  908. return range * ( 0.5 - Math.random() );
  909. },
  910. sign: function ( x ) {
  911. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  912. }
  913. };
  914. /**
  915. * @author alteredq / http://alteredqualia.com/
  916. */
  917. THREE.Matrix3 = function () {
  918. this.m = [];
  919. };
  920. THREE.Matrix3.prototype = {
  921. constructor: THREE.Matrix3,
  922. getInverse: function ( matrix ) {
  923. // input: THREE.Matrix4
  924. // ( based on http://code.google.com/p/webgl-mjs/ )
  925. var a11 = matrix.elements[10] * matrix.elements[5] - matrix.elements[6] * matrix.elements[9];
  926. var a21 = - matrix.elements[10] * matrix.elements[1] + matrix.elements[2] * matrix.elements[9];
  927. var a31 = matrix.elements[6] * matrix.elements[1] - matrix.elements[2] * matrix.elements[5];
  928. var a12 = - matrix.elements[10] * matrix.elements[4] + matrix.elements[6] * matrix.elements[8];
  929. var a22 = matrix.elements[10] * matrix.elements[0] - matrix.elements[2] * matrix.elements[8];
  930. var a32 = - matrix.elements[6] * matrix.elements[0] + matrix.elements[2] * matrix.elements[4];
  931. var a13 = matrix.elements[9] * matrix.elements[4] - matrix.elements[5] * matrix.elements[8];
  932. var a23 = - matrix.elements[9] * matrix.elements[0] + matrix.elements[1] * matrix.elements[8];
  933. var a33 = matrix.elements[5] * matrix.elements[0] - matrix.elements[1] * matrix.elements[4];
  934. var det = matrix.elements[0] * a11 + matrix.elements[1] * a12 + matrix.elements[2] * a13;
  935. // no inverse
  936. if ( det === 0 ) {
  937. console.warn( "Matrix3.getInverse(): determinant == 0" );
  938. }
  939. var idet = 1.0 / det;
  940. var m = this.m;
  941. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  942. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  943. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  944. return this;
  945. },
  946. /*
  947. transpose: function () {
  948. var tmp, m = this.m;
  949. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  950. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  951. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  952. return this;
  953. },
  954. */
  955. transposeIntoArray: function ( r ) {
  956. var m = this.m;
  957. r[ 0 ] = m[ 0 ];
  958. r[ 1 ] = m[ 3 ];
  959. r[ 2 ] = m[ 6 ];
  960. r[ 3 ] = m[ 1 ];
  961. r[ 4 ] = m[ 4 ];
  962. r[ 5 ] = m[ 7 ];
  963. r[ 6 ] = m[ 2 ];
  964. r[ 7 ] = m[ 5 ];
  965. r[ 8 ] = m[ 8 ];
  966. return this;
  967. }
  968. };
  969. /**
  970. * @author mr.doob / http://mrdoob.com/
  971. * @author supereggbert / http://www.paulbrunt.co.uk/
  972. * @author philogb / http://blog.thejit.org/
  973. * @author jordi_ros / http://plattsoft.com
  974. * @author D1plo1d / http://github.com/D1plo1d
  975. * @author alteredq / http://alteredqualia.com/
  976. * @author mikael emtinger / http://gomo.se/
  977. * @author timknip / http://www.floorplanner.com/
  978. */
  979. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  980. this.elements = new Float32Array(16);
  981. this.set(
  982. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  983. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  984. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  985. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  986. );
  987. };
  988. THREE.Matrix4.prototype = {
  989. constructor: THREE.Matrix4,
  990. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  991. var te = this.elements;
  992. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  993. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  994. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  995. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  996. return this;
  997. },
  998. identity: function () {
  999. this.set(
  1000. 1, 0, 0, 0,
  1001. 0, 1, 0, 0,
  1002. 0, 0, 1, 0,
  1003. 0, 0, 0, 1
  1004. );
  1005. return this;
  1006. },
  1007. copy: function ( m ) {
  1008. this.set(
  1009. m.elements[0], m.elements[4], m.elements[8], m.elements[12],
  1010. m.elements[1], m.elements[5], m.elements[9], m.elements[13],
  1011. m.elements[2], m.elements[6], m.elements[10], m.elements[14],
  1012. m.elements[3], m.elements[7], m.elements[11], m.elements[15]
  1013. );
  1014. return this;
  1015. },
  1016. lookAt: function ( eye, target, up ) {
  1017. var te = this.elements;
  1018. var x = THREE.Matrix4.__v1;
  1019. var y = THREE.Matrix4.__v2;
  1020. var z = THREE.Matrix4.__v3;
  1021. z.sub( eye, target ).normalize();
  1022. if ( z.length() === 0 ) {
  1023. z.z = 1;
  1024. }
  1025. x.cross( up, z ).normalize();
  1026. if ( x.length() === 0 ) {
  1027. z.x += 0.0001;
  1028. x.cross( up, z ).normalize();
  1029. }
  1030. y.cross( z, x );
  1031. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1032. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1033. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1034. return this;
  1035. },
  1036. multiply: function ( a, b ) {
  1037. var ae = a.elements,
  1038. be = b.elements,
  1039. te = this.elements;
  1040. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1041. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1042. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1043. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1044. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1045. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1046. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1047. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1048. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1049. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1050. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1051. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1052. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1053. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1054. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1055. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1056. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1057. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1058. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1059. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1060. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1061. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1062. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1063. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1064. return this;
  1065. },
  1066. multiplySelf: function ( m ) {
  1067. return this.multiply( this, m );
  1068. },
  1069. multiplyToArray: function ( a, b, r ) {
  1070. var te = this.elements;
  1071. this.multiply( a, b );
  1072. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1073. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1074. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1075. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1076. return this;
  1077. },
  1078. multiplyScalar: function ( s ) {
  1079. var te = this.elements;
  1080. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1081. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1082. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1083. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1084. return this;
  1085. },
  1086. multiplyVector3: function ( v ) {
  1087. var te = this.elements;
  1088. var vx = v.x, vy = v.y, vz = v.z;
  1089. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1090. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1091. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1092. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1093. return v;
  1094. },
  1095. multiplyVector4: function ( v ) {
  1096. var te = this.elements;
  1097. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1098. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1099. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1100. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1101. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1102. return v;
  1103. },
  1104. rotateAxis: function ( v ) {
  1105. var te = this.elements;
  1106. var vx = v.x, vy = v.y, vz = v.z;
  1107. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1108. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1109. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1110. v.normalize();
  1111. return v;
  1112. },
  1113. crossVector: function ( a ) {
  1114. var te = this.elements;
  1115. var v = new THREE.Vector4();
  1116. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1117. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1118. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1119. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1120. return v;
  1121. },
  1122. determinant: function () {
  1123. var te = this.elements;
  1124. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1125. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1126. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1127. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1128. //TODO: make this more efficient
  1129. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1130. return (
  1131. n14 * n23 * n32 * n41-
  1132. n13 * n24 * n32 * n41-
  1133. n14 * n22 * n33 * n41+
  1134. n12 * n24 * n33 * n41+
  1135. n13 * n22 * n34 * n41-
  1136. n12 * n23 * n34 * n41-
  1137. n14 * n23 * n31 * n42+
  1138. n13 * n24 * n31 * n42+
  1139. n14 * n21 * n33 * n42-
  1140. n11 * n24 * n33 * n42-
  1141. n13 * n21 * n34 * n42+
  1142. n11 * n23 * n34 * n42+
  1143. n14 * n22 * n31 * n43-
  1144. n12 * n24 * n31 * n43-
  1145. n14 * n21 * n32 * n43+
  1146. n11 * n24 * n32 * n43+
  1147. n12 * n21 * n34 * n43-
  1148. n11 * n22 * n34 * n43-
  1149. n13 * n22 * n31 * n44+
  1150. n12 * n23 * n31 * n44+
  1151. n13 * n21 * n32 * n44-
  1152. n11 * n23 * n32 * n44-
  1153. n12 * n21 * n33 * n44+
  1154. n11 * n22 * n33 * n44
  1155. );
  1156. },
  1157. transpose: function () {
  1158. var te = this.elements;
  1159. var tmp;
  1160. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1161. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1162. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1163. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1164. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1165. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1166. return this;
  1167. },
  1168. flattenToArray: function ( flat ) {
  1169. var te = this.elements;
  1170. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1171. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1172. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1173. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1174. return flat;
  1175. },
  1176. flattenToArrayOffset: function( flat, offset ) {
  1177. var te = this.elements;
  1178. flat[ offset ] = te[0];
  1179. flat[ offset + 1 ] = te[1];
  1180. flat[ offset + 2 ] = te[2];
  1181. flat[ offset + 3 ] = te[3];
  1182. flat[ offset + 4 ] = te[4];
  1183. flat[ offset + 5 ] = te[5];
  1184. flat[ offset + 6 ] = te[6];
  1185. flat[ offset + 7 ] = te[7];
  1186. flat[ offset + 8 ] = te[8];
  1187. flat[ offset + 9 ] = te[9];
  1188. flat[ offset + 10 ] = te[10];
  1189. flat[ offset + 11 ] = te[11];
  1190. flat[ offset + 12 ] = te[12];
  1191. flat[ offset + 13 ] = te[13];
  1192. flat[ offset + 14 ] = te[14];
  1193. flat[ offset + 15 ] = te[15];
  1194. return flat;
  1195. },
  1196. getPosition: function () {
  1197. var te = this.elements;
  1198. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1199. },
  1200. setPosition: function ( v ) {
  1201. var te = this.elements;
  1202. te[12] = v.x;
  1203. te[13] = v.y;
  1204. te[14] = v.z;
  1205. return this;
  1206. },
  1207. getColumnX: function () {
  1208. var te = this.elements;
  1209. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1210. },
  1211. getColumnY: function () {
  1212. var te = this.elements;
  1213. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1214. },
  1215. getColumnZ: function() {
  1216. var te = this.elements;
  1217. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1218. },
  1219. getInverse: function ( m ) {
  1220. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1221. var te = this.elements;
  1222. var n11 = m.elements[0], n12 = m.elements[4], n13 = m.elements[8], n14 = m.elements[12];
  1223. var n21 = m.elements[1], n22 = m.elements[5], n23 = m.elements[9], n24 = m.elements[13];
  1224. var n31 = m.elements[2], n32 = m.elements[6], n33 = m.elements[10], n34 = m.elements[14];
  1225. var n41 = m.elements[3], n42 = m.elements[7], n43 = m.elements[11], n44 = m.elements[15];
  1226. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1227. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1228. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1229. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1230. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1231. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1232. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1233. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1234. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1235. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1236. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1237. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1238. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1239. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1240. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1241. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1242. this.multiplyScalar( 1 / m.determinant() );
  1243. return this;
  1244. },
  1245. setRotationFromEuler: function( v, order ) {
  1246. var te = this.elements;
  1247. var x = v.x, y = v.y, z = v.z;
  1248. var a = Math.cos( x ), b = Math.sin( x );
  1249. var c = Math.cos( y ), d = Math.sin( y );
  1250. var e = Math.cos( z ), f = Math.sin( z );
  1251. switch ( order ) {
  1252. case 'YXZ':
  1253. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1254. te[0] = ce + df * b;
  1255. te[4] = de * b - cf;
  1256. te[8] = a * d;
  1257. te[1] = a * f;
  1258. te[5] = a * e;
  1259. te[9] = - b;
  1260. te[2] = cf * b - de;
  1261. te[6] = df + ce * b;
  1262. te[10] = a * c;
  1263. break;
  1264. case 'ZXY':
  1265. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1266. te[0] = ce - df * b;
  1267. te[4] = - a * f;
  1268. te[8] = de + cf * b;
  1269. te[1] = cf + de * b;
  1270. te[5] = a * e;
  1271. te[9] = df - ce * b;
  1272. te[2] = - a * d;
  1273. te[6] = b;
  1274. te[10] = a * c;
  1275. break;
  1276. case 'ZYX':
  1277. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1278. te[0] = c * e;
  1279. te[4] = be * d - af;
  1280. te[8] = ae * d + bf;
  1281. te[1] = c * f;
  1282. te[5] = bf * d + ae;
  1283. te[9] = af * d - be;
  1284. te[2] = - d;
  1285. te[6] = b * c;
  1286. te[10] = a * c;
  1287. break;
  1288. case 'YZX':
  1289. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1290. te[0] = c * e;
  1291. te[4] = bd - ac * f;
  1292. te[8] = bc * f + ad;
  1293. te[1] = f;
  1294. te[5] = a * e;
  1295. te[9] = - b * e;
  1296. te[2] = - d * e;
  1297. te[6] = ad * f + bc;
  1298. te[10] = ac - bd * f;
  1299. break;
  1300. case 'XZY':
  1301. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1302. te[0] = c * e;
  1303. te[4] = - f;
  1304. te[8] = d * e;
  1305. te[1] = ac * f + bd;
  1306. te[5] = a * e;
  1307. te[9] = ad * f - bc;
  1308. te[2] = bc * f - ad;
  1309. te[6] = b * e;
  1310. te[10] = bd * f + ac;
  1311. break;
  1312. default: // 'XYZ'
  1313. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1314. te[0] = c * e;
  1315. te[4] = - c * f;
  1316. te[8] = d;
  1317. te[1] = af + be * d;
  1318. te[5] = ae - bf * d;
  1319. te[9] = - b * c;
  1320. te[2] = bf - ae * d;
  1321. te[6] = be + af * d;
  1322. te[10] = a * c;
  1323. break;
  1324. }
  1325. return this;
  1326. },
  1327. setRotationFromQuaternion: function( q ) {
  1328. var te = this.elements;
  1329. var x = q.x, y = q.y, z = q.z, w = q.w;
  1330. var x2 = x + x, y2 = y + y, z2 = z + z;
  1331. var xx = x * x2, xy = x * y2, xz = x * z2;
  1332. var yy = y * y2, yz = y * z2, zz = z * z2;
  1333. var wx = w * x2, wy = w * y2, wz = w * z2;
  1334. te[0] = 1 - ( yy + zz );
  1335. te[4] = xy - wz;
  1336. te[8] = xz + wy;
  1337. te[1] = xy + wz;
  1338. te[5] = 1 - ( xx + zz );
  1339. te[9] = yz - wx;
  1340. te[2] = xz - wy;
  1341. te[6] = yz + wx;
  1342. te[10] = 1 - ( xx + yy );
  1343. return this;
  1344. },
  1345. compose: function ( translation, rotation, scale ) {
  1346. var te = this.elements;
  1347. var mRotation = THREE.Matrix4.__m1;
  1348. var mScale = THREE.Matrix4.__m2;
  1349. mRotation.identity();
  1350. mRotation.setRotationFromQuaternion( rotation );
  1351. mScale.makeScale( scale.x, scale.y, scale.z );
  1352. this.multiply( mRotation, mScale );
  1353. te[12] = translation.x;
  1354. te[13] = translation.y;
  1355. te[14] = translation.z;
  1356. return this;
  1357. },
  1358. decompose: function ( translation, rotation, scale ) {
  1359. // grab the axis vectors
  1360. var te = this.elements;
  1361. var x = THREE.Matrix4.__v1;
  1362. var y = THREE.Matrix4.__v2;
  1363. var z = THREE.Matrix4.__v3;
  1364. x.set( te[0], te[1], te[2] );
  1365. y.set( te[4], te[5], te[6] );
  1366. z.set( te[8], te[9], te[10] );
  1367. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1368. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1369. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1370. scale.x = x.length();
  1371. scale.y = y.length();
  1372. scale.z = z.length();
  1373. translation.x = te[12];
  1374. translation.y = te[13];
  1375. translation.z = te[14];
  1376. // scale the rotation part
  1377. var matrix = THREE.Matrix4.__m1;
  1378. matrix.copy( this );
  1379. matrix.elements[0] /= scale.x;
  1380. matrix.elements[1] /= scale.x;
  1381. matrix.elements[2] /= scale.x;
  1382. matrix.elements[4] /= scale.y;
  1383. matrix.elements[5] /= scale.y;
  1384. matrix.elements[6] /= scale.y;
  1385. matrix.elements[8] /= scale.z;
  1386. matrix.elements[9] /= scale.z;
  1387. matrix.elements[10] /= scale.z;
  1388. rotation.setFromRotationMatrix( matrix );
  1389. return [ translation, rotation, scale ];
  1390. },
  1391. extractPosition: function ( m ) {
  1392. var te = this.elements;
  1393. te[12] = m.elements[12];
  1394. te[13] = m.elements[13];
  1395. te[14] = m.elements[14];
  1396. return this;
  1397. },
  1398. extractRotation: function ( m ) {
  1399. var te = this.elements;
  1400. var vector = THREE.Matrix4.__v1;
  1401. var scaleX = 1 / vector.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1402. var scaleY = 1 / vector.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1403. var scaleZ = 1 / vector.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1404. te[0] = m.elements[0] * scaleX;
  1405. te[1] = m.elements[1] * scaleX;
  1406. te[2] = m.elements[2] * scaleX;
  1407. te[4] = m.elements[4] * scaleY;
  1408. te[5] = m.elements[5] * scaleY;
  1409. te[6] = m.elements[6] * scaleY;
  1410. te[8] = m.elements[8] * scaleZ;
  1411. te[9] = m.elements[9] * scaleZ;
  1412. te[10] = m.elements[10] * scaleZ;
  1413. return this;
  1414. },
  1415. //
  1416. translate: function ( v ) {
  1417. var te = this.elements;
  1418. var x = v.x, y = v.y, z = v.z;
  1419. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1420. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1421. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1422. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1423. return this;
  1424. },
  1425. rotateX: function ( angle ) {
  1426. var te = this.elements;
  1427. var m12 = te[4];
  1428. var m22 = te[5];
  1429. var m32 = te[6];
  1430. var m42 = te[7];
  1431. var m13 = te[8];
  1432. var m23 = te[9];
  1433. var m33 = te[10];
  1434. var m43 = te[11];
  1435. var c = Math.cos( angle );
  1436. var s = Math.sin( angle );
  1437. te[4] = c * m12 + s * m13;
  1438. te[5] = c * m22 + s * m23;
  1439. te[6] = c * m32 + s * m33;
  1440. te[7] = c * m42 + s * m43;
  1441. te[8] = c * m13 - s * m12;
  1442. te[9] = c * m23 - s * m22;
  1443. te[10] = c * m33 - s * m32;
  1444. te[11] = c * m43 - s * m42;
  1445. return this;
  1446. },
  1447. rotateY: function ( angle ) {
  1448. var te = this.elements;
  1449. var m11 = te[0];
  1450. var m21 = te[1];
  1451. var m31 = te[2];
  1452. var m41 = te[3];
  1453. var m13 = te[8];
  1454. var m23 = te[9];
  1455. var m33 = te[10];
  1456. var m43 = te[11];
  1457. var c = Math.cos( angle );
  1458. var s = Math.sin( angle );
  1459. te[0] = c * m11 - s * m13;
  1460. te[1] = c * m21 - s * m23;
  1461. te[2] = c * m31 - s * m33;
  1462. te[3] = c * m41 - s * m43;
  1463. te[8] = c * m13 + s * m11;
  1464. te[9] = c * m23 + s * m21;
  1465. te[10] = c * m33 + s * m31;
  1466. te[11] = c * m43 + s * m41;
  1467. return this;
  1468. },
  1469. rotateZ: function ( angle ) {
  1470. var te = this.elements;
  1471. var m11 = te[0];
  1472. var m21 = te[1];
  1473. var m31 = te[2];
  1474. var m41 = te[3];
  1475. var m12 = te[4];
  1476. var m22 = te[5];
  1477. var m32 = te[6];
  1478. var m42 = te[7];
  1479. var c = Math.cos( angle );
  1480. var s = Math.sin( angle );
  1481. te[0] = c * m11 + s * m12;
  1482. te[1] = c * m21 + s * m22;
  1483. te[2] = c * m31 + s * m32;
  1484. te[3] = c * m41 + s * m42;
  1485. te[4] = c * m12 - s * m11;
  1486. te[5] = c * m22 - s * m21;
  1487. te[6] = c * m32 - s * m31;
  1488. te[7] = c * m42 - s * m41;
  1489. return this;
  1490. },
  1491. rotateByAxis: function ( axis, angle ) {
  1492. var te = this.elements;
  1493. // optimize by checking axis
  1494. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1495. return this.rotateX( angle );
  1496. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1497. return this.rotateY( angle );
  1498. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1499. return this.rotateZ( angle );
  1500. }
  1501. var x = axis.x, y = axis.y, z = axis.z;
  1502. var n = Math.sqrt(x * x + y * y + z * z);
  1503. x /= n;
  1504. y /= n;
  1505. z /= n;
  1506. var xx = x * x, yy = y * y, zz = z * z;
  1507. var c = Math.cos( angle );
  1508. var s = Math.sin( angle );
  1509. var oneMinusCosine = 1 - c;
  1510. var xy = x * y * oneMinusCosine;
  1511. var xz = x * z * oneMinusCosine;
  1512. var yz = y * z * oneMinusCosine;
  1513. var xs = x * s;
  1514. var ys = y * s;
  1515. var zs = z * s;
  1516. var r11 = xx + (1 - xx) * c;
  1517. var r21 = xy + zs;
  1518. var r31 = xz - ys;
  1519. var r12 = xy - zs;
  1520. var r22 = yy + (1 - yy) * c;
  1521. var r32 = yz + xs;
  1522. var r13 = xz + ys;
  1523. var r23 = yz - xs;
  1524. var r33 = zz + (1 - zz) * c;
  1525. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1526. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1527. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1528. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1529. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1530. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1531. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1532. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1533. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1534. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1535. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1536. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1537. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1538. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1539. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1540. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1541. return this;
  1542. },
  1543. scale: function ( v ) {
  1544. var te = this.elements;
  1545. var x = v.x, y = v.y, z = v.z;
  1546. te[0] *= x; te[4] *= y; te[8] *= z;
  1547. te[1] *= x; te[5] *= y; te[9] *= z;
  1548. te[2] *= x; te[6] *= y; te[10] *= z;
  1549. te[3] *= x; te[7] *= y; te[11] *= z;
  1550. return this;
  1551. },
  1552. //
  1553. makeTranslation: function ( x, y, z ) {
  1554. this.set(
  1555. 1, 0, 0, x,
  1556. 0, 1, 0, y,
  1557. 0, 0, 1, z,
  1558. 0, 0, 0, 1
  1559. );
  1560. return this;
  1561. },
  1562. makeRotationX: function ( theta ) {
  1563. var c = Math.cos( theta ), s = Math.sin( theta );
  1564. this.set(
  1565. 1, 0, 0, 0,
  1566. 0, c, -s, 0,
  1567. 0, s, c, 0,
  1568. 0, 0, 0, 1
  1569. );
  1570. return this;
  1571. },
  1572. makeRotationY: function ( theta ) {
  1573. var c = Math.cos( theta ), s = Math.sin( theta );
  1574. this.set(
  1575. c, 0, s, 0,
  1576. 0, 1, 0, 0,
  1577. -s, 0, c, 0,
  1578. 0, 0, 0, 1
  1579. );
  1580. return this;
  1581. },
  1582. makeRotationZ: function ( theta ) {
  1583. var c = Math.cos( theta ), s = Math.sin( theta );
  1584. this.set(
  1585. c, -s, 0, 0,
  1586. s, c, 0, 0,
  1587. 0, 0, 1, 0,
  1588. 0, 0, 0, 1
  1589. );
  1590. return this;
  1591. },
  1592. makeRotationAxis: function ( axis, angle ) {
  1593. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1594. var c = Math.cos( angle );
  1595. var s = Math.sin( angle );
  1596. var t = 1 - c;
  1597. var x = axis.x, y = axis.y, z = axis.z;
  1598. var tx = t * x, ty = t * y;
  1599. this.set(
  1600. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1601. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1602. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1603. 0, 0, 0, 1
  1604. );
  1605. return this;
  1606. },
  1607. makeScale: function ( x, y, z ) {
  1608. this.set(
  1609. x, 0, 0, 0,
  1610. 0, y, 0, 0,
  1611. 0, 0, z, 0,
  1612. 0, 0, 0, 1
  1613. );
  1614. return this;
  1615. },
  1616. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1617. var te = this.elements;
  1618. var x = 2 * near / ( right - left );
  1619. var y = 2 * near / ( top - bottom );
  1620. var a = ( right + left ) / ( right - left );
  1621. var b = ( top + bottom ) / ( top - bottom );
  1622. var c = - ( far + near ) / ( far - near );
  1623. var d = - 2 * far * near / ( far - near );
  1624. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1625. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1626. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1627. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1628. return this;
  1629. },
  1630. makePerspective: function ( fov, aspect, near, far ) {
  1631. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1632. var ymin = - ymax;
  1633. var xmin = ymin * aspect;
  1634. var xmax = ymax * aspect;
  1635. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1636. },
  1637. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1638. var te = this.elements;
  1639. var w = right - left;
  1640. var h = top - bottom;
  1641. var p = far - near;
  1642. var x = ( right + left ) / w;
  1643. var y = ( top + bottom ) / h;
  1644. var z = ( far + near ) / p;
  1645. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1646. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1647. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1648. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1649. return this;
  1650. },
  1651. clone: function () {
  1652. var te = this.elements;
  1653. return new THREE.Matrix4(
  1654. te[0], te[4], te[8], te[12],
  1655. te[1], te[5], te[9], te[13],
  1656. te[2], te[6], te[10], te[14],
  1657. te[3], te[7], te[11], te[15]
  1658. );
  1659. }
  1660. };
  1661. THREE.Matrix4.__v1 = new THREE.Vector3();
  1662. THREE.Matrix4.__v2 = new THREE.Vector3();
  1663. THREE.Matrix4.__v3 = new THREE.Vector3();
  1664. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1665. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1666. /**
  1667. * @author mr.doob / http://mrdoob.com/
  1668. * @author mikael emtinger / http://gomo.se/
  1669. * @author alteredq / http://alteredqualia.com/
  1670. */
  1671. THREE.Object3D = function () {
  1672. this.id = THREE.Object3DCount ++;
  1673. this.name = '';
  1674. this.parent = undefined;
  1675. this.children = [];
  1676. this.up = new THREE.Vector3( 0, 1, 0 );
  1677. this.position = new THREE.Vector3();
  1678. this.rotation = new THREE.Vector3();
  1679. this.eulerOrder = 'XYZ';
  1680. this.scale = new THREE.Vector3( 1, 1, 1 );
  1681. this.doubleSided = false;
  1682. this.flipSided = false;
  1683. this.renderDepth = null;
  1684. this.rotationAutoUpdate = true;
  1685. this.matrix = new THREE.Matrix4();
  1686. this.matrixWorld = new THREE.Matrix4();
  1687. this.matrixRotationWorld = new THREE.Matrix4();
  1688. this.matrixAutoUpdate = true;
  1689. this.matrixWorldNeedsUpdate = true;
  1690. this.quaternion = new THREE.Quaternion();
  1691. this.useQuaternion = false;
  1692. this.boundRadius = 0.0;
  1693. this.boundRadiusScale = 1.0;
  1694. this.visible = true;
  1695. this.castShadow = false;
  1696. this.receiveShadow = false;
  1697. this.frustumCulled = true;
  1698. this._vector = new THREE.Vector3();
  1699. };
  1700. THREE.Object3D.prototype = {
  1701. constructor: THREE.Object3D,
  1702. applyMatrix: function ( matrix ) {
  1703. this.matrix.multiply( matrix, this.matrix );
  1704. this.scale.getScaleFromMatrix( this.matrix );
  1705. this.rotation.getRotationFromMatrix( this.matrix, this.scale );
  1706. this.position.getPositionFromMatrix( this.matrix );
  1707. },
  1708. translate: function ( distance, axis ) {
  1709. this.matrix.rotateAxis( axis );
  1710. this.position.addSelf( axis.multiplyScalar( distance ) );
  1711. },
  1712. translateX: function ( distance ) {
  1713. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  1714. },
  1715. translateY: function ( distance ) {
  1716. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  1717. },
  1718. translateZ: function ( distance ) {
  1719. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  1720. },
  1721. lookAt: function ( vector ) {
  1722. // TODO: Add hierarchy support.
  1723. this.matrix.lookAt( vector, this.position, this.up );
  1724. if ( this.rotationAutoUpdate ) {
  1725. this.rotation.getRotationFromMatrix( this.matrix );
  1726. }
  1727. },
  1728. add: function ( object ) {
  1729. if ( object === this ) {
  1730. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  1731. return;
  1732. }
  1733. if ( this.children.indexOf( object ) === - 1 ) {
  1734. if ( object.parent !== undefined ) {
  1735. object.parent.remove( object );
  1736. }
  1737. object.parent = this;
  1738. this.children.push( object );
  1739. // add to scene
  1740. var scene = this;
  1741. while ( scene.parent !== undefined ) {
  1742. scene = scene.parent;
  1743. }
  1744. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  1745. scene.__addObject( object );
  1746. }
  1747. }
  1748. },
  1749. remove: function ( object ) {
  1750. var index = this.children.indexOf( object );
  1751. if ( index !== - 1 ) {
  1752. object.parent = undefined;
  1753. this.children.splice( index, 1 );
  1754. // remove from scene
  1755. var scene = this;
  1756. while ( scene.parent !== undefined ) {
  1757. scene = scene.parent;
  1758. }
  1759. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  1760. scene.__removeObject( object );
  1761. }
  1762. }
  1763. },
  1764. getChildByName: function ( name, recursive ) {
  1765. var c, cl, child;
  1766. for ( c = 0, cl = this.children.length; c < cl; c ++ ) {
  1767. child = this.children[ c ];
  1768. if ( child.name === name ) {
  1769. return child;
  1770. }
  1771. if ( recursive ) {
  1772. child = child.getChildByName( name, recursive );
  1773. if ( child !== undefined ) {
  1774. return child;
  1775. }
  1776. }
  1777. }
  1778. return undefined;
  1779. },
  1780. updateMatrix: function () {
  1781. this.matrix.setPosition( this.position );
  1782. if ( this.useQuaternion ) {
  1783. this.matrix.setRotationFromQuaternion( this.quaternion );
  1784. } else {
  1785. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  1786. }
  1787. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  1788. this.matrix.scale( this.scale );
  1789. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  1790. }
  1791. this.matrixWorldNeedsUpdate = true;
  1792. },
  1793. updateMatrixWorld: function ( force ) {
  1794. this.matrixAutoUpdate && this.updateMatrix();
  1795. // update matrixWorld
  1796. if ( this.matrixWorldNeedsUpdate || force ) {
  1797. if ( this.parent ) {
  1798. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  1799. } else {
  1800. this.matrixWorld.copy( this.matrix );
  1801. }
  1802. this.matrixWorldNeedsUpdate = false;
  1803. force = true;
  1804. }
  1805. // update children
  1806. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  1807. this.children[ i ].updateMatrixWorld( force );
  1808. }
  1809. }
  1810. };
  1811. THREE.Object3DCount = 0;
  1812. /**
  1813. * @author mr.doob / http://mrdoob.com/
  1814. * @author supereggbert / http://www.paulbrunt.co.uk/
  1815. * @author julianwa / https://github.com/julianwa
  1816. */
  1817. THREE.Projector = function() {
  1818. var _object, _objectCount, _objectPool = [],
  1819. _vertex, _vertexCount, _vertexPool = [],
  1820. _face, _face3Count, _face3Pool = [], _face4Count, _face4Pool = [],
  1821. _line, _lineCount, _linePool = [],
  1822. _particle, _particleCount, _particlePool = [],
  1823. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  1824. _vector3 = new THREE.Vector3(),
  1825. _vector4 = new THREE.Vector4(),
  1826. _projScreenMatrix = new THREE.Matrix4(),
  1827. _projScreenobjectMatrixWorld = new THREE.Matrix4(),
  1828. _frustum = new THREE.Frustum(),
  1829. _clippedVertex1PositionScreen = new THREE.Vector4(),
  1830. _clippedVertex2PositionScreen = new THREE.Vector4(),
  1831. _face3VertexNormals;
  1832. this.projectVector = function ( vector, camera ) {
  1833. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  1834. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  1835. _projScreenMatrix.multiplyVector3( vector );
  1836. return vector;
  1837. };
  1838. this.unprojectVector = function ( vector, camera ) {
  1839. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  1840. _projScreenMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  1841. _projScreenMatrix.multiplyVector3( vector );
  1842. return vector;
  1843. };
  1844. this.pickingRay = function ( vector, camera ) {
  1845. var end, ray, t;
  1846. // set two vectors with opposing z values
  1847. vector.z = -1.0;
  1848. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  1849. this.unprojectVector( vector, camera );
  1850. this.unprojectVector( end, camera );
  1851. // find direction from vector to end
  1852. end.subSelf( vector ).normalize();
  1853. return new THREE.Ray( vector, end );
  1854. };
  1855. this.projectGraph = function ( root, sort ) {
  1856. _objectCount = 0;
  1857. _renderData.objects.length = 0;
  1858. _renderData.sprites.length = 0;
  1859. _renderData.lights.length = 0;
  1860. var projectObject = function ( object ) {
  1861. if ( object.visible === false ) return;
  1862. if ( ( object instanceof THREE.Mesh || object instanceof THREE.Line ) &&
  1863. ( object.frustumCulled === false || _frustum.contains( object ) ) ) {
  1864. _vector3.copy( object.matrixWorld.getPosition() );
  1865. _projScreenMatrix.multiplyVector3( _vector3 );
  1866. _object = getNextObjectInPool();
  1867. _object.object = object;
  1868. _object.z = _vector3.z;
  1869. _renderData.objects.push( _object );
  1870. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  1871. _vector3.copy( object.matrixWorld.getPosition() );
  1872. _projScreenMatrix.multiplyVector3( _vector3 );
  1873. _object = getNextObjectInPool();
  1874. _object.object = object;
  1875. _object.z = _vector3.z;
  1876. _renderData.sprites.push( _object );
  1877. } else if ( object instanceof THREE.Light ) {
  1878. _renderData.lights.push( object );
  1879. }
  1880. for ( var c = 0, cl = object.children.length; c < cl; c ++ ) {
  1881. projectObject( object.children[ c ] );
  1882. }
  1883. };
  1884. projectObject( root );
  1885. sort && _renderData.objects.sort( painterSort );
  1886. return _renderData;
  1887. };
  1888. this.projectScene = function ( scene, camera, sort ) {
  1889. var near = camera.near, far = camera.far, visible = false,
  1890. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  1891. objectMatrixWorld, objectMatrixWorldRotation,
  1892. geometry, geometryMaterials, vertices, vertex, vertexPositionScreen,
  1893. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  1894. v1, v2, v3, v4;
  1895. _face3Count = 0;
  1896. _face4Count = 0;
  1897. _lineCount = 0;
  1898. _particleCount = 0;
  1899. _renderData.elements.length = 0;
  1900. if ( camera.parent === undefined ) {
  1901. console.warn( 'DEPRECATED: Camera hasn\'t been added to a Scene. Adding it...' );
  1902. scene.add( camera );
  1903. }
  1904. scene.updateMatrixWorld();
  1905. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  1906. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  1907. _frustum.setFromMatrix( _projScreenMatrix );
  1908. _renderData = this.projectGraph( scene, false );
  1909. for ( o = 0, ol = _renderData.objects.length; o < ol; o++ ) {
  1910. object = _renderData.objects[ o ].object;
  1911. objectMatrixWorld = object.matrixWorld;
  1912. _vertexCount = 0;
  1913. if ( object instanceof THREE.Mesh ) {
  1914. geometry = object.geometry;
  1915. geometryMaterials = object.geometry.materials;
  1916. vertices = geometry.vertices;
  1917. faces = geometry.faces;
  1918. faceVertexUvs = geometry.faceVertexUvs;
  1919. objectMatrixWorldRotation = object.matrixRotationWorld.extractRotation( objectMatrixWorld );
  1920. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  1921. _vertex = getNextVertexInPool();
  1922. _vertex.positionWorld.copy( vertices[ v ].position );
  1923. objectMatrixWorld.multiplyVector3( _vertex.positionWorld );
  1924. _vertex.positionScreen.copy( _vertex.positionWorld );
  1925. _projScreenMatrix.multiplyVector4( _vertex.positionScreen );
  1926. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  1927. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  1928. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  1929. }
  1930. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  1931. face = faces[ f ];
  1932. if ( face instanceof THREE.Face3 ) {
  1933. v1 = _vertexPool[ face.a ];
  1934. v2 = _vertexPool[ face.b ];
  1935. v3 = _vertexPool[ face.c ];
  1936. if ( v1.visible && v2.visible && v3.visible ) {
  1937. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  1938. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  1939. if ( object.doubleSided || visible != object.flipSided ) {
  1940. _face = getNextFace3InPool();
  1941. _face.v1.copy( v1 );
  1942. _face.v2.copy( v2 );
  1943. _face.v3.copy( v3 );
  1944. } else {
  1945. continue;
  1946. }
  1947. } else {
  1948. continue;
  1949. }
  1950. } else if ( face instanceof THREE.Face4 ) {
  1951. v1 = _vertexPool[ face.a ];
  1952. v2 = _vertexPool[ face.b ];
  1953. v3 = _vertexPool[ face.c ];
  1954. v4 = _vertexPool[ face.d ];
  1955. if ( v1.visible && v2.visible && v3.visible && v4.visible ) {
  1956. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  1957. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  1958. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  1959. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  1960. if ( object.doubleSided || visible != object.flipSided ) {
  1961. _face = getNextFace4InPool();
  1962. _face.v1.copy( v1 );
  1963. _face.v2.copy( v2 );
  1964. _face.v3.copy( v3 );
  1965. _face.v4.copy( v4 );
  1966. } else {
  1967. continue;
  1968. }
  1969. } else {
  1970. continue;
  1971. }
  1972. }
  1973. _face.normalWorld.copy( face.normal );
  1974. if ( !visible && ( object.flipSided || object.doubleSided ) ) _face.normalWorld.negate();
  1975. objectMatrixWorldRotation.multiplyVector3( _face.normalWorld );
  1976. _face.centroidWorld.copy( face.centroid );
  1977. objectMatrixWorld.multiplyVector3( _face.centroidWorld );
  1978. _face.centroidScreen.copy( _face.centroidWorld );
  1979. _projScreenMatrix.multiplyVector3( _face.centroidScreen );
  1980. faceVertexNormals = face.vertexNormals;
  1981. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  1982. normal = _face.vertexNormalsWorld[ n ];
  1983. normal.copy( faceVertexNormals[ n ] );
  1984. if ( !visible && ( object.flipSided || object.doubleSided ) ) normal.negate();
  1985. objectMatrixWorldRotation.multiplyVector3( normal );
  1986. }
  1987. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  1988. uvs = faceVertexUvs[ c ][ f ];
  1989. if ( !uvs ) continue;
  1990. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  1991. _face.uvs[ c ][ u ] = uvs[ u ];
  1992. }
  1993. }
  1994. _face.material = object.material;
  1995. _face.faceMaterial = face.materialIndex !== null ? geometryMaterials[ face.materialIndex ] : null;
  1996. _face.z = _face.centroidScreen.z;
  1997. _renderData.elements.push( _face );
  1998. }
  1999. } else if ( object instanceof THREE.Line ) {
  2000. _projScreenobjectMatrixWorld.multiply( _projScreenMatrix, objectMatrixWorld );
  2001. vertices = object.geometry.vertices;
  2002. v1 = getNextVertexInPool();
  2003. v1.positionScreen.copy( vertices[ 0 ].position );
  2004. _projScreenobjectMatrixWorld.multiplyVector4( v1.positionScreen );
  2005. // Handle LineStrip and LinePieces
  2006. var step = object.type === THREE.LinePieces ? 2 : 1;
  2007. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2008. v1 = getNextVertexInPool();
  2009. v1.positionScreen.copy( vertices[ v ].position );
  2010. _projScreenobjectMatrixWorld.multiplyVector4( v1.positionScreen );
  2011. if ( ( v + 1 ) % step > 0 ) continue;
  2012. v2 = _vertexPool[ _vertexCount - 2 ];
  2013. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2014. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2015. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) ) {
  2016. // Perform the perspective divide
  2017. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2018. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2019. _line = getNextLineInPool();
  2020. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2021. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2022. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2023. _line.material = object.material;
  2024. _renderData.elements.push( _line );
  2025. }
  2026. }
  2027. }
  2028. }
  2029. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2030. object = _renderData.sprites[ o ].object;
  2031. objectMatrixWorld = object.matrixWorld;
  2032. if ( object instanceof THREE.Particle ) {
  2033. _vector4.set( objectMatrixWorld.elements[12], objectMatrixWorld.elements[13], objectMatrixWorld.elements[14], 1 );
  2034. _projScreenMatrix.multiplyVector4( _vector4 );
  2035. _vector4.z /= _vector4.w;
  2036. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2037. _particle = getNextParticleInPool();
  2038. _particle.x = _vector4.x / _vector4.w;
  2039. _particle.y = _vector4.y / _vector4.w;
  2040. _particle.z = _vector4.z;
  2041. _particle.rotation = object.rotation.z;
  2042. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2043. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2044. _particle.material = object.material;
  2045. _renderData.elements.push( _particle );
  2046. }
  2047. }
  2048. }
  2049. sort && _renderData.elements.sort( painterSort );
  2050. return _renderData;
  2051. };
  2052. // Pools
  2053. function getNextObjectInPool() {
  2054. var object = _objectPool[ _objectCount ] = _objectPool[ _objectCount ] || new THREE.RenderableObject();
  2055. _objectCount ++;
  2056. return object;
  2057. }
  2058. function getNextVertexInPool() {
  2059. var vertex = _vertexPool[ _vertexCount ] = _vertexPool[ _vertexCount ] || new THREE.RenderableVertex();
  2060. _vertexCount ++;
  2061. return vertex;
  2062. }
  2063. function getNextFace3InPool() {
  2064. var face = _face3Pool[ _face3Count ] = _face3Pool[ _face3Count ] || new THREE.RenderableFace3();
  2065. _face3Count ++;
  2066. return face;
  2067. }
  2068. function getNextFace4InPool() {
  2069. var face = _face4Pool[ _face4Count ] = _face4Pool[ _face4Count ] || new THREE.RenderableFace4();
  2070. _face4Count ++;
  2071. return face;
  2072. }
  2073. function getNextLineInPool() {
  2074. var line = _linePool[ _lineCount ] = _linePool[ _lineCount ] || new THREE.RenderableLine();
  2075. _lineCount ++;
  2076. return line;
  2077. }
  2078. function getNextParticleInPool() {
  2079. var particle = _particlePool[ _particleCount ] = _particlePool[ _particleCount ] || new THREE.RenderableParticle();
  2080. _particleCount ++;
  2081. return particle;
  2082. }
  2083. //
  2084. function painterSort( a, b ) {
  2085. return b.z - a.z;
  2086. }
  2087. function clipLine( s1, s2 ) {
  2088. var alpha1 = 0, alpha2 = 1,
  2089. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2090. // Z = -1 and Z = +1, respectively.
  2091. bc1near = s1.z + s1.w,
  2092. bc2near = s2.z + s2.w,
  2093. bc1far = - s1.z + s1.w,
  2094. bc2far = - s2.z + s2.w;
  2095. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2096. // Both vertices lie entirely within all clip planes.
  2097. return true;
  2098. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2099. // Both vertices lie entirely outside one of the clip planes.
  2100. return false;
  2101. } else {
  2102. // The line segment spans at least one clip plane.
  2103. if ( bc1near < 0 ) {
  2104. // v1 lies outside the near plane, v2 inside
  2105. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2106. } else if ( bc2near < 0 ) {
  2107. // v2 lies outside the near plane, v1 inside
  2108. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2109. }
  2110. if ( bc1far < 0 ) {
  2111. // v1 lies outside the far plane, v2 inside
  2112. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2113. } else if ( bc2far < 0 ) {
  2114. // v2 lies outside the far plane, v2 inside
  2115. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2116. }
  2117. if ( alpha2 < alpha1 ) {
  2118. // The line segment spans two boundaries, but is outside both of them.
  2119. // (This can't happen when we're only clipping against just near/far but good
  2120. // to leave the check here for future usage if other clip planes are added.)
  2121. return false;
  2122. } else {
  2123. // Update the s1 and s2 vertices to match the clipped line segment.
  2124. s1.lerpSelf( s2, alpha1 );
  2125. s2.lerpSelf( s1, 1 - alpha2 );
  2126. return true;
  2127. }
  2128. }
  2129. }
  2130. };
  2131. /**
  2132. * @author mikael emtinger / http://gomo.se/
  2133. * @author alteredq / http://alteredqualia.com/
  2134. */
  2135. THREE.Quaternion = function( x, y, z, w ) {
  2136. this.x = x || 0;
  2137. this.y = y || 0;
  2138. this.z = z || 0;
  2139. this.w = ( w !== undefined ) ? w : 1;
  2140. };
  2141. THREE.Quaternion.prototype = {
  2142. constructor: THREE.Quaternion,
  2143. set: function ( x, y, z, w ) {
  2144. this.x = x;
  2145. this.y = y;
  2146. this.z = z;
  2147. this.w = w;
  2148. return this;
  2149. },
  2150. copy: function ( q ) {
  2151. this.x = q.x;
  2152. this.y = q.y;
  2153. this.z = q.z;
  2154. this.w = q.w;
  2155. return this;
  2156. },
  2157. setFromEuler: function ( vector ) {
  2158. var c = Math.PI / 360, // 0.5 * Math.PI / 360, // 0.5 is an optimization
  2159. x = vector.x * c,
  2160. y = vector.y * c,
  2161. z = vector.z * c,
  2162. c1 = Math.cos( y ),
  2163. s1 = Math.sin( y ),
  2164. c2 = Math.cos( -z ),
  2165. s2 = Math.sin( -z ),
  2166. c3 = Math.cos( x ),
  2167. s3 = Math.sin( x ),
  2168. c1c2 = c1 * c2,
  2169. s1s2 = s1 * s2;
  2170. this.w = c1c2 * c3 - s1s2 * s3;
  2171. this.x = c1c2 * s3 + s1s2 * c3;
  2172. this.y = s1 * c2 * c3 + c1 * s2 * s3;
  2173. this.z = c1 * s2 * c3 - s1 * c2 * s3;
  2174. return this;
  2175. },
  2176. setFromAxisAngle: function ( axis, angle ) {
  2177. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2178. // axis have to be normalized
  2179. var halfAngle = angle / 2,
  2180. s = Math.sin( halfAngle );
  2181. this.x = axis.x * s;
  2182. this.y = axis.y * s;
  2183. this.z = axis.z * s;
  2184. this.w = Math.cos( halfAngle );
  2185. return this;
  2186. },
  2187. setFromRotationMatrix: function ( m ) {
  2188. // Adapted from: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2189. function copySign( a, b ) {
  2190. return b < 0 ? -Math.abs( a ) : Math.abs( a );
  2191. }
  2192. var absQ = Math.pow( m.determinant(), 1.0 / 3.0 );
  2193. this.w = Math.sqrt( Math.max( 0, absQ + m.elements[0] + m.elements[5] + m.elements[10] ) ) / 2;
  2194. this.x = Math.sqrt( Math.max( 0, absQ + m.elements[0] - m.elements[5] - m.elements[10] ) ) / 2;
  2195. this.y = Math.sqrt( Math.max( 0, absQ - m.elements[0] + m.elements[5] - m.elements[10] ) ) / 2;
  2196. this.z = Math.sqrt( Math.max( 0, absQ - m.elements[0] - m.elements[5] + m.elements[10] ) ) / 2;
  2197. this.x = copySign( this.x, ( m.elements[6] - m.elements[9] ) );
  2198. this.y = copySign( this.y, ( m.elements[8] - m.elements[2] ) );
  2199. this.z = copySign( this.z, ( m.elements[1] - m.elements[4] ) );
  2200. this.normalize();
  2201. return this;
  2202. },
  2203. calculateW : function () {
  2204. this.w = - Math.sqrt( Math.abs( 1.0 - this.x * this.x - this.y * this.y - this.z * this.z ) );
  2205. return this;
  2206. },
  2207. inverse: function () {
  2208. this.x *= -1;
  2209. this.y *= -1;
  2210. this.z *= -1;
  2211. return this;
  2212. },
  2213. length: function () {
  2214. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2215. },
  2216. normalize: function () {
  2217. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2218. if ( l === 0 ) {
  2219. this.x = 0;
  2220. this.y = 0;
  2221. this.z = 0;
  2222. this.w = 0;
  2223. } else {
  2224. l = 1 / l;
  2225. this.x = this.x * l;
  2226. this.y = this.y * l;
  2227. this.z = this.z * l;
  2228. this.w = this.w * l;
  2229. }
  2230. return this;
  2231. },
  2232. multiply: function ( a, b ) {
  2233. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2234. this.x = a.x * b.w + a.y * b.z - a.z * b.y + a.w * b.x;
  2235. this.y = -a.x * b.z + a.y * b.w + a.z * b.x + a.w * b.y;
  2236. this.z = a.x * b.y - a.y * b.x + a.z * b.w + a.w * b.z;
  2237. this.w = -a.x * b.x - a.y * b.y - a.z * b.z + a.w * b.w;
  2238. return this;
  2239. },
  2240. multiplySelf: function ( b ) {
  2241. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2242. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2243. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2244. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2245. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2246. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2247. return this;
  2248. },
  2249. multiplyVector3: function ( vector, dest ) {
  2250. if ( !dest ) { dest = vector; }
  2251. var x = vector.x, y = vector.y, z = vector.z,
  2252. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2253. // calculate quat * vector
  2254. var ix = qw * x + qy * z - qz * y,
  2255. iy = qw * y + qz * x - qx * z,
  2256. iz = qw * z + qx * y - qy * x,
  2257. iw = -qx * x - qy * y - qz * z;
  2258. // calculate result * inverse quat
  2259. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2260. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2261. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2262. return dest;
  2263. },
  2264. clone: function () {
  2265. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2266. }
  2267. }
  2268. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2269. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2270. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2271. if (cosHalfTheta < 0) {
  2272. qm.w = -qb.w; qm.x = -qb.x; qm.y = -qb.y; qm.z = -qb.z;
  2273. cosHalfTheta = -cosHalfTheta;
  2274. } else {
  2275. qm.copy(qb);
  2276. }
  2277. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2278. qm.w = qa.w; qm.x = qa.x; qm.y = qa.y; qm.z = qa.z;
  2279. return qm;
  2280. }
  2281. var halfTheta = Math.acos( cosHalfTheta ),
  2282. sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2283. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2284. qm.w = 0.5 * ( qa.w + qb.w );
  2285. qm.x = 0.5 * ( qa.x + qb.x );
  2286. qm.y = 0.5 * ( qa.y + qb.y );
  2287. qm.z = 0.5 * ( qa.z + qb.z );
  2288. return qm;
  2289. }
  2290. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2291. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2292. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2293. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2294. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2295. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2296. return qm;
  2297. }
  2298. /**
  2299. * @author mr.doob / http://mrdoob.com/
  2300. */
  2301. THREE.Vertex = function ( position ) {
  2302. this.position = position || new THREE.Vector3();
  2303. };
  2304. THREE.Vertex.prototype = {
  2305. constructor: THREE.Vertex,
  2306. clone: function () {
  2307. return new THREE.Vertex( this.position.clone() );
  2308. }
  2309. };
  2310. /**
  2311. * @author mr.doob / http://mrdoob.com/
  2312. * @author alteredq / http://alteredqualia.com/
  2313. */
  2314. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2315. this.a = a;
  2316. this.b = b;
  2317. this.c = c;
  2318. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2319. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2320. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2321. this.vertexColors = color instanceof Array ? color : [];
  2322. this.vertexTangents = [];
  2323. this.materialIndex = materialIndex;
  2324. this.centroid = new THREE.Vector3();
  2325. };
  2326. THREE.Face3.prototype = {
  2327. constructor: THREE.Face3,
  2328. clone: function () {
  2329. var face = new THREE.Face3( this.a, this.b, this.c );
  2330. face.normal.copy( this.normal );
  2331. face.color.copy( this.color );
  2332. face.centroid.copy( this.centroid );
  2333. face.materialIndex = this.materialIndex;
  2334. var i, il;
  2335. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2336. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2337. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2338. return face;
  2339. }
  2340. };
  2341. /**
  2342. * @author mr.doob / http://mrdoob.com/
  2343. * @author alteredq / http://alteredqualia.com/
  2344. */
  2345. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2346. this.a = a;
  2347. this.b = b;
  2348. this.c = c;
  2349. this.d = d;
  2350. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2351. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2352. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2353. this.vertexColors = color instanceof Array ? color : [];
  2354. this.vertexTangents = [];
  2355. this.materialIndex = materialIndex;
  2356. this.centroid = new THREE.Vector3();
  2357. };
  2358. THREE.Face4.prototype = {
  2359. constructor: THREE.Face4,
  2360. clone: function () {
  2361. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  2362. face.normal.copy( this.normal );
  2363. face.color.copy( this.color );
  2364. face.centroid.copy( this.centroid );
  2365. face.materialIndex = this.materialIndex;
  2366. var i, il;
  2367. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2368. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2369. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2370. return face;
  2371. }
  2372. };
  2373. /**
  2374. * @author mr.doob / http://mrdoob.com/
  2375. */
  2376. THREE.UV = function ( u, v ) {
  2377. this.u = u || 0;
  2378. this.v = v || 0;
  2379. };
  2380. THREE.UV.prototype = {
  2381. constructor: THREE.UV,
  2382. set: function ( u, v ) {
  2383. this.u = u;
  2384. this.v = v;
  2385. return this;
  2386. },
  2387. copy: function ( uv ) {
  2388. this.u = uv.u;
  2389. this.v = uv.v;
  2390. return this;
  2391. },
  2392. lerpSelf: function ( uv, alpha ) {
  2393. this.u += ( uv.u - this.u ) * alpha;
  2394. this.v += ( uv.v - this.v ) * alpha;
  2395. return this;
  2396. },
  2397. clone: function () {
  2398. return new THREE.UV( this.u, this.v );
  2399. }
  2400. };
  2401. /**
  2402. * @author mr.doob / http://mrdoob.com/
  2403. * @author kile / http://kile.stravaganza.org/
  2404. * @author alteredq / http://alteredqualia.com/
  2405. * @author mikael emtinger / http://gomo.se/
  2406. * @author zz85 / http://www.lab4games.net/zz85/blog
  2407. */
  2408. THREE.Geometry = function () {
  2409. this.id = THREE.GeometryCount ++;
  2410. this.vertices = [];
  2411. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  2412. this.materials = [];
  2413. this.faces = [];
  2414. this.faceUvs = [[]];
  2415. this.faceVertexUvs = [[]];
  2416. this.morphTargets = [];
  2417. this.morphColors = [];
  2418. this.morphNormals = [];
  2419. this.skinWeights = [];
  2420. this.skinIndices = [];
  2421. this.boundingBox = null;
  2422. this.boundingSphere = null;
  2423. this.hasTangents = false;
  2424. this.dynamic = false; // unless set to true the *Arrays will be deleted once sent to a buffer.
  2425. };
  2426. THREE.Geometry.prototype = {
  2427. constructor : THREE.Geometry,
  2428. applyMatrix: function ( matrix ) {
  2429. var matrixRotation = new THREE.Matrix4();
  2430. matrixRotation.extractRotation( matrix );
  2431. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  2432. var vertex = this.vertices[ i ];
  2433. matrix.multiplyVector3( vertex.position );
  2434. }
  2435. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  2436. var face = this.faces[ i ];
  2437. matrixRotation.multiplyVector3( face.normal );
  2438. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  2439. matrixRotation.multiplyVector3( face.vertexNormals[ j ] );
  2440. }
  2441. matrix.multiplyVector3( face.centroid );
  2442. }
  2443. },
  2444. computeCentroids: function () {
  2445. var f, fl, face;
  2446. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2447. face = this.faces[ f ];
  2448. face.centroid.set( 0, 0, 0 );
  2449. if ( face instanceof THREE.Face3 ) {
  2450. face.centroid.addSelf( this.vertices[ face.a ].position );
  2451. face.centroid.addSelf( this.vertices[ face.b ].position );
  2452. face.centroid.addSelf( this.vertices[ face.c ].position );
  2453. face.centroid.divideScalar( 3 );
  2454. } else if ( face instanceof THREE.Face4 ) {
  2455. face.centroid.addSelf( this.vertices[ face.a ].position );
  2456. face.centroid.addSelf( this.vertices[ face.b ].position );
  2457. face.centroid.addSelf( this.vertices[ face.c ].position );
  2458. face.centroid.addSelf( this.vertices[ face.d ].position );
  2459. face.centroid.divideScalar( 4 );
  2460. }
  2461. }
  2462. },
  2463. computeFaceNormals: function () {
  2464. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  2465. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  2466. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2467. face = this.faces[ f ];
  2468. vA = this.vertices[ face.a ];
  2469. vB = this.vertices[ face.b ];
  2470. vC = this.vertices[ face.c ];
  2471. cb.sub( vC.position, vB.position );
  2472. ab.sub( vA.position, vB.position );
  2473. cb.crossSelf( ab );
  2474. if ( !cb.isZero() ) {
  2475. cb.normalize();
  2476. }
  2477. face.normal.copy( cb );
  2478. }
  2479. },
  2480. computeVertexNormals: function () {
  2481. var v, vl, f, fl, face, vertices;
  2482. // create internal buffers for reuse when calling this method repeatedly
  2483. // (otherwise memory allocation / deallocation every frame is big resource hog)
  2484. if ( this.__tmpVertices === undefined ) {
  2485. this.__tmpVertices = new Array( this.vertices.length );
  2486. vertices = this.__tmpVertices;
  2487. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2488. vertices[ v ] = new THREE.Vector3();
  2489. }
  2490. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2491. face = this.faces[ f ];
  2492. if ( face instanceof THREE.Face3 ) {
  2493. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2494. } else if ( face instanceof THREE.Face4 ) {
  2495. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2496. }
  2497. }
  2498. } else {
  2499. vertices = this.__tmpVertices;
  2500. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2501. vertices[ v ].set( 0, 0, 0 );
  2502. }
  2503. }
  2504. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2505. face = this.faces[ f ];
  2506. if ( face instanceof THREE.Face3 ) {
  2507. vertices[ face.a ].addSelf( face.normal );
  2508. vertices[ face.b ].addSelf( face.normal );
  2509. vertices[ face.c ].addSelf( face.normal );
  2510. } else if ( face instanceof THREE.Face4 ) {
  2511. vertices[ face.a ].addSelf( face.normal );
  2512. vertices[ face.b ].addSelf( face.normal );
  2513. vertices[ face.c ].addSelf( face.normal );
  2514. vertices[ face.d ].addSelf( face.normal );
  2515. }
  2516. }
  2517. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2518. vertices[ v ].normalize();
  2519. }
  2520. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2521. face = this.faces[ f ];
  2522. if ( face instanceof THREE.Face3 ) {
  2523. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  2524. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  2525. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  2526. } else if ( face instanceof THREE.Face4 ) {
  2527. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  2528. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  2529. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  2530. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  2531. }
  2532. }
  2533. },
  2534. computeMorphNormals: function () {
  2535. var i, il, f, fl, face;
  2536. // save original normals
  2537. // - create temp variables on first access
  2538. // otherwise just copy (for faster repeated calls)
  2539. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2540. face = this.faces[ f ];
  2541. if ( ! face.__originalFaceNormal ) {
  2542. face.__originalFaceNormal = face.normal.clone();
  2543. } else {
  2544. face.__originalFaceNormal.copy( face.normal );
  2545. }
  2546. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  2547. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  2548. if ( ! face.__originalVertexNormals[ i ] ) {
  2549. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  2550. } else {
  2551. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  2552. }
  2553. }
  2554. }
  2555. // use temp geometry to compute face and vertex normals for each morph
  2556. var tmpGeo = new THREE.Geometry();
  2557. tmpGeo.faces = this.faces;
  2558. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  2559. // create on first access
  2560. if ( ! this.morphNormals[ i ] ) {
  2561. this.morphNormals[ i ] = {};
  2562. this.morphNormals[ i ].faceNormals = [];
  2563. this.morphNormals[ i ].vertexNormals = [];
  2564. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  2565. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  2566. var faceNormal, vertexNormals;
  2567. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2568. face = this.faces[ f ];
  2569. faceNormal = new THREE.Vector3();
  2570. if ( face instanceof THREE.Face3 ) {
  2571. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  2572. } else {
  2573. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  2574. }
  2575. dstNormalsFace.push( faceNormal );
  2576. dstNormalsVertex.push( vertexNormals );
  2577. }
  2578. }
  2579. var morphNormals = this.morphNormals[ i ];
  2580. // set vertices to morph target
  2581. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  2582. // compute morph normals
  2583. tmpGeo.computeFaceNormals();
  2584. tmpGeo.computeVertexNormals();
  2585. // store morph normals
  2586. var faceNormal, vertexNormals;
  2587. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2588. face = this.faces[ f ];
  2589. faceNormal = morphNormals.faceNormals[ f ];
  2590. vertexNormals = morphNormals.vertexNormals[ f ];
  2591. faceNormal.copy( face.normal );
  2592. if ( face instanceof THREE.Face3 ) {
  2593. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  2594. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  2595. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  2596. } else {
  2597. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  2598. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  2599. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  2600. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  2601. }
  2602. }
  2603. }
  2604. // restore original normals
  2605. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2606. face = this.faces[ f ];
  2607. face.normal = face.__originalFaceNormal;
  2608. face.vertexNormals = face.__originalVertexNormals;
  2609. }
  2610. },
  2611. computeTangents: function () {
  2612. // based on http://www.terathon.com/code/tangent.html
  2613. // tangents go to vertices
  2614. var f, fl, v, vl, i, il, vertexIndex,
  2615. face, uv, vA, vB, vC, uvA, uvB, uvC,
  2616. x1, x2, y1, y2, z1, z2,
  2617. s1, s2, t1, t2, r, t, test,
  2618. tan1 = [], tan2 = [],
  2619. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  2620. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  2621. n = new THREE.Vector3(), w;
  2622. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2623. tan1[ v ] = new THREE.Vector3();
  2624. tan2[ v ] = new THREE.Vector3();
  2625. }
  2626. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  2627. vA = context.vertices[ a ].position;
  2628. vB = context.vertices[ b ].position;
  2629. vC = context.vertices[ c ].position;
  2630. uvA = uv[ ua ];
  2631. uvB = uv[ ub ];
  2632. uvC = uv[ uc ];
  2633. x1 = vB.x - vA.x;
  2634. x2 = vC.x - vA.x;
  2635. y1 = vB.y - vA.y;
  2636. y2 = vC.y - vA.y;
  2637. z1 = vB.z - vA.z;
  2638. z2 = vC.z - vA.z;
  2639. s1 = uvB.u - uvA.u;
  2640. s2 = uvC.u - uvA.u;
  2641. t1 = uvB.v - uvA.v;
  2642. t2 = uvC.v - uvA.v;
  2643. r = 1.0 / ( s1 * t2 - s2 * t1 );
  2644. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  2645. ( t2 * y1 - t1 * y2 ) * r,
  2646. ( t2 * z1 - t1 * z2 ) * r );
  2647. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  2648. ( s1 * y2 - s2 * y1 ) * r,
  2649. ( s1 * z2 - s2 * z1 ) * r );
  2650. tan1[ a ].addSelf( sdir );
  2651. tan1[ b ].addSelf( sdir );
  2652. tan1[ c ].addSelf( sdir );
  2653. tan2[ a ].addSelf( tdir );
  2654. tan2[ b ].addSelf( tdir );
  2655. tan2[ c ].addSelf( tdir );
  2656. }
  2657. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2658. face = this.faces[ f ];
  2659. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  2660. if ( face instanceof THREE.Face3 ) {
  2661. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  2662. } else if ( face instanceof THREE.Face4 ) {
  2663. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  2664. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  2665. }
  2666. }
  2667. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  2668. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2669. face = this.faces[ f ];
  2670. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  2671. n.copy( face.vertexNormals[ i ] );
  2672. vertexIndex = face[ faceIndex[ i ] ];
  2673. t = tan1[ vertexIndex ];
  2674. // Gram-Schmidt orthogonalize
  2675. tmp.copy( t );
  2676. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  2677. // Calculate handedness
  2678. tmp2.cross( face.vertexNormals[ i ], t );
  2679. test = tmp2.dot( tan2[ vertexIndex ] );
  2680. w = (test < 0.0) ? -1.0 : 1.0;
  2681. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  2682. }
  2683. }
  2684. this.hasTangents = true;
  2685. },
  2686. computeBoundingBox: function () {
  2687. if ( ! this.boundingBox ) {
  2688. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  2689. }
  2690. if ( this.vertices.length > 0 ) {
  2691. var position, firstPosition = this.vertices[ 0 ].position;
  2692. this.boundingBox.min.copy( firstPosition );
  2693. this.boundingBox.max.copy( firstPosition );
  2694. var min = this.boundingBox.min,
  2695. max = this.boundingBox.max;
  2696. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  2697. position = this.vertices[ v ].position;
  2698. if ( position.x < min.x ) {
  2699. min.x = position.x;
  2700. } else if ( position.x > max.x ) {
  2701. max.x = position.x;
  2702. }
  2703. if ( position.y < min.y ) {
  2704. min.y = position.y;
  2705. } else if ( position.y > max.y ) {
  2706. max.y = position.y;
  2707. }
  2708. if ( position.z < min.z ) {
  2709. min.z = position.z;
  2710. } else if ( position.z > max.z ) {
  2711. max.z = position.z;
  2712. }
  2713. }
  2714. } else {
  2715. this.boundingBox.min.set( 0, 0, 0 );
  2716. this.boundingBox.max.set( 0, 0, 0 );
  2717. }
  2718. },
  2719. computeBoundingSphere: function () {
  2720. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  2721. var radius, maxRadius = 0;
  2722. for ( var v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2723. radius = this.vertices[ v ].position.length();
  2724. if ( radius > maxRadius ) maxRadius = radius;
  2725. }
  2726. this.boundingSphere.radius = maxRadius;
  2727. },
  2728. /*
  2729. * Checks for duplicate vertices with hashmap.
  2730. * Duplicated vertices are removed
  2731. * and faces' vertices are updated.
  2732. */
  2733. mergeVertices: function() {
  2734. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  2735. var unique = [], changes = [];
  2736. var v, key;
  2737. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  2738. var precision = Math.pow( 10, precisionPoints );
  2739. var i,il, face;
  2740. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  2741. v = this.vertices[ i ].position;
  2742. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  2743. if ( verticesMap[ key ] === undefined ) {
  2744. verticesMap[ key ] = i;
  2745. unique.push( this.vertices[ i ] );
  2746. changes[ i ] = unique.length - 1;
  2747. } else {
  2748. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  2749. changes[ i ] = changes[ verticesMap[ key ] ];
  2750. }
  2751. };
  2752. // Start to patch face indices
  2753. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  2754. face = this.faces[ i ];
  2755. if ( face instanceof THREE.Face3 ) {
  2756. face.a = changes[ face.a ];
  2757. face.b = changes[ face.b ];
  2758. face.c = changes[ face.c ];
  2759. } else if ( face instanceof THREE.Face4 ) {
  2760. face.a = changes[ face.a ];
  2761. face.b = changes[ face.b ];
  2762. face.c = changes[ face.c ];
  2763. face.d = changes[ face.d ];
  2764. }
  2765. }
  2766. // Use unique set of vertices
  2767. this.vertices = unique;
  2768. }
  2769. };
  2770. THREE.GeometryCount = 0;
  2771. /**
  2772. * Spline from Tween.js, slightly optimized (and trashed)
  2773. * http://sole.github.com/tween.js/examples/05_spline.html
  2774. *
  2775. * @author mrdoob / http://mrdoob.com/
  2776. * @author alteredq / http://alteredqualia.com/
  2777. */
  2778. THREE.Spline = function ( points ) {
  2779. this.points = points;
  2780. var c = [], v3 = { x: 0, y: 0, z: 0 },
  2781. point, intPoint, weight, w2, w3,
  2782. pa, pb, pc, pd;
  2783. this.initFromArray = function( a ) {
  2784. this.points = [];
  2785. for ( var i = 0; i < a.length; i++ ) {
  2786. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  2787. }
  2788. };
  2789. this.getPoint = function ( k ) {
  2790. point = ( this.points.length - 1 ) * k;
  2791. intPoint = Math.floor( point );
  2792. weight = point - intPoint;
  2793. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  2794. c[ 1 ] = intPoint;
  2795. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  2796. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  2797. pa = this.points[ c[ 0 ] ];
  2798. pb = this.points[ c[ 1 ] ];
  2799. pc = this.points[ c[ 2 ] ];
  2800. pd = this.points[ c[ 3 ] ];
  2801. w2 = weight * weight;
  2802. w3 = weight * w2;
  2803. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  2804. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  2805. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  2806. return v3;
  2807. };
  2808. this.getControlPointsArray = function () {
  2809. var i, p, l = this.points.length,
  2810. coords = [];
  2811. for ( i = 0; i < l; i ++ ) {
  2812. p = this.points[ i ];
  2813. coords[ i ] = [ p.x, p.y, p.z ];
  2814. }
  2815. return coords;
  2816. };
  2817. // approximate length by summing linear segments
  2818. this.getLength = function ( nSubDivisions ) {
  2819. var i, index, nSamples, position,
  2820. point = 0, intPoint = 0, oldIntPoint = 0,
  2821. oldPosition = new THREE.Vector3(),
  2822. tmpVec = new THREE.Vector3(),
  2823. chunkLengths = [],
  2824. totalLength = 0;
  2825. // first point has 0 length
  2826. chunkLengths[ 0 ] = 0;
  2827. if ( !nSubDivisions ) nSubDivisions = 100;
  2828. nSamples = this.points.length * nSubDivisions;
  2829. oldPosition.copy( this.points[ 0 ] );
  2830. for ( i = 1; i < nSamples; i ++ ) {
  2831. index = i / nSamples;
  2832. position = this.getPoint( index );
  2833. tmpVec.copy( position );
  2834. totalLength += tmpVec.distanceTo( oldPosition );
  2835. oldPosition.copy( position );
  2836. point = ( this.points.length - 1 ) * index;
  2837. intPoint = Math.floor( point );
  2838. if ( intPoint != oldIntPoint ) {
  2839. chunkLengths[ intPoint ] = totalLength;
  2840. oldIntPoint = intPoint;
  2841. }
  2842. }
  2843. // last point ends with total length
  2844. chunkLengths[ chunkLengths.length ] = totalLength;
  2845. return { chunks: chunkLengths, total: totalLength };
  2846. };
  2847. this.reparametrizeByArcLength = function ( samplingCoef ) {
  2848. var i, j,
  2849. index, indexCurrent, indexNext,
  2850. linearDistance, realDistance,
  2851. sampling, position,
  2852. newpoints = [],
  2853. tmpVec = new THREE.Vector3(),
  2854. sl = this.getLength();
  2855. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  2856. for ( i = 1; i < this.points.length; i++ ) {
  2857. //tmpVec.copy( this.points[ i - 1 ] );
  2858. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  2859. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  2860. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  2861. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  2862. indexNext = i / ( this.points.length - 1 );
  2863. for ( j = 1; j < sampling - 1; j++ ) {
  2864. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  2865. position = this.getPoint( index );
  2866. newpoints.push( tmpVec.copy( position ).clone() );
  2867. }
  2868. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  2869. }
  2870. this.points = newpoints;
  2871. };
  2872. // Catmull-Rom
  2873. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  2874. var v0 = ( p2 - p0 ) * 0.5,
  2875. v1 = ( p3 - p1 ) * 0.5;
  2876. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  2877. };
  2878. };
  2879. /**
  2880. * @author mr.doob / http://mrdoob.com/
  2881. * @author mikael emtinger / http://gomo.se/
  2882. */
  2883. THREE.Camera = function () {
  2884. THREE.Object3D.call( this );
  2885. this.matrixWorldInverse = new THREE.Matrix4();
  2886. this.projectionMatrix = new THREE.Matrix4();
  2887. this.projectionMatrixInverse = new THREE.Matrix4();
  2888. };
  2889. THREE.Camera.prototype = new THREE.Object3D();
  2890. THREE.Camera.prototype.constructor = THREE.Camera;
  2891. THREE.Camera.prototype.lookAt = function ( vector ) {
  2892. // TODO: Add hierarchy support.
  2893. this.matrix.lookAt( this.position, vector, this.up );
  2894. if ( this.rotationAutoUpdate ) {
  2895. this.rotation.getRotationFromMatrix( this.matrix );
  2896. }
  2897. };
  2898. /**
  2899. * @author alteredq / http://alteredqualia.com/
  2900. */
  2901. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  2902. THREE.Camera.call( this );
  2903. this.left = left;
  2904. this.right = right;
  2905. this.top = top;
  2906. this.bottom = bottom;
  2907. this.near = ( near !== undefined ) ? near : 0.1;
  2908. this.far = ( far !== undefined ) ? far : 2000;
  2909. this.updateProjectionMatrix();
  2910. };
  2911. THREE.OrthographicCamera.prototype = new THREE.Camera();
  2912. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  2913. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  2914. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  2915. };
  2916. /**
  2917. * @author mr.doob / http://mrdoob.com/
  2918. * @author greggman / http://games.greggman.com/
  2919. * @author zz85 / http://www.lab4games.net/zz85/blog
  2920. */
  2921. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  2922. THREE.Camera.call( this );
  2923. this.fov = fov !== undefined ? fov : 50;
  2924. this.aspect = aspect !== undefined ? aspect : 1;
  2925. this.near = near !== undefined ? near : 0.1;
  2926. this.far = far !== undefined ? far : 2000;
  2927. this.updateProjectionMatrix();
  2928. };
  2929. THREE.PerspectiveCamera.prototype = new THREE.Camera();
  2930. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  2931. /**
  2932. * Uses Focal Length (in mm) to estimate and set FOV
  2933. * 35mm (fullframe) camera is used if frame size is not specified;
  2934. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  2935. */
  2936. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  2937. frameHeight = frameHeight !== undefined ? frameHeight : 24;
  2938. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  2939. this.updateProjectionMatrix();
  2940. }
  2941. /**
  2942. * Sets an offset in a larger frustum. This is useful for multi-window or
  2943. * multi-monitor/multi-machine setups.
  2944. *
  2945. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  2946. * the monitors are in grid like this
  2947. *
  2948. * +---+---+---+
  2949. * | A | B | C |
  2950. * +---+---+---+
  2951. * | D | E | F |
  2952. * +---+---+---+
  2953. *
  2954. * then for each monitor you would call it like this
  2955. *
  2956. * var w = 1920;
  2957. * var h = 1080;
  2958. * var fullWidth = w * 3;
  2959. * var fullHeight = h * 2;
  2960. *
  2961. * --A--
  2962. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  2963. * --B--
  2964. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  2965. * --C--
  2966. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  2967. * --D--
  2968. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  2969. * --E--
  2970. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  2971. * --F--
  2972. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  2973. *
  2974. * Note there is no reason monitors have to be the same size or in a grid.
  2975. */
  2976. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  2977. this.fullWidth = fullWidth;
  2978. this.fullHeight = fullHeight;
  2979. this.x = x;
  2980. this.y = y;
  2981. this.width = width;
  2982. this.height = height;
  2983. this.updateProjectionMatrix();
  2984. };
  2985. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  2986. if ( this.fullWidth ) {
  2987. var aspect = this.fullWidth / this.fullHeight;
  2988. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  2989. var bottom = -top;
  2990. var left = aspect * bottom;
  2991. var right = aspect * top;
  2992. var width = Math.abs( right - left );
  2993. var height = Math.abs( top - bottom );
  2994. this.projectionMatrix.makeFrustum(
  2995. left + this.x * width / this.fullWidth,
  2996. left + ( this.x + this.width ) * width / this.fullWidth,
  2997. top - ( this.y + this.height ) * height / this.fullHeight,
  2998. top - this.y * height / this.fullHeight,
  2999. this.near,
  3000. this.far
  3001. );
  3002. } else {
  3003. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  3004. }
  3005. };
  3006. /**
  3007. * @author mr.doob / http://mrdoob.com/
  3008. * @author alteredq / http://alteredqualia.com/
  3009. */
  3010. THREE.Light = function ( hex ) {
  3011. THREE.Object3D.call( this );
  3012. this.color = new THREE.Color( hex );
  3013. };
  3014. THREE.Light.prototype = new THREE.Object3D();
  3015. THREE.Light.prototype.constructor = THREE.Light;
  3016. THREE.Light.prototype.supr = THREE.Object3D.prototype;
  3017. /**
  3018. * @author mr.doob / http://mrdoob.com/
  3019. */
  3020. THREE.AmbientLight = function ( hex ) {
  3021. THREE.Light.call( this, hex );
  3022. };
  3023. THREE.AmbientLight.prototype = new THREE.Light();
  3024. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  3025. /**
  3026. * @author mr.doob / http://mrdoob.com/
  3027. * @author alteredq / http://alteredqualia.com/
  3028. */
  3029. THREE.DirectionalLight = function ( hex, intensity, distance ) {
  3030. THREE.Light.call( this, hex );
  3031. this.position = new THREE.Vector3( 0, 1, 0 );
  3032. this.target = new THREE.Object3D();
  3033. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3034. this.distance = ( distance !== undefined ) ? distance : 0;
  3035. this.castShadow = false;
  3036. this.onlyShadow = false;
  3037. //
  3038. this.shadowCameraNear = 50;
  3039. this.shadowCameraFar = 5000;
  3040. this.shadowCameraLeft = -500;
  3041. this.shadowCameraRight = 500;
  3042. this.shadowCameraTop = 500;
  3043. this.shadowCameraBottom = -500;
  3044. this.shadowCameraVisible = false;
  3045. this.shadowBias = 0;
  3046. this.shadowDarkness = 0.5;
  3047. this.shadowMapWidth = 512;
  3048. this.shadowMapHeight = 512;
  3049. //
  3050. this.shadowCascade = false;
  3051. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  3052. this.shadowCascadeCount = 2;
  3053. this.shadowCascadeBias = [ 0, 0, 0 ];
  3054. this.shadowCascadeWidth = [ 512, 512, 512 ];
  3055. this.shadowCascadeHeight = [ 512, 512, 512 ];
  3056. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  3057. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  3058. this.shadowCascadeArray = [];
  3059. //
  3060. this.shadowMap = null;
  3061. this.shadowMapSize = null;
  3062. this.shadowCamera = null;
  3063. this.shadowMatrix = null;
  3064. };
  3065. THREE.DirectionalLight.prototype = new THREE.Light();
  3066. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  3067. /**
  3068. * @author mr.doob / http://mrdoob.com/
  3069. */
  3070. THREE.PointLight = function ( hex, intensity, distance ) {
  3071. THREE.Light.call( this, hex );
  3072. this.position = new THREE.Vector3( 0, 0, 0 );
  3073. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3074. this.distance = ( distance !== undefined ) ? distance : 0;
  3075. };
  3076. THREE.PointLight.prototype = new THREE.Light();
  3077. THREE.PointLight.prototype.constructor = THREE.PointLight;
  3078. /**
  3079. * @author alteredq / http://alteredqualia.com/
  3080. */
  3081. THREE.SpotLight = function ( hex, intensity, distance ) {
  3082. THREE.Light.call( this, hex );
  3083. this.position = new THREE.Vector3( 0, 1, 0 );
  3084. this.target = new THREE.Object3D();
  3085. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3086. this.distance = ( distance !== undefined ) ? distance : 0;
  3087. this.castShadow = false;
  3088. this.onlyShadow = false;
  3089. //
  3090. this.shadowCameraNear = 50;
  3091. this.shadowCameraFar = 5000;
  3092. this.shadowCameraFov = 50;
  3093. this.shadowCameraVisible = false;
  3094. this.shadowBias = 0;
  3095. this.shadowDarkness = 0.5;
  3096. this.shadowMapWidth = 512;
  3097. this.shadowMapHeight = 512;
  3098. //
  3099. this.shadowMap = null;
  3100. this.shadowMapSize = null;
  3101. this.shadowCamera = null;
  3102. this.shadowMatrix = null;
  3103. };
  3104. THREE.SpotLight.prototype = new THREE.Light();
  3105. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  3106. /**
  3107. * @author mr.doob / http://mrdoob.com/
  3108. * @author alteredq / http://alteredqualia.com/
  3109. */
  3110. THREE.Material = function ( parameters ) {
  3111. parameters = parameters || {};
  3112. this.id = THREE.MaterialCount ++;
  3113. this.name = '';
  3114. this.opacity = parameters.opacity !== undefined ? parameters.opacity : 1;
  3115. this.transparent = parameters.transparent !== undefined ? parameters.transparent : false;
  3116. this.blending = parameters.blending !== undefined ? parameters.blending : THREE.NormalBlending;
  3117. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  3118. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  3119. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  3120. this.depthTest = parameters.depthTest !== undefined ? parameters.depthTest : true;
  3121. this.depthWrite = parameters.depthWrite !== undefined ? parameters.depthWrite : true;
  3122. this.polygonOffset = parameters.polygonOffset !== undefined ? parameters.polygonOffset : false;
  3123. this.polygonOffsetFactor = parameters.polygonOffsetFactor !== undefined ? parameters.polygonOffsetFactor : 0;
  3124. this.polygonOffsetUnits = parameters.polygonOffsetUnits !== undefined ? parameters.polygonOffsetUnits : 0;
  3125. this.alphaTest = parameters.alphaTest !== undefined ? parameters.alphaTest : 0;
  3126. this.overdraw = parameters.overdraw !== undefined ? parameters.overdraw : false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  3127. this.needsUpdate = true;
  3128. }
  3129. THREE.MaterialCount = 0;
  3130. // shading
  3131. THREE.NoShading = 0;
  3132. THREE.FlatShading = 1;
  3133. THREE.SmoothShading = 2;
  3134. // colors
  3135. THREE.NoColors = 0;
  3136. THREE.FaceColors = 1;
  3137. THREE.VertexColors = 2;
  3138. // blending modes
  3139. THREE.NoBlending = 0;
  3140. THREE.NormalBlending = 1;
  3141. THREE.AdditiveBlending = 2;
  3142. THREE.SubtractiveBlending = 3;
  3143. THREE.MultiplyBlending = 4;
  3144. THREE.AdditiveAlphaBlending = 5;
  3145. THREE.CustomBlending = 6;
  3146. // custom blending equations
  3147. // (numbers start from 100 not to clash with other
  3148. // mappings to OpenGL constants defined in Texture.js)
  3149. THREE.AddEquation = 100;
  3150. THREE.SubtractEquation = 101;
  3151. THREE.ReverseSubtractEquation = 102;
  3152. // custom blending destination factors
  3153. THREE.ZeroFactor = 200;
  3154. THREE.OneFactor = 201;
  3155. THREE.SrcColorFactor = 202;
  3156. THREE.OneMinusSrcColorFactor = 203;
  3157. THREE.SrcAlphaFactor = 204;
  3158. THREE.OneMinusSrcAlphaFactor = 205;
  3159. THREE.DstAlphaFactor = 206;
  3160. THREE.OneMinusDstAlphaFactor = 207;
  3161. // custom blending source factors
  3162. //THREE.ZeroFactor = 200;
  3163. //THREE.OneFactor = 201;
  3164. //THREE.SrcAlphaFactor = 204;
  3165. //THREE.OneMinusSrcAlphaFactor = 205;
  3166. //THREE.DstAlphaFactor = 206;
  3167. //THREE.OneMinusDstAlphaFactor = 207;
  3168. THREE.DstColorFactor = 208;
  3169. THREE.OneMinusDstColorFactor = 209;
  3170. THREE.SrcAlphaSaturateFactor = 210;
  3171. /**
  3172. * @author mr.doob / http://mrdoob.com/
  3173. * @author alteredq / http://alteredqualia.com/
  3174. *
  3175. * parameters = {
  3176. * color: <hex>,
  3177. * opacity: <float>,
  3178. *
  3179. * blending: THREE.NormalBlending,
  3180. * depthTest: <bool>,
  3181. *
  3182. * linewidth: <float>,
  3183. * linecap: "round",
  3184. * linejoin: "round",
  3185. *
  3186. * vertexColors: <bool>
  3187. *
  3188. * fog: <bool>
  3189. * }
  3190. */
  3191. THREE.LineBasicMaterial = function ( parameters ) {
  3192. THREE.Material.call( this, parameters );
  3193. parameters = parameters || {};
  3194. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3195. this.linewidth = parameters.linewidth !== undefined ? parameters.linewidth : 1;
  3196. this.linecap = parameters.linecap !== undefined ? parameters.linecap : 'round';
  3197. this.linejoin = parameters.linejoin !== undefined ? parameters.linejoin : 'round';
  3198. this.vertexColors = parameters.vertexColors ? parameters.vertexColors : false;
  3199. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3200. };
  3201. THREE.LineBasicMaterial.prototype = new THREE.Material();
  3202. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  3203. /**
  3204. * @author mr.doob / http://mrdoob.com/
  3205. * @author alteredq / http://alteredqualia.com/
  3206. *
  3207. * parameters = {
  3208. * color: <hex>,
  3209. * opacity: <float>,
  3210. * map: new THREE.Texture( <Image> ),
  3211. *
  3212. * lightMap: new THREE.Texture( <Image> ),
  3213. *
  3214. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  3215. * combine: THREE.Multiply,
  3216. * reflectivity: <float>,
  3217. * refractionRatio: <float>,
  3218. *
  3219. * shading: THREE.SmoothShading,
  3220. * blending: THREE.NormalBlending,
  3221. * depthTest: <bool>,
  3222. *
  3223. * wireframe: <boolean>,
  3224. * wireframeLinewidth: <float>,
  3225. *
  3226. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3227. *
  3228. * skinning: <bool>,
  3229. * morphTargets: <bool>,
  3230. *
  3231. * fog: <bool>
  3232. * }
  3233. */
  3234. THREE.MeshBasicMaterial = function ( parameters ) {
  3235. THREE.Material.call( this, parameters );
  3236. parameters = parameters || {};
  3237. // color property represents emissive for MeshBasicMaterial
  3238. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3239. this.map = parameters.map !== undefined ? parameters.map : null;
  3240. this.lightMap = parameters.lightMap !== undefined ? parameters.lightMap : null;
  3241. this.envMap = parameters.envMap !== undefined ? parameters.envMap : null;
  3242. this.combine = parameters.combine !== undefined ? parameters.combine : THREE.MultiplyOperation;
  3243. this.reflectivity = parameters.reflectivity !== undefined ? parameters.reflectivity : 1;
  3244. this.refractionRatio = parameters.refractionRatio !== undefined ? parameters.refractionRatio : 0.98;
  3245. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3246. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3247. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3248. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3249. this.wireframeLinecap = parameters.wireframeLinecap !== undefined ? parameters.wireframeLinecap : 'round';
  3250. this.wireframeLinejoin = parameters.wireframeLinejoin !== undefined ? parameters.wireframeLinejoin : 'round';
  3251. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors;
  3252. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false;
  3253. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false;
  3254. };
  3255. THREE.MeshBasicMaterial.prototype = new THREE.Material();
  3256. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  3257. /**
  3258. * @author mr.doob / http://mrdoob.com/
  3259. * @author alteredq / http://alteredqualia.com/
  3260. *
  3261. * parameters = {
  3262. * color: <hex>,
  3263. * ambient: <hex>,
  3264. * emissive: <hex>,
  3265. * opacity: <float>,
  3266. *
  3267. * map: new THREE.Texture( <Image> ),
  3268. *
  3269. * lightMap: new THREE.Texture( <Image> ),
  3270. *
  3271. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  3272. * combine: THREE.Multiply,
  3273. * reflectivity: <float>,
  3274. * refractionRatio: <float>,
  3275. *
  3276. * shading: THREE.SmoothShading,
  3277. * blending: THREE.NormalBlending,
  3278. * depthTest: <bool>,
  3279. *
  3280. * wireframe: <boolean>,
  3281. * wireframeLinewidth: <float>,
  3282. *
  3283. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3284. *
  3285. * skinning: <bool>,
  3286. * morphTargets: <bool>,
  3287. * morphNormals: <bool>,
  3288. *
  3289. * fog: <bool>
  3290. * }
  3291. */
  3292. THREE.MeshLambertMaterial = function ( parameters ) {
  3293. THREE.Material.call( this, parameters );
  3294. parameters = parameters || {};
  3295. // color property represents diffuse for MeshLambertMaterial
  3296. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3297. this.ambient = parameters.ambient !== undefined ? new THREE.Color( parameters.ambient ) : new THREE.Color( 0xffffff );
  3298. this.emissive = parameters.emissive !== undefined ? new THREE.Color( parameters.emissive ) : new THREE.Color( 0x000000 );
  3299. this.wrapAround = parameters.wrapAround !== undefined ? parameters.wrapAround: false;
  3300. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  3301. this.map = parameters.map !== undefined ? parameters.map : null;
  3302. this.lightMap = parameters.lightMap !== undefined ? parameters.lightMap : null;
  3303. this.envMap = parameters.envMap !== undefined ? parameters.envMap : null;
  3304. this.combine = parameters.combine !== undefined ? parameters.combine : THREE.MultiplyOperation;
  3305. this.reflectivity = parameters.reflectivity !== undefined ? parameters.reflectivity : 1;
  3306. this.refractionRatio = parameters.refractionRatio !== undefined ? parameters.refractionRatio : 0.98;
  3307. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3308. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3309. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3310. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3311. this.wireframeLinecap = parameters.wireframeLinecap !== undefined ? parameters.wireframeLinecap : 'round';
  3312. this.wireframeLinejoin = parameters.wireframeLinejoin !== undefined ? parameters.wireframeLinejoin : 'round';
  3313. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors;
  3314. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false;
  3315. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false;
  3316. this.morphNormals = parameters.morphNormals !== undefined ? parameters.morphNormals : false;
  3317. };
  3318. THREE.MeshLambertMaterial.prototype = new THREE.Material();
  3319. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  3320. /**
  3321. * @author mr.doob / http://mrdoob.com/
  3322. * @author alteredq / http://alteredqualia.com/
  3323. *
  3324. * parameters = {
  3325. * color: <hex>,
  3326. * ambient: <hex>,
  3327. * emissive: <hex>,
  3328. * specular: <hex>,
  3329. * shininess: <float>,
  3330. * opacity: <float>,
  3331. *
  3332. * map: new THREE.Texture( <Image> ),
  3333. *
  3334. * lightMap: new THREE.Texture( <Image> ),
  3335. *
  3336. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  3337. * combine: THREE.Multiply,
  3338. * reflectivity: <float>,
  3339. * refractionRatio: <float>,
  3340. *
  3341. * shading: THREE.SmoothShading,
  3342. * blending: THREE.NormalBlending,
  3343. * depthTest: <bool>,
  3344. *
  3345. * wireframe: <boolean>,
  3346. * wireframeLinewidth: <float>,
  3347. *
  3348. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3349. *
  3350. * skinning: <bool>,
  3351. * morphTargets: <bool>,
  3352. * morphNormals: <bool>,
  3353. *
  3354. * fog: <bool>
  3355. * }
  3356. */
  3357. THREE.MeshPhongMaterial = function ( parameters ) {
  3358. THREE.Material.call( this, parameters );
  3359. parameters = parameters || {};
  3360. // color property represents diffuse for MeshPhongMaterial
  3361. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3362. this.ambient = parameters.ambient !== undefined ? new THREE.Color( parameters.ambient ) : new THREE.Color( 0xffffff );
  3363. this.emissive = parameters.emissive !== undefined ? new THREE.Color( parameters.emissive ) : new THREE.Color( 0x000000 );
  3364. this.specular = parameters.specular !== undefined ? new THREE.Color( parameters.specular ) : new THREE.Color( 0x111111 );
  3365. this.shininess = parameters.shininess !== undefined ? parameters.shininess : 30;
  3366. this.metal = parameters.metal !== undefined ? parameters.metal : false;
  3367. this.perPixel = parameters.perPixel !== undefined ? parameters.perPixel : false;
  3368. this.wrapAround = parameters.wrapAround !== undefined ? parameters.wrapAround: false;
  3369. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  3370. this.map = parameters.map !== undefined ? parameters.map : null;
  3371. this.lightMap = parameters.lightMap !== undefined ? parameters.lightMap : null;
  3372. this.envMap = parameters.envMap !== undefined ? parameters.envMap : null;
  3373. this.combine = parameters.combine !== undefined ? parameters.combine : THREE.MultiplyOperation;
  3374. this.reflectivity = parameters.reflectivity !== undefined ? parameters.reflectivity : 1;
  3375. this.refractionRatio = parameters.refractionRatio !== undefined ? parameters.refractionRatio : 0.98;
  3376. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3377. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3378. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3379. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3380. this.wireframeLinecap = parameters.wireframeLinecap !== undefined ? parameters.wireframeLinecap : 'round';
  3381. this.wireframeLinejoin = parameters.wireframeLinejoin !== undefined ? parameters.wireframeLinejoin : 'round';
  3382. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors;
  3383. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false;
  3384. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false;
  3385. this.morphNormals = parameters.morphNormals !== undefined ? parameters.morphNormals : false;
  3386. };
  3387. THREE.MeshPhongMaterial.prototype = new THREE.Material();
  3388. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  3389. /**
  3390. * @author mr.doob / http://mrdoob.com/
  3391. * @author alteredq / http://alteredqualia.com/
  3392. *
  3393. * parameters = {
  3394. * opacity: <float>,
  3395. * blending: THREE.NormalBlending,
  3396. * depthTest: <bool>,
  3397. * wireframe: <boolean>,
  3398. * wireframeLinewidth: <float>
  3399. * }
  3400. */
  3401. THREE.MeshDepthMaterial = function ( parameters ) {
  3402. THREE.Material.call( this, parameters );
  3403. parameters = parameters || {};
  3404. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading; // doesn't really apply here, normals are not used
  3405. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3406. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3407. };
  3408. THREE.MeshDepthMaterial.prototype = new THREE.Material();
  3409. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  3410. /**
  3411. * @author mr.doob / http://mrdoob.com/
  3412. *
  3413. * parameters = {
  3414. * opacity: <float>,
  3415. * shading: THREE.FlatShading,
  3416. * blending: THREE.NormalBlending,
  3417. * depthTest: <bool>,
  3418. * wireframe: <boolean>,
  3419. * wireframeLinewidth: <float>
  3420. * }
  3421. */
  3422. THREE.MeshNormalMaterial = function ( parameters ) {
  3423. THREE.Material.call( this, parameters );
  3424. parameters = parameters || {};
  3425. this.shading = parameters.shading ? parameters.shading : THREE.FlatShading;
  3426. this.wireframe = parameters.wireframe ? parameters.wireframe : false;
  3427. this.wireframeLinewidth = parameters.wireframeLinewidth ? parameters.wireframeLinewidth : 1;
  3428. };
  3429. THREE.MeshNormalMaterial.prototype = new THREE.Material();
  3430. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  3431. /**
  3432. * @author mr.doob / http://mrdoob.com/
  3433. */
  3434. THREE.MeshFaceMaterial = function () {
  3435. };
  3436. /**
  3437. * @author mr.doob / http://mrdoob.com/
  3438. * @author alteredq / http://alteredqualia.com/
  3439. *
  3440. * parameters = {
  3441. * color: <hex>,
  3442. * opacity: <float>,
  3443. * map: new THREE.Texture( <Image> ),
  3444. *
  3445. * size: <float>,
  3446. *
  3447. * blending: THREE.NormalBlending,
  3448. * depthTest: <bool>,
  3449. *
  3450. * vertexColors: <bool>,
  3451. *
  3452. * fog: <bool>
  3453. * }
  3454. */
  3455. THREE.ParticleBasicMaterial = function ( parameters ) {
  3456. THREE.Material.call( this, parameters );
  3457. parameters = parameters || {};
  3458. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3459. this.map = parameters.map !== undefined ? parameters.map : null;
  3460. this.size = parameters.size !== undefined ? parameters.size : 1;
  3461. this.sizeAttenuation = parameters.sizeAttenuation !== undefined ? parameters.sizeAttenuation : true;
  3462. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : false;
  3463. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3464. };
  3465. THREE.ParticleBasicMaterial.prototype = new THREE.Material();
  3466. THREE.ParticleBasicMaterial.prototype.constructor = THREE.ParticleBasicMaterial;
  3467. /**
  3468. * @author mr.doob / http://mrdoob.com/
  3469. *
  3470. * parameters = {
  3471. * color: <hex>,
  3472. * program: <function>,
  3473. * opacity: <float>,
  3474. * blending: THREE.NormalBlending
  3475. * }
  3476. */
  3477. THREE.ParticleCanvasMaterial = function ( parameters ) {
  3478. THREE.Material.call( this, parameters );
  3479. parameters = parameters || {};
  3480. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3481. this.program = parameters.program !== undefined ? parameters.program : function ( context, color ) {};
  3482. };
  3483. THREE.ParticleCanvasMaterial.prototype = new THREE.Material();
  3484. THREE.ParticleCanvasMaterial.prototype.constructor = THREE.ParticleCanvasMaterial;
  3485. /**
  3486. * @author mr.doob / http://mrdoob.com/
  3487. */
  3488. THREE.ParticleDOMMaterial = function ( domElement ) {
  3489. THREE.Material.call( this );
  3490. this.domElement = domElement;
  3491. };
  3492. /**
  3493. * @author alteredq / http://alteredqualia.com/
  3494. *
  3495. * parameters = {
  3496. * fragmentShader: <string>,
  3497. * vertexShader: <string>,
  3498. *
  3499. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  3500. *
  3501. * shading: THREE.SmoothShading,
  3502. * blending: THREE.NormalBlending,
  3503. * depthTest: <bool>,
  3504. *
  3505. * wireframe: <boolean>,
  3506. * wireframeLinewidth: <float>,
  3507. *
  3508. * lights: <bool>,
  3509. *
  3510. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3511. *
  3512. * skinning: <bool>,
  3513. * morphTargets: <bool>,
  3514. * morphNormals: <bool>,
  3515. *
  3516. * fog: <bool>
  3517. * }
  3518. */
  3519. THREE.ShaderMaterial = function ( parameters ) {
  3520. THREE.Material.call( this, parameters );
  3521. parameters = parameters || {};
  3522. this.fragmentShader = parameters.fragmentShader !== undefined ? parameters.fragmentShader : "void main() {}";
  3523. this.vertexShader = parameters.vertexShader !== undefined ? parameters.vertexShader : "void main() {}";
  3524. this.uniforms = parameters.uniforms !== undefined ? parameters.uniforms : {};
  3525. this.attributes = parameters.attributes;
  3526. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3527. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3528. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3529. this.fog = parameters.fog !== undefined ? parameters.fog : false; // set to use scene fog
  3530. this.lights = parameters.lights !== undefined ? parameters.lights : false; // set to use scene lights
  3531. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors; // set to use "color" attribute stream
  3532. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false; // set to use skinning attribute streams
  3533. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false; // set to use morph targets
  3534. this.morphNormals = parameters.morphNormals !== undefined ? parameters.morphNormals : false; // set to use morph normals
  3535. };
  3536. THREE.ShaderMaterial.prototype = new THREE.Material();
  3537. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  3538. /**
  3539. * @author mr.doob / http://mrdoob.com/
  3540. * @author alteredq / http://alteredqualia.com/
  3541. * @author szimek / https://github.com/szimek/
  3542. */
  3543. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type ) {
  3544. this.id = THREE.TextureCount ++;
  3545. this.image = image;
  3546. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  3547. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  3548. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  3549. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  3550. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  3551. this.format = format !== undefined ? format : THREE.RGBAFormat;
  3552. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  3553. this.offset = new THREE.Vector2( 0, 0 );
  3554. this.repeat = new THREE.Vector2( 1, 1 );
  3555. this.generateMipmaps = true;
  3556. this.premultiplyAlpha = false;
  3557. this.needsUpdate = false;
  3558. this.onUpdate = null;
  3559. };
  3560. THREE.Texture.prototype = {
  3561. constructor: THREE.Texture,
  3562. clone: function () {
  3563. var clonedTexture = new THREE.Texture( this.image, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter, this.format, this.type );
  3564. clonedTexture.offset.copy( this.offset );
  3565. clonedTexture.repeat.copy( this.repeat );
  3566. return clonedTexture;
  3567. }
  3568. };
  3569. THREE.TextureCount = 0;
  3570. THREE.MultiplyOperation = 0;
  3571. THREE.MixOperation = 1;
  3572. // Mapping modes
  3573. THREE.UVMapping = function () {};
  3574. THREE.CubeReflectionMapping = function () {};
  3575. THREE.CubeRefractionMapping = function () {};
  3576. THREE.SphericalReflectionMapping = function () {};
  3577. THREE.SphericalRefractionMapping = function () {};
  3578. // Wrapping modes
  3579. THREE.RepeatWrapping = 0;
  3580. THREE.ClampToEdgeWrapping = 1;
  3581. THREE.MirroredRepeatWrapping = 2;
  3582. // Filters
  3583. THREE.NearestFilter = 3;
  3584. THREE.NearestMipMapNearestFilter = 4;
  3585. THREE.NearestMipMapLinearFilter = 5;
  3586. THREE.LinearFilter = 6;
  3587. THREE.LinearMipMapNearestFilter = 7;
  3588. THREE.LinearMipMapLinearFilter = 8;
  3589. // Types
  3590. THREE.ByteType = 9;
  3591. THREE.UnsignedByteType = 10;
  3592. THREE.ShortType = 11;
  3593. THREE.UnsignedShortType = 12;
  3594. THREE.IntType = 13;
  3595. THREE.UnsignedIntType = 14;
  3596. THREE.FloatType = 15;
  3597. // Formats
  3598. THREE.AlphaFormat = 16;
  3599. THREE.RGBFormat = 17;
  3600. THREE.RGBAFormat = 18;
  3601. THREE.LuminanceFormat = 19;
  3602. THREE.LuminanceAlphaFormat = 20;
  3603. /**
  3604. * @author alteredq / http://alteredqualia.com/
  3605. */
  3606. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  3607. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  3608. this.image = { data: data, width: width, height: height };
  3609. };
  3610. THREE.DataTexture.prototype = new THREE.Texture();
  3611. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  3612. THREE.DataTexture.prototype.clone = function () {
  3613. 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 );
  3614. clonedTexture.offset.copy( this.offset );
  3615. clonedTexture.repeat.copy( this.repeat );
  3616. return clonedTexture;
  3617. };
  3618. /**
  3619. * @author mr.doob / http://mrdoob.com/
  3620. */
  3621. THREE.Particle = function ( material ) {
  3622. THREE.Object3D.call( this );
  3623. this.material = material;
  3624. };
  3625. THREE.Particle.prototype = new THREE.Object3D();
  3626. THREE.Particle.prototype.constructor = THREE.Particle;
  3627. /**
  3628. * @author alteredq / http://alteredqualia.com/
  3629. */
  3630. THREE.ParticleSystem = function ( geometry, material ) {
  3631. THREE.Object3D.call( this );
  3632. this.geometry = geometry;
  3633. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  3634. this.sortParticles = false;
  3635. if ( this.geometry ) {
  3636. // calc bound radius
  3637. if( !this.geometry.boundingSphere ) {
  3638. this.geometry.computeBoundingSphere();
  3639. }
  3640. this.boundRadius = geometry.boundingSphere.radius;
  3641. }
  3642. this.frustumCulled = false;
  3643. };
  3644. THREE.ParticleSystem.prototype = new THREE.Object3D();
  3645. THREE.ParticleSystem.prototype.constructor = THREE.ParticleSystem;
  3646. /**
  3647. * @author mr.doob / http://mrdoob.com/
  3648. */
  3649. THREE.Line = function ( geometry, material, type ) {
  3650. THREE.Object3D.call( this );
  3651. this.geometry = geometry;
  3652. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  3653. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  3654. if ( this.geometry ) {
  3655. if ( ! this.geometry.boundingSphere ) {
  3656. this.geometry.computeBoundingSphere();
  3657. }
  3658. }
  3659. };
  3660. THREE.LineStrip = 0;
  3661. THREE.LinePieces = 1;
  3662. THREE.Line.prototype = new THREE.Object3D();
  3663. THREE.Line.prototype.constructor = THREE.Line;
  3664. /**
  3665. * @author mr.doob / http://mrdoob.com/
  3666. * @author alteredq / http://alteredqualia.com/
  3667. * @author mikael emtinger / http://gomo.se/
  3668. */
  3669. THREE.Mesh = function ( geometry, material ) {
  3670. THREE.Object3D.call( this );
  3671. this.geometry = geometry;
  3672. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  3673. if ( this.geometry ) {
  3674. // calc bound radius
  3675. if( ! this.geometry.boundingSphere ) {
  3676. this.geometry.computeBoundingSphere();
  3677. }
  3678. this.boundRadius = geometry.boundingSphere.radius;
  3679. // setup morph targets
  3680. if( this.geometry.morphTargets.length ) {
  3681. this.morphTargetBase = -1;
  3682. this.morphTargetForcedOrder = [];
  3683. this.morphTargetInfluences = [];
  3684. this.morphTargetDictionary = {};
  3685. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  3686. this.morphTargetInfluences.push( 0 );
  3687. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  3688. }
  3689. }
  3690. }
  3691. }
  3692. THREE.Mesh.prototype = new THREE.Object3D();
  3693. THREE.Mesh.prototype.constructor = THREE.Mesh;
  3694. THREE.Mesh.prototype.supr = THREE.Object3D.prototype;
  3695. /*
  3696. * Get Morph Target Index by Name
  3697. */
  3698. THREE.Mesh.prototype.getMorphTargetIndexByName = function( name ) {
  3699. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  3700. return this.morphTargetDictionary[ name ];
  3701. }
  3702. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  3703. return 0;
  3704. }
  3705. /**
  3706. * @author mikael emtinger / http://gomo.se/
  3707. * @author alteredq / http://alteredqualia.com/
  3708. */
  3709. THREE.Bone = function( belongsToSkin ) {
  3710. THREE.Object3D.call( this );
  3711. this.skin = belongsToSkin;
  3712. this.skinMatrix = new THREE.Matrix4();
  3713. };
  3714. THREE.Bone.prototype = new THREE.Object3D();
  3715. THREE.Bone.prototype.constructor = THREE.Bone;
  3716. THREE.Bone.prototype.supr = THREE.Object3D.prototype;
  3717. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  3718. // update local
  3719. if ( this.matrixAutoUpdate ) {
  3720. forceUpdate |= this.updateMatrix();
  3721. }
  3722. // update skin matrix
  3723. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  3724. if( parentSkinMatrix ) {
  3725. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  3726. } else {
  3727. this.skinMatrix.copy( this.matrix );
  3728. }
  3729. this.matrixWorldNeedsUpdate = false;
  3730. forceUpdate = true;
  3731. }
  3732. // update children
  3733. var child, i, l = this.children.length;
  3734. for ( i = 0; i < l; i ++ ) {
  3735. this.children[ i ].update( this.skinMatrix, forceUpdate );
  3736. }
  3737. };
  3738. /**
  3739. * @author mikael emtinger / http://gomo.se/
  3740. * @author alteredq / http://alteredqualia.com/
  3741. */
  3742. THREE.SkinnedMesh = function ( geometry, material ) {
  3743. THREE.Mesh.call( this, geometry, material );
  3744. // init bones
  3745. this.identityMatrix = new THREE.Matrix4();
  3746. this.bones = [];
  3747. this.boneMatrices = [];
  3748. var b, bone, gbone, p, q, s;
  3749. if ( this.geometry.bones !== undefined ) {
  3750. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  3751. gbone = this.geometry.bones[ b ];
  3752. p = gbone.pos;
  3753. q = gbone.rotq;
  3754. s = gbone.scl;
  3755. bone = this.addBone();
  3756. bone.name = gbone.name;
  3757. bone.position.set( p[0], p[1], p[2] );
  3758. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  3759. bone.useQuaternion = true;
  3760. if ( s !== undefined ) {
  3761. bone.scale.set( s[0], s[1], s[2] );
  3762. } else {
  3763. bone.scale.set( 1, 1, 1 );
  3764. }
  3765. }
  3766. for ( b = 0; b < this.bones.length; b ++ ) {
  3767. gbone = this.geometry.bones[ b ];
  3768. bone = this.bones[ b ];
  3769. if ( gbone.parent === -1 ) {
  3770. this.add( bone );
  3771. } else {
  3772. this.bones[ gbone.parent ].add( bone );
  3773. }
  3774. }
  3775. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  3776. this.pose();
  3777. }
  3778. };
  3779. THREE.SkinnedMesh.prototype = new THREE.Mesh();
  3780. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  3781. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  3782. if ( bone === undefined ) {
  3783. bone = new THREE.Bone( this );
  3784. }
  3785. this.bones.push( bone );
  3786. return bone;
  3787. };
  3788. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  3789. this.matrixAutoUpdate && this.updateMatrix();
  3790. // update matrixWorld
  3791. if ( this.matrixWorldNeedsUpdate || force ) {
  3792. if ( this.parent ) {
  3793. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  3794. } else {
  3795. this.matrixWorld.copy( this.matrix );
  3796. }
  3797. this.matrixWorldNeedsUpdate = false;
  3798. force = true;
  3799. }
  3800. // update children
  3801. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3802. var child = this.children[ i ];
  3803. if ( child instanceof THREE.Bone ) {
  3804. child.update( this.identityMatrix, false );
  3805. } else {
  3806. child.updateMatrixWorld( true );
  3807. }
  3808. }
  3809. // flatten bone matrices to array
  3810. var b, bl = this.bones.length,
  3811. ba = this.bones,
  3812. bm = this.boneMatrices;
  3813. for ( b = 0; b < bl; b ++ ) {
  3814. ba[ b ].skinMatrix.flattenToArrayOffset( bm, b * 16 );
  3815. }
  3816. };
  3817. /*
  3818. * Pose
  3819. */
  3820. THREE.SkinnedMesh.prototype.pose = function() {
  3821. this.updateMatrixWorld( true );
  3822. var bim, bone, boneInverses = [];
  3823. for ( var b = 0; b < this.bones.length; b ++ ) {
  3824. bone = this.bones[ b ];
  3825. var inverseMatrix = new THREE.Matrix4();
  3826. inverseMatrix.getInverse( bone.skinMatrix );
  3827. boneInverses.push( inverseMatrix );
  3828. bone.skinMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  3829. }
  3830. // project vertices to local
  3831. if ( this.geometry.skinVerticesA === undefined ) {
  3832. this.geometry.skinVerticesA = [];
  3833. this.geometry.skinVerticesB = [];
  3834. var orgVertex, vertex;
  3835. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  3836. orgVertex = this.geometry.vertices[ i ].position;
  3837. var indexA = this.geometry.skinIndices[ i ].x;
  3838. var indexB = this.geometry.skinIndices[ i ].y;
  3839. vertex = new THREE.Vector3( orgVertex.x, orgVertex.y, orgVertex.z );
  3840. this.geometry.skinVerticesA.push( boneInverses[ indexA ].multiplyVector3( vertex ) );
  3841. vertex = new THREE.Vector3( orgVertex.x, orgVertex.y, orgVertex.z );
  3842. this.geometry.skinVerticesB.push( boneInverses[ indexB ].multiplyVector3( vertex ) );
  3843. // todo: add more influences
  3844. // normalize weights
  3845. if ( this.geometry.skinWeights[ i ].x + this.geometry.skinWeights[ i ].y !== 1 ) {
  3846. var len = ( 1.0 - ( this.geometry.skinWeights[ i ].x + this.geometry.skinWeights[ i ].y ) ) * 0.5;
  3847. this.geometry.skinWeights[ i ].x += len;
  3848. this.geometry.skinWeights[ i ].y += len;
  3849. }
  3850. }
  3851. }
  3852. };
  3853. /**
  3854. * @author alteredq / http://alteredqualia.com/
  3855. */
  3856. THREE.MorphAnimMesh = function ( geometry, material ) {
  3857. THREE.Mesh.call( this, geometry, material );
  3858. // API
  3859. this.duration = 1000; // milliseconds
  3860. this.mirroredLoop = false;
  3861. this.time = 0;
  3862. // internals
  3863. this.lastKeyframe = 0;
  3864. this.currentKeyframe = 0;
  3865. this.direction = 1;
  3866. this.directionBackwards = false;
  3867. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  3868. };
  3869. THREE.MorphAnimMesh.prototype = new THREE.Mesh();
  3870. THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh;
  3871. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  3872. this.startKeyframe = start;
  3873. this.endKeyframe = end;
  3874. this.length = this.endKeyframe - this.startKeyframe + 1;
  3875. };
  3876. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  3877. this.direction = 1;
  3878. this.directionBackwards = false;
  3879. };
  3880. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  3881. this.direction = -1;
  3882. this.directionBackwards = true;
  3883. };
  3884. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  3885. var geometry = this.geometry;
  3886. if ( ! geometry.animations ) geometry.animations = {};
  3887. var firstAnimation, animations = geometry.animations;
  3888. var pattern = /([a-z]+)(\d+)/;
  3889. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  3890. var morph = geometry.morphTargets[ i ];
  3891. var parts = morph.name.match( pattern );
  3892. if ( parts && parts.length > 1 ) {
  3893. var label = parts[ 1 ];
  3894. var num = parts[ 2 ];
  3895. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  3896. var animation = animations[ label ];
  3897. if ( i < animation.start ) animation.start = i;
  3898. if ( i > animation.end ) animation.end = i;
  3899. if ( ! firstAnimation ) firstAnimation = label;
  3900. }
  3901. }
  3902. geometry.firstAnimation = firstAnimation;
  3903. };
  3904. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  3905. if ( ! this.geometry.animations ) this.geometry.animations = {};
  3906. this.geometry.animations[ label ] = { start: start, end: end };
  3907. };
  3908. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  3909. var animation = this.geometry.animations[ label ];
  3910. if ( animation ) {
  3911. this.setFrameRange( animation.start, animation.end );
  3912. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  3913. this.time = 0;
  3914. } else {
  3915. console.warn( "animation[" + label + "] undefined" );
  3916. }
  3917. };
  3918. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  3919. var frameTime = this.duration / this.length;
  3920. this.time += this.direction * delta;
  3921. if ( this.mirroredLoop ) {
  3922. if ( this.time > this.duration || this.time < 0 ) {
  3923. this.direction *= -1;
  3924. if ( this.time > this.duration ) {
  3925. this.time = this.duration;
  3926. this.directionBackwards = true;
  3927. }
  3928. if ( this.time < 0 ) {
  3929. this.time = 0;
  3930. this.directionBackwards = false;
  3931. }
  3932. }
  3933. } else {
  3934. this.time = this.time % this.duration;
  3935. if ( this.time < 0 ) this.time += this.duration;
  3936. }
  3937. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  3938. if ( keyframe !== this.currentKeyframe ) {
  3939. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  3940. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  3941. this.morphTargetInfluences[ keyframe ] = 0;
  3942. this.lastKeyframe = this.currentKeyframe;
  3943. this.currentKeyframe = keyframe;
  3944. }
  3945. var mix = ( this.time % frameTime ) / frameTime;
  3946. if ( this.directionBackwards ) {
  3947. mix = 1 - mix;
  3948. }
  3949. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  3950. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  3951. };
  3952. /**
  3953. * @author alteredq / http://alteredqualia.com/
  3954. */
  3955. THREE.Ribbon = function ( geometry, material ) {
  3956. THREE.Object3D.call( this );
  3957. this.geometry = geometry;
  3958. this.material = material;
  3959. };
  3960. THREE.Ribbon.prototype = new THREE.Object3D();
  3961. THREE.Ribbon.prototype.constructor = THREE.Ribbon;
  3962. /**
  3963. * @author mikael emtinger / http://gomo.se/
  3964. * @author alteredq / http://alteredqualia.com/
  3965. * @author mr.doob / http://mrdoob.com/
  3966. */
  3967. THREE.LOD = function () {
  3968. THREE.Object3D.call( this );
  3969. this.LODs = [];
  3970. };
  3971. THREE.LOD.prototype = new THREE.Object3D();
  3972. THREE.LOD.prototype.constructor = THREE.LOD;
  3973. THREE.LOD.prototype.supr = THREE.Object3D.prototype;
  3974. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  3975. if ( visibleAtDistance === undefined ) {
  3976. visibleAtDistance = 0;
  3977. }
  3978. visibleAtDistance = Math.abs( visibleAtDistance );
  3979. for ( var l = 0; l < this.LODs.length; l ++ ) {
  3980. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  3981. break;
  3982. }
  3983. }
  3984. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  3985. this.add( object3D );
  3986. };
  3987. THREE.LOD.prototype.update = function ( camera ) {
  3988. if ( this.LODs.length > 1 ) {
  3989. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3990. var inverse = camera.matrixWorldInverse;
  3991. 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] );
  3992. this.LODs[ 0 ].object3D.visible = true;
  3993. for ( var l = 1; l < this.LODs.length; l ++ ) {
  3994. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  3995. this.LODs[ l - 1 ].object3D.visible = false;
  3996. this.LODs[ l ].object3D.visible = true;
  3997. } else {
  3998. break;
  3999. }
  4000. }
  4001. for( ; l < this.LODs.length; l ++ ) {
  4002. this.LODs[ l ].object3D.visible = false;
  4003. }
  4004. }
  4005. };
  4006. /**
  4007. * @author mikael emtinger / http://gomo.se/
  4008. */
  4009. THREE.Sprite = function ( parameters ) {
  4010. THREE.Object3D.call( this );
  4011. this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  4012. this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();
  4013. this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;
  4014. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  4015. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  4016. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  4017. this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
  4018. this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
  4019. this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
  4020. this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
  4021. this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center;
  4022. this.rotation3d = this.rotation;
  4023. this.rotation = 0;
  4024. this.opacity = 1;
  4025. this.uvOffset = new THREE.Vector2( 0, 0 );
  4026. this.uvScale = new THREE.Vector2( 1, 1 );
  4027. };
  4028. THREE.Sprite.prototype = new THREE.Object3D();
  4029. THREE.Sprite.prototype.constructor = THREE.Sprite;
  4030. /*
  4031. * Custom update matrix
  4032. */
  4033. THREE.Sprite.prototype.updateMatrix = function () {
  4034. this.matrix.setPosition( this.position );
  4035. this.rotation3d.set( 0, 0, this.rotation );
  4036. this.matrix.setRotationFromEuler( this.rotation3d );
  4037. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  4038. this.matrix.scale( this.scale );
  4039. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  4040. }
  4041. this.matrixWorldNeedsUpdate = true;
  4042. };
  4043. /*
  4044. * Alignment
  4045. */
  4046. THREE.SpriteAlignment = {};
  4047. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  4048. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  4049. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  4050. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  4051. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  4052. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  4053. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  4054. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  4055. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  4056. /**
  4057. * @author mr.doob / http://mrdoob.com/
  4058. */
  4059. THREE.Scene = function () {
  4060. THREE.Object3D.call( this );
  4061. this.fog = null;
  4062. this.overrideMaterial = null;
  4063. this.matrixAutoUpdate = false;
  4064. this.__objects = [];
  4065. this.__lights = [];
  4066. this.__objectsAdded = [];
  4067. this.__objectsRemoved = [];
  4068. };
  4069. THREE.Scene.prototype = new THREE.Object3D();
  4070. THREE.Scene.prototype.constructor = THREE.Scene;
  4071. THREE.Scene.prototype.__addObject = function ( object ) {
  4072. if ( object instanceof THREE.Light ) {
  4073. if ( this.__lights.indexOf( object ) === - 1 ) {
  4074. this.__lights.push( object );
  4075. }
  4076. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  4077. if ( this.__objects.indexOf( object ) === - 1 ) {
  4078. this.__objects.push( object );
  4079. this.__objectsAdded.push( object );
  4080. // check if previously removed
  4081. var i = this.__objectsRemoved.indexOf( object );
  4082. if ( i !== -1 ) {
  4083. this.__objectsRemoved.splice( i, 1 );
  4084. }
  4085. }
  4086. }
  4087. for ( var c = 0; c < object.children.length; c ++ ) {
  4088. this.__addObject( object.children[ c ] );
  4089. }
  4090. };
  4091. THREE.Scene.prototype.__removeObject = function ( object ) {
  4092. if ( object instanceof THREE.Light ) {
  4093. var i = this.__lights.indexOf( object );
  4094. if ( i !== -1 ) {
  4095. this.__lights.splice( i, 1 );
  4096. }
  4097. } else if ( !( object instanceof THREE.Camera ) ) {
  4098. var i = this.__objects.indexOf( object );
  4099. if( i !== -1 ) {
  4100. this.__objects.splice( i, 1 );
  4101. this.__objectsRemoved.push( object );
  4102. // check if previously added
  4103. var ai = this.__objectsAdded.indexOf( object );
  4104. if ( ai !== -1 ) {
  4105. this.__objectsAdded.splice( ai, 1 );
  4106. }
  4107. }
  4108. }
  4109. for ( var c = 0; c < object.children.length; c ++ ) {
  4110. this.__removeObject( object.children[ c ] );
  4111. }
  4112. };
  4113. /**
  4114. * @author mr.doob / http://mrdoob.com/
  4115. * @author alteredq / http://alteredqualia.com/
  4116. */
  4117. THREE.Fog = function ( hex, near, far ) {
  4118. this.color = new THREE.Color( hex );
  4119. this.near = ( near !== undefined ) ? near : 1;
  4120. this.far = ( far !== undefined ) ? far : 1000;
  4121. };
  4122. /**
  4123. * @author mr.doob / http://mrdoob.com/
  4124. * @author alteredq / http://alteredqualia.com/
  4125. */
  4126. THREE.FogExp2 = function ( hex, density ) {
  4127. this.color = new THREE.Color( hex );
  4128. this.density = ( density !== undefined ) ? density : 0.00025;
  4129. };
  4130. /**
  4131. * @author mr.doob / http://mrdoob.com/
  4132. */
  4133. THREE.DOMRenderer = function () {
  4134. var _renderData, _elements,
  4135. _width, _height, _widthHalf, _heightHalf, _transformProp,
  4136. _projector = new THREE.Projector();
  4137. var getSupportedProp = function ( proparray ) {
  4138. var root = document.documentElement
  4139. for ( var i = 0; i < proparray.length; i ++ ) {
  4140. if ( typeof root.style[ proparray[ i ] ] === "string" ) {
  4141. return proparray[i];
  4142. }
  4143. }
  4144. return null;
  4145. };
  4146. _transformProp = getSupportedProp( [ 'transform', 'MozTransform', 'WebkitTransform', 'msTransform', 'OTransform' ] );
  4147. this.domElement = document.createElement( 'div' );
  4148. this.setSize = function ( width, height ) {
  4149. _width = width;
  4150. _height = height;
  4151. _widthHalf = _width / 2;
  4152. _heightHalf = _height / 2;
  4153. };
  4154. this.render = function ( scene, camera ) {
  4155. var e, el, m, ml, element, material, dom, v1x, v1y;
  4156. _renderData = _projector.projectScene( scene, camera );
  4157. _elements = _renderData.elements;
  4158. for ( e = 0, el = _elements.length; e < el; e ++ ) {
  4159. element = _elements[ e ];
  4160. if ( element instanceof THREE.RenderableParticle && element.material instanceof THREE.ParticleDOMMaterial ) {
  4161. dom = element.material.domElement;
  4162. v1x = element.x * _widthHalf + _widthHalf - ( dom.offsetWidth >> 1 );
  4163. v1y = element.y * _heightHalf + _heightHalf - ( dom.offsetHeight >> 1 );
  4164. dom.style.left = v1x + 'px';
  4165. dom.style.top = v1y + 'px';
  4166. dom.style.zIndex = Math.abs( Math.floor( ( 1 - element.z ) * camera.far / camera.near ) )
  4167. if ( _transformProp ) {
  4168. var scaleX = element.scale.x * _widthHalf;
  4169. var scaleY = element.scale.y * _heightHalf;
  4170. var scaleVal = "scale(" + scaleX + "," + scaleY + ")";
  4171. dom.style[ _transformProp ] = scaleVal;
  4172. }
  4173. }
  4174. }
  4175. };
  4176. };
  4177. /**
  4178. * @author mr.doob / http://mrdoob.com/
  4179. */
  4180. THREE.CanvasRenderer = function ( parameters ) {
  4181. parameters = parameters || {};
  4182. var _this = this,
  4183. _renderData, _elements, _lights,
  4184. _projector = new THREE.Projector(),
  4185. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  4186. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  4187. _context = _canvas.getContext( '2d' ),
  4188. _clearColor = new THREE.Color( 0x000000 ),
  4189. _clearOpacity = 0,
  4190. _contextGlobalAlpha = 1,
  4191. _contextGlobalCompositeOperation = 0,
  4192. _contextStrokeStyle = null,
  4193. _contextFillStyle = null,
  4194. _contextLineWidth = null,
  4195. _contextLineCap = null,
  4196. _contextLineJoin = null,
  4197. _v1, _v2, _v3, _v4,
  4198. _v5 = new THREE.RenderableVertex(),
  4199. _v6 = new THREE.RenderableVertex(),
  4200. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  4201. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  4202. _color = new THREE.Color(),
  4203. _color1 = new THREE.Color(),
  4204. _color2 = new THREE.Color(),
  4205. _color3 = new THREE.Color(),
  4206. _color4 = new THREE.Color(),
  4207. _patterns = [], _imagedatas = [],
  4208. _near, _far,
  4209. _image, _uvs,
  4210. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  4211. _clipRect = new THREE.Rectangle(),
  4212. _clearRect = new THREE.Rectangle(),
  4213. _bboxRect = new THREE.Rectangle(),
  4214. _enableLighting = false,
  4215. _ambientLight = new THREE.Color(),
  4216. _directionalLights = new THREE.Color(),
  4217. _pointLights = new THREE.Color(),
  4218. _pi2 = Math.PI * 2,
  4219. _vector3 = new THREE.Vector3(), // Needed for PointLight
  4220. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  4221. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  4222. _pixelMap = document.createElement( 'canvas' );
  4223. _pixelMap.width = _pixelMap.height = 2;
  4224. _pixelMapContext = _pixelMap.getContext( '2d' );
  4225. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  4226. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  4227. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  4228. _pixelMapData = _pixelMapImage.data;
  4229. _gradientMap = document.createElement( 'canvas' );
  4230. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  4231. _gradientMapContext = _gradientMap.getContext( '2d' );
  4232. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  4233. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  4234. _gradientMapQuality --; // Fix UVs
  4235. this.domElement = _canvas;
  4236. this.autoClear = true;
  4237. this.sortObjects = true;
  4238. this.sortElements = true;
  4239. this.info = {
  4240. render: {
  4241. vertices: 0,
  4242. faces: 0
  4243. }
  4244. }
  4245. this.setSize = function ( width, height ) {
  4246. _canvasWidth = width;
  4247. _canvasHeight = height;
  4248. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  4249. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  4250. _canvas.width = _canvasWidth;
  4251. _canvas.height = _canvasHeight;
  4252. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4253. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4254. _contextGlobalAlpha = 1;
  4255. _contextGlobalCompositeOperation = 0;
  4256. _contextStrokeStyle = null;
  4257. _contextFillStyle = null;
  4258. _contextLineWidth = null;
  4259. _contextLineCap = null;
  4260. _contextLineJoin = null;
  4261. };
  4262. this.setClearColor = function ( color, opacity ) {
  4263. _clearColor.copy( color );
  4264. _clearOpacity = opacity !== undefined ? opacity : 1;
  4265. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4266. };
  4267. this.setClearColorHex = function ( hex, opacity ) {
  4268. _clearColor.setHex( hex );
  4269. _clearOpacity = opacity !== undefined ? opacity : 1;
  4270. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4271. };
  4272. this.clear = function () {
  4273. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  4274. if ( !_clearRect.isEmpty() ) {
  4275. _clearRect.minSelf( _clipRect );
  4276. _clearRect.inflate( 2 );
  4277. if ( _clearOpacity < 1 ) {
  4278. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  4279. }
  4280. if ( _clearOpacity > 0 ) {
  4281. setBlending( THREE.NormalBlending );
  4282. setOpacity( 1 );
  4283. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  4284. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  4285. }
  4286. _clearRect.empty();
  4287. }
  4288. };
  4289. this.render = function ( scene, camera ) {
  4290. var e, el, element, material;
  4291. this.autoClear ? this.clear() : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  4292. _this.info.render.vertices = 0;
  4293. _this.info.render.faces = 0;
  4294. _renderData = _projector.projectScene( scene, camera, this.sortElements );
  4295. _elements = _renderData.elements;
  4296. _lights = _renderData.lights;
  4297. /* DEBUG
  4298. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  4299. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  4300. */
  4301. _enableLighting = _lights.length > 0;
  4302. if ( _enableLighting ) {
  4303. calculateLights( _lights );
  4304. }
  4305. for ( e = 0, el = _elements.length; e < el; e++ ) {
  4306. element = _elements[ e ];
  4307. material = element.material;
  4308. material = material instanceof THREE.MeshFaceMaterial ? element.faceMaterial : material;
  4309. if ( material == null || material.opacity == 0 ) continue;
  4310. _bboxRect.empty();
  4311. if ( element instanceof THREE.RenderableParticle ) {
  4312. _v1 = element;
  4313. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  4314. renderParticle( _v1, element, material, scene );
  4315. } else if ( element instanceof THREE.RenderableLine ) {
  4316. _v1 = element.v1; _v2 = element.v2;
  4317. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  4318. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  4319. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4320. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4321. if ( _clipRect.intersects( _bboxRect ) ) {
  4322. renderLine( _v1, _v2, element, material, scene );
  4323. }
  4324. } else if ( element instanceof THREE.RenderableFace3 ) {
  4325. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  4326. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  4327. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  4328. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  4329. if ( material.overdraw ) {
  4330. expand( _v1.positionScreen, _v2.positionScreen );
  4331. expand( _v2.positionScreen, _v3.positionScreen );
  4332. expand( _v3.positionScreen, _v1.positionScreen );
  4333. }
  4334. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  4335. _v2.positionScreen.x, _v2.positionScreen.y,
  4336. _v3.positionScreen.x, _v3.positionScreen.y );
  4337. if ( _clipRect.intersects( _bboxRect ) ) {
  4338. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  4339. }
  4340. } else if ( element instanceof THREE.RenderableFace4 ) {
  4341. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  4342. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  4343. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  4344. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  4345. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  4346. _v5.positionScreen.copy( _v2.positionScreen );
  4347. _v6.positionScreen.copy( _v4.positionScreen );
  4348. if ( material.overdraw ) {
  4349. expand( _v1.positionScreen, _v2.positionScreen );
  4350. expand( _v2.positionScreen, _v4.positionScreen );
  4351. expand( _v4.positionScreen, _v1.positionScreen );
  4352. expand( _v3.positionScreen, _v5.positionScreen );
  4353. expand( _v3.positionScreen, _v6.positionScreen );
  4354. }
  4355. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4356. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4357. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  4358. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  4359. if ( _clipRect.intersects( _bboxRect ) ) {
  4360. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  4361. }
  4362. }
  4363. /*
  4364. _context.lineWidth = 1;
  4365. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  4366. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  4367. */
  4368. _clearRect.addRectangle( _bboxRect );
  4369. }
  4370. /* DEBUG
  4371. _context.lineWidth = 1;
  4372. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  4373. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  4374. */
  4375. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  4376. //
  4377. function calculateLights( lights ) {
  4378. var l, ll, light, lightColor;
  4379. _ambientLight.setRGB( 0, 0, 0 );
  4380. _directionalLights.setRGB( 0, 0, 0 );
  4381. _pointLights.setRGB( 0, 0, 0 );
  4382. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  4383. light = lights[ l ];
  4384. lightColor = light.color;
  4385. if ( light instanceof THREE.AmbientLight ) {
  4386. _ambientLight.r += lightColor.r;
  4387. _ambientLight.g += lightColor.g;
  4388. _ambientLight.b += lightColor.b;
  4389. } else if ( light instanceof THREE.DirectionalLight ) {
  4390. // for particles
  4391. _directionalLights.r += lightColor.r;
  4392. _directionalLights.g += lightColor.g;
  4393. _directionalLights.b += lightColor.b;
  4394. } else if ( light instanceof THREE.PointLight ) {
  4395. // for particles
  4396. _pointLights.r += lightColor.r;
  4397. _pointLights.g += lightColor.g;
  4398. _pointLights.b += lightColor.b;
  4399. }
  4400. }
  4401. }
  4402. function calculateLight( lights, position, normal, color ) {
  4403. var l, ll, light, lightColor, lightPosition, amount;
  4404. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  4405. light = lights[ l ];
  4406. lightColor = light.color;
  4407. if ( light instanceof THREE.DirectionalLight ) {
  4408. lightPosition = light.matrixWorld.getPosition();
  4409. amount = normal.dot( lightPosition );
  4410. if ( amount <= 0 ) continue;
  4411. amount *= light.intensity;
  4412. color.r += lightColor.r * amount;
  4413. color.g += lightColor.g * amount;
  4414. color.b += lightColor.b * amount;
  4415. } else if ( light instanceof THREE.PointLight ) {
  4416. lightPosition = light.matrixWorld.getPosition();
  4417. amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  4418. if ( amount <= 0 ) continue;
  4419. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  4420. if ( amount == 0 ) continue;
  4421. amount *= light.intensity;
  4422. color.r += lightColor.r * amount;
  4423. color.g += lightColor.g * amount;
  4424. color.b += lightColor.b * amount;
  4425. }
  4426. }
  4427. }
  4428. function renderParticle ( v1, element, material, scene ) {
  4429. setOpacity( material.opacity );
  4430. setBlending( material.blending );
  4431. var width, height, scaleX, scaleY,
  4432. bitmap, bitmapWidth, bitmapHeight;
  4433. if ( material instanceof THREE.ParticleBasicMaterial ) {
  4434. if ( material.map ) {
  4435. bitmap = material.map.image;
  4436. bitmapWidth = bitmap.width >> 1;
  4437. bitmapHeight = bitmap.height >> 1;
  4438. scaleX = element.scale.x * _canvasWidthHalf;
  4439. scaleY = element.scale.y * _canvasHeightHalf;
  4440. width = scaleX * bitmapWidth;
  4441. height = scaleY * bitmapHeight;
  4442. // TODO: Rotations break this...
  4443. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  4444. if ( !_clipRect.intersects( _bboxRect ) ) {
  4445. return;
  4446. }
  4447. _context.save();
  4448. _context.translate( v1.x, v1.y );
  4449. _context.rotate( - element.rotation );
  4450. _context.scale( scaleX, - scaleY );
  4451. _context.translate( - bitmapWidth, - bitmapHeight );
  4452. _context.drawImage( bitmap, 0, 0 );
  4453. _context.restore();
  4454. }
  4455. /* DEBUG
  4456. _context.beginPath();
  4457. _context.moveTo( v1.x - 10, v1.y );
  4458. _context.lineTo( v1.x + 10, v1.y );
  4459. _context.moveTo( v1.x, v1.y - 10 );
  4460. _context.lineTo( v1.x, v1.y + 10 );
  4461. _context.closePath();
  4462. _context.strokeStyle = 'rgb(255,255,0)';
  4463. _context.stroke();
  4464. */
  4465. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  4466. width = element.scale.x * _canvasWidthHalf;
  4467. height = element.scale.y * _canvasHeightHalf;
  4468. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  4469. if ( !_clipRect.intersects( _bboxRect ) ) {
  4470. return;
  4471. }
  4472. setStrokeStyle( material.color.getContextStyle() );
  4473. setFillStyle( material.color.getContextStyle() );
  4474. _context.save();
  4475. _context.translate( v1.x, v1.y );
  4476. _context.rotate( - element.rotation );
  4477. _context.scale( width, height );
  4478. material.program( _context );
  4479. _context.restore();
  4480. }
  4481. }
  4482. function renderLine( v1, v2, element, material, scene ) {
  4483. setOpacity( material.opacity );
  4484. setBlending( material.blending );
  4485. _context.beginPath();
  4486. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  4487. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  4488. _context.closePath();
  4489. if ( material instanceof THREE.LineBasicMaterial ) {
  4490. setLineWidth( material.linewidth );
  4491. setLineCap( material.linecap );
  4492. setLineJoin( material.linejoin );
  4493. setStrokeStyle( material.color.getContextStyle() );
  4494. _context.stroke();
  4495. _bboxRect.inflate( material.linewidth * 2 );
  4496. }
  4497. }
  4498. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  4499. _this.info.render.vertices += 3;
  4500. _this.info.render.faces ++;
  4501. setOpacity( material.opacity );
  4502. setBlending( material.blending );
  4503. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  4504. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  4505. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  4506. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  4507. if ( material instanceof THREE.MeshBasicMaterial ) {
  4508. if ( material.map/* && !material.wireframe*/ ) {
  4509. if ( material.map.mapping instanceof THREE.UVMapping ) {
  4510. _uvs = element.uvs[ 0 ];
  4511. 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 );
  4512. }
  4513. } else if ( material.envMap ) {
  4514. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  4515. var cameraMatrix = camera.matrixWorldInverse;
  4516. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  4517. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  4518. _uv1y = - ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  4519. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  4520. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  4521. _uv2y = - ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  4522. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  4523. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  4524. _uv3y = - ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  4525. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  4526. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  4527. }*/
  4528. } else {
  4529. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4530. }
  4531. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  4532. if ( material.map && !material.wireframe ) {
  4533. if ( material.map.mapping instanceof THREE.UVMapping ) {
  4534. _uvs = element.uvs[ 0 ];
  4535. 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 );
  4536. }
  4537. setBlending( THREE.SubtractiveBlending );
  4538. }
  4539. if ( _enableLighting ) {
  4540. if ( !material.wireframe && material.shading == THREE.SmoothShading && element.vertexNormalsWorld.length == 3 ) {
  4541. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  4542. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  4543. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  4544. calculateLight( _lights, element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  4545. calculateLight( _lights, element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  4546. calculateLight( _lights, element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  4547. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  4548. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  4549. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  4550. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  4551. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  4552. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  4553. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  4554. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  4555. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  4556. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  4557. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  4558. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  4559. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4560. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  4561. } else {
  4562. _color.r = _ambientLight.r;
  4563. _color.g = _ambientLight.g;
  4564. _color.b = _ambientLight.b;
  4565. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  4566. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  4567. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  4568. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  4569. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4570. }
  4571. } else {
  4572. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4573. }
  4574. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  4575. _near = camera.near;
  4576. _far = camera.far;
  4577. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  4578. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  4579. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  4580. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  4581. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  4582. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  4583. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4584. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  4585. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  4586. _color.r = normalToComponent( element.normalWorld.x );
  4587. _color.g = normalToComponent( element.normalWorld.y );
  4588. _color.b = normalToComponent( element.normalWorld.z );
  4589. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4590. }
  4591. }
  4592. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  4593. _this.info.render.vertices += 4;
  4594. _this.info.render.faces ++;
  4595. setOpacity( material.opacity );
  4596. setBlending( material.blending );
  4597. if ( material.map || material.envMap ) {
  4598. // Let renderFace3() handle this
  4599. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  4600. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  4601. return;
  4602. }
  4603. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  4604. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  4605. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  4606. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  4607. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  4608. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  4609. if ( material instanceof THREE.MeshBasicMaterial ) {
  4610. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4611. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4612. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  4613. if ( _enableLighting ) {
  4614. if ( !material.wireframe && material.shading == THREE.SmoothShading && element.vertexNormalsWorld.length == 4 ) {
  4615. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  4616. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  4617. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  4618. calculateLight( _lights, element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  4619. calculateLight( _lights, element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  4620. calculateLight( _lights, element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  4621. calculateLight( _lights, element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  4622. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  4623. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  4624. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  4625. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  4626. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  4627. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  4628. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  4629. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  4630. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  4631. _color4.r = Math.max( 0, Math.min( material.color.r * _color4.r, 1 ) );
  4632. _color4.g = Math.max( 0, Math.min( material.color.g * _color4.g, 1 ) );
  4633. _color4.b = Math.max( 0, Math.min( material.color.b * _color4.b, 1 ) );
  4634. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4635. // TODO: UVs are incorrect, v4->v3?
  4636. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  4637. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  4638. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  4639. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  4640. } else {
  4641. _color.r = _ambientLight.r;
  4642. _color.g = _ambientLight.g;
  4643. _color.b = _ambientLight.b;
  4644. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  4645. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  4646. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  4647. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  4648. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4649. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4650. }
  4651. } else {
  4652. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4653. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4654. }
  4655. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  4656. _color.r = normalToComponent( element.normalWorld.x );
  4657. _color.g = normalToComponent( element.normalWorld.y );
  4658. _color.b = normalToComponent( element.normalWorld.z );
  4659. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4660. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4661. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  4662. _near = camera.near;
  4663. _far = camera.far;
  4664. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  4665. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  4666. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  4667. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  4668. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4669. // TODO: UVs are incorrect, v4->v3?
  4670. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  4671. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  4672. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  4673. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  4674. }
  4675. }
  4676. //
  4677. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  4678. _context.beginPath();
  4679. _context.moveTo( x0, y0 );
  4680. _context.lineTo( x1, y1 );
  4681. _context.lineTo( x2, y2 );
  4682. _context.lineTo( x0, y0 );
  4683. _context.closePath();
  4684. }
  4685. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  4686. _context.beginPath();
  4687. _context.moveTo( x0, y0 );
  4688. _context.lineTo( x1, y1 );
  4689. _context.lineTo( x2, y2 );
  4690. _context.lineTo( x3, y3 );
  4691. _context.lineTo( x0, y0 );
  4692. _context.closePath();
  4693. }
  4694. function strokePath( color, linewidth, linecap, linejoin ) {
  4695. setLineWidth( linewidth );
  4696. setLineCap( linecap );
  4697. setLineJoin( linejoin );
  4698. setStrokeStyle( color.getContextStyle() );
  4699. _context.stroke();
  4700. _bboxRect.inflate( linewidth * 2 );
  4701. }
  4702. function fillPath( color ) {
  4703. setFillStyle( color.getContextStyle() );
  4704. _context.fill();
  4705. }
  4706. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  4707. if ( texture.image.width == 0 ) return;
  4708. if ( texture.needsUpdate == true || _patterns[ texture.id ] == undefined ) {
  4709. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  4710. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  4711. _patterns[ texture.id ] = _context.createPattern( texture.image, repeatX && repeatY ? 'repeat' : repeatX && !repeatY ? 'repeat-x' : !repeatX && repeatY ? 'repeat-y' : 'no-repeat' );
  4712. texture.needsUpdate = false;
  4713. }
  4714. setFillStyle( _patterns[ texture.id ] );
  4715. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  4716. var a, b, c, d, e, f, det, idet,
  4717. offsetX = texture.offset.x / texture.repeat.x,
  4718. offsetY = texture.offset.y / texture.repeat.y,
  4719. width = texture.image.width * texture.repeat.x,
  4720. height = texture.image.height * texture.repeat.y;
  4721. u0 = ( u0 + offsetX ) * width;
  4722. v0 = ( v0 + offsetY ) * height;
  4723. u1 = ( u1 + offsetX ) * width;
  4724. v1 = ( v1 + offsetY ) * height;
  4725. u2 = ( u2 + offsetX ) * width;
  4726. v2 = ( v2 + offsetY ) * height;
  4727. x1 -= x0; y1 -= y0;
  4728. x2 -= x0; y2 -= y0;
  4729. u1 -= u0; v1 -= v0;
  4730. u2 -= u0; v2 -= v0;
  4731. det = u1 * v2 - u2 * v1;
  4732. if ( det == 0 ) {
  4733. if ( _imagedatas[ texture.id ] === undefined ) {
  4734. var canvas = document.createElement( 'canvas' )
  4735. canvas.width = texture.image.width;
  4736. canvas.height = texture.image.height;
  4737. var context = canvas.getContext( '2d' );
  4738. context.drawImage( texture.image, 0, 0 );
  4739. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  4740. // variables cannot be deleted in ES5 strict mode
  4741. //delete canvas;
  4742. }
  4743. var data = _imagedatas[ texture.id ];
  4744. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  4745. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  4746. fillPath( _color );
  4747. return;
  4748. }
  4749. idet = 1 / det;
  4750. a = ( v2 * x1 - v1 * x2 ) * idet;
  4751. b = ( v2 * y1 - v1 * y2 ) * idet;
  4752. c = ( u1 * x2 - u2 * x1 ) * idet;
  4753. d = ( u1 * y2 - u2 * y1 ) * idet;
  4754. e = x0 - a * u0 - c * v0;
  4755. f = y0 - b * u0 - d * v0;
  4756. _context.save();
  4757. _context.transform( a, b, c, d, e, f );
  4758. _context.fill();
  4759. _context.restore();
  4760. }
  4761. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  4762. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  4763. var a, b, c, d, e, f, det, idet,
  4764. width = image.width - 1,
  4765. height = image.height - 1;
  4766. u0 *= width; v0 *= height;
  4767. u1 *= width; v1 *= height;
  4768. u2 *= width; v2 *= height;
  4769. x1 -= x0; y1 -= y0;
  4770. x2 -= x0; y2 -= y0;
  4771. u1 -= u0; v1 -= v0;
  4772. u2 -= u0; v2 -= v0;
  4773. det = u1 * v2 - u2 * v1;
  4774. idet = 1 / det;
  4775. a = ( v2 * x1 - v1 * x2 ) * idet;
  4776. b = ( v2 * y1 - v1 * y2 ) * idet;
  4777. c = ( u1 * x2 - u2 * x1 ) * idet;
  4778. d = ( u1 * y2 - u2 * y1 ) * idet;
  4779. e = x0 - a * u0 - c * v0;
  4780. f = y0 - b * u0 - d * v0;
  4781. _context.save();
  4782. _context.transform( a, b, c, d, e, f );
  4783. _context.clip();
  4784. _context.drawImage( image, 0, 0 );
  4785. _context.restore();
  4786. }
  4787. function getGradientTexture( color1, color2, color3, color4 ) {
  4788. // http://mrdoob.com/blog/post/710
  4789. var c1r = ~~ ( color1.r * 255 ), c1g = ~~ ( color1.g * 255 ), c1b = ~~ ( color1.b * 255 ),
  4790. c2r = ~~ ( color2.r * 255 ), c2g = ~~ ( color2.g * 255 ), c2b = ~~ ( color2.b * 255 ),
  4791. c3r = ~~ ( color3.r * 255 ), c3g = ~~ ( color3.g * 255 ), c3b = ~~ ( color3.b * 255 ),
  4792. c4r = ~~ ( color4.r * 255 ), c4g = ~~ ( color4.g * 255 ), c4b = ~~ ( color4.b * 255 );
  4793. _pixelMapData[ 0 ] = c1r < 0 ? 0 : c1r > 255 ? 255 : c1r;
  4794. _pixelMapData[ 1 ] = c1g < 0 ? 0 : c1g > 255 ? 255 : c1g;
  4795. _pixelMapData[ 2 ] = c1b < 0 ? 0 : c1b > 255 ? 255 : c1b;
  4796. _pixelMapData[ 4 ] = c2r < 0 ? 0 : c2r > 255 ? 255 : c2r;
  4797. _pixelMapData[ 5 ] = c2g < 0 ? 0 : c2g > 255 ? 255 : c2g;
  4798. _pixelMapData[ 6 ] = c2b < 0 ? 0 : c2b > 255 ? 255 : c2b;
  4799. _pixelMapData[ 8 ] = c3r < 0 ? 0 : c3r > 255 ? 255 : c3r;
  4800. _pixelMapData[ 9 ] = c3g < 0 ? 0 : c3g > 255 ? 255 : c3g;
  4801. _pixelMapData[ 10 ] = c3b < 0 ? 0 : c3b > 255 ? 255 : c3b;
  4802. _pixelMapData[ 12 ] = c4r < 0 ? 0 : c4r > 255 ? 255 : c4r;
  4803. _pixelMapData[ 13 ] = c4g < 0 ? 0 : c4g > 255 ? 255 : c4g;
  4804. _pixelMapData[ 14 ] = c4b < 0 ? 0 : c4b > 255 ? 255 : c4b;
  4805. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  4806. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  4807. return _gradientMap;
  4808. }
  4809. function smoothstep( value, min, max ) {
  4810. var x = ( value - min ) / ( max - min );
  4811. return x * x * ( 3 - 2 * x );
  4812. }
  4813. function normalToComponent( normal ) {
  4814. var component = ( normal + 1 ) * 0.5;
  4815. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  4816. }
  4817. // Hide anti-alias gaps
  4818. function expand( v1, v2 ) {
  4819. var x = v2.x - v1.x, y = v2.y - v1.y,
  4820. det = x * x + y * y, idet;
  4821. if ( det == 0 ) return;
  4822. idet = 1 / Math.sqrt( det );
  4823. x *= idet; y *= idet;
  4824. v2.x += x; v2.y += y;
  4825. v1.x -= x; v1.y -= y;
  4826. }
  4827. };
  4828. // Context cached methods.
  4829. function setOpacity( value ) {
  4830. if ( _contextGlobalAlpha != value ) {
  4831. _context.globalAlpha = _contextGlobalAlpha = value;
  4832. }
  4833. }
  4834. function setBlending( value ) {
  4835. if ( _contextGlobalCompositeOperation != value ) {
  4836. switch ( value ) {
  4837. case THREE.NormalBlending:
  4838. _context.globalCompositeOperation = 'source-over';
  4839. break;
  4840. case THREE.AdditiveBlending:
  4841. _context.globalCompositeOperation = 'lighter';
  4842. break;
  4843. case THREE.SubtractiveBlending:
  4844. _context.globalCompositeOperation = 'darker';
  4845. break;
  4846. }
  4847. _contextGlobalCompositeOperation = value;
  4848. }
  4849. }
  4850. function setLineWidth( value ) {
  4851. if ( _contextLineWidth != value ) {
  4852. _context.lineWidth = _contextLineWidth = value;
  4853. }
  4854. }
  4855. function setLineCap( value ) {
  4856. // "butt", "round", "square"
  4857. if ( _contextLineCap != value ) {
  4858. _context.lineCap = _contextLineCap = value;
  4859. }
  4860. }
  4861. function setLineJoin( value ) {
  4862. // "round", "bevel", "miter"
  4863. if ( _contextLineJoin != value ) {
  4864. _context.lineJoin = _contextLineJoin = value;
  4865. }
  4866. }
  4867. function setStrokeStyle( style ) {
  4868. if ( _contextStrokeStyle != style ) {
  4869. _context.strokeStyle = _contextStrokeStyle = style;
  4870. }
  4871. }
  4872. function setFillStyle( style ) {
  4873. if ( _contextFillStyle != style ) {
  4874. _context.fillStyle = _contextFillStyle = style;
  4875. }
  4876. }
  4877. };
  4878. /**
  4879. * @author mr.doob / http://mrdoob.com/
  4880. */
  4881. THREE.SVGRenderer = function () {
  4882. var _this = this,
  4883. _renderData, _elements, _lights,
  4884. _projector = new THREE.Projector(),
  4885. _svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
  4886. _svgWidth, _svgHeight, _svgWidthHalf, _svgHeightHalf,
  4887. _v1, _v2, _v3, _v4,
  4888. _clipRect = new THREE.Rectangle(),
  4889. _bboxRect = new THREE.Rectangle(),
  4890. _enableLighting = false,
  4891. _color = new THREE.Color(),
  4892. _ambientLight = new THREE.Color(),
  4893. _directionalLights = new THREE.Color(),
  4894. _pointLights = new THREE.Color(),
  4895. _w, // z-buffer to w-buffer
  4896. _vector3 = new THREE.Vector3(), // Needed for PointLight
  4897. _svgPathPool = [], _svgCirclePool = [], _svgLinePool = [],
  4898. _svgNode, _pathCount, _circleCount, _lineCount,
  4899. _quality = 1;
  4900. this.domElement = _svg;
  4901. this.autoClear = true;
  4902. this.sortObjects = true;
  4903. this.sortElements = true;
  4904. this.info = {
  4905. render: {
  4906. vertices: 0,
  4907. faces: 0
  4908. }
  4909. }
  4910. this.setQuality = function( quality ) {
  4911. switch(quality) {
  4912. case "high": _quality = 1; break;
  4913. case "low": _quality = 0; break;
  4914. }
  4915. };
  4916. this.setSize = function( width, height ) {
  4917. _svgWidth = width; _svgHeight = height;
  4918. _svgWidthHalf = _svgWidth / 2; _svgHeightHalf = _svgHeight / 2;
  4919. _svg.setAttribute( 'viewBox', ( - _svgWidthHalf ) + ' ' + ( - _svgHeightHalf ) + ' ' + _svgWidth + ' ' + _svgHeight );
  4920. _svg.setAttribute( 'width', _svgWidth );
  4921. _svg.setAttribute( 'height', _svgHeight );
  4922. _clipRect.set( - _svgWidthHalf, - _svgHeightHalf, _svgWidthHalf, _svgHeightHalf );
  4923. };
  4924. this.clear = function () {
  4925. while ( _svg.childNodes.length > 0 ) {
  4926. _svg.removeChild( _svg.childNodes[ 0 ] );
  4927. }
  4928. };
  4929. this.render = function ( scene, camera ) {
  4930. var e, el, element, material;
  4931. this.autoClear && this.clear();
  4932. _this.info.render.vertices = 0;
  4933. _this.info.render.faces = 0;
  4934. _renderData = _projector.projectScene( scene, camera, this.sortElements );
  4935. _elements = _renderData.elements;
  4936. _lights = _renderData.lights;
  4937. _pathCount = 0; _circleCount = 0; _lineCount = 0;
  4938. _enableLighting = _lights.length > 0;
  4939. if ( _enableLighting ) {
  4940. calculateLights( _lights );
  4941. }
  4942. for ( e = 0, el = _elements.length; e < el; e ++ ) {
  4943. element = _elements[ e ];
  4944. material = element.material;
  4945. material = material instanceof THREE.MeshFaceMaterial ? element.faceMaterial : material;
  4946. if ( material == null || material.opacity == 0 ) continue;
  4947. _bboxRect.empty();
  4948. if ( element instanceof THREE.RenderableParticle ) {
  4949. _v1 = element;
  4950. _v1.x *= _svgWidthHalf; _v1.y *= -_svgHeightHalf;
  4951. renderParticle( _v1, element, material, scene );
  4952. } else if ( element instanceof THREE.RenderableLine ) {
  4953. _v1 = element.v1; _v2 = element.v2;
  4954. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf;
  4955. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf;
  4956. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4957. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4958. if ( !_clipRect.intersects( _bboxRect ) ) {
  4959. continue;
  4960. }
  4961. renderLine( _v1, _v2, element, material, scene );
  4962. } else if ( element instanceof THREE.RenderableFace3 ) {
  4963. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  4964. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf;
  4965. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf;
  4966. _v3.positionScreen.x *= _svgWidthHalf; _v3.positionScreen.y *= - _svgHeightHalf;
  4967. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4968. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4969. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  4970. if ( !_clipRect.intersects( _bboxRect ) ) {
  4971. continue;
  4972. }
  4973. renderFace3( _v1, _v2, _v3, element, material, scene );
  4974. } else if ( element instanceof THREE.RenderableFace4 ) {
  4975. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  4976. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= -_svgHeightHalf;
  4977. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= -_svgHeightHalf;
  4978. _v3.positionScreen.x *= _svgWidthHalf; _v3.positionScreen.y *= -_svgHeightHalf;
  4979. _v4.positionScreen.x *= _svgWidthHalf; _v4.positionScreen.y *= -_svgHeightHalf;
  4980. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4981. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4982. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  4983. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  4984. if ( !_clipRect.intersects( _bboxRect) ) {
  4985. continue;
  4986. }
  4987. renderFace4( _v1, _v2, _v3, _v4, element, material, scene );
  4988. }
  4989. }
  4990. };
  4991. function calculateLights( lights ) {
  4992. var l, ll, light, lightColor;
  4993. _ambientLight.setRGB( 0, 0, 0 );
  4994. _directionalLights.setRGB( 0, 0, 0 );
  4995. _pointLights.setRGB( 0, 0, 0 );
  4996. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  4997. light = lights[ l ];
  4998. lightColor = light.color;
  4999. if ( light instanceof THREE.AmbientLight ) {
  5000. _ambientLight.r += lightColor.r;
  5001. _ambientLight.g += lightColor.g;
  5002. _ambientLight.b += lightColor.b;
  5003. } else if ( light instanceof THREE.DirectionalLight ) {
  5004. _directionalLights.r += lightColor.r;
  5005. _directionalLights.g += lightColor.g;
  5006. _directionalLights.b += lightColor.b;
  5007. } else if ( light instanceof THREE.PointLight ) {
  5008. _pointLights.r += lightColor.r;
  5009. _pointLights.g += lightColor.g;
  5010. _pointLights.b += lightColor.b;
  5011. }
  5012. }
  5013. }
  5014. function calculateLight( lights, position, normal, color ) {
  5015. var l, ll, light, lightColor, lightPosition, amount;
  5016. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  5017. light = lights[ l ];
  5018. lightColor = light.color;
  5019. if ( light instanceof THREE.DirectionalLight ) {
  5020. lightPosition = light.matrixWorld.getPosition();
  5021. amount = normal.dot( lightPosition );
  5022. if ( amount <= 0 ) continue;
  5023. amount *= light.intensity;
  5024. color.r += lightColor.r * amount;
  5025. color.g += lightColor.g * amount;
  5026. color.b += lightColor.b * amount;
  5027. } else if ( light instanceof THREE.PointLight ) {
  5028. lightPosition = light.matrixWorld.getPosition();
  5029. amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  5030. if ( amount <= 0 ) continue;
  5031. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  5032. if ( amount == 0 ) continue;
  5033. amount *= light.intensity;
  5034. color.r += lightColor.r * amount;
  5035. color.g += lightColor.g * amount;
  5036. color.b += lightColor.b * amount;
  5037. }
  5038. }
  5039. }
  5040. function renderParticle( v1, element, material, scene ) {
  5041. /*
  5042. _svgNode = getCircleNode( _circleCount++ );
  5043. _svgNode.setAttribute( 'cx', v1.x );
  5044. _svgNode.setAttribute( 'cy', v1.y );
  5045. _svgNode.setAttribute( 'r', element.scale.x * _svgWidthHalf );
  5046. if ( material instanceof THREE.ParticleCircleMaterial ) {
  5047. if ( _enableLighting ) {
  5048. _color.r = _ambientLight.r + _directionalLights.r + _pointLights.r;
  5049. _color.g = _ambientLight.g + _directionalLights.g + _pointLights.g;
  5050. _color.b = _ambientLight.b + _directionalLights.b + _pointLights.b;
  5051. _color.r = material.color.r * _color.r;
  5052. _color.g = material.color.g * _color.g;
  5053. _color.b = material.color.b * _color.b;
  5054. _color.updateStyleString();
  5055. } else {
  5056. _color = material.color;
  5057. }
  5058. _svgNode.setAttribute( 'style', 'fill: ' + _color.__styleString );
  5059. }
  5060. _svg.appendChild( _svgNode );
  5061. */
  5062. }
  5063. function renderLine ( v1, v2, element, material, scene ) {
  5064. _svgNode = getLineNode( _lineCount ++ );
  5065. _svgNode.setAttribute( 'x1', v1.positionScreen.x );
  5066. _svgNode.setAttribute( 'y1', v1.positionScreen.y );
  5067. _svgNode.setAttribute( 'x2', v2.positionScreen.x );
  5068. _svgNode.setAttribute( 'y2', v2.positionScreen.y );
  5069. if ( material instanceof THREE.LineBasicMaterial ) {
  5070. _svgNode.setAttribute( 'style', 'fill: none; stroke: ' + material.color.getContextStyle() + '; stroke-width: ' + material.linewidth + '; stroke-opacity: ' + material.opacity + '; stroke-linecap: ' + material.linecap + '; stroke-linejoin: ' + material.linejoin );
  5071. _svg.appendChild( _svgNode );
  5072. }
  5073. }
  5074. function renderFace3( v1, v2, v3, element, material, scene ) {
  5075. _this.info.render.vertices += 3;
  5076. _this.info.render.faces ++;
  5077. _svgNode = getPathNode( _pathCount ++ );
  5078. _svgNode.setAttribute( 'd', 'M ' + v1.positionScreen.x + ' ' + v1.positionScreen.y + ' L ' + v2.positionScreen.x + ' ' + v2.positionScreen.y + ' L ' + v3.positionScreen.x + ',' + v3.positionScreen.y + 'z' );
  5079. if ( material instanceof THREE.MeshBasicMaterial ) {
  5080. _color.copy( material.color );
  5081. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  5082. if ( _enableLighting ) {
  5083. _color.r = _ambientLight.r;
  5084. _color.g = _ambientLight.g;
  5085. _color.b = _ambientLight.b;
  5086. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  5087. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  5088. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  5089. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  5090. } else {
  5091. _color.copy( material.color );
  5092. }
  5093. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  5094. _w = 1 - ( material.__2near / (material.__farPlusNear - element.z * material.__farMinusNear) );
  5095. _color.setRGB( _w, _w, _w );
  5096. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  5097. _color.setRGB( normalToComponent( element.normalWorld.x ), normalToComponent( element.normalWorld.y ), normalToComponent( element.normalWorld.z ) );
  5098. }
  5099. if ( material.wireframe ) {
  5100. _svgNode.setAttribute( 'style', 'fill: none; stroke: ' + _color.getContextStyle() + '; stroke-width: ' + material.wireframeLinewidth + '; stroke-opacity: ' + material.opacity + '; stroke-linecap: ' + material.wireframeLinecap + '; stroke-linejoin: ' + material.wireframeLinejoin );
  5101. } else {
  5102. _svgNode.setAttribute( 'style', 'fill: ' + _color.getContextStyle() + '; fill-opacity: ' + material.opacity );
  5103. }
  5104. _svg.appendChild( _svgNode );
  5105. }
  5106. function renderFace4( v1, v2, v3, v4, element, material, scene ) {
  5107. _this.info.render.vertices += 4;
  5108. _this.info.render.faces ++;
  5109. _svgNode = getPathNode( _pathCount ++ );
  5110. _svgNode.setAttribute( 'd', 'M ' + v1.positionScreen.x + ' ' + v1.positionScreen.y + ' L ' + v2.positionScreen.x + ' ' + v2.positionScreen.y + ' L ' + v3.positionScreen.x + ',' + v3.positionScreen.y + ' L ' + v4.positionScreen.x + ',' + v4.positionScreen.y + 'z' );
  5111. if ( material instanceof THREE.MeshBasicMaterial ) {
  5112. _color.copy( material.color );
  5113. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  5114. if ( _enableLighting ) {
  5115. _color.r = _ambientLight.r;
  5116. _color.g = _ambientLight.g;
  5117. _color.b = _ambientLight.b;
  5118. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  5119. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  5120. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  5121. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  5122. } else {
  5123. _color.copy( material.color );
  5124. }
  5125. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  5126. _w = 1 - ( material.__2near / (material.__farPlusNear - element.z * material.__farMinusNear) );
  5127. _color.setRGB( _w, _w, _w );
  5128. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  5129. _color.setRGB( normalToComponent( element.normalWorld.x ), normalToComponent( element.normalWorld.y ), normalToComponent( element.normalWorld.z ) );
  5130. }
  5131. if ( material.wireframe ) {
  5132. _svgNode.setAttribute( 'style', 'fill: none; stroke: ' + _color.getContextStyle() + '; stroke-width: ' + material.wireframeLinewidth + '; stroke-opacity: ' + material.opacity + '; stroke-linecap: ' + material.wireframeLinecap + '; stroke-linejoin: ' + material.wireframeLinejoin );
  5133. } else {
  5134. _svgNode.setAttribute( 'style', 'fill: ' + _color.getContextStyle() + '; fill-opacity: ' + material.opacity );
  5135. }
  5136. _svg.appendChild( _svgNode );
  5137. }
  5138. function getLineNode( id ) {
  5139. if ( _svgLinePool[ id ] == null ) {
  5140. _svgLinePool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'line' );
  5141. if ( _quality == 0 ) {
  5142. _svgLinePool[ id ].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  5143. }
  5144. return _svgLinePool[ id ];
  5145. }
  5146. return _svgLinePool[ id ];
  5147. }
  5148. function getPathNode( id ) {
  5149. if ( _svgPathPool[ id ] == null ) {
  5150. _svgPathPool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
  5151. if ( _quality == 0 ) {
  5152. _svgPathPool[ id ].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  5153. }
  5154. return _svgPathPool[ id ];
  5155. }
  5156. return _svgPathPool[ id ];
  5157. }
  5158. function getCircleNode( id ) {
  5159. if ( _svgCirclePool[id] == null ) {
  5160. _svgCirclePool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'circle' );
  5161. if ( _quality == 0 ) {
  5162. _svgCirclePool[id].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  5163. }
  5164. return _svgCirclePool[ id ];
  5165. }
  5166. return _svgCirclePool[ id ];
  5167. }
  5168. function normalToComponent( normal ) {
  5169. var component = ( normal + 1 ) * 0.5;
  5170. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  5171. }
  5172. function pad( str ) {
  5173. while ( str.length < 6 ) str = '0' + str;
  5174. return str;
  5175. }
  5176. };
  5177. /**
  5178. * @author alteredq / http://alteredqualia.com/
  5179. * @author mrdoob / http://mrdoob.com/
  5180. * @author mikael emtinger / http://gomo.se/
  5181. */
  5182. THREE.ShaderChunk = {
  5183. // FOG
  5184. fog_pars_fragment: [
  5185. "#ifdef USE_FOG",
  5186. "uniform vec3 fogColor;",
  5187. "#ifdef FOG_EXP2",
  5188. "uniform float fogDensity;",
  5189. "#else",
  5190. "uniform float fogNear;",
  5191. "uniform float fogFar;",
  5192. "#endif",
  5193. "#endif"
  5194. ].join("\n"),
  5195. fog_fragment: [
  5196. "#ifdef USE_FOG",
  5197. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  5198. "#ifdef FOG_EXP2",
  5199. "const float LOG2 = 1.442695;",
  5200. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  5201. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  5202. "#else",
  5203. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  5204. "#endif",
  5205. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  5206. "#endif"
  5207. ].join("\n"),
  5208. // ENVIRONMENT MAP
  5209. envmap_pars_fragment: [
  5210. "#ifdef USE_ENVMAP",
  5211. "varying vec3 vReflect;",
  5212. "uniform float reflectivity;",
  5213. "uniform samplerCube envMap;",
  5214. "uniform float flipEnvMap;",
  5215. "uniform int combine;",
  5216. "#endif"
  5217. ].join("\n"),
  5218. envmap_fragment: [
  5219. "#ifdef USE_ENVMAP",
  5220. "#ifdef DOUBLE_SIDED",
  5221. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  5222. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * vReflect.x, vReflect.yz ) );",
  5223. "#else",
  5224. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * vReflect.x, vReflect.yz ) );",
  5225. "#endif",
  5226. "#ifdef GAMMA_INPUT",
  5227. "cubeColor.xyz *= cubeColor.xyz;",
  5228. "#endif",
  5229. "if ( combine == 1 ) {",
  5230. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, reflectivity );",
  5231. "} else {",
  5232. "gl_FragColor.xyz = gl_FragColor.xyz * cubeColor.xyz;",
  5233. "}",
  5234. "#endif"
  5235. ].join("\n"),
  5236. envmap_pars_vertex: [
  5237. "#ifdef USE_ENVMAP",
  5238. "varying vec3 vReflect;",
  5239. "uniform float refractionRatio;",
  5240. "uniform bool useRefract;",
  5241. "#endif"
  5242. ].join("\n"),
  5243. envmap_vertex : [
  5244. "#ifdef USE_ENVMAP",
  5245. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  5246. "vec3 nWorld = mat3( objectMatrix[ 0 ].xyz, objectMatrix[ 1 ].xyz, objectMatrix[ 2 ].xyz ) * normal;",
  5247. "if ( useRefract ) {",
  5248. "vReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refractionRatio );",
  5249. "} else {",
  5250. "vReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );",
  5251. "}",
  5252. "#endif"
  5253. ].join("\n"),
  5254. // COLOR MAP (particles)
  5255. map_particle_pars_fragment: [
  5256. "#ifdef USE_MAP",
  5257. "uniform sampler2D map;",
  5258. "#endif"
  5259. ].join("\n"),
  5260. map_particle_fragment: [
  5261. "#ifdef USE_MAP",
  5262. "gl_FragColor = gl_FragColor * texture2D( map, gl_PointCoord );",
  5263. "#endif"
  5264. ].join("\n"),
  5265. // COLOR MAP (triangles)
  5266. map_pars_vertex: [
  5267. "#ifdef USE_MAP",
  5268. "varying vec2 vUv;",
  5269. "uniform vec4 offsetRepeat;",
  5270. "#endif"
  5271. ].join("\n"),
  5272. map_pars_fragment: [
  5273. "#ifdef USE_MAP",
  5274. "varying vec2 vUv;",
  5275. "uniform sampler2D map;",
  5276. "#endif"
  5277. ].join("\n"),
  5278. map_vertex: [
  5279. "#ifdef USE_MAP",
  5280. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  5281. "#endif"
  5282. ].join("\n"),
  5283. map_fragment: [
  5284. "#ifdef USE_MAP",
  5285. "#ifdef GAMMA_INPUT",
  5286. "vec4 texelColor = texture2D( map, vUv );",
  5287. "texelColor.xyz *= texelColor.xyz;",
  5288. "gl_FragColor = gl_FragColor * texelColor;",
  5289. "#else",
  5290. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  5291. "#endif",
  5292. "#endif"
  5293. ].join("\n"),
  5294. // LIGHT MAP
  5295. lightmap_pars_fragment: [
  5296. "#ifdef USE_LIGHTMAP",
  5297. "varying vec2 vUv2;",
  5298. "uniform sampler2D lightMap;",
  5299. "#endif"
  5300. ].join("\n"),
  5301. lightmap_pars_vertex: [
  5302. "#ifdef USE_LIGHTMAP",
  5303. "varying vec2 vUv2;",
  5304. "#endif"
  5305. ].join("\n"),
  5306. lightmap_fragment: [
  5307. "#ifdef USE_LIGHTMAP",
  5308. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  5309. "#endif"
  5310. ].join("\n"),
  5311. lightmap_vertex: [
  5312. "#ifdef USE_LIGHTMAP",
  5313. "vUv2 = uv2;",
  5314. "#endif"
  5315. ].join("\n"),
  5316. // LIGHTS LAMBERT
  5317. lights_lambert_pars_vertex: [
  5318. "uniform vec3 ambient;",
  5319. "uniform vec3 diffuse;",
  5320. "uniform vec3 emissive;",
  5321. "uniform vec3 ambientLightColor;",
  5322. "#if MAX_DIR_LIGHTS > 0",
  5323. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  5324. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  5325. "#endif",
  5326. "#if MAX_POINT_LIGHTS > 0",
  5327. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  5328. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  5329. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  5330. "#endif",
  5331. "#ifdef WRAP_AROUND",
  5332. "uniform vec3 wrapRGB;",
  5333. "#endif",
  5334. ].join("\n"),
  5335. lights_lambert_vertex: [
  5336. "vLightFront = vec3( 0.0 );",
  5337. "#ifdef DOUBLE_SIDED",
  5338. "vLightBack = vec3( 0.0 );",
  5339. "#endif",
  5340. "transformedNormal = normalize( transformedNormal );",
  5341. "#if MAX_DIR_LIGHTS > 0",
  5342. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  5343. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  5344. "vec3 dirVector = normalize( lDirection.xyz );",
  5345. "float dotProduct = dot( transformedNormal, dirVector );",
  5346. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  5347. "#ifdef DOUBLE_SIDED",
  5348. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  5349. "#ifdef WRAP_AROUND",
  5350. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  5351. "#endif",
  5352. "#endif",
  5353. "#ifdef WRAP_AROUND",
  5354. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  5355. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  5356. "#ifdef DOUBLE_SIDED",
  5357. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  5358. "#endif",
  5359. "#endif",
  5360. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  5361. "#ifdef DOUBLE_SIDED",
  5362. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  5363. "#endif",
  5364. "}",
  5365. "#endif",
  5366. "#if MAX_POINT_LIGHTS > 0",
  5367. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  5368. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  5369. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  5370. "float lDistance = 1.0;",
  5371. "if ( pointLightDistance[ i ] > 0.0 )",
  5372. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  5373. "lVector = normalize( lVector );",
  5374. "float dotProduct = dot( transformedNormal, lVector );",
  5375. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  5376. "#ifdef DOUBLE_SIDED",
  5377. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  5378. "#ifdef WRAP_AROUND",
  5379. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  5380. "#endif",
  5381. "#endif",
  5382. "#ifdef WRAP_AROUND",
  5383. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  5384. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  5385. "#ifdef DOUBLE_SIDED",
  5386. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  5387. "#endif",
  5388. "#endif",
  5389. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  5390. "#ifdef DOUBLE_SIDED",
  5391. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  5392. "#endif",
  5393. "}",
  5394. "#endif",
  5395. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  5396. "#ifdef DOUBLE_SIDED",
  5397. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  5398. "#endif",
  5399. ].join("\n"),
  5400. // LIGHTS PHONG
  5401. lights_phong_pars_vertex: [
  5402. "#if MAX_POINT_LIGHTS > 0",
  5403. "#ifndef PHONG_PER_PIXEL",
  5404. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  5405. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  5406. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  5407. "#endif",
  5408. "#endif"
  5409. ].join("\n"),
  5410. lights_phong_vertex: [
  5411. "#if MAX_POINT_LIGHTS > 0",
  5412. "#ifndef PHONG_PER_PIXEL",
  5413. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  5414. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  5415. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  5416. "float lDistance = 1.0;",
  5417. "if ( pointLightDistance[ i ] > 0.0 )",
  5418. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  5419. "vPointLight[ i ] = vec4( lVector, lDistance );",
  5420. "}",
  5421. "#endif",
  5422. "#endif"
  5423. ].join("\n"),
  5424. lights_phong_pars_fragment: [
  5425. "uniform vec3 ambientLightColor;",
  5426. "#if MAX_DIR_LIGHTS > 0",
  5427. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  5428. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  5429. "#endif",
  5430. "#if MAX_POINT_LIGHTS > 0",
  5431. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  5432. "#ifdef PHONG_PER_PIXEL",
  5433. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  5434. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  5435. "#else",
  5436. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  5437. "#endif",
  5438. "#endif",
  5439. "#ifdef WRAP_AROUND",
  5440. "uniform vec3 wrapRGB;",
  5441. "#endif",
  5442. "varying vec3 vViewPosition;",
  5443. "varying vec3 vNormal;"
  5444. ].join("\n"),
  5445. lights_phong_fragment: [
  5446. "vec3 normal = normalize( vNormal );",
  5447. "vec3 viewPosition = normalize( vViewPosition );",
  5448. "#ifdef DOUBLE_SIDED",
  5449. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  5450. "#endif",
  5451. "#if MAX_POINT_LIGHTS > 0",
  5452. "vec3 pointDiffuse = vec3( 0.0 );",
  5453. "vec3 pointSpecular = vec3( 0.0 );",
  5454. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  5455. "#ifdef PHONG_PER_PIXEL",
  5456. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  5457. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  5458. "float lDistance = 1.0;",
  5459. "if ( pointLightDistance[ i ] > 0.0 )",
  5460. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  5461. "lVector = normalize( lVector );",
  5462. "#else",
  5463. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  5464. "float lDistance = vPointLight[ i ].w;",
  5465. "#endif",
  5466. // diffuse
  5467. "float dotProduct = dot( normal, lVector );",
  5468. "#ifdef WRAP_AROUND",
  5469. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  5470. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  5471. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  5472. "#else",
  5473. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  5474. "#endif",
  5475. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  5476. // specular
  5477. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  5478. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  5479. "float pointSpecularWeight = max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  5480. "#ifdef PHYSICALLY_BASED_SHADING",
  5481. // 2.0 => 2.0001 is hack to work around ANGLE bug
  5482. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  5483. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  5484. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  5485. "#else",
  5486. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  5487. "#endif",
  5488. "}",
  5489. "#endif",
  5490. "#if MAX_DIR_LIGHTS > 0",
  5491. "vec3 dirDiffuse = vec3( 0.0 );",
  5492. "vec3 dirSpecular = vec3( 0.0 );" ,
  5493. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  5494. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  5495. "vec3 dirVector = normalize( lDirection.xyz );",
  5496. // diffuse
  5497. "float dotProduct = dot( normal, dirVector );",
  5498. "#ifdef WRAP_AROUND",
  5499. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  5500. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  5501. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  5502. "#else",
  5503. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  5504. "#endif",
  5505. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  5506. // specular
  5507. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  5508. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  5509. "float dirSpecularWeight = max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  5510. "#ifdef PHYSICALLY_BASED_SHADING",
  5511. /*
  5512. // fresnel term from skin shader
  5513. "const float F0 = 0.128;",
  5514. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  5515. "float exponential = pow( base, 5.0 );",
  5516. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  5517. */
  5518. /*
  5519. // fresnel term from fresnel shader
  5520. "const float mFresnelBias = 0.08;",
  5521. "const float mFresnelScale = 0.3;",
  5522. "const float mFresnelPower = 5.0;",
  5523. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  5524. */
  5525. // 2.0 => 2.0001 is hack to work around ANGLE bug
  5526. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  5527. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  5528. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  5529. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  5530. "#else",
  5531. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  5532. "#endif",
  5533. "}",
  5534. "#endif",
  5535. "vec3 totalDiffuse = vec3( 0.0 );",
  5536. "vec3 totalSpecular = vec3( 0.0 );",
  5537. "#if MAX_DIR_LIGHTS > 0",
  5538. "totalDiffuse += dirDiffuse;",
  5539. "totalSpecular += dirSpecular;",
  5540. "#endif",
  5541. "#if MAX_POINT_LIGHTS > 0",
  5542. "totalDiffuse += pointDiffuse;",
  5543. "totalSpecular += pointSpecular;",
  5544. "#endif",
  5545. "#ifdef METAL",
  5546. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  5547. "#else",
  5548. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  5549. "#endif"
  5550. ].join("\n"),
  5551. // VERTEX COLORS
  5552. color_pars_fragment: [
  5553. "#ifdef USE_COLOR",
  5554. "varying vec3 vColor;",
  5555. "#endif"
  5556. ].join("\n"),
  5557. color_fragment: [
  5558. "#ifdef USE_COLOR",
  5559. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  5560. "#endif"
  5561. ].join("\n"),
  5562. color_pars_vertex: [
  5563. "#ifdef USE_COLOR",
  5564. "varying vec3 vColor;",
  5565. "#endif"
  5566. ].join("\n"),
  5567. color_vertex: [
  5568. "#ifdef USE_COLOR",
  5569. "#ifdef GAMMA_INPUT",
  5570. "vColor = color * color;",
  5571. "#else",
  5572. "vColor = color;",
  5573. "#endif",
  5574. "#endif"
  5575. ].join("\n"),
  5576. // SKINNING
  5577. skinning_pars_vertex: [
  5578. "#ifdef USE_SKINNING",
  5579. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  5580. "#endif"
  5581. ].join("\n"),
  5582. skinning_vertex: [
  5583. "#ifdef USE_SKINNING",
  5584. "gl_Position = ( boneGlobalMatrices[ int( skinIndex.x ) ] * skinVertexA ) * skinWeight.x;",
  5585. "gl_Position += ( boneGlobalMatrices[ int( skinIndex.y ) ] * skinVertexB ) * skinWeight.y;",
  5586. "gl_Position = projectionMatrix * modelViewMatrix * gl_Position;",
  5587. "#endif"
  5588. ].join("\n"),
  5589. // MORPHING
  5590. morphtarget_pars_vertex: [
  5591. "#ifdef USE_MORPHTARGETS",
  5592. "#ifndef USE_MORPHNORMALS",
  5593. "uniform float morphTargetInfluences[ 8 ];",
  5594. "#else",
  5595. "uniform float morphTargetInfluences[ 4 ];",
  5596. "#endif",
  5597. "#endif"
  5598. ].join("\n"),
  5599. morphtarget_vertex: [
  5600. "#ifdef USE_MORPHTARGETS",
  5601. "vec3 morphed = vec3( 0.0 );",
  5602. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  5603. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  5604. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  5605. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  5606. "#ifndef USE_MORPHNORMALS",
  5607. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  5608. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  5609. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  5610. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  5611. "#endif",
  5612. "morphed += position;",
  5613. "gl_Position = projectionMatrix * modelViewMatrix * vec4( morphed, 1.0 );",
  5614. "#endif"
  5615. ].join("\n"),
  5616. default_vertex : [
  5617. "#ifndef USE_MORPHTARGETS",
  5618. "#ifndef USE_SKINNING",
  5619. "gl_Position = projectionMatrix * mvPosition;",
  5620. "#endif",
  5621. "#endif"
  5622. ].join("\n"),
  5623. morphnormal_vertex: [
  5624. "#ifdef USE_MORPHNORMALS",
  5625. "vec3 morphedNormal = vec3( 0.0 );",
  5626. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  5627. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  5628. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  5629. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  5630. "morphedNormal += normal;",
  5631. "vec3 transformedNormal = normalMatrix * morphedNormal;",
  5632. "#else",
  5633. "vec3 transformedNormal = normalMatrix * normal;",
  5634. "#endif"
  5635. ].join("\n"),
  5636. // SHADOW MAP
  5637. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  5638. // http://spidergl.org/example.php?id=6
  5639. // http://fabiensanglard.net/shadowmapping
  5640. shadowmap_pars_fragment: [
  5641. "#ifdef USE_SHADOWMAP",
  5642. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  5643. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  5644. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  5645. "uniform float shadowBias[ MAX_SHADOWS ];",
  5646. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  5647. "float unpackDepth( const in vec4 rgba_depth ) {",
  5648. "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 );",
  5649. "float depth = dot( rgba_depth, bit_shift );",
  5650. "return depth;",
  5651. "}",
  5652. "#endif"
  5653. ].join("\n"),
  5654. shadowmap_fragment: [
  5655. "#ifdef USE_SHADOWMAP",
  5656. "#ifdef SHADOWMAP_DEBUG",
  5657. "vec3 frustumColors[3];",
  5658. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  5659. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  5660. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  5661. "#endif",
  5662. "#ifdef SHADOWMAP_CASCADE",
  5663. "int inFrustumCount = 0;",
  5664. "#endif",
  5665. "float fDepth;",
  5666. "vec3 shadowColor = vec3( 1.0 );",
  5667. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  5668. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  5669. // "if ( something && something )" breaks ATI OpenGL shader compiler
  5670. // "if ( all( something, something ) )" using this instead
  5671. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  5672. "bool inFrustum = all( inFrustumVec );",
  5673. // don't shadow pixels outside of light frustum
  5674. // use just first frustum (for cascades)
  5675. // don't shadow pixels behind far plane of light frustum
  5676. "#ifdef SHADOWMAP_CASCADE",
  5677. "inFrustumCount += int( inFrustum );",
  5678. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  5679. "#else",
  5680. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  5681. "#endif",
  5682. "bool frustumTest = all( frustumTestVec );",
  5683. "if ( frustumTest ) {",
  5684. "shadowCoord.z += shadowBias[ i ];",
  5685. "#ifdef SHADOWMAP_SOFT",
  5686. // Percentage-close filtering
  5687. // (9 pixel kernel)
  5688. // http://fabiensanglard.net/shadowmappingPCF/
  5689. "float shadow = 0.0;",
  5690. /*
  5691. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  5692. // must enroll loop manually
  5693. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  5694. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  5695. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  5696. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  5697. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  5698. "float fDepth = unpackDepth( rgbaDepth );",
  5699. "if ( fDepth < shadowCoord.z )",
  5700. "shadow += 1.0;",
  5701. "}",
  5702. "shadow /= 9.0;",
  5703. */
  5704. "const float shadowDelta = 1.0 / 9.0;",
  5705. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  5706. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  5707. "float dx0 = -1.25 * xPixelOffset;",
  5708. "float dy0 = -1.25 * yPixelOffset;",
  5709. "float dx1 = 1.25 * xPixelOffset;",
  5710. "float dy1 = 1.25 * yPixelOffset;",
  5711. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  5712. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5713. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  5714. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5715. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  5716. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5717. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  5718. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5719. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  5720. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5721. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  5722. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5723. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  5724. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5725. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  5726. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5727. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  5728. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5729. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  5730. "#else",
  5731. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  5732. "float fDepth = unpackDepth( rgbaDepth );",
  5733. "if ( fDepth < shadowCoord.z )",
  5734. // spot with multiple shadows is darker
  5735. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  5736. // spot with multiple shadows has the same color as single shadow spot
  5737. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  5738. "#endif",
  5739. "}",
  5740. "#ifdef SHADOWMAP_DEBUG",
  5741. "#ifdef SHADOWMAP_CASCADE",
  5742. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  5743. "#else",
  5744. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  5745. "#endif",
  5746. "#endif",
  5747. "}",
  5748. "#ifdef GAMMA_OUTPUT",
  5749. "shadowColor *= shadowColor;",
  5750. "#endif",
  5751. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  5752. "#endif"
  5753. ].join("\n"),
  5754. shadowmap_pars_vertex: [
  5755. "#ifdef USE_SHADOWMAP",
  5756. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  5757. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  5758. "#endif"
  5759. ].join("\n"),
  5760. shadowmap_vertex: [
  5761. "#ifdef USE_SHADOWMAP",
  5762. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  5763. "#ifdef USE_MORPHTARGETS",
  5764. "vShadowCoord[ i ] = shadowMatrix[ i ] * objectMatrix * vec4( morphed, 1.0 );",
  5765. "#else",
  5766. "vShadowCoord[ i ] = shadowMatrix[ i ] * objectMatrix * vec4( position, 1.0 );",
  5767. "#endif",
  5768. "}",
  5769. "#endif"
  5770. ].join("\n"),
  5771. // ALPHATEST
  5772. alphatest_fragment: [
  5773. "#ifdef ALPHATEST",
  5774. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  5775. "#endif"
  5776. ].join("\n"),
  5777. // LINEAR SPACE
  5778. linear_to_gamma_fragment: [
  5779. "#ifdef GAMMA_OUTPUT",
  5780. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  5781. "#endif"
  5782. ].join("\n"),
  5783. };
  5784. THREE.UniformsUtils = {
  5785. merge: function ( uniforms ) {
  5786. var u, p, tmp, merged = {};
  5787. for ( u = 0; u < uniforms.length; u++ ) {
  5788. tmp = this.clone( uniforms[ u ] );
  5789. for ( p in tmp ) {
  5790. merged[ p ] = tmp[ p ];
  5791. }
  5792. }
  5793. return merged;
  5794. },
  5795. clone: function ( uniforms_src ) {
  5796. var u, p, parameter, parameter_src, uniforms_dst = {};
  5797. for ( u in uniforms_src ) {
  5798. uniforms_dst[ u ] = {};
  5799. for ( p in uniforms_src[ u ] ) {
  5800. parameter_src = uniforms_src[ u ][ p ];
  5801. if ( parameter_src instanceof THREE.Color ||
  5802. parameter_src instanceof THREE.Vector2 ||
  5803. parameter_src instanceof THREE.Vector3 ||
  5804. parameter_src instanceof THREE.Vector4 ||
  5805. parameter_src instanceof THREE.Matrix4 ||
  5806. parameter_src instanceof THREE.Texture ) {
  5807. uniforms_dst[ u ][ p ] = parameter_src.clone();
  5808. } else if ( parameter_src instanceof Array ) {
  5809. uniforms_dst[ u ][ p ] = parameter_src.slice();
  5810. } else {
  5811. uniforms_dst[ u ][ p ] = parameter_src;
  5812. }
  5813. }
  5814. }
  5815. return uniforms_dst;
  5816. }
  5817. };
  5818. THREE.UniformsLib = {
  5819. common: {
  5820. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  5821. "opacity" : { type: "f", value: 1.0 },
  5822. "map" : { type: "t", value: 0, texture: null },
  5823. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  5824. "lightMap" : { type: "t", value: 2, texture: null },
  5825. "envMap" : { type: "t", value: 1, texture: null },
  5826. "flipEnvMap" : { type: "f", value: -1 },
  5827. "useRefract" : { type: "i", value: 0 },
  5828. "reflectivity" : { type: "f", value: 1.0 },
  5829. "refractionRatio" : { type: "f", value: 0.98 },
  5830. "combine" : { type: "i", value: 0 },
  5831. "morphTargetInfluences" : { type: "f", value: 0 }
  5832. },
  5833. fog : {
  5834. "fogDensity" : { type: "f", value: 0.00025 },
  5835. "fogNear" : { type: "f", value: 1 },
  5836. "fogFar" : { type: "f", value: 2000 },
  5837. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  5838. },
  5839. lights: {
  5840. "ambientLightColor" : { type: "fv", value: [] },
  5841. "directionalLightDirection" : { type: "fv", value: [] },
  5842. "directionalLightColor" : { type: "fv", value: [] },
  5843. "pointLightColor" : { type: "fv", value: [] },
  5844. "pointLightPosition" : { type: "fv", value: [] },
  5845. "pointLightDistance" : { type: "fv1", value: [] }
  5846. },
  5847. particle: {
  5848. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  5849. "opacity" : { type: "f", value: 1.0 },
  5850. "size" : { type: "f", value: 1.0 },
  5851. "scale" : { type: "f", value: 1.0 },
  5852. "map" : { type: "t", value: 0, texture: null },
  5853. "fogDensity" : { type: "f", value: 0.00025 },
  5854. "fogNear" : { type: "f", value: 1 },
  5855. "fogFar" : { type: "f", value: 2000 },
  5856. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  5857. },
  5858. shadowmap: {
  5859. "shadowMap": { type: "tv", value: 6, texture: [] },
  5860. "shadowMapSize": { type: "v2v", value: [] },
  5861. "shadowBias" : { type: "fv1", value: [] },
  5862. "shadowDarkness": { type: "fv1", value: [] },
  5863. "shadowMatrix" : { type: "m4v", value: [] },
  5864. }
  5865. };
  5866. THREE.ShaderLib = {
  5867. 'depth': {
  5868. uniforms: {
  5869. "mNear": { type: "f", value: 1.0 },
  5870. "mFar" : { type: "f", value: 2000.0 },
  5871. "opacity" : { type: "f", value: 1.0 }
  5872. },
  5873. vertexShader: [
  5874. "void main() {",
  5875. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  5876. "}"
  5877. ].join("\n"),
  5878. fragmentShader: [
  5879. "uniform float mNear;",
  5880. "uniform float mFar;",
  5881. "uniform float opacity;",
  5882. "void main() {",
  5883. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  5884. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  5885. "gl_FragColor = vec4( vec3( color ), opacity );",
  5886. "}"
  5887. ].join("\n")
  5888. },
  5889. 'normal': {
  5890. uniforms: {
  5891. "opacity" : { type: "f", value: 1.0 }
  5892. },
  5893. vertexShader: [
  5894. "varying vec3 vNormal;",
  5895. "void main() {",
  5896. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  5897. "vNormal = normalMatrix * normal;",
  5898. "gl_Position = projectionMatrix * mvPosition;",
  5899. "}"
  5900. ].join("\n"),
  5901. fragmentShader: [
  5902. "uniform float opacity;",
  5903. "varying vec3 vNormal;",
  5904. "void main() {",
  5905. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  5906. "}"
  5907. ].join("\n")
  5908. },
  5909. 'basic': {
  5910. uniforms: THREE.UniformsUtils.merge( [
  5911. THREE.UniformsLib[ "common" ],
  5912. THREE.UniformsLib[ "fog" ],
  5913. THREE.UniformsLib[ "shadowmap" ]
  5914. ] ),
  5915. vertexShader: [
  5916. THREE.ShaderChunk[ "map_pars_vertex" ],
  5917. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  5918. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  5919. THREE.ShaderChunk[ "color_pars_vertex" ],
  5920. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  5921. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  5922. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  5923. "void main() {",
  5924. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  5925. THREE.ShaderChunk[ "map_vertex" ],
  5926. THREE.ShaderChunk[ "lightmap_vertex" ],
  5927. THREE.ShaderChunk[ "envmap_vertex" ],
  5928. THREE.ShaderChunk[ "color_vertex" ],
  5929. THREE.ShaderChunk[ "skinning_vertex" ],
  5930. THREE.ShaderChunk[ "morphtarget_vertex" ],
  5931. THREE.ShaderChunk[ "default_vertex" ],
  5932. THREE.ShaderChunk[ "shadowmap_vertex" ],
  5933. "}"
  5934. ].join("\n"),
  5935. fragmentShader: [
  5936. "uniform vec3 diffuse;",
  5937. "uniform float opacity;",
  5938. THREE.ShaderChunk[ "color_pars_fragment" ],
  5939. THREE.ShaderChunk[ "map_pars_fragment" ],
  5940. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  5941. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  5942. THREE.ShaderChunk[ "fog_pars_fragment" ],
  5943. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  5944. "void main() {",
  5945. "gl_FragColor = vec4( diffuse, opacity );",
  5946. THREE.ShaderChunk[ "map_fragment" ],
  5947. THREE.ShaderChunk[ "alphatest_fragment" ],
  5948. THREE.ShaderChunk[ "lightmap_fragment" ],
  5949. THREE.ShaderChunk[ "color_fragment" ],
  5950. THREE.ShaderChunk[ "envmap_fragment" ],
  5951. THREE.ShaderChunk[ "shadowmap_fragment" ],
  5952. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  5953. THREE.ShaderChunk[ "fog_fragment" ],
  5954. "}"
  5955. ].join("\n")
  5956. },
  5957. 'lambert': {
  5958. uniforms: THREE.UniformsUtils.merge( [
  5959. THREE.UniformsLib[ "common" ],
  5960. THREE.UniformsLib[ "fog" ],
  5961. THREE.UniformsLib[ "lights" ],
  5962. THREE.UniformsLib[ "shadowmap" ],
  5963. {
  5964. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  5965. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  5966. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  5967. }
  5968. ] ),
  5969. vertexShader: [
  5970. "varying vec3 vLightFront;",
  5971. "#ifdef DOUBLE_SIDED",
  5972. "varying vec3 vLightBack;",
  5973. "#endif",
  5974. THREE.ShaderChunk[ "map_pars_vertex" ],
  5975. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  5976. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  5977. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  5978. THREE.ShaderChunk[ "color_pars_vertex" ],
  5979. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  5980. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  5981. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  5982. "void main() {",
  5983. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  5984. THREE.ShaderChunk[ "map_vertex" ],
  5985. THREE.ShaderChunk[ "lightmap_vertex" ],
  5986. THREE.ShaderChunk[ "envmap_vertex" ],
  5987. THREE.ShaderChunk[ "color_vertex" ],
  5988. THREE.ShaderChunk[ "morphnormal_vertex" ],
  5989. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  5990. THREE.ShaderChunk[ "skinning_vertex" ],
  5991. THREE.ShaderChunk[ "morphtarget_vertex" ],
  5992. THREE.ShaderChunk[ "default_vertex" ],
  5993. THREE.ShaderChunk[ "shadowmap_vertex" ],
  5994. "}"
  5995. ].join("\n"),
  5996. fragmentShader: [
  5997. "uniform float opacity;",
  5998. "varying vec3 vLightFront;",
  5999. "#ifdef DOUBLE_SIDED",
  6000. "varying vec3 vLightBack;",
  6001. "#endif",
  6002. THREE.ShaderChunk[ "color_pars_fragment" ],
  6003. THREE.ShaderChunk[ "map_pars_fragment" ],
  6004. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  6005. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  6006. THREE.ShaderChunk[ "fog_pars_fragment" ],
  6007. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  6008. "void main() {",
  6009. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  6010. THREE.ShaderChunk[ "map_fragment" ],
  6011. THREE.ShaderChunk[ "alphatest_fragment" ],
  6012. "#ifdef DOUBLE_SIDED",
  6013. //"float isFront = float( gl_FrontFacing );",
  6014. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  6015. "if ( gl_FrontFacing )",
  6016. "gl_FragColor.xyz *= vLightFront;",
  6017. "else",
  6018. "gl_FragColor.xyz *= vLightBack;",
  6019. "#else",
  6020. "gl_FragColor.xyz *= vLightFront;",
  6021. "#endif",
  6022. THREE.ShaderChunk[ "lightmap_fragment" ],
  6023. THREE.ShaderChunk[ "color_fragment" ],
  6024. THREE.ShaderChunk[ "envmap_fragment" ],
  6025. THREE.ShaderChunk[ "shadowmap_fragment" ],
  6026. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  6027. THREE.ShaderChunk[ "fog_fragment" ],
  6028. "}"
  6029. ].join("\n")
  6030. },
  6031. 'phong': {
  6032. uniforms: THREE.UniformsUtils.merge( [
  6033. THREE.UniformsLib[ "common" ],
  6034. THREE.UniformsLib[ "fog" ],
  6035. THREE.UniformsLib[ "lights" ],
  6036. THREE.UniformsLib[ "shadowmap" ],
  6037. {
  6038. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  6039. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  6040. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  6041. "shininess": { type: "f", value: 30 },
  6042. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  6043. }
  6044. ] ),
  6045. vertexShader: [
  6046. "varying vec3 vViewPosition;",
  6047. "varying vec3 vNormal;",
  6048. THREE.ShaderChunk[ "map_pars_vertex" ],
  6049. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  6050. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  6051. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  6052. THREE.ShaderChunk[ "color_pars_vertex" ],
  6053. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  6054. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  6055. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  6056. "void main() {",
  6057. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  6058. THREE.ShaderChunk[ "map_vertex" ],
  6059. THREE.ShaderChunk[ "lightmap_vertex" ],
  6060. THREE.ShaderChunk[ "envmap_vertex" ],
  6061. THREE.ShaderChunk[ "color_vertex" ],
  6062. "#ifndef USE_ENVMAP",
  6063. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  6064. "#endif",
  6065. "vViewPosition = -mvPosition.xyz;",
  6066. THREE.ShaderChunk[ "morphnormal_vertex" ],
  6067. "vNormal = transformedNormal;",
  6068. THREE.ShaderChunk[ "lights_phong_vertex" ],
  6069. THREE.ShaderChunk[ "skinning_vertex" ],
  6070. THREE.ShaderChunk[ "morphtarget_vertex" ],
  6071. THREE.ShaderChunk[ "default_vertex" ],
  6072. THREE.ShaderChunk[ "shadowmap_vertex" ],
  6073. "}"
  6074. ].join("\n"),
  6075. fragmentShader: [
  6076. "uniform vec3 diffuse;",
  6077. "uniform float opacity;",
  6078. "uniform vec3 ambient;",
  6079. "uniform vec3 emissive;",
  6080. "uniform vec3 specular;",
  6081. "uniform float shininess;",
  6082. THREE.ShaderChunk[ "color_pars_fragment" ],
  6083. THREE.ShaderChunk[ "map_pars_fragment" ],
  6084. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  6085. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  6086. THREE.ShaderChunk[ "fog_pars_fragment" ],
  6087. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  6088. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  6089. "void main() {",
  6090. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  6091. THREE.ShaderChunk[ "map_fragment" ],
  6092. THREE.ShaderChunk[ "alphatest_fragment" ],
  6093. THREE.ShaderChunk[ "lights_phong_fragment" ],
  6094. THREE.ShaderChunk[ "lightmap_fragment" ],
  6095. THREE.ShaderChunk[ "color_fragment" ],
  6096. THREE.ShaderChunk[ "envmap_fragment" ],
  6097. THREE.ShaderChunk[ "shadowmap_fragment" ],
  6098. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  6099. THREE.ShaderChunk[ "fog_fragment" ],
  6100. "}"
  6101. ].join("\n")
  6102. },
  6103. 'particle_basic': {
  6104. uniforms: THREE.UniformsUtils.merge( [
  6105. THREE.UniformsLib[ "particle" ],
  6106. THREE.UniformsLib[ "shadowmap" ]
  6107. ] ),
  6108. vertexShader: [
  6109. "uniform float size;",
  6110. "uniform float scale;",
  6111. THREE.ShaderChunk[ "color_pars_vertex" ],
  6112. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  6113. "void main() {",
  6114. THREE.ShaderChunk[ "color_vertex" ],
  6115. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  6116. "#ifdef USE_SIZEATTENUATION",
  6117. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  6118. "#else",
  6119. "gl_PointSize = size;",
  6120. "#endif",
  6121. "gl_Position = projectionMatrix * mvPosition;",
  6122. THREE.ShaderChunk[ "shadowmap_vertex" ],
  6123. "}"
  6124. ].join("\n"),
  6125. fragmentShader: [
  6126. "uniform vec3 psColor;",
  6127. "uniform float opacity;",
  6128. THREE.ShaderChunk[ "color_pars_fragment" ],
  6129. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  6130. THREE.ShaderChunk[ "fog_pars_fragment" ],
  6131. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  6132. "void main() {",
  6133. "gl_FragColor = vec4( psColor, opacity );",
  6134. THREE.ShaderChunk[ "map_particle_fragment" ],
  6135. THREE.ShaderChunk[ "alphatest_fragment" ],
  6136. THREE.ShaderChunk[ "color_fragment" ],
  6137. THREE.ShaderChunk[ "shadowmap_fragment" ],
  6138. THREE.ShaderChunk[ "fog_fragment" ],
  6139. "}"
  6140. ].join("\n")
  6141. },
  6142. // Depth encoding into RGBA texture
  6143. // based on SpiderGL shadow map example
  6144. // http://spidergl.org/example.php?id=6
  6145. // originally from
  6146. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  6147. // see also here:
  6148. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  6149. 'depthRGBA': {
  6150. uniforms: {},
  6151. vertexShader: [
  6152. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  6153. "void main() {",
  6154. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  6155. THREE.ShaderChunk[ "morphtarget_vertex" ],
  6156. THREE.ShaderChunk[ "default_vertex" ],
  6157. "}"
  6158. ].join("\n"),
  6159. fragmentShader: [
  6160. "vec4 pack_depth( const in float depth ) {",
  6161. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  6162. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  6163. "vec4 res = fract( depth * bit_shift );",
  6164. "res -= res.xxyz * bit_mask;",
  6165. "return res;",
  6166. "}",
  6167. "void main() {",
  6168. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  6169. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  6170. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  6171. //"gl_FragData[ 0 ] = pack_depth( z );",
  6172. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  6173. "}"
  6174. ].join("\n")
  6175. }
  6176. };/**
  6177. * @author supereggbert / http://www.paulbrunt.co.uk/
  6178. * @author mrdoob / http://mrdoob.com/
  6179. * @author alteredq / http://alteredqualia.com/
  6180. * @author szimek / https://github.com/szimek/
  6181. */
  6182. THREE.WebGLRenderer = function ( parameters ) {
  6183. // constructor parameters
  6184. parameters = parameters || {};
  6185. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  6186. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  6187. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  6188. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  6189. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  6190. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  6191. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  6192. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  6193. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,
  6194. _maxLights = parameters.maxLights !== undefined ? parameters.maxLights : 4;
  6195. // public properties
  6196. this.domElement = _canvas;
  6197. this.context = null;
  6198. // clearing
  6199. this.autoClear = true;
  6200. this.autoClearColor = true;
  6201. this.autoClearDepth = true;
  6202. this.autoClearStencil = true;
  6203. // scene graph
  6204. this.sortObjects = true;
  6205. this.autoUpdateObjects = true;
  6206. this.autoUpdateScene = true;
  6207. // physically based shading
  6208. this.gammaInput = false;
  6209. this.gammaOutput = false;
  6210. this.physicallyBasedShading = false;
  6211. // shadow map
  6212. this.shadowMapEnabled = false;
  6213. this.shadowMapAutoUpdate = true;
  6214. this.shadowMapSoft = true;
  6215. this.shadowMapCullFrontFaces = true;
  6216. this.shadowMapDebug = false;
  6217. this.shadowMapCascade = false;
  6218. // morphs
  6219. this.maxMorphTargets = 8;
  6220. this.maxMorphNormals = 4;
  6221. // flags
  6222. this.autoScaleCubemaps = true;
  6223. // custom render plugins
  6224. this.renderPluginsPre = [];
  6225. this.renderPluginsPost = [];
  6226. // info
  6227. this.info = {
  6228. memory: {
  6229. programs: 0,
  6230. geometries: 0,
  6231. textures: 0
  6232. },
  6233. render: {
  6234. calls: 0,
  6235. vertices: 0,
  6236. faces: 0,
  6237. points: 0
  6238. }
  6239. };
  6240. // internal properties
  6241. var _this = this,
  6242. _gl,
  6243. _programs = [],
  6244. // internal state cache
  6245. _currentProgram = null,
  6246. _currentFramebuffer = null,
  6247. _currentMaterialId = -1,
  6248. _currentGeometryGroupHash = null,
  6249. _currentCamera = null,
  6250. _geometryGroupCounter = 0,
  6251. // GL state cache
  6252. _oldDoubleSided = null,
  6253. _oldFlipSided = null,
  6254. _oldBlending = null,
  6255. _oldBlendEquation = null,
  6256. _oldBlendSrc = null,
  6257. _oldBlendDst = null,
  6258. _oldDepthTest = null,
  6259. _oldDepthWrite = null,
  6260. _oldPolygonOffset = null,
  6261. _oldPolygonOffsetFactor = null,
  6262. _oldPolygonOffsetUnits = null,
  6263. _oldLineWidth = null,
  6264. _viewportX = 0,
  6265. _viewportY = 0,
  6266. _viewportWidth = 0,
  6267. _viewportHeight = 0,
  6268. _currentWidth = 0,
  6269. _currentHeight = 0,
  6270. // frustum
  6271. _frustum = new THREE.Frustum(),
  6272. // camera matrices cache
  6273. _projScreenMatrix = new THREE.Matrix4(),
  6274. _projScreenMatrixPS = new THREE.Matrix4(),
  6275. _vector3 = new THREE.Vector4(),
  6276. // light arrays cache
  6277. _direction = new THREE.Vector3(),
  6278. _lights = {
  6279. ambient: [ 0, 0, 0 ],
  6280. directional: { length: 0, colors: new Array(), positions: new Array() },
  6281. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() }
  6282. };
  6283. // initialize
  6284. _gl = initGL();
  6285. setDefaultGLState();
  6286. this.context = _gl;
  6287. // GPU capabilities
  6288. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ),
  6289. _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ),
  6290. _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  6291. // API
  6292. this.getContext = function () {
  6293. return _gl;
  6294. };
  6295. this.supportsVertexTextures = function () {
  6296. return _maxVertexTextures > 0;
  6297. };
  6298. this.setSize = function ( width, height ) {
  6299. _canvas.width = width;
  6300. _canvas.height = height;
  6301. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  6302. };
  6303. this.setViewport = function ( x, y, width, height ) {
  6304. _viewportX = x;
  6305. _viewportY = y;
  6306. _viewportWidth = width;
  6307. _viewportHeight = height;
  6308. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  6309. };
  6310. this.setScissor = function ( x, y, width, height ) {
  6311. _gl.scissor( x, y, width, height );
  6312. };
  6313. this.enableScissorTest = function ( enable ) {
  6314. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  6315. };
  6316. // Clearing
  6317. this.setClearColorHex = function ( hex, alpha ) {
  6318. _clearColor.setHex( hex );
  6319. _clearAlpha = alpha;
  6320. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  6321. };
  6322. this.setClearColor = function ( color, alpha ) {
  6323. _clearColor.copy( color );
  6324. _clearAlpha = alpha;
  6325. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  6326. };
  6327. this.getClearColor = function () {
  6328. return _clearColor;
  6329. };
  6330. this.getClearAlpha = function () {
  6331. return _clearAlpha;
  6332. };
  6333. this.clear = function ( color, depth, stencil ) {
  6334. var bits = 0;
  6335. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  6336. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  6337. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  6338. _gl.clear( bits );
  6339. };
  6340. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  6341. this.setRenderTarget( renderTarget );
  6342. this.clear( color, depth, stencil );
  6343. };
  6344. // Plugins
  6345. this.addPostPlugin = function ( plugin ) {
  6346. plugin.init( this );
  6347. this.renderPluginsPost.push( plugin );
  6348. };
  6349. this.addPrePlugin = function ( plugin ) {
  6350. plugin.init( this );
  6351. this.renderPluginsPre.push( plugin );
  6352. };
  6353. // Deallocation
  6354. this.deallocateObject = function ( object ) {
  6355. if ( ! object.__webglInit ) return;
  6356. object.__webglInit = false;
  6357. delete object._modelViewMatrix;
  6358. delete object._normalMatrix;
  6359. delete object._normalMatrixArray;
  6360. delete object._modelViewMatrixArray;
  6361. delete object._objectMatrixArray;
  6362. if ( object instanceof THREE.Mesh ) {
  6363. for ( var g in object.geometry.geometryGroups ) {
  6364. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  6365. }
  6366. } else if ( object instanceof THREE.Ribbon ) {
  6367. deleteRibbonBuffers( object.geometry );
  6368. } else if ( object instanceof THREE.Line ) {
  6369. deleteLineBuffers( object.geometry );
  6370. } else if ( object instanceof THREE.ParticleSystem ) {
  6371. deleteParticleBuffers( object.geometry );
  6372. }
  6373. };
  6374. this.deallocateTexture = function ( texture ) {
  6375. if ( ! texture.__webglInit ) return;
  6376. texture.__webglInit = false;
  6377. _gl.deleteTexture( texture.__webglTexture );
  6378. _this.info.memory.textures --;
  6379. };
  6380. this.deallocateRenderTarget = function ( renderTarget ) {
  6381. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  6382. _gl.deleteTexture( renderTarget.__webglTexture );
  6383. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  6384. for ( var i = 0; i < 6; i ++ ) {
  6385. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  6386. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  6387. }
  6388. } else {
  6389. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  6390. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  6391. }
  6392. };
  6393. // Rendering
  6394. this.updateShadowMap = function ( scene, camera ) {
  6395. _currentProgram = null;
  6396. _oldBlending = -1;
  6397. _oldDepthTest = -1;
  6398. _oldDepthWrite = -1;
  6399. _currentGeometryGroupHash = -1;
  6400. _currentMaterialId = -1;
  6401. this.shadowMapPlugin.update( scene, camera );
  6402. };
  6403. // Internal functions
  6404. // Buffer allocation
  6405. function createParticleBuffers ( geometry ) {
  6406. geometry.__webglVertexBuffer = _gl.createBuffer();
  6407. geometry.__webglColorBuffer = _gl.createBuffer();
  6408. _this.info.geometries ++;
  6409. };
  6410. function createLineBuffers ( geometry ) {
  6411. geometry.__webglVertexBuffer = _gl.createBuffer();
  6412. geometry.__webglColorBuffer = _gl.createBuffer();
  6413. _this.info.memory.geometries ++;
  6414. };
  6415. function createRibbonBuffers ( geometry ) {
  6416. geometry.__webglVertexBuffer = _gl.createBuffer();
  6417. geometry.__webglColorBuffer = _gl.createBuffer();
  6418. _this.info.memory.geometries ++;
  6419. };
  6420. function createMeshBuffers ( geometryGroup ) {
  6421. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  6422. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  6423. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  6424. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  6425. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  6426. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  6427. geometryGroup.__webglSkinVertexABuffer = _gl.createBuffer();
  6428. geometryGroup.__webglSkinVertexBBuffer = _gl.createBuffer();
  6429. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  6430. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  6431. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  6432. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  6433. var m, ml;
  6434. if ( geometryGroup.numMorphTargets ) {
  6435. geometryGroup.__webglMorphTargetsBuffers = [];
  6436. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  6437. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  6438. }
  6439. }
  6440. if ( geometryGroup.numMorphNormals ) {
  6441. geometryGroup.__webglMorphNormalsBuffers = [];
  6442. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  6443. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  6444. }
  6445. }
  6446. _this.info.memory.geometries ++;
  6447. };
  6448. // Buffer deallocation
  6449. function deleteParticleBuffers ( geometry ) {
  6450. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  6451. _gl.deleteBuffer( geometry.__webglColorBuffer );
  6452. _this.info.memory.geometries --;
  6453. };
  6454. function deleteLineBuffers ( geometry ) {
  6455. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  6456. _gl.deleteBuffer( geometry.__webglColorBuffer );
  6457. _this.info.memory.geometries --;
  6458. };
  6459. function deleteRibbonBuffers ( geometry ) {
  6460. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  6461. _gl.deleteBuffer( geometry.__webglColorBuffer );
  6462. _this.info.memory.geometries --;
  6463. };
  6464. function deleteMeshBuffers ( geometryGroup ) {
  6465. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  6466. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  6467. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  6468. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  6469. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  6470. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  6471. _gl.deleteBuffer( geometryGroup.__webglSkinVertexABuffer );
  6472. _gl.deleteBuffer( geometryGroup.__webglSkinVertexBBuffer );
  6473. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  6474. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  6475. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  6476. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  6477. var m, ml;
  6478. if ( geometryGroup.numMorphTargets ) {
  6479. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  6480. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  6481. }
  6482. }
  6483. if ( geometryGroup.numMorphNormals ) {
  6484. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  6485. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  6486. }
  6487. }
  6488. if ( geometryGroup.__webglCustomAttributesList ) {
  6489. for ( var id in geometryGroup.__webglCustomAttributesList ) {
  6490. _gl.deleteBuffer( geometryGroup.__webglCustomAttributesList[ id ].buffer );
  6491. }
  6492. }
  6493. _this.info.memory.geometries --;
  6494. };
  6495. // Buffer initialization
  6496. function initCustomAttributes ( geometry, object ) {
  6497. var nvertices = geometry.vertices.length;
  6498. var material = object.material;
  6499. if ( material.attributes ) {
  6500. if ( geometry.__webglCustomAttributesList === undefined ) {
  6501. geometry.__webglCustomAttributesList = [];
  6502. }
  6503. for ( var a in material.attributes ) {
  6504. var attribute = material.attributes[ a ];
  6505. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  6506. attribute.__webglInitialized = true;
  6507. var size = 1; // "f" and "i"
  6508. if ( attribute.type === "v2" ) size = 2;
  6509. else if ( attribute.type === "v3" ) size = 3;
  6510. else if ( attribute.type === "v4" ) size = 4;
  6511. else if ( attribute.type === "c" ) size = 3;
  6512. attribute.size = size;
  6513. attribute.array = new Float32Array( nvertices * size );
  6514. attribute.buffer = _gl.createBuffer();
  6515. attribute.buffer.belongsToAttribute = a;
  6516. attribute.needsUpdate = true;
  6517. }
  6518. geometry.__webglCustomAttributesList.push( attribute );
  6519. }
  6520. }
  6521. };
  6522. function initParticleBuffers ( geometry, object ) {
  6523. var nvertices = geometry.vertices.length;
  6524. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  6525. geometry.__colorArray = new Float32Array( nvertices * 3 );
  6526. geometry.__sortArray = [];
  6527. geometry.__webglParticleCount = nvertices;
  6528. initCustomAttributes ( geometry, object );
  6529. };
  6530. function initLineBuffers ( geometry, object ) {
  6531. var nvertices = geometry.vertices.length;
  6532. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  6533. geometry.__colorArray = new Float32Array( nvertices * 3 );
  6534. geometry.__webglLineCount = nvertices;
  6535. initCustomAttributes ( geometry, object );
  6536. };
  6537. function initRibbonBuffers ( geometry ) {
  6538. var nvertices = geometry.vertices.length;
  6539. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  6540. geometry.__colorArray = new Float32Array( nvertices * 3 );
  6541. geometry.__webglVertexCount = nvertices;
  6542. };
  6543. function initMeshBuffers ( geometryGroup, object ) {
  6544. var geometry = object.geometry,
  6545. faces3 = geometryGroup.faces3,
  6546. faces4 = geometryGroup.faces4,
  6547. nvertices = faces3.length * 3 + faces4.length * 4,
  6548. ntris = faces3.length * 1 + faces4.length * 2,
  6549. nlines = faces3.length * 3 + faces4.length * 4,
  6550. material = getBufferMaterial( object, geometryGroup ),
  6551. uvType = bufferGuessUVType( material ),
  6552. normalType = bufferGuessNormalType( material ),
  6553. vertexColorType = bufferGuessVertexColorType( material );
  6554. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  6555. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  6556. if ( normalType ) {
  6557. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  6558. }
  6559. if ( geometry.hasTangents ) {
  6560. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  6561. }
  6562. if ( vertexColorType ) {
  6563. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  6564. }
  6565. if ( uvType ) {
  6566. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  6567. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  6568. }
  6569. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  6570. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  6571. }
  6572. }
  6573. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  6574. geometryGroup.__skinVertexAArray = new Float32Array( nvertices * 4 );
  6575. geometryGroup.__skinVertexBArray = new Float32Array( nvertices * 4 );
  6576. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  6577. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  6578. }
  6579. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  6580. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  6581. var m, ml;
  6582. if ( geometryGroup.numMorphTargets ) {
  6583. geometryGroup.__morphTargetsArrays = [];
  6584. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  6585. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  6586. }
  6587. }
  6588. if ( geometryGroup.numMorphNormals ) {
  6589. geometryGroup.__morphNormalsArrays = [];
  6590. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  6591. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  6592. }
  6593. }
  6594. geometryGroup.__webglFaceCount = ntris * 3;
  6595. geometryGroup.__webglLineCount = nlines * 2;
  6596. // custom attributes
  6597. if ( material.attributes ) {
  6598. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  6599. geometryGroup.__webglCustomAttributesList = [];
  6600. }
  6601. for ( var a in material.attributes ) {
  6602. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  6603. // attribute buffers which are correctly indexed in the setMeshBuffers function
  6604. var originalAttribute = material.attributes[ a ];
  6605. var attribute = {};
  6606. for ( var property in originalAttribute ) {
  6607. attribute[ property ] = originalAttribute[ property ];
  6608. }
  6609. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  6610. attribute.__webglInitialized = true;
  6611. var size = 1; // "f" and "i"
  6612. if( attribute.type === "v2" ) size = 2;
  6613. else if( attribute.type === "v3" ) size = 3;
  6614. else if( attribute.type === "v4" ) size = 4;
  6615. else if( attribute.type === "c" ) size = 3;
  6616. attribute.size = size;
  6617. attribute.array = new Float32Array( nvertices * size );
  6618. attribute.buffer = _gl.createBuffer();
  6619. attribute.buffer.belongsToAttribute = a;
  6620. originalAttribute.needsUpdate = true;
  6621. attribute.__original = originalAttribute;
  6622. }
  6623. geometryGroup.__webglCustomAttributesList.push( attribute );
  6624. }
  6625. }
  6626. geometryGroup.__inittedArrays = true;
  6627. };
  6628. function getBufferMaterial( object, geometryGroup ) {
  6629. if ( object.material && ! ( object.material instanceof THREE.MeshFaceMaterial ) ) {
  6630. return object.material;
  6631. } else if ( geometryGroup.materialIndex >= 0 ) {
  6632. return object.geometry.materials[ geometryGroup.materialIndex ];
  6633. }
  6634. };
  6635. function materialNeedsSmoothNormals ( material ) {
  6636. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  6637. };
  6638. function bufferGuessNormalType ( material ) {
  6639. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  6640. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  6641. return false;
  6642. }
  6643. if ( materialNeedsSmoothNormals( material ) ) {
  6644. return THREE.SmoothShading;
  6645. } else {
  6646. return THREE.FlatShading;
  6647. }
  6648. };
  6649. function bufferGuessVertexColorType ( material ) {
  6650. if ( material.vertexColors ) {
  6651. return material.vertexColors;
  6652. }
  6653. return false;
  6654. };
  6655. function bufferGuessUVType ( material ) {
  6656. // material must use some texture to require uvs
  6657. if ( material.map || material.lightMap || material instanceof THREE.ShaderMaterial ) {
  6658. return true;
  6659. }
  6660. return false;
  6661. };
  6662. // Buffer setting
  6663. function setParticleBuffers ( geometry, hint, object ) {
  6664. var v, c, vertex, offset, index, color,
  6665. vertices = geometry.vertices,
  6666. vl = vertices.length,
  6667. colors = geometry.colors,
  6668. cl = colors.length,
  6669. vertexArray = geometry.__vertexArray,
  6670. colorArray = geometry.__colorArray,
  6671. sortArray = geometry.__sortArray,
  6672. dirtyVertices = geometry.__dirtyVertices,
  6673. dirtyElements = geometry.__dirtyElements,
  6674. dirtyColors = geometry.__dirtyColors,
  6675. customAttributes = geometry.__webglCustomAttributesList,
  6676. i, il,
  6677. a, ca, cal, value,
  6678. customAttribute;
  6679. if ( object.sortParticles ) {
  6680. _projScreenMatrixPS.copy( _projScreenMatrix );
  6681. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  6682. for ( v = 0; v < vl; v ++ ) {
  6683. vertex = vertices[ v ].position;
  6684. _vector3.copy( vertex );
  6685. _projScreenMatrixPS.multiplyVector3( _vector3 );
  6686. sortArray[ v ] = [ _vector3.z, v ];
  6687. }
  6688. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  6689. for ( v = 0; v < vl; v ++ ) {
  6690. vertex = vertices[ sortArray[v][1] ].position;
  6691. offset = v * 3;
  6692. vertexArray[ offset ] = vertex.x;
  6693. vertexArray[ offset + 1 ] = vertex.y;
  6694. vertexArray[ offset + 2 ] = vertex.z;
  6695. }
  6696. for ( c = 0; c < cl; c ++ ) {
  6697. offset = c * 3;
  6698. color = colors[ sortArray[c][1] ];
  6699. colorArray[ offset ] = color.r;
  6700. colorArray[ offset + 1 ] = color.g;
  6701. colorArray[ offset + 2 ] = color.b;
  6702. }
  6703. if ( customAttributes ) {
  6704. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6705. customAttribute = customAttributes[ i ];
  6706. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  6707. offset = 0;
  6708. cal = customAttribute.value.length;
  6709. if ( customAttribute.size === 1 ) {
  6710. for ( ca = 0; ca < cal; ca ++ ) {
  6711. index = sortArray[ ca ][ 1 ];
  6712. customAttribute.array[ ca ] = customAttribute.value[ index ];
  6713. }
  6714. } else if ( customAttribute.size === 2 ) {
  6715. for ( ca = 0; ca < cal; ca ++ ) {
  6716. index = sortArray[ ca ][ 1 ];
  6717. value = customAttribute.value[ index ];
  6718. customAttribute.array[ offset ] = value.x;
  6719. customAttribute.array[ offset + 1 ] = value.y;
  6720. offset += 2;
  6721. }
  6722. } else if ( customAttribute.size === 3 ) {
  6723. if ( customAttribute.type === "c" ) {
  6724. for ( ca = 0; ca < cal; ca ++ ) {
  6725. index = sortArray[ ca ][ 1 ];
  6726. value = customAttribute.value[ index ];
  6727. customAttribute.array[ offset ] = value.r;
  6728. customAttribute.array[ offset + 1 ] = value.g;
  6729. customAttribute.array[ offset + 2 ] = value.b;
  6730. offset += 3;
  6731. }
  6732. } else {
  6733. for ( ca = 0; ca < cal; ca ++ ) {
  6734. index = sortArray[ ca ][ 1 ];
  6735. value = customAttribute.value[ index ];
  6736. customAttribute.array[ offset ] = value.x;
  6737. customAttribute.array[ offset + 1 ] = value.y;
  6738. customAttribute.array[ offset + 2 ] = value.z;
  6739. offset += 3;
  6740. }
  6741. }
  6742. } else if ( customAttribute.size === 4 ) {
  6743. for ( ca = 0; ca < cal; ca ++ ) {
  6744. index = sortArray[ ca ][ 1 ];
  6745. value = customAttribute.value[ index ];
  6746. customAttribute.array[ offset ] = value.x;
  6747. customAttribute.array[ offset + 1 ] = value.y;
  6748. customAttribute.array[ offset + 2 ] = value.z;
  6749. customAttribute.array[ offset + 3 ] = value.w;
  6750. offset += 4;
  6751. }
  6752. }
  6753. }
  6754. }
  6755. } else {
  6756. if ( dirtyVertices ) {
  6757. for ( v = 0; v < vl; v ++ ) {
  6758. vertex = vertices[ v ].position;
  6759. offset = v * 3;
  6760. vertexArray[ offset ] = vertex.x;
  6761. vertexArray[ offset + 1 ] = vertex.y;
  6762. vertexArray[ offset + 2 ] = vertex.z;
  6763. }
  6764. }
  6765. if ( dirtyColors ) {
  6766. for ( c = 0; c < cl; c ++ ) {
  6767. color = colors[ c ];
  6768. offset = c * 3;
  6769. colorArray[ offset ] = color.r;
  6770. colorArray[ offset + 1 ] = color.g;
  6771. colorArray[ offset + 2 ] = color.b;
  6772. }
  6773. }
  6774. if ( customAttributes ) {
  6775. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6776. customAttribute = customAttributes[ i ];
  6777. if ( customAttribute.needsUpdate &&
  6778. ( customAttribute.boundTo === undefined ||
  6779. customAttribute.boundTo === "vertices") ) {
  6780. cal = customAttribute.value.length;
  6781. offset = 0;
  6782. if ( customAttribute.size === 1 ) {
  6783. for ( ca = 0; ca < cal; ca ++ ) {
  6784. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  6785. }
  6786. } else if ( customAttribute.size === 2 ) {
  6787. for ( ca = 0; ca < cal; ca ++ ) {
  6788. value = customAttribute.value[ ca ];
  6789. customAttribute.array[ offset ] = value.x;
  6790. customAttribute.array[ offset + 1 ] = value.y;
  6791. offset += 2;
  6792. }
  6793. } else if ( customAttribute.size === 3 ) {
  6794. if ( customAttribute.type === "c" ) {
  6795. for ( ca = 0; ca < cal; ca ++ ) {
  6796. value = customAttribute.value[ ca ];
  6797. customAttribute.array[ offset ] = value.r;
  6798. customAttribute.array[ offset + 1 ] = value.g;
  6799. customAttribute.array[ offset + 2 ] = value.b;
  6800. offset += 3;
  6801. }
  6802. } else {
  6803. for ( ca = 0; ca < cal; ca ++ ) {
  6804. value = customAttribute.value[ ca ];
  6805. customAttribute.array[ offset ] = value.x;
  6806. customAttribute.array[ offset + 1 ] = value.y;
  6807. customAttribute.array[ offset + 2 ] = value.z;
  6808. offset += 3;
  6809. }
  6810. }
  6811. } else if ( customAttribute.size === 4 ) {
  6812. for ( ca = 0; ca < cal; ca ++ ) {
  6813. value = customAttribute.value[ ca ];
  6814. customAttribute.array[ offset ] = value.x;
  6815. customAttribute.array[ offset + 1 ] = value.y;
  6816. customAttribute.array[ offset + 2 ] = value.z;
  6817. customAttribute.array[ offset + 3 ] = value.w;
  6818. offset += 4;
  6819. }
  6820. }
  6821. }
  6822. }
  6823. }
  6824. }
  6825. if ( dirtyVertices || object.sortParticles ) {
  6826. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  6827. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  6828. }
  6829. if ( dirtyColors || object.sortParticles ) {
  6830. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  6831. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  6832. }
  6833. if ( customAttributes ) {
  6834. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6835. customAttribute = customAttributes[ i ];
  6836. if ( customAttribute.needsUpdate || object.sortParticles ) {
  6837. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  6838. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  6839. }
  6840. }
  6841. }
  6842. };
  6843. function setLineBuffers ( geometry, hint ) {
  6844. var v, c, vertex, offset, color,
  6845. vertices = geometry.vertices,
  6846. colors = geometry.colors,
  6847. vl = vertices.length,
  6848. cl = colors.length,
  6849. vertexArray = geometry.__vertexArray,
  6850. colorArray = geometry.__colorArray,
  6851. dirtyVertices = geometry.__dirtyVertices,
  6852. dirtyColors = geometry.__dirtyColors,
  6853. customAttributes = geometry.__webglCustomAttributesList,
  6854. i, il,
  6855. a, ca, cal, value,
  6856. customAttribute;
  6857. if ( dirtyVertices ) {
  6858. for ( v = 0; v < vl; v ++ ) {
  6859. vertex = vertices[ v ].position;
  6860. offset = v * 3;
  6861. vertexArray[ offset ] = vertex.x;
  6862. vertexArray[ offset + 1 ] = vertex.y;
  6863. vertexArray[ offset + 2 ] = vertex.z;
  6864. }
  6865. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  6866. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  6867. }
  6868. if ( dirtyColors ) {
  6869. for ( c = 0; c < cl; c ++ ) {
  6870. color = colors[ c ];
  6871. offset = c * 3;
  6872. colorArray[ offset ] = color.r;
  6873. colorArray[ offset + 1 ] = color.g;
  6874. colorArray[ offset + 2 ] = color.b;
  6875. }
  6876. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  6877. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  6878. }
  6879. if ( customAttributes ) {
  6880. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6881. customAttribute = customAttributes[ i ];
  6882. if ( customAttribute.needsUpdate &&
  6883. ( customAttribute.boundTo === undefined ||
  6884. customAttribute.boundTo === "vertices" ) ) {
  6885. offset = 0;
  6886. cal = customAttribute.value.length;
  6887. if ( customAttribute.size === 1 ) {
  6888. for ( ca = 0; ca < cal; ca ++ ) {
  6889. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  6890. }
  6891. } else if ( customAttribute.size === 2 ) {
  6892. for ( ca = 0; ca < cal; ca ++ ) {
  6893. value = customAttribute.value[ ca ];
  6894. customAttribute.array[ offset ] = value.x;
  6895. customAttribute.array[ offset + 1 ] = value.y;
  6896. offset += 2;
  6897. }
  6898. } else if ( customAttribute.size === 3 ) {
  6899. if ( customAttribute.type === "c" ) {
  6900. for ( ca = 0; ca < cal; ca ++ ) {
  6901. value = customAttribute.value[ ca ];
  6902. customAttribute.array[ offset ] = value.r;
  6903. customAttribute.array[ offset + 1 ] = value.g;
  6904. customAttribute.array[ offset + 2 ] = value.b;
  6905. offset += 3;
  6906. }
  6907. } else {
  6908. for ( ca = 0; ca < cal; ca ++ ) {
  6909. value = customAttribute.value[ ca ];
  6910. customAttribute.array[ offset ] = value.x;
  6911. customAttribute.array[ offset + 1 ] = value.y;
  6912. customAttribute.array[ offset + 2 ] = value.z;
  6913. offset += 3;
  6914. }
  6915. }
  6916. } else if ( customAttribute.size === 4 ) {
  6917. for ( ca = 0; ca < cal; ca ++ ) {
  6918. value = customAttribute.value[ ca ];
  6919. customAttribute.array[ offset ] = value.x;
  6920. customAttribute.array[ offset + 1 ] = value.y;
  6921. customAttribute.array[ offset + 2 ] = value.z;
  6922. customAttribute.array[ offset + 3 ] = value.w;
  6923. offset += 4;
  6924. }
  6925. }
  6926. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  6927. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  6928. }
  6929. }
  6930. }
  6931. };
  6932. function setRibbonBuffers ( geometry, hint ) {
  6933. var v, c, vertex, offset, color,
  6934. vertices = geometry.vertices,
  6935. colors = geometry.colors,
  6936. vl = vertices.length,
  6937. cl = colors.length,
  6938. vertexArray = geometry.__vertexArray,
  6939. colorArray = geometry.__colorArray,
  6940. dirtyVertices = geometry.__dirtyVertices,
  6941. dirtyColors = geometry.__dirtyColors;
  6942. if ( dirtyVertices ) {
  6943. for ( v = 0; v < vl; v ++ ) {
  6944. vertex = vertices[ v ].position;
  6945. offset = v * 3;
  6946. vertexArray[ offset ] = vertex.x;
  6947. vertexArray[ offset + 1 ] = vertex.y;
  6948. vertexArray[ offset + 2 ] = vertex.z;
  6949. }
  6950. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  6951. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  6952. }
  6953. if ( dirtyColors ) {
  6954. for ( c = 0; c < cl; c ++ ) {
  6955. color = colors[ c ];
  6956. offset = c * 3;
  6957. colorArray[ offset ] = color.r;
  6958. colorArray[ offset + 1 ] = color.g;
  6959. colorArray[ offset + 2 ] = color.b;
  6960. }
  6961. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  6962. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  6963. }
  6964. };
  6965. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  6966. if ( ! geometryGroup.__inittedArrays ) {
  6967. // console.log( object );
  6968. return;
  6969. }
  6970. var normalType = bufferGuessNormalType( material ),
  6971. vertexColorType = bufferGuessVertexColorType( material ),
  6972. uvType = bufferGuessUVType( material ),
  6973. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  6974. var f, fl, fi, face,
  6975. vertexNormals, faceNormal, normal,
  6976. vertexColors, faceColor,
  6977. vertexTangents,
  6978. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  6979. c1, c2, c3, c4,
  6980. sw1, sw2, sw3, sw4,
  6981. si1, si2, si3, si4,
  6982. sa1, sa2, sa3, sa4,
  6983. sb1, sb2, sb3, sb4,
  6984. m, ml, i, il,
  6985. vn, uvi, uv2i,
  6986. vk, vkl, vka,
  6987. nka, chf, faceVertexNormals,
  6988. a,
  6989. vertexIndex = 0,
  6990. offset = 0,
  6991. offset_uv = 0,
  6992. offset_uv2 = 0,
  6993. offset_face = 0,
  6994. offset_normal = 0,
  6995. offset_tangent = 0,
  6996. offset_line = 0,
  6997. offset_color = 0,
  6998. offset_skin = 0,
  6999. offset_morphTarget = 0,
  7000. offset_custom = 0,
  7001. offset_customSrc = 0,
  7002. value,
  7003. vertexArray = geometryGroup.__vertexArray,
  7004. uvArray = geometryGroup.__uvArray,
  7005. uv2Array = geometryGroup.__uv2Array,
  7006. normalArray = geometryGroup.__normalArray,
  7007. tangentArray = geometryGroup.__tangentArray,
  7008. colorArray = geometryGroup.__colorArray,
  7009. skinVertexAArray = geometryGroup.__skinVertexAArray,
  7010. skinVertexBArray = geometryGroup.__skinVertexBArray,
  7011. skinIndexArray = geometryGroup.__skinIndexArray,
  7012. skinWeightArray = geometryGroup.__skinWeightArray,
  7013. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  7014. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  7015. customAttributes = geometryGroup.__webglCustomAttributesList,
  7016. customAttribute,
  7017. faceArray = geometryGroup.__faceArray,
  7018. lineArray = geometryGroup.__lineArray,
  7019. geometry = object.geometry, // this is shared for all chunks
  7020. dirtyVertices = geometry.__dirtyVertices,
  7021. dirtyElements = geometry.__dirtyElements,
  7022. dirtyUvs = geometry.__dirtyUvs,
  7023. dirtyNormals = geometry.__dirtyNormals,
  7024. dirtyTangents = geometry.__dirtyTangents,
  7025. dirtyColors = geometry.__dirtyColors,
  7026. dirtyMorphTargets = geometry.__dirtyMorphTargets,
  7027. vertices = geometry.vertices,
  7028. chunk_faces3 = geometryGroup.faces3,
  7029. chunk_faces4 = geometryGroup.faces4,
  7030. obj_faces = geometry.faces,
  7031. obj_uvs = geometry.faceVertexUvs[ 0 ],
  7032. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  7033. obj_colors = geometry.colors,
  7034. obj_skinVerticesA = geometry.skinVerticesA,
  7035. obj_skinVerticesB = geometry.skinVerticesB,
  7036. obj_skinIndices = geometry.skinIndices,
  7037. obj_skinWeights = geometry.skinWeights,
  7038. morphTargets = geometry.morphTargets,
  7039. morphNormals = geometry.morphNormals;
  7040. if ( dirtyVertices ) {
  7041. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7042. face = obj_faces[ chunk_faces3[ f ] ];
  7043. v1 = vertices[ face.a ].position;
  7044. v2 = vertices[ face.b ].position;
  7045. v3 = vertices[ face.c ].position;
  7046. vertexArray[ offset ] = v1.x;
  7047. vertexArray[ offset + 1 ] = v1.y;
  7048. vertexArray[ offset + 2 ] = v1.z;
  7049. vertexArray[ offset + 3 ] = v2.x;
  7050. vertexArray[ offset + 4 ] = v2.y;
  7051. vertexArray[ offset + 5 ] = v2.z;
  7052. vertexArray[ offset + 6 ] = v3.x;
  7053. vertexArray[ offset + 7 ] = v3.y;
  7054. vertexArray[ offset + 8 ] = v3.z;
  7055. offset += 9;
  7056. }
  7057. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7058. face = obj_faces[ chunk_faces4[ f ] ];
  7059. v1 = vertices[ face.a ].position;
  7060. v2 = vertices[ face.b ].position;
  7061. v3 = vertices[ face.c ].position;
  7062. v4 = vertices[ face.d ].position;
  7063. vertexArray[ offset ] = v1.x;
  7064. vertexArray[ offset + 1 ] = v1.y;
  7065. vertexArray[ offset + 2 ] = v1.z;
  7066. vertexArray[ offset + 3 ] = v2.x;
  7067. vertexArray[ offset + 4 ] = v2.y;
  7068. vertexArray[ offset + 5 ] = v2.z;
  7069. vertexArray[ offset + 6 ] = v3.x;
  7070. vertexArray[ offset + 7 ] = v3.y;
  7071. vertexArray[ offset + 8 ] = v3.z;
  7072. vertexArray[ offset + 9 ] = v4.x;
  7073. vertexArray[ offset + 10 ] = v4.y;
  7074. vertexArray[ offset + 11 ] = v4.z;
  7075. offset += 12;
  7076. }
  7077. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  7078. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  7079. }
  7080. if ( dirtyMorphTargets ) {
  7081. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  7082. offset_morphTarget = 0;
  7083. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7084. chf = chunk_faces3[ f ];
  7085. face = obj_faces[ chf ];
  7086. // morph positions
  7087. v1 = morphTargets[ vk ].vertices[ face.a ].position;
  7088. v2 = morphTargets[ vk ].vertices[ face.b ].position;
  7089. v3 = morphTargets[ vk ].vertices[ face.c ].position;
  7090. vka = morphTargetsArrays[ vk ];
  7091. vka[ offset_morphTarget ] = v1.x;
  7092. vka[ offset_morphTarget + 1 ] = v1.y;
  7093. vka[ offset_morphTarget + 2 ] = v1.z;
  7094. vka[ offset_morphTarget + 3 ] = v2.x;
  7095. vka[ offset_morphTarget + 4 ] = v2.y;
  7096. vka[ offset_morphTarget + 5 ] = v2.z;
  7097. vka[ offset_morphTarget + 6 ] = v3.x;
  7098. vka[ offset_morphTarget + 7 ] = v3.y;
  7099. vka[ offset_morphTarget + 8 ] = v3.z;
  7100. // morph normals
  7101. if ( material.morphNormals ) {
  7102. if ( needsSmoothNormals ) {
  7103. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  7104. n1 = faceVertexNormals.a;
  7105. n2 = faceVertexNormals.b;
  7106. n3 = faceVertexNormals.c;
  7107. } else {
  7108. n1 = morphNormals[ vk ].faceNormals[ chf ];
  7109. n2 = n1;
  7110. n3 = n1;
  7111. }
  7112. nka = morphNormalsArrays[ vk ];
  7113. nka[ offset_morphTarget ] = n1.x;
  7114. nka[ offset_morphTarget + 1 ] = n1.y;
  7115. nka[ offset_morphTarget + 2 ] = n1.z;
  7116. nka[ offset_morphTarget + 3 ] = n2.x;
  7117. nka[ offset_morphTarget + 4 ] = n2.y;
  7118. nka[ offset_morphTarget + 5 ] = n2.z;
  7119. nka[ offset_morphTarget + 6 ] = n3.x;
  7120. nka[ offset_morphTarget + 7 ] = n3.y;
  7121. nka[ offset_morphTarget + 8 ] = n3.z;
  7122. }
  7123. //
  7124. offset_morphTarget += 9;
  7125. }
  7126. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7127. chf = chunk_faces4[ f ];
  7128. face = obj_faces[ chf ];
  7129. // morph positions
  7130. v1 = morphTargets[ vk ].vertices[ face.a ].position;
  7131. v2 = morphTargets[ vk ].vertices[ face.b ].position;
  7132. v3 = morphTargets[ vk ].vertices[ face.c ].position;
  7133. v4 = morphTargets[ vk ].vertices[ face.d ].position;
  7134. vka = morphTargetsArrays[ vk ];
  7135. vka[ offset_morphTarget ] = v1.x;
  7136. vka[ offset_morphTarget + 1 ] = v1.y;
  7137. vka[ offset_morphTarget + 2 ] = v1.z;
  7138. vka[ offset_morphTarget + 3 ] = v2.x;
  7139. vka[ offset_morphTarget + 4 ] = v2.y;
  7140. vka[ offset_morphTarget + 5 ] = v2.z;
  7141. vka[ offset_morphTarget + 6 ] = v3.x;
  7142. vka[ offset_morphTarget + 7 ] = v3.y;
  7143. vka[ offset_morphTarget + 8 ] = v3.z;
  7144. vka[ offset_morphTarget + 9 ] = v4.x;
  7145. vka[ offset_morphTarget + 10 ] = v4.y;
  7146. vka[ offset_morphTarget + 11 ] = v4.z;
  7147. // morph normals
  7148. if ( material.morphNormals ) {
  7149. if ( needsSmoothNormals ) {
  7150. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  7151. n1 = faceVertexNormals.a;
  7152. n2 = faceVertexNormals.b;
  7153. n3 = faceVertexNormals.c;
  7154. n4 = faceVertexNormals.d;
  7155. } else {
  7156. n1 = morphNormals[ vk ].faceNormals[ chf ];
  7157. n2 = n1;
  7158. n3 = n1;
  7159. n4 = n1;
  7160. }
  7161. nka = morphNormalsArrays[ vk ];
  7162. nka[ offset_morphTarget ] = n1.x;
  7163. nka[ offset_morphTarget + 1 ] = n1.y;
  7164. nka[ offset_morphTarget + 2 ] = n1.z;
  7165. nka[ offset_morphTarget + 3 ] = n2.x;
  7166. nka[ offset_morphTarget + 4 ] = n2.y;
  7167. nka[ offset_morphTarget + 5 ] = n2.z;
  7168. nka[ offset_morphTarget + 6 ] = n3.x;
  7169. nka[ offset_morphTarget + 7 ] = n3.y;
  7170. nka[ offset_morphTarget + 8 ] = n3.z;
  7171. nka[ offset_morphTarget + 9 ] = n4.x;
  7172. nka[ offset_morphTarget + 10 ] = n4.y;
  7173. nka[ offset_morphTarget + 11 ] = n4.z;
  7174. }
  7175. //
  7176. offset_morphTarget += 12;
  7177. }
  7178. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  7179. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  7180. if ( material.morphNormals ) {
  7181. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  7182. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  7183. }
  7184. }
  7185. }
  7186. if ( obj_skinWeights.length ) {
  7187. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7188. face = obj_faces[ chunk_faces3[ f ] ];
  7189. // weights
  7190. sw1 = obj_skinWeights[ face.a ];
  7191. sw2 = obj_skinWeights[ face.b ];
  7192. sw3 = obj_skinWeights[ face.c ];
  7193. skinWeightArray[ offset_skin ] = sw1.x;
  7194. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  7195. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  7196. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  7197. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  7198. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  7199. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  7200. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  7201. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  7202. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  7203. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  7204. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  7205. // indices
  7206. si1 = obj_skinIndices[ face.a ];
  7207. si2 = obj_skinIndices[ face.b ];
  7208. si3 = obj_skinIndices[ face.c ];
  7209. skinIndexArray[ offset_skin ] = si1.x;
  7210. skinIndexArray[ offset_skin + 1 ] = si1.y;
  7211. skinIndexArray[ offset_skin + 2 ] = si1.z;
  7212. skinIndexArray[ offset_skin + 3 ] = si1.w;
  7213. skinIndexArray[ offset_skin + 4 ] = si2.x;
  7214. skinIndexArray[ offset_skin + 5 ] = si2.y;
  7215. skinIndexArray[ offset_skin + 6 ] = si2.z;
  7216. skinIndexArray[ offset_skin + 7 ] = si2.w;
  7217. skinIndexArray[ offset_skin + 8 ] = si3.x;
  7218. skinIndexArray[ offset_skin + 9 ] = si3.y;
  7219. skinIndexArray[ offset_skin + 10 ] = si3.z;
  7220. skinIndexArray[ offset_skin + 11 ] = si3.w;
  7221. // vertices A
  7222. sa1 = obj_skinVerticesA[ face.a ];
  7223. sa2 = obj_skinVerticesA[ face.b ];
  7224. sa3 = obj_skinVerticesA[ face.c ];
  7225. skinVertexAArray[ offset_skin ] = sa1.x;
  7226. skinVertexAArray[ offset_skin + 1 ] = sa1.y;
  7227. skinVertexAArray[ offset_skin + 2 ] = sa1.z;
  7228. skinVertexAArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7229. skinVertexAArray[ offset_skin + 4 ] = sa2.x;
  7230. skinVertexAArray[ offset_skin + 5 ] = sa2.y;
  7231. skinVertexAArray[ offset_skin + 6 ] = sa2.z;
  7232. skinVertexAArray[ offset_skin + 7 ] = 1;
  7233. skinVertexAArray[ offset_skin + 8 ] = sa3.x;
  7234. skinVertexAArray[ offset_skin + 9 ] = sa3.y;
  7235. skinVertexAArray[ offset_skin + 10 ] = sa3.z;
  7236. skinVertexAArray[ offset_skin + 11 ] = 1;
  7237. // vertices B
  7238. sb1 = obj_skinVerticesB[ face.a ];
  7239. sb2 = obj_skinVerticesB[ face.b ];
  7240. sb3 = obj_skinVerticesB[ face.c ];
  7241. skinVertexBArray[ offset_skin ] = sb1.x;
  7242. skinVertexBArray[ offset_skin + 1 ] = sb1.y;
  7243. skinVertexBArray[ offset_skin + 2 ] = sb1.z;
  7244. skinVertexBArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7245. skinVertexBArray[ offset_skin + 4 ] = sb2.x;
  7246. skinVertexBArray[ offset_skin + 5 ] = sb2.y;
  7247. skinVertexBArray[ offset_skin + 6 ] = sb2.z;
  7248. skinVertexBArray[ offset_skin + 7 ] = 1;
  7249. skinVertexBArray[ offset_skin + 8 ] = sb3.x;
  7250. skinVertexBArray[ offset_skin + 9 ] = sb3.y;
  7251. skinVertexBArray[ offset_skin + 10 ] = sb3.z;
  7252. skinVertexBArray[ offset_skin + 11 ] = 1;
  7253. offset_skin += 12;
  7254. }
  7255. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7256. face = obj_faces[ chunk_faces4[ f ] ];
  7257. // weights
  7258. sw1 = obj_skinWeights[ face.a ];
  7259. sw2 = obj_skinWeights[ face.b ];
  7260. sw3 = obj_skinWeights[ face.c ];
  7261. sw4 = obj_skinWeights[ face.d ];
  7262. skinWeightArray[ offset_skin ] = sw1.x;
  7263. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  7264. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  7265. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  7266. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  7267. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  7268. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  7269. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  7270. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  7271. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  7272. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  7273. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  7274. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  7275. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  7276. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  7277. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  7278. // indices
  7279. si1 = obj_skinIndices[ face.a ];
  7280. si2 = obj_skinIndices[ face.b ];
  7281. si3 = obj_skinIndices[ face.c ];
  7282. si4 = obj_skinIndices[ face.d ];
  7283. skinIndexArray[ offset_skin ] = si1.x;
  7284. skinIndexArray[ offset_skin + 1 ] = si1.y;
  7285. skinIndexArray[ offset_skin + 2 ] = si1.z;
  7286. skinIndexArray[ offset_skin + 3 ] = si1.w;
  7287. skinIndexArray[ offset_skin + 4 ] = si2.x;
  7288. skinIndexArray[ offset_skin + 5 ] = si2.y;
  7289. skinIndexArray[ offset_skin + 6 ] = si2.z;
  7290. skinIndexArray[ offset_skin + 7 ] = si2.w;
  7291. skinIndexArray[ offset_skin + 8 ] = si3.x;
  7292. skinIndexArray[ offset_skin + 9 ] = si3.y;
  7293. skinIndexArray[ offset_skin + 10 ] = si3.z;
  7294. skinIndexArray[ offset_skin + 11 ] = si3.w;
  7295. skinIndexArray[ offset_skin + 12 ] = si4.x;
  7296. skinIndexArray[ offset_skin + 13 ] = si4.y;
  7297. skinIndexArray[ offset_skin + 14 ] = si4.z;
  7298. skinIndexArray[ offset_skin + 15 ] = si4.w;
  7299. // vertices A
  7300. sa1 = obj_skinVerticesA[ face.a ];
  7301. sa2 = obj_skinVerticesA[ face.b ];
  7302. sa3 = obj_skinVerticesA[ face.c ];
  7303. sa4 = obj_skinVerticesA[ face.d ];
  7304. skinVertexAArray[ offset_skin ] = sa1.x;
  7305. skinVertexAArray[ offset_skin + 1 ] = sa1.y;
  7306. skinVertexAArray[ offset_skin + 2 ] = sa1.z;
  7307. skinVertexAArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7308. skinVertexAArray[ offset_skin + 4 ] = sa2.x;
  7309. skinVertexAArray[ offset_skin + 5 ] = sa2.y;
  7310. skinVertexAArray[ offset_skin + 6 ] = sa2.z;
  7311. skinVertexAArray[ offset_skin + 7 ] = 1;
  7312. skinVertexAArray[ offset_skin + 8 ] = sa3.x;
  7313. skinVertexAArray[ offset_skin + 9 ] = sa3.y;
  7314. skinVertexAArray[ offset_skin + 10 ] = sa3.z;
  7315. skinVertexAArray[ offset_skin + 11 ] = 1;
  7316. skinVertexAArray[ offset_skin + 12 ] = sa4.x;
  7317. skinVertexAArray[ offset_skin + 13 ] = sa4.y;
  7318. skinVertexAArray[ offset_skin + 14 ] = sa4.z;
  7319. skinVertexAArray[ offset_skin + 15 ] = 1;
  7320. // vertices B
  7321. sb1 = obj_skinVerticesB[ face.a ];
  7322. sb2 = obj_skinVerticesB[ face.b ];
  7323. sb3 = obj_skinVerticesB[ face.c ];
  7324. sb4 = obj_skinVerticesB[ face.d ];
  7325. skinVertexBArray[ offset_skin ] = sb1.x;
  7326. skinVertexBArray[ offset_skin + 1 ] = sb1.y;
  7327. skinVertexBArray[ offset_skin + 2 ] = sb1.z;
  7328. skinVertexBArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7329. skinVertexBArray[ offset_skin + 4 ] = sb2.x;
  7330. skinVertexBArray[ offset_skin + 5 ] = sb2.y;
  7331. skinVertexBArray[ offset_skin + 6 ] = sb2.z;
  7332. skinVertexBArray[ offset_skin + 7 ] = 1;
  7333. skinVertexBArray[ offset_skin + 8 ] = sb3.x;
  7334. skinVertexBArray[ offset_skin + 9 ] = sb3.y;
  7335. skinVertexBArray[ offset_skin + 10 ] = sb3.z;
  7336. skinVertexBArray[ offset_skin + 11 ] = 1;
  7337. skinVertexBArray[ offset_skin + 12 ] = sb4.x;
  7338. skinVertexBArray[ offset_skin + 13 ] = sb4.y;
  7339. skinVertexBArray[ offset_skin + 14 ] = sb4.z;
  7340. skinVertexBArray[ offset_skin + 15 ] = 1;
  7341. offset_skin += 16;
  7342. }
  7343. if ( offset_skin > 0 ) {
  7344. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexABuffer );
  7345. _gl.bufferData( _gl.ARRAY_BUFFER, skinVertexAArray, hint );
  7346. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexBBuffer );
  7347. _gl.bufferData( _gl.ARRAY_BUFFER, skinVertexBArray, hint );
  7348. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  7349. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  7350. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  7351. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  7352. }
  7353. }
  7354. if ( dirtyColors && vertexColorType ) {
  7355. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7356. face = obj_faces[ chunk_faces3[ f ] ];
  7357. vertexColors = face.vertexColors;
  7358. faceColor = face.color;
  7359. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  7360. c1 = vertexColors[ 0 ];
  7361. c2 = vertexColors[ 1 ];
  7362. c3 = vertexColors[ 2 ];
  7363. } else {
  7364. c1 = faceColor;
  7365. c2 = faceColor;
  7366. c3 = faceColor;
  7367. }
  7368. colorArray[ offset_color ] = c1.r;
  7369. colorArray[ offset_color + 1 ] = c1.g;
  7370. colorArray[ offset_color + 2 ] = c1.b;
  7371. colorArray[ offset_color + 3 ] = c2.r;
  7372. colorArray[ offset_color + 4 ] = c2.g;
  7373. colorArray[ offset_color + 5 ] = c2.b;
  7374. colorArray[ offset_color + 6 ] = c3.r;
  7375. colorArray[ offset_color + 7 ] = c3.g;
  7376. colorArray[ offset_color + 8 ] = c3.b;
  7377. offset_color += 9;
  7378. }
  7379. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7380. face = obj_faces[ chunk_faces4[ f ] ];
  7381. vertexColors = face.vertexColors;
  7382. faceColor = face.color;
  7383. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  7384. c1 = vertexColors[ 0 ];
  7385. c2 = vertexColors[ 1 ];
  7386. c3 = vertexColors[ 2 ];
  7387. c4 = vertexColors[ 3 ];
  7388. } else {
  7389. c1 = faceColor;
  7390. c2 = faceColor;
  7391. c3 = faceColor;
  7392. c4 = faceColor;
  7393. }
  7394. colorArray[ offset_color ] = c1.r;
  7395. colorArray[ offset_color + 1 ] = c1.g;
  7396. colorArray[ offset_color + 2 ] = c1.b;
  7397. colorArray[ offset_color + 3 ] = c2.r;
  7398. colorArray[ offset_color + 4 ] = c2.g;
  7399. colorArray[ offset_color + 5 ] = c2.b;
  7400. colorArray[ offset_color + 6 ] = c3.r;
  7401. colorArray[ offset_color + 7 ] = c3.g;
  7402. colorArray[ offset_color + 8 ] = c3.b;
  7403. colorArray[ offset_color + 9 ] = c4.r;
  7404. colorArray[ offset_color + 10 ] = c4.g;
  7405. colorArray[ offset_color + 11 ] = c4.b;
  7406. offset_color += 12;
  7407. }
  7408. if ( offset_color > 0 ) {
  7409. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  7410. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  7411. }
  7412. }
  7413. if ( dirtyTangents && geometry.hasTangents ) {
  7414. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7415. face = obj_faces[ chunk_faces3[ f ] ];
  7416. vertexTangents = face.vertexTangents;
  7417. t1 = vertexTangents[ 0 ];
  7418. t2 = vertexTangents[ 1 ];
  7419. t3 = vertexTangents[ 2 ];
  7420. tangentArray[ offset_tangent ] = t1.x;
  7421. tangentArray[ offset_tangent + 1 ] = t1.y;
  7422. tangentArray[ offset_tangent + 2 ] = t1.z;
  7423. tangentArray[ offset_tangent + 3 ] = t1.w;
  7424. tangentArray[ offset_tangent + 4 ] = t2.x;
  7425. tangentArray[ offset_tangent + 5 ] = t2.y;
  7426. tangentArray[ offset_tangent + 6 ] = t2.z;
  7427. tangentArray[ offset_tangent + 7 ] = t2.w;
  7428. tangentArray[ offset_tangent + 8 ] = t3.x;
  7429. tangentArray[ offset_tangent + 9 ] = t3.y;
  7430. tangentArray[ offset_tangent + 10 ] = t3.z;
  7431. tangentArray[ offset_tangent + 11 ] = t3.w;
  7432. offset_tangent += 12;
  7433. }
  7434. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7435. face = obj_faces[ chunk_faces4[ f ] ];
  7436. vertexTangents = face.vertexTangents;
  7437. t1 = vertexTangents[ 0 ];
  7438. t2 = vertexTangents[ 1 ];
  7439. t3 = vertexTangents[ 2 ];
  7440. t4 = vertexTangents[ 3 ];
  7441. tangentArray[ offset_tangent ] = t1.x;
  7442. tangentArray[ offset_tangent + 1 ] = t1.y;
  7443. tangentArray[ offset_tangent + 2 ] = t1.z;
  7444. tangentArray[ offset_tangent + 3 ] = t1.w;
  7445. tangentArray[ offset_tangent + 4 ] = t2.x;
  7446. tangentArray[ offset_tangent + 5 ] = t2.y;
  7447. tangentArray[ offset_tangent + 6 ] = t2.z;
  7448. tangentArray[ offset_tangent + 7 ] = t2.w;
  7449. tangentArray[ offset_tangent + 8 ] = t3.x;
  7450. tangentArray[ offset_tangent + 9 ] = t3.y;
  7451. tangentArray[ offset_tangent + 10 ] = t3.z;
  7452. tangentArray[ offset_tangent + 11 ] = t3.w;
  7453. tangentArray[ offset_tangent + 12 ] = t4.x;
  7454. tangentArray[ offset_tangent + 13 ] = t4.y;
  7455. tangentArray[ offset_tangent + 14 ] = t4.z;
  7456. tangentArray[ offset_tangent + 15 ] = t4.w;
  7457. offset_tangent += 16;
  7458. }
  7459. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  7460. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  7461. }
  7462. if ( dirtyNormals && normalType ) {
  7463. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7464. face = obj_faces[ chunk_faces3[ f ] ];
  7465. vertexNormals = face.vertexNormals;
  7466. faceNormal = face.normal;
  7467. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  7468. for ( i = 0; i < 3; i ++ ) {
  7469. vn = vertexNormals[ i ];
  7470. normalArray[ offset_normal ] = vn.x;
  7471. normalArray[ offset_normal + 1 ] = vn.y;
  7472. normalArray[ offset_normal + 2 ] = vn.z;
  7473. offset_normal += 3;
  7474. }
  7475. } else {
  7476. for ( i = 0; i < 3; i ++ ) {
  7477. normalArray[ offset_normal ] = faceNormal.x;
  7478. normalArray[ offset_normal + 1 ] = faceNormal.y;
  7479. normalArray[ offset_normal + 2 ] = faceNormal.z;
  7480. offset_normal += 3;
  7481. }
  7482. }
  7483. }
  7484. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7485. face = obj_faces[ chunk_faces4[ f ] ];
  7486. vertexNormals = face.vertexNormals;
  7487. faceNormal = face.normal;
  7488. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  7489. for ( i = 0; i < 4; i ++ ) {
  7490. vn = vertexNormals[ i ];
  7491. normalArray[ offset_normal ] = vn.x;
  7492. normalArray[ offset_normal + 1 ] = vn.y;
  7493. normalArray[ offset_normal + 2 ] = vn.z;
  7494. offset_normal += 3;
  7495. }
  7496. } else {
  7497. for ( i = 0; i < 4; i ++ ) {
  7498. normalArray[ offset_normal ] = faceNormal.x;
  7499. normalArray[ offset_normal + 1 ] = faceNormal.y;
  7500. normalArray[ offset_normal + 2 ] = faceNormal.z;
  7501. offset_normal += 3;
  7502. }
  7503. }
  7504. }
  7505. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  7506. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  7507. }
  7508. if ( dirtyUvs && obj_uvs && uvType ) {
  7509. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7510. fi = chunk_faces3[ f ];
  7511. face = obj_faces[ fi ];
  7512. uv = obj_uvs[ fi ];
  7513. if ( uv === undefined ) continue;
  7514. for ( i = 0; i < 3; i ++ ) {
  7515. uvi = uv[ i ];
  7516. uvArray[ offset_uv ] = uvi.u;
  7517. uvArray[ offset_uv + 1 ] = uvi.v;
  7518. offset_uv += 2;
  7519. }
  7520. }
  7521. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7522. fi = chunk_faces4[ f ];
  7523. face = obj_faces[ fi ];
  7524. uv = obj_uvs[ fi ];
  7525. if ( uv === undefined ) continue;
  7526. for ( i = 0; i < 4; i ++ ) {
  7527. uvi = uv[ i ];
  7528. uvArray[ offset_uv ] = uvi.u;
  7529. uvArray[ offset_uv + 1 ] = uvi.v;
  7530. offset_uv += 2;
  7531. }
  7532. }
  7533. if ( offset_uv > 0 ) {
  7534. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  7535. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  7536. }
  7537. }
  7538. if ( dirtyUvs && obj_uvs2 && uvType ) {
  7539. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7540. fi = chunk_faces3[ f ];
  7541. face = obj_faces[ fi ];
  7542. uv2 = obj_uvs2[ fi ];
  7543. if ( uv2 === undefined ) continue;
  7544. for ( i = 0; i < 3; i ++ ) {
  7545. uv2i = uv2[ i ];
  7546. uv2Array[ offset_uv2 ] = uv2i.u;
  7547. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  7548. offset_uv2 += 2;
  7549. }
  7550. }
  7551. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7552. fi = chunk_faces4[ f ];
  7553. face = obj_faces[ fi ];
  7554. uv2 = obj_uvs2[ fi ];
  7555. if ( uv2 === undefined ) continue;
  7556. for ( i = 0; i < 4; i ++ ) {
  7557. uv2i = uv2[ i ];
  7558. uv2Array[ offset_uv2 ] = uv2i.u;
  7559. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  7560. offset_uv2 += 2;
  7561. }
  7562. }
  7563. if ( offset_uv2 > 0 ) {
  7564. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  7565. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  7566. }
  7567. }
  7568. if ( dirtyElements ) {
  7569. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7570. face = obj_faces[ chunk_faces3[ f ] ];
  7571. faceArray[ offset_face ] = vertexIndex;
  7572. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  7573. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  7574. offset_face += 3;
  7575. lineArray[ offset_line ] = vertexIndex;
  7576. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  7577. lineArray[ offset_line + 2 ] = vertexIndex;
  7578. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  7579. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  7580. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  7581. offset_line += 6;
  7582. vertexIndex += 3;
  7583. }
  7584. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7585. face = obj_faces[ chunk_faces4[ f ] ];
  7586. faceArray[ offset_face ] = vertexIndex;
  7587. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  7588. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  7589. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  7590. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  7591. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  7592. offset_face += 6;
  7593. lineArray[ offset_line ] = vertexIndex;
  7594. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  7595. lineArray[ offset_line + 2 ] = vertexIndex;
  7596. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  7597. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  7598. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  7599. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  7600. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  7601. offset_line += 8;
  7602. vertexIndex += 4;
  7603. }
  7604. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  7605. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  7606. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  7607. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  7608. }
  7609. if ( customAttributes ) {
  7610. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  7611. customAttribute = customAttributes[ i ];
  7612. if ( ! customAttribute.__original.needsUpdate ) continue;
  7613. offset_custom = 0;
  7614. offset_customSrc = 0;
  7615. if ( customAttribute.size === 1 ) {
  7616. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7617. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7618. face = obj_faces[ chunk_faces3[ f ] ];
  7619. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  7620. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  7621. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  7622. offset_custom += 3;
  7623. }
  7624. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7625. face = obj_faces[ chunk_faces4[ f ] ];
  7626. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  7627. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  7628. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  7629. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  7630. offset_custom += 4;
  7631. }
  7632. } else if ( customAttribute.boundTo === "faces" ) {
  7633. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7634. value = customAttribute.value[ chunk_faces3[ f ] ];
  7635. customAttribute.array[ offset_custom ] = value;
  7636. customAttribute.array[ offset_custom + 1 ] = value;
  7637. customAttribute.array[ offset_custom + 2 ] = value;
  7638. offset_custom += 3;
  7639. }
  7640. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7641. value = customAttribute.value[ chunk_faces4[ f ] ];
  7642. customAttribute.array[ offset_custom ] = value;
  7643. customAttribute.array[ offset_custom + 1 ] = value;
  7644. customAttribute.array[ offset_custom + 2 ] = value;
  7645. customAttribute.array[ offset_custom + 3 ] = value;
  7646. offset_custom += 4;
  7647. }
  7648. }
  7649. } else if ( customAttribute.size === 2 ) {
  7650. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7651. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7652. face = obj_faces[ chunk_faces3[ f ] ];
  7653. v1 = customAttribute.value[ face.a ];
  7654. v2 = customAttribute.value[ face.b ];
  7655. v3 = customAttribute.value[ face.c ];
  7656. customAttribute.array[ offset_custom ] = v1.x;
  7657. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7658. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7659. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7660. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7661. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7662. offset_custom += 6;
  7663. }
  7664. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7665. face = obj_faces[ chunk_faces4[ f ] ];
  7666. v1 = customAttribute.value[ face.a ];
  7667. v2 = customAttribute.value[ face.b ];
  7668. v3 = customAttribute.value[ face.c ];
  7669. v4 = customAttribute.value[ face.d ];
  7670. customAttribute.array[ offset_custom ] = v1.x;
  7671. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7672. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7673. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7674. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7675. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7676. customAttribute.array[ offset_custom + 6 ] = v4.x;
  7677. customAttribute.array[ offset_custom + 7 ] = v4.y;
  7678. offset_custom += 8;
  7679. }
  7680. } else if ( customAttribute.boundTo === "faces" ) {
  7681. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7682. value = customAttribute.value[ chunk_faces3[ f ] ];
  7683. v1 = value;
  7684. v2 = value;
  7685. v3 = value;
  7686. customAttribute.array[ offset_custom ] = v1.x;
  7687. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7688. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7689. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7690. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7691. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7692. offset_custom += 6;
  7693. }
  7694. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7695. value = customAttribute.value[ chunk_faces4[ f ] ];
  7696. v1 = value;
  7697. v2 = value;
  7698. v3 = value;
  7699. v4 = value;
  7700. customAttribute.array[ offset_custom ] = v1.x;
  7701. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7702. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7703. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7704. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7705. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7706. customAttribute.array[ offset_custom + 6 ] = v4.x;
  7707. customAttribute.array[ offset_custom + 7 ] = v4.y;
  7708. offset_custom += 8;
  7709. }
  7710. }
  7711. } else if ( customAttribute.size === 3 ) {
  7712. var pp;
  7713. if ( customAttribute.type === "c" ) {
  7714. pp = [ "r", "g", "b" ];
  7715. } else {
  7716. pp = [ "x", "y", "z" ];
  7717. }
  7718. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7719. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7720. face = obj_faces[ chunk_faces3[ f ] ];
  7721. v1 = customAttribute.value[ face.a ];
  7722. v2 = customAttribute.value[ face.b ];
  7723. v3 = customAttribute.value[ face.c ];
  7724. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7725. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7726. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7727. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7728. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7729. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7730. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7731. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7732. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7733. offset_custom += 9;
  7734. }
  7735. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7736. face = obj_faces[ chunk_faces4[ f ] ];
  7737. v1 = customAttribute.value[ face.a ];
  7738. v2 = customAttribute.value[ face.b ];
  7739. v3 = customAttribute.value[ face.c ];
  7740. v4 = customAttribute.value[ face.d ];
  7741. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7742. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7743. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7744. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7745. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7746. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7747. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7748. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7749. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7750. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  7751. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  7752. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  7753. offset_custom += 12;
  7754. }
  7755. } else if ( customAttribute.boundTo === "faces" ) {
  7756. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7757. value = customAttribute.value[ chunk_faces3[ f ] ];
  7758. v1 = value;
  7759. v2 = value;
  7760. v3 = value;
  7761. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7762. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7763. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7764. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7765. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7766. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7767. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7768. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7769. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7770. offset_custom += 9;
  7771. }
  7772. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7773. value = customAttribute.value[ chunk_faces4[ f ] ];
  7774. v1 = value;
  7775. v2 = value;
  7776. v3 = value;
  7777. v4 = value;
  7778. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7779. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7780. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7781. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7782. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7783. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7784. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7785. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7786. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7787. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  7788. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  7789. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  7790. offset_custom += 12;
  7791. }
  7792. }
  7793. } else if ( customAttribute.size === 4 ) {
  7794. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7795. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7796. face = obj_faces[ chunk_faces3[ f ] ];
  7797. v1 = customAttribute.value[ face.a ];
  7798. v2 = customAttribute.value[ face.b ];
  7799. v3 = customAttribute.value[ face.c ];
  7800. customAttribute.array[ offset_custom ] = v1.x;
  7801. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7802. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7803. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7804. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7805. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7806. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7807. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7808. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7809. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7810. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7811. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7812. offset_custom += 12;
  7813. }
  7814. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7815. face = obj_faces[ chunk_faces4[ f ] ];
  7816. v1 = customAttribute.value[ face.a ];
  7817. v2 = customAttribute.value[ face.b ];
  7818. v3 = customAttribute.value[ face.c ];
  7819. v4 = customAttribute.value[ face.d ];
  7820. customAttribute.array[ offset_custom ] = v1.x;
  7821. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7822. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7823. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7824. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7825. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7826. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7827. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7828. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7829. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7830. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7831. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7832. customAttribute.array[ offset_custom + 12 ] = v4.x;
  7833. customAttribute.array[ offset_custom + 13 ] = v4.y;
  7834. customAttribute.array[ offset_custom + 14 ] = v4.z;
  7835. customAttribute.array[ offset_custom + 15 ] = v4.w;
  7836. offset_custom += 16;
  7837. }
  7838. } else if ( customAttribute.boundTo === "faces" ) {
  7839. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7840. value = customAttribute.value[ chunk_faces3[ f ] ];
  7841. v1 = value;
  7842. v2 = value;
  7843. v3 = value;
  7844. customAttribute.array[ offset_custom ] = v1.x;
  7845. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7846. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7847. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7848. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7849. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7850. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7851. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7852. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7853. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7854. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7855. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7856. offset_custom += 12;
  7857. }
  7858. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7859. value = customAttribute.value[ chunk_faces4[ f ] ];
  7860. v1 = value;
  7861. v2 = value;
  7862. v3 = value;
  7863. v4 = value;
  7864. customAttribute.array[ offset_custom ] = v1.x;
  7865. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7866. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7867. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7868. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7869. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7870. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7871. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7872. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7873. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7874. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7875. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7876. customAttribute.array[ offset_custom + 12 ] = v4.x;
  7877. customAttribute.array[ offset_custom + 13 ] = v4.y;
  7878. customAttribute.array[ offset_custom + 14 ] = v4.z;
  7879. customAttribute.array[ offset_custom + 15 ] = v4.w;
  7880. offset_custom += 16;
  7881. }
  7882. }
  7883. }
  7884. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  7885. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  7886. }
  7887. }
  7888. if ( dispose ) {
  7889. delete geometryGroup.__inittedArrays;
  7890. delete geometryGroup.__colorArray;
  7891. delete geometryGroup.__normalArray;
  7892. delete geometryGroup.__tangentArray;
  7893. delete geometryGroup.__uvArray;
  7894. delete geometryGroup.__uv2Array;
  7895. delete geometryGroup.__faceArray;
  7896. delete geometryGroup.__vertexArray;
  7897. delete geometryGroup.__lineArray;
  7898. delete geometryGroup.__skinVertexAArray;
  7899. delete geometryGroup.__skinVertexBArray;
  7900. delete geometryGroup.__skinIndexArray;
  7901. delete geometryGroup.__skinWeightArray;
  7902. }
  7903. };
  7904. // Buffer rendering
  7905. this.renderBufferImmediate = function ( object, program, shading ) {
  7906. if ( ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  7907. if ( ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  7908. if ( object.hasPos ) {
  7909. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  7910. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  7911. _gl.enableVertexAttribArray( program.attributes.position );
  7912. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  7913. }
  7914. if ( object.hasNormal ) {
  7915. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  7916. if ( shading === THREE.FlatShading ) {
  7917. var nx, ny, nz,
  7918. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  7919. normalArray,
  7920. i, il = object.count * 3;
  7921. for( i = 0; i < il; i += 9 ) {
  7922. normalArray = object.normalArray;
  7923. nax = normalArray[ i ];
  7924. nay = normalArray[ i + 1 ];
  7925. naz = normalArray[ i + 2 ];
  7926. nbx = normalArray[ i + 3 ];
  7927. nby = normalArray[ i + 4 ];
  7928. nbz = normalArray[ i + 5 ];
  7929. ncx = normalArray[ i + 6 ];
  7930. ncy = normalArray[ i + 7 ];
  7931. ncz = normalArray[ i + 8 ];
  7932. nx = ( nax + nbx + ncx ) / 3;
  7933. ny = ( nay + nby + ncy ) / 3;
  7934. nz = ( naz + nbz + ncz ) / 3;
  7935. normalArray[ i ] = nx;
  7936. normalArray[ i + 1 ] = ny;
  7937. normalArray[ i + 2 ] = nz;
  7938. normalArray[ i + 3 ] = nx;
  7939. normalArray[ i + 4 ] = ny;
  7940. normalArray[ i + 5 ] = nz;
  7941. normalArray[ i + 6 ] = nx;
  7942. normalArray[ i + 7 ] = ny;
  7943. normalArray[ i + 8 ] = nz;
  7944. }
  7945. }
  7946. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  7947. _gl.enableVertexAttribArray( program.attributes.normal );
  7948. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  7949. }
  7950. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  7951. object.count = 0;
  7952. };
  7953. this.renderBufferDirect = function ( camera, lights, fog, material, geometryGroup, object ) {
  7954. if ( material.opacity === 0 ) return;
  7955. var program, attributes, linewidth, primitives, a, attribute;
  7956. program = setProgram( camera, lights, fog, material, object );
  7957. attributes = program.attributes;
  7958. var updateBuffers = false,
  7959. wireframeBit = material.wireframe ? 1 : 0,
  7960. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  7961. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  7962. _currentGeometryGroupHash = geometryGroupHash;
  7963. updateBuffers = true;
  7964. }
  7965. // render mesh
  7966. if ( object instanceof THREE.Mesh ) {
  7967. var offsets = geometryGroup.offsets;
  7968. for ( var i = 0, il = offsets.length; i < il; ++ i ) {
  7969. if ( updateBuffers ) {
  7970. // vertices
  7971. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexPositionBuffer );
  7972. _gl.vertexAttribPointer( attributes.position, geometryGroup.vertexPositionBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 3 );
  7973. // normals
  7974. if ( attributes.normal >= 0 && geometryGroup.vertexNormalBuffer ) {
  7975. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexNormalBuffer );
  7976. _gl.vertexAttribPointer( attributes.normal, geometryGroup.vertexNormalBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 3 );
  7977. }
  7978. // uvs
  7979. if ( attributes.uv >= 0 && geometryGroup.vertexUvBuffer ) {
  7980. if ( geometryGroup.vertexUvBuffer ) {
  7981. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexUvBuffer );
  7982. _gl.vertexAttribPointer( attributes.uv, geometryGroup.vertexUvBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 2 );
  7983. _gl.enableVertexAttribArray( attributes.uv );
  7984. } else {
  7985. _gl.disableVertexAttribArray( attributes.uv );
  7986. }
  7987. }
  7988. // colors
  7989. if ( attributes.color >= 0 && geometryGroup.vertexColorBuffer ) {
  7990. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexColorBuffer );
  7991. _gl.vertexAttribPointer( attributes.color, geometryGroup.vertexColorBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 4 );
  7992. }
  7993. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.vertexIndexBuffer );
  7994. }
  7995. // render indexed triangles
  7996. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 = Uint16
  7997. _this.info.render.calls ++;
  7998. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  7999. _this.info.render.faces += offsets[ i ].count / 3;
  8000. }
  8001. }
  8002. };
  8003. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  8004. if ( material.opacity === 0 ) return;
  8005. var program, attributes, linewidth, primitives, a, attribute, i, il;
  8006. program = setProgram( camera, lights, fog, material, object );
  8007. attributes = program.attributes;
  8008. var updateBuffers = false,
  8009. wireframeBit = material.wireframe ? 1 : 0,
  8010. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  8011. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  8012. _currentGeometryGroupHash = geometryGroupHash;
  8013. updateBuffers = true;
  8014. }
  8015. // vertices
  8016. if ( !material.morphTargets && attributes.position >= 0 ) {
  8017. if ( updateBuffers ) {
  8018. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  8019. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  8020. }
  8021. } else {
  8022. if ( object.morphTargetBase ) {
  8023. setupMorphTargets( material, geometryGroup, object );
  8024. }
  8025. }
  8026. if ( updateBuffers ) {
  8027. // custom attributes
  8028. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  8029. if ( geometryGroup.__webglCustomAttributesList ) {
  8030. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  8031. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  8032. if( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  8033. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  8034. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  8035. }
  8036. }
  8037. }
  8038. // colors
  8039. if ( attributes.color >= 0 ) {
  8040. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  8041. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  8042. }
  8043. // normals
  8044. if ( attributes.normal >= 0 ) {
  8045. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  8046. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  8047. }
  8048. // tangents
  8049. if ( attributes.tangent >= 0 ) {
  8050. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  8051. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  8052. }
  8053. // uvs
  8054. if ( attributes.uv >= 0 ) {
  8055. if ( geometryGroup.__webglUVBuffer ) {
  8056. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  8057. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  8058. _gl.enableVertexAttribArray( attributes.uv );
  8059. } else {
  8060. _gl.disableVertexAttribArray( attributes.uv );
  8061. }
  8062. }
  8063. if ( attributes.uv2 >= 0 ) {
  8064. if ( geometryGroup.__webglUV2Buffer ) {
  8065. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  8066. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  8067. _gl.enableVertexAttribArray( attributes.uv2 );
  8068. } else {
  8069. _gl.disableVertexAttribArray( attributes.uv2 );
  8070. }
  8071. }
  8072. if ( material.skinning &&
  8073. attributes.skinVertexA >= 0 && attributes.skinVertexB >= 0 &&
  8074. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  8075. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexABuffer );
  8076. _gl.vertexAttribPointer( attributes.skinVertexA, 4, _gl.FLOAT, false, 0, 0 );
  8077. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexBBuffer );
  8078. _gl.vertexAttribPointer( attributes.skinVertexB, 4, _gl.FLOAT, false, 0, 0 );
  8079. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  8080. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  8081. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  8082. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  8083. }
  8084. }
  8085. // render mesh
  8086. if ( object instanceof THREE.Mesh ) {
  8087. // wireframe
  8088. if ( material.wireframe ) {
  8089. setLineWidth( material.wireframeLinewidth );
  8090. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  8091. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  8092. // triangles
  8093. } else {
  8094. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  8095. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  8096. }
  8097. _this.info.render.calls ++;
  8098. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  8099. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  8100. // render lines
  8101. } else if ( object instanceof THREE.Line ) {
  8102. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  8103. setLineWidth( material.linewidth );
  8104. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  8105. _this.info.render.calls ++;
  8106. // render particles
  8107. } else if ( object instanceof THREE.ParticleSystem ) {
  8108. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  8109. _this.info.render.calls ++;
  8110. _this.info.render.points += geometryGroup.__webglParticleCount;
  8111. // render ribbon
  8112. } else if ( object instanceof THREE.Ribbon ) {
  8113. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  8114. _this.info.render.calls ++;
  8115. }
  8116. };
  8117. function setupMorphTargets ( material, geometryGroup, object ) {
  8118. // set base
  8119. var attributes = material.program.attributes;
  8120. if ( object.morphTargetBase !== - 1 ) {
  8121. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  8122. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  8123. } else if ( attributes.position >= 0 ) {
  8124. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  8125. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  8126. }
  8127. if ( object.morphTargetForcedOrder.length ) {
  8128. // set forced order
  8129. var m = 0;
  8130. var order = object.morphTargetForcedOrder;
  8131. var influences = object.morphTargetInfluences;
  8132. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  8133. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  8134. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8135. if ( material.morphNormals ) {
  8136. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  8137. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8138. }
  8139. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  8140. m ++;
  8141. }
  8142. } else {
  8143. // find most influencing
  8144. var used = [];
  8145. var candidateInfluence = - 1;
  8146. var candidate = 0;
  8147. var influences = object.morphTargetInfluences;
  8148. var i, il = influences.length;
  8149. var m = 0;
  8150. if ( object.morphTargetBase !== - 1 ) {
  8151. used[ object.morphTargetBase ] = true;
  8152. }
  8153. while ( m < material.numSupportedMorphTargets ) {
  8154. for ( i = 0; i < il; i ++ ) {
  8155. if ( !used[ i ] && influences[ i ] > candidateInfluence ) {
  8156. candidate = i;
  8157. candidateInfluence = influences[ candidate ];
  8158. }
  8159. }
  8160. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ candidate ] );
  8161. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8162. if ( material.morphNormals ) {
  8163. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ candidate ] );
  8164. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8165. }
  8166. object.__webglMorphTargetInfluences[ m ] = candidateInfluence;
  8167. used[ candidate ] = 1;
  8168. candidateInfluence = -1;
  8169. m ++;
  8170. }
  8171. }
  8172. // load updated influences uniform
  8173. if( material.program.uniforms.morphTargetInfluences !== null ) {
  8174. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  8175. }
  8176. };
  8177. function painterSort ( a, b ) {
  8178. return b.z - a.z;
  8179. };
  8180. // Rendering
  8181. this.render = function ( scene, camera, renderTarget, forceClear ) {
  8182. var i, il,
  8183. webglObject, object,
  8184. renderList,
  8185. lights = scene.__lights,
  8186. fog = scene.fog;
  8187. _currentMaterialId = -1;
  8188. // update scene graph
  8189. if ( camera.parent === undefined ) {
  8190. console.warn( 'DEPRECATED: Camera hasn\'t been added to a Scene. Adding it...' );
  8191. scene.add( camera );
  8192. }
  8193. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  8194. // update camera matrices and frustum
  8195. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  8196. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  8197. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  8198. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  8199. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  8200. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  8201. _frustum.setFromMatrix( _projScreenMatrix );
  8202. // update WebGL objects
  8203. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  8204. // custom render plugins (pre pass)
  8205. renderPlugins( this.renderPluginsPre, scene, camera );
  8206. //
  8207. _this.info.render.calls = 0;
  8208. _this.info.render.vertices = 0;
  8209. _this.info.render.faces = 0;
  8210. _this.info.render.points = 0;
  8211. this.setRenderTarget( renderTarget );
  8212. if ( this.autoClear || forceClear ) {
  8213. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  8214. }
  8215. // set matrices for regular objects (frustum culled)
  8216. renderList = scene.__webglObjects;
  8217. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  8218. webglObject = renderList[ i ];
  8219. object = webglObject.object;
  8220. webglObject.render = false;
  8221. if ( object.visible ) {
  8222. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  8223. object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8224. setupMatrices( object, camera );
  8225. unrollBufferMaterial( webglObject );
  8226. webglObject.render = true;
  8227. if ( this.sortObjects ) {
  8228. if ( object.renderDepth ) {
  8229. webglObject.z = object.renderDepth;
  8230. } else {
  8231. _vector3.copy( object.matrixWorld.getPosition() );
  8232. _projScreenMatrix.multiplyVector3( _vector3 );
  8233. webglObject.z = _vector3.z;
  8234. }
  8235. }
  8236. }
  8237. }
  8238. }
  8239. if ( this.sortObjects ) {
  8240. renderList.sort( painterSort );
  8241. }
  8242. // set matrices for immediate objects
  8243. renderList = scene.__webglObjectsImmediate;
  8244. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  8245. webglObject = renderList[ i ];
  8246. object = webglObject.object;
  8247. if ( object.visible ) {
  8248. if( object.matrixAutoUpdate ) {
  8249. object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8250. }
  8251. setupMatrices( object, camera );
  8252. unrollImmediateBufferMaterial( webglObject );
  8253. }
  8254. }
  8255. if ( scene.overrideMaterial ) {
  8256. var material = scene.overrideMaterial;
  8257. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8258. this.setDepthTest( material.depthTest );
  8259. this.setDepthWrite( material.depthWrite );
  8260. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  8261. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  8262. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  8263. } else {
  8264. // opaque pass (front-to-back order)
  8265. this.setBlending( THREE.NormalBlending );
  8266. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  8267. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  8268. // transparent pass (back-to-front order)
  8269. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  8270. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  8271. }
  8272. // custom render plugins (post pass)
  8273. renderPlugins( this.renderPluginsPost, scene, camera );
  8274. // Generate mipmap if we're using any kind of mipmap filtering
  8275. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  8276. updateRenderTargetMipmap( renderTarget );
  8277. }
  8278. // Ensure depth buffer writing is enabled so it can be cleared on next render
  8279. this.setDepthTest( true );
  8280. this.setDepthWrite( true );
  8281. // _gl.finish();
  8282. };
  8283. function renderPlugins( plugins, scene, camera ) {
  8284. if ( ! plugins.length ) return;
  8285. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  8286. _currentProgram = null;
  8287. _currentCamera = null;
  8288. _oldBlending = -1;
  8289. _oldDepthTest = -1;
  8290. _oldDepthWrite = -1;
  8291. _currentGeometryGroupHash = -1;
  8292. _currentMaterialId = -1;
  8293. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  8294. _currentProgram = null;
  8295. _currentCamera = null;
  8296. _oldBlending = -1;
  8297. _oldDepthTest = -1;
  8298. _oldDepthWrite = -1;
  8299. _currentGeometryGroupHash = -1;
  8300. _currentMaterialId = -1;
  8301. }
  8302. };
  8303. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  8304. var webglObject, object, buffer, material, start, end, delta;
  8305. if ( reverse ) {
  8306. start = renderList.length - 1;
  8307. end = -1;
  8308. delta = -1;
  8309. } else {
  8310. start = 0;
  8311. end = renderList.length;
  8312. delta = 1;
  8313. }
  8314. for ( var i = start; i !== end; i += delta ) {
  8315. webglObject = renderList[ i ];
  8316. if ( webglObject.render ) {
  8317. object = webglObject.object;
  8318. buffer = webglObject.buffer;
  8319. if ( overrideMaterial ) {
  8320. material = overrideMaterial;
  8321. } else {
  8322. material = webglObject[ materialType ];
  8323. if ( ! material ) continue;
  8324. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8325. _this.setDepthTest( material.depthTest );
  8326. _this.setDepthWrite( material.depthWrite );
  8327. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  8328. }
  8329. _this.setObjectFaces( object );
  8330. if ( buffer instanceof THREE.BufferGeometry ) {
  8331. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  8332. } else {
  8333. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  8334. }
  8335. }
  8336. }
  8337. };
  8338. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  8339. var webglObject, object, material, program;
  8340. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  8341. webglObject = renderList[ i ];
  8342. object = webglObject.object;
  8343. if ( object.visible ) {
  8344. if ( overrideMaterial ) {
  8345. material = overrideMaterial;
  8346. } else {
  8347. material = webglObject[ materialType ];
  8348. if ( ! material ) continue;
  8349. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8350. _this.setDepthTest( material.depthTest );
  8351. _this.setDepthWrite( material.depthWrite );
  8352. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  8353. }
  8354. _this.renderImmediateObject( camera, lights, fog, material, object );
  8355. }
  8356. }
  8357. };
  8358. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  8359. var program = setProgram( camera, lights, fog, material, object );
  8360. _currentGeometryGroupHash = -1;
  8361. _this.setObjectFaces( object );
  8362. if ( object.immediateRenderCallback ) {
  8363. object.immediateRenderCallback( program, _gl, _frustum );
  8364. } else {
  8365. object.render( function( object ) { _this.renderBufferImmediate( object, program, material.shading ); } );
  8366. }
  8367. };
  8368. function unrollImmediateBufferMaterial ( globject ) {
  8369. var object = globject.object,
  8370. material = object.material;
  8371. if ( material.transparent ) {
  8372. globject.transparent = material;
  8373. globject.opaque = null;
  8374. } else {
  8375. globject.opaque = material;
  8376. globject.transparent = null;
  8377. }
  8378. };
  8379. function unrollBufferMaterial ( globject ) {
  8380. var object = globject.object,
  8381. buffer = globject.buffer,
  8382. material, materialIndex, meshMaterial;
  8383. meshMaterial = object.material;
  8384. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  8385. materialIndex = buffer.materialIndex;
  8386. if ( materialIndex >= 0 ) {
  8387. material = object.geometry.materials[ materialIndex ];
  8388. if ( material.transparent ) {
  8389. globject.transparent = material;
  8390. globject.opaque = null;
  8391. } else {
  8392. globject.opaque = material;
  8393. globject.transparent = null;
  8394. }
  8395. }
  8396. } else {
  8397. material = meshMaterial;
  8398. if ( material ) {
  8399. if ( material.transparent ) {
  8400. globject.transparent = material;
  8401. globject.opaque = null;
  8402. } else {
  8403. globject.opaque = material;
  8404. globject.transparent = null;
  8405. }
  8406. }
  8407. }
  8408. };
  8409. // Geometry splitting
  8410. function sortFacesByMaterial ( geometry ) {
  8411. var f, fl, face, materialIndex, vertices,
  8412. materialHash, groupHash,
  8413. hash_map = {};
  8414. var numMorphTargets = geometry.morphTargets.length;
  8415. var numMorphNormals = geometry.morphNormals.length;
  8416. geometry.geometryGroups = {};
  8417. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  8418. face = geometry.faces[ f ];
  8419. materialIndex = face.materialIndex;
  8420. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  8421. if ( hash_map[ materialHash ] === undefined ) {
  8422. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  8423. }
  8424. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  8425. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  8426. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  8427. }
  8428. vertices = face instanceof THREE.Face3 ? 3 : 4;
  8429. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  8430. hash_map[ materialHash ].counter += 1;
  8431. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  8432. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  8433. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  8434. }
  8435. }
  8436. if ( face instanceof THREE.Face3 ) {
  8437. geometry.geometryGroups[ groupHash ].faces3.push( f );
  8438. } else {
  8439. geometry.geometryGroups[ groupHash ].faces4.push( f );
  8440. }
  8441. geometry.geometryGroups[ groupHash ].vertices += vertices;
  8442. }
  8443. geometry.geometryGroupsList = [];
  8444. for ( var g in geometry.geometryGroups ) {
  8445. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  8446. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  8447. }
  8448. };
  8449. // Objects refresh
  8450. this.initWebGLObjects = function ( scene ) {
  8451. if ( !scene.__webglObjects ) {
  8452. scene.__webglObjects = [];
  8453. scene.__webglObjectsImmediate = [];
  8454. scene.__webglSprites = [];
  8455. scene.__webglFlares = [];
  8456. }
  8457. while ( scene.__objectsAdded.length ) {
  8458. addObject( scene.__objectsAdded[ 0 ], scene );
  8459. scene.__objectsAdded.splice( 0, 1 );
  8460. }
  8461. while ( scene.__objectsRemoved.length ) {
  8462. removeObject( scene.__objectsRemoved[ 0 ], scene );
  8463. scene.__objectsRemoved.splice( 0, 1 );
  8464. }
  8465. // update must be called after objects adding / removal
  8466. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  8467. updateObject( scene.__webglObjects[ o ].object );
  8468. }
  8469. };
  8470. // Objects adding
  8471. function addObject ( object, scene ) {
  8472. var g, geometry, geometryGroup;
  8473. if ( ! object.__webglInit ) {
  8474. object.__webglInit = true;
  8475. object._modelViewMatrix = new THREE.Matrix4();
  8476. object._normalMatrix = new THREE.Matrix3();
  8477. object._normalMatrixArray = new Float32Array( 9 );
  8478. object._modelViewMatrixArray = new Float32Array( 16 );
  8479. object._objectMatrixArray = new Float32Array( 16 );
  8480. object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8481. if ( object instanceof THREE.Mesh ) {
  8482. geometry = object.geometry;
  8483. if ( geometry instanceof THREE.Geometry ) {
  8484. if ( geometry.geometryGroups === undefined ) {
  8485. sortFacesByMaterial( geometry );
  8486. }
  8487. // create separate VBOs per geometry chunk
  8488. for ( g in geometry.geometryGroups ) {
  8489. geometryGroup = geometry.geometryGroups[ g ];
  8490. // initialise VBO on the first access
  8491. if ( ! geometryGroup.__webglVertexBuffer ) {
  8492. createMeshBuffers( geometryGroup );
  8493. initMeshBuffers( geometryGroup, object );
  8494. geometry.__dirtyVertices = true;
  8495. geometry.__dirtyMorphTargets = true;
  8496. geometry.__dirtyElements = true;
  8497. geometry.__dirtyUvs = true;
  8498. geometry.__dirtyNormals = true;
  8499. geometry.__dirtyTangents = true;
  8500. geometry.__dirtyColors = true;
  8501. }
  8502. }
  8503. }
  8504. } else if ( object instanceof THREE.Ribbon ) {
  8505. geometry = object.geometry;
  8506. if( ! geometry.__webglVertexBuffer ) {
  8507. createRibbonBuffers( geometry );
  8508. initRibbonBuffers( geometry );
  8509. geometry.__dirtyVertices = true;
  8510. geometry.__dirtyColors = true;
  8511. }
  8512. } else if ( object instanceof THREE.Line ) {
  8513. geometry = object.geometry;
  8514. if( ! geometry.__webglVertexBuffer ) {
  8515. createLineBuffers( geometry );
  8516. initLineBuffers( geometry, object );
  8517. geometry.__dirtyVertices = true;
  8518. geometry.__dirtyColors = true;
  8519. }
  8520. } else if ( object instanceof THREE.ParticleSystem ) {
  8521. geometry = object.geometry;
  8522. if ( ! geometry.__webglVertexBuffer ) {
  8523. createParticleBuffers( geometry );
  8524. initParticleBuffers( geometry, object );
  8525. geometry.__dirtyVertices = true;
  8526. geometry.__dirtyColors = true;
  8527. }
  8528. }
  8529. }
  8530. if ( ! object.__webglActive ) {
  8531. if ( object instanceof THREE.Mesh ) {
  8532. geometry = object.geometry;
  8533. if ( geometry instanceof THREE.BufferGeometry ) {
  8534. addBuffer( scene.__webglObjects, geometry, object );
  8535. } else {
  8536. for ( g in geometry.geometryGroups ) {
  8537. geometryGroup = geometry.geometryGroups[ g ];
  8538. addBuffer( scene.__webglObjects, geometryGroup, object );
  8539. }
  8540. }
  8541. } else if ( object instanceof THREE.Ribbon ||
  8542. object instanceof THREE.Line ||
  8543. object instanceof THREE.ParticleSystem ) {
  8544. geometry = object.geometry;
  8545. addBuffer( scene.__webglObjects, geometry, object );
  8546. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  8547. addBufferImmediate( scene.__webglObjectsImmediate, object );
  8548. } else if ( object instanceof THREE.Sprite ) {
  8549. scene.__webglSprites.push( object );
  8550. } else if ( object instanceof THREE.LensFlare ) {
  8551. scene.__webglFlares.push( object );
  8552. }
  8553. object.__webglActive = true;
  8554. }
  8555. };
  8556. function addBuffer ( objlist, buffer, object ) {
  8557. objlist.push(
  8558. {
  8559. buffer: buffer,
  8560. object: object,
  8561. opaque: null,
  8562. transparent: null
  8563. }
  8564. );
  8565. };
  8566. function addBufferImmediate ( objlist, object ) {
  8567. objlist.push(
  8568. {
  8569. object: object,
  8570. opaque: null,
  8571. transparent: null
  8572. }
  8573. );
  8574. };
  8575. // Objects updates
  8576. function updateObject ( object ) {
  8577. var geometry = object.geometry,
  8578. geometryGroup, customAttributesDirty, material;
  8579. if ( object instanceof THREE.Mesh ) {
  8580. if ( geometry instanceof THREE.BufferGeometry ) {
  8581. /*
  8582. if ( geometry.__dirtyVertices || geometry.__dirtyElements ||
  8583. geometry.__dirtyUvs || geometry.__dirtyNormals ||
  8584. geometry.__dirtyColors ) {
  8585. // TODO
  8586. // set buffers from typed arrays
  8587. }
  8588. */
  8589. geometry.__dirtyVertices = false;
  8590. geometry.__dirtyElements = false;
  8591. geometry.__dirtyUvs = false;
  8592. geometry.__dirtyNormals = false;
  8593. geometry.__dirtyColors = false;
  8594. } else {
  8595. // check all geometry groups
  8596. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  8597. geometryGroup = geometry.geometryGroupsList[ i ];
  8598. material = getBufferMaterial( object, geometryGroup );
  8599. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  8600. if ( geometry.__dirtyVertices || geometry.__dirtyMorphTargets || geometry.__dirtyElements ||
  8601. geometry.__dirtyUvs || geometry.__dirtyNormals ||
  8602. geometry.__dirtyColors || geometry.__dirtyTangents || customAttributesDirty ) {
  8603. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  8604. }
  8605. }
  8606. geometry.__dirtyVertices = false;
  8607. geometry.__dirtyMorphTargets = false;
  8608. geometry.__dirtyElements = false;
  8609. geometry.__dirtyUvs = false;
  8610. geometry.__dirtyNormals = false;
  8611. geometry.__dirtyColors = false;
  8612. geometry.__dirtyTangents = false;
  8613. material.attributes && clearCustomAttributes( material );
  8614. }
  8615. } else if ( object instanceof THREE.Ribbon ) {
  8616. if ( geometry.__dirtyVertices || geometry.__dirtyColors ) {
  8617. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  8618. }
  8619. geometry.__dirtyVertices = false;
  8620. geometry.__dirtyColors = false;
  8621. } else if ( object instanceof THREE.Line ) {
  8622. material = getBufferMaterial( object, geometryGroup );
  8623. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  8624. if ( geometry.__dirtyVertices || geometry.__dirtyColors || customAttributesDirty ) {
  8625. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  8626. }
  8627. geometry.__dirtyVertices = false;
  8628. geometry.__dirtyColors = false;
  8629. material.attributes && clearCustomAttributes( material );
  8630. } else if ( object instanceof THREE.ParticleSystem ) {
  8631. material = getBufferMaterial( object, geometryGroup );
  8632. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  8633. if ( geometry.__dirtyVertices || geometry.__dirtyColors || object.sortParticles || customAttributesDirty ) {
  8634. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  8635. }
  8636. geometry.__dirtyVertices = false;
  8637. geometry.__dirtyColors = false;
  8638. material.attributes && clearCustomAttributes( material );
  8639. }
  8640. };
  8641. // Objects updates - custom attributes check
  8642. function areCustomAttributesDirty ( material ) {
  8643. for ( var a in material.attributes ) {
  8644. if ( material.attributes[ a ].needsUpdate ) return true;
  8645. }
  8646. return false;
  8647. };
  8648. function clearCustomAttributes ( material ) {
  8649. for ( var a in material.attributes ) {
  8650. material.attributes[ a ].needsUpdate = false;
  8651. }
  8652. };
  8653. // Objects removal
  8654. function removeObject ( object, scene ) {
  8655. if ( object instanceof THREE.Mesh ||
  8656. object instanceof THREE.ParticleSystem ||
  8657. object instanceof THREE.Ribbon ||
  8658. object instanceof THREE.Line ) {
  8659. removeInstances( scene.__webglObjects, object );
  8660. } else if ( object instanceof THREE.Sprite ) {
  8661. removeInstancesDirect( scene.__webglSprites, object );
  8662. } else if ( object instanceof THREE.LensFlare ) {
  8663. removeInstancesDirect( scene.__webglFlares, object );
  8664. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  8665. removeInstances( scene.__webglObjectsImmediate, object );
  8666. }
  8667. object.__webglActive = false;
  8668. };
  8669. function removeInstances ( objlist, object ) {
  8670. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  8671. if ( objlist[ o ].object === object ) {
  8672. objlist.splice( o, 1 );
  8673. }
  8674. }
  8675. };
  8676. function removeInstancesDirect ( objlist, object ) {
  8677. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  8678. if ( objlist[ o ] === object ) {
  8679. objlist.splice( o, 1 );
  8680. }
  8681. }
  8682. };
  8683. // Materials
  8684. this.initMaterial = function ( material, lights, fog, object ) {
  8685. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  8686. if ( material instanceof THREE.MeshDepthMaterial ) {
  8687. shaderID = 'depth';
  8688. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8689. shaderID = 'normal';
  8690. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8691. shaderID = 'basic';
  8692. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  8693. shaderID = 'lambert';
  8694. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  8695. shaderID = 'phong';
  8696. } else if ( material instanceof THREE.LineBasicMaterial ) {
  8697. shaderID = 'basic';
  8698. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  8699. shaderID = 'particle_basic';
  8700. }
  8701. if ( shaderID ) {
  8702. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  8703. }
  8704. // heuristics to create shader parameters according to lights in the scene
  8705. // (not to blow over maxLights budget)
  8706. maxLightCount = allocateLights( lights );
  8707. maxShadows = allocateShadows( lights );
  8708. maxBones = allocateBones( object );
  8709. parameters = {
  8710. map: !!material.map, envMap: !!material.envMap, lightMap: !!material.lightMap,
  8711. vertexColors: material.vertexColors,
  8712. fog: fog, useFog: material.fog,
  8713. sizeAttenuation: material.sizeAttenuation,
  8714. skinning: material.skinning,
  8715. morphTargets: material.morphTargets,
  8716. morphNormals: material.morphNormals,
  8717. maxMorphTargets: this.maxMorphTargets,
  8718. maxMorphNormals: this.maxMorphNormals,
  8719. maxDirLights: maxLightCount.directional, maxPointLights: maxLightCount.point,
  8720. maxBones: maxBones,
  8721. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  8722. shadowMapSoft: this.shadowMapSoft,
  8723. shadowMapDebug: this.shadowMapDebug,
  8724. shadowMapCascade: this.shadowMapCascade,
  8725. maxShadows: maxShadows,
  8726. alphaTest: material.alphaTest,
  8727. metal: material.metal,
  8728. perPixel: material.perPixel,
  8729. wrapAround: material.wrapAround,
  8730. doubleSided: object && object.doubleSided
  8731. };
  8732. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, parameters );
  8733. var attributes = material.program.attributes;
  8734. if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
  8735. if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
  8736. if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
  8737. if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );
  8738. if ( material.skinning &&
  8739. attributes.skinVertexA >=0 && attributes.skinVertexB >= 0 &&
  8740. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  8741. _gl.enableVertexAttribArray( attributes.skinVertexA );
  8742. _gl.enableVertexAttribArray( attributes.skinVertexB );
  8743. _gl.enableVertexAttribArray( attributes.skinIndex );
  8744. _gl.enableVertexAttribArray( attributes.skinWeight );
  8745. }
  8746. if ( material.attributes ) {
  8747. for ( a in material.attributes ) {
  8748. if( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );
  8749. }
  8750. }
  8751. if ( material.morphTargets ) {
  8752. material.numSupportedMorphTargets = 0;
  8753. var id, base = "morphTarget";
  8754. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  8755. id = base + i;
  8756. if ( attributes[ id ] >= 0 ) {
  8757. _gl.enableVertexAttribArray( attributes[ id ] );
  8758. material.numSupportedMorphTargets ++;
  8759. }
  8760. }
  8761. }
  8762. if ( material.morphNormals ) {
  8763. material.numSupportedMorphNormals = 0;
  8764. var id, base = "morphNormal";
  8765. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  8766. id = base + i;
  8767. if ( attributes[ id ] >= 0 ) {
  8768. _gl.enableVertexAttribArray( attributes[ id ] );
  8769. material.numSupportedMorphNormals ++;
  8770. }
  8771. }
  8772. }
  8773. material.uniformsList = [];
  8774. for ( u in material.uniforms ) {
  8775. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  8776. }
  8777. };
  8778. function setMaterialShaders( material, shaders ) {
  8779. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  8780. material.vertexShader = shaders.vertexShader;
  8781. material.fragmentShader = shaders.fragmentShader;
  8782. };
  8783. function setProgram( camera, lights, fog, material, object ) {
  8784. if ( ! material.program || material.needsUpdate ) {
  8785. _this.initMaterial( material, lights, fog, object );
  8786. material.needsUpdate = false;
  8787. }
  8788. if ( material.morphTargets ) {
  8789. if ( ! object.__webglMorphTargetInfluences ) {
  8790. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  8791. for ( var i = 0, il = _this.maxMorphTargets; i < il; i ++ ) {
  8792. object.__webglMorphTargetInfluences[ i ] = 0;
  8793. }
  8794. }
  8795. }
  8796. var refreshMaterial = false;
  8797. var program = material.program,
  8798. p_uniforms = program.uniforms,
  8799. m_uniforms = material.uniforms;
  8800. if ( program !== _currentProgram ) {
  8801. _gl.useProgram( program );
  8802. _currentProgram = program;
  8803. refreshMaterial = true;
  8804. }
  8805. if ( material.id !== _currentMaterialId ) {
  8806. _currentMaterialId = material.id;
  8807. refreshMaterial = true;
  8808. }
  8809. if ( refreshMaterial || camera !== _currentCamera ) {
  8810. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  8811. if ( camera !== _currentCamera ) _currentCamera = camera;
  8812. }
  8813. if ( refreshMaterial ) {
  8814. // refresh uniforms common to several materials
  8815. if ( fog && material.fog ) {
  8816. refreshUniformsFog( m_uniforms, fog );
  8817. }
  8818. if ( material instanceof THREE.MeshPhongMaterial ||
  8819. material instanceof THREE.MeshLambertMaterial ||
  8820. material.lights ) {
  8821. setupLights( program, lights );
  8822. refreshUniformsLights( m_uniforms, _lights );
  8823. }
  8824. if ( material instanceof THREE.MeshBasicMaterial ||
  8825. material instanceof THREE.MeshLambertMaterial ||
  8826. material instanceof THREE.MeshPhongMaterial ) {
  8827. refreshUniformsCommon( m_uniforms, material );
  8828. }
  8829. // refresh single material specific uniforms
  8830. if ( material instanceof THREE.LineBasicMaterial ) {
  8831. refreshUniformsLine( m_uniforms, material );
  8832. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  8833. refreshUniformsParticle( m_uniforms, material );
  8834. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  8835. refreshUniformsPhong( m_uniforms, material );
  8836. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  8837. refreshUniformsLambert( m_uniforms, material );
  8838. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8839. m_uniforms.mNear.value = camera.near;
  8840. m_uniforms.mFar.value = camera.far;
  8841. m_uniforms.opacity.value = material.opacity;
  8842. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8843. m_uniforms.opacity.value = material.opacity;
  8844. }
  8845. if ( object.receiveShadow && ! material._shadowPass ) {
  8846. refreshUniformsShadow( m_uniforms, lights );
  8847. }
  8848. // load common uniforms
  8849. loadUniformsGeneric( program, material.uniformsList );
  8850. // load material specific uniforms
  8851. // (shader material also gets them for the sake of genericity)
  8852. if ( material instanceof THREE.ShaderMaterial ||
  8853. material instanceof THREE.MeshPhongMaterial ||
  8854. material.envMap ) {
  8855. if ( p_uniforms.cameraPosition !== null ) {
  8856. var position = camera.matrixWorld.getPosition();
  8857. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  8858. }
  8859. }
  8860. if ( material instanceof THREE.MeshPhongMaterial ||
  8861. material instanceof THREE.MeshLambertMaterial ||
  8862. material instanceof THREE.ShaderMaterial ||
  8863. material.skinning ) {
  8864. if ( p_uniforms.viewMatrix !== null ) {
  8865. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  8866. }
  8867. }
  8868. if ( material.skinning ) {
  8869. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  8870. }
  8871. }
  8872. loadUniformsMatrices( p_uniforms, object );
  8873. if ( material instanceof THREE.ShaderMaterial ||
  8874. material.envMap ||
  8875. material.skinning ||
  8876. object.receiveShadow ) {
  8877. if ( p_uniforms.objectMatrix !== null ) {
  8878. _gl.uniformMatrix4fv( p_uniforms.objectMatrix, false, object._objectMatrixArray );
  8879. }
  8880. }
  8881. return program;
  8882. };
  8883. // Uniforms (refresh uniforms objects)
  8884. function refreshUniformsCommon ( uniforms, material ) {
  8885. uniforms.opacity.value = material.opacity;
  8886. if ( _this.gammaInput ) {
  8887. uniforms.diffuse.value.copyGammaToLinear( material.color );
  8888. } else {
  8889. uniforms.diffuse.value = material.color;
  8890. }
  8891. uniforms.map.texture = material.map;
  8892. if ( material.map ) {
  8893. uniforms.offsetRepeat.value.set( material.map.offset.x, material.map.offset.y, material.map.repeat.x, material.map.repeat.y );
  8894. }
  8895. uniforms.lightMap.texture = material.lightMap;
  8896. uniforms.envMap.texture = material.envMap;
  8897. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  8898. if ( _this.gammaInput ) {
  8899. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  8900. uniforms.reflectivity.value = material.reflectivity;
  8901. } else {
  8902. uniforms.reflectivity.value = material.reflectivity;
  8903. }
  8904. uniforms.refractionRatio.value = material.refractionRatio;
  8905. uniforms.combine.value = material.combine;
  8906. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  8907. };
  8908. function refreshUniformsLine ( uniforms, material ) {
  8909. uniforms.diffuse.value = material.color;
  8910. uniforms.opacity.value = material.opacity;
  8911. };
  8912. function refreshUniformsParticle ( uniforms, material ) {
  8913. uniforms.psColor.value = material.color;
  8914. uniforms.opacity.value = material.opacity;
  8915. uniforms.size.value = material.size;
  8916. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  8917. uniforms.map.texture = material.map;
  8918. };
  8919. function refreshUniformsFog ( uniforms, fog ) {
  8920. uniforms.fogColor.value = fog.color;
  8921. if ( fog instanceof THREE.Fog ) {
  8922. uniforms.fogNear.value = fog.near;
  8923. uniforms.fogFar.value = fog.far;
  8924. } else if ( fog instanceof THREE.FogExp2 ) {
  8925. uniforms.fogDensity.value = fog.density;
  8926. }
  8927. };
  8928. function refreshUniformsPhong ( uniforms, material ) {
  8929. uniforms.shininess.value = material.shininess;
  8930. if ( _this.gammaInput ) {
  8931. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  8932. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  8933. uniforms.specular.value.copyGammaToLinear( material.specular );
  8934. } else {
  8935. uniforms.ambient.value = material.ambient;
  8936. uniforms.emissive.value = material.emissive;
  8937. uniforms.specular.value = material.specular;
  8938. }
  8939. if ( material.wrapAround ) {
  8940. uniforms.wrapRGB.value.copy( material.wrapRGB );
  8941. }
  8942. };
  8943. function refreshUniformsLambert ( uniforms, material ) {
  8944. if ( _this.gammaInput ) {
  8945. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  8946. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  8947. } else {
  8948. uniforms.ambient.value = material.ambient;
  8949. uniforms.emissive.value = material.emissive;
  8950. }
  8951. if ( material.wrapAround ) {
  8952. uniforms.wrapRGB.value.copy( material.wrapRGB );
  8953. }
  8954. };
  8955. function refreshUniformsLights ( uniforms, lights ) {
  8956. uniforms.ambientLightColor.value = lights.ambient;
  8957. uniforms.directionalLightColor.value = lights.directional.colors;
  8958. uniforms.directionalLightDirection.value = lights.directional.positions;
  8959. uniforms.pointLightColor.value = lights.point.colors;
  8960. uniforms.pointLightPosition.value = lights.point.positions;
  8961. uniforms.pointLightDistance.value = lights.point.distances;
  8962. };
  8963. function refreshUniformsShadow ( uniforms, lights ) {
  8964. if ( uniforms.shadowMatrix ) {
  8965. var j = 0;
  8966. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  8967. var light = lights[ i ];
  8968. if ( ! light.castShadow ) continue;
  8969. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  8970. uniforms.shadowMap.texture[ j ] = light.shadowMap;
  8971. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  8972. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  8973. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  8974. uniforms.shadowBias.value[ j ] = light.shadowBias;
  8975. j ++;
  8976. }
  8977. }
  8978. }
  8979. };
  8980. // Uniforms (load to GPU)
  8981. function loadUniformsMatrices ( uniforms, object ) {
  8982. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrixArray );
  8983. if ( uniforms.normalMatrix ) {
  8984. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrixArray );
  8985. }
  8986. };
  8987. function loadUniformsGeneric ( program, uniforms ) {
  8988. var uniform, value, type, location, texture, i, il, j, jl, offset;
  8989. for( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  8990. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  8991. if ( !location ) continue;
  8992. uniform = uniforms[ j ][ 0 ];
  8993. type = uniform.type;
  8994. value = uniform.value;
  8995. // single integer
  8996. if( type === "i" ) {
  8997. _gl.uniform1i( location, value );
  8998. // single float
  8999. } else if( type === "f" ) {
  9000. _gl.uniform1f( location, value );
  9001. // single THREE.Vector2
  9002. } else if( type === "v2" ) {
  9003. _gl.uniform2f( location, value.x, value.y );
  9004. // single THREE.Vector3
  9005. } else if( type === "v3" ) {
  9006. _gl.uniform3f( location, value.x, value.y, value.z );
  9007. // single THREE.Vector4
  9008. } else if( type === "v4" ) {
  9009. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  9010. // single THREE.Color
  9011. } else if( type === "c" ) {
  9012. _gl.uniform3f( location, value.r, value.g, value.b );
  9013. // flat array of floats (JS or typed array)
  9014. } else if( type === "fv1" ) {
  9015. _gl.uniform1fv( location, value );
  9016. // flat array of floats with 3 x N size (JS or typed array)
  9017. } else if( type === "fv" ) {
  9018. _gl.uniform3fv( location, value );
  9019. // array of THREE.Vector2
  9020. } else if( type === "v2v" ) {
  9021. if ( ! uniform._array ) {
  9022. uniform._array = new Float32Array( 2 * value.length );
  9023. }
  9024. for ( i = 0, il = value.length; i < il; i ++ ) {
  9025. offset = i * 2;
  9026. uniform._array[ offset ] = value[ i ].x;
  9027. uniform._array[ offset + 1 ] = value[ i ].y;
  9028. }
  9029. _gl.uniform2fv( location, uniform._array );
  9030. // array of THREE.Vector3
  9031. } else if( type === "v3v" ) {
  9032. if ( ! uniform._array ) {
  9033. uniform._array = new Float32Array( 3 * value.length );
  9034. }
  9035. for ( i = 0, il = value.length; i < il; i ++ ) {
  9036. offset = i * 3;
  9037. uniform._array[ offset ] = value[ i ].x;
  9038. uniform._array[ offset + 1 ] = value[ i ].y;
  9039. uniform._array[ offset + 2 ] = value[ i ].z;
  9040. }
  9041. _gl.uniform3fv( location, uniform._array );
  9042. // array of THREE.Vector4
  9043. } else if( type == "v4v" ) {
  9044. if ( ! uniform._array ) {
  9045. uniform._array = new Float32Array( 4 * value.length );
  9046. }
  9047. for ( i = 0, il = value.length; i < il; i ++ ) {
  9048. offset = i * 4;
  9049. uniform._array[ offset ] = value[ i ].x;
  9050. uniform._array[ offset + 1 ] = value[ i ].y;
  9051. uniform._array[ offset + 2 ] = value[ i ].z;
  9052. uniform._array[ offset + 3 ] = value[ i ].w;
  9053. }
  9054. _gl.uniform4fv( location, uniform._array );
  9055. // single THREE.Matrix4
  9056. } else if( type === "m4" ) {
  9057. if ( ! uniform._array ) {
  9058. uniform._array = new Float32Array( 16 );
  9059. }
  9060. value.flattenToArray( uniform._array );
  9061. _gl.uniformMatrix4fv( location, false, uniform._array );
  9062. // array of THREE.Matrix4
  9063. } else if( type === "m4v" ) {
  9064. if ( ! uniform._array ) {
  9065. uniform._array = new Float32Array( 16 * value.length );
  9066. }
  9067. for ( i = 0, il = value.length; i < il; i ++ ) {
  9068. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  9069. }
  9070. _gl.uniformMatrix4fv( location, false, uniform._array );
  9071. // single THREE.Texture (2d or cube)
  9072. } else if( type === "t" ) {
  9073. _gl.uniform1i( location, value );
  9074. texture = uniform.texture;
  9075. if ( !texture ) continue;
  9076. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  9077. setCubeTexture( texture, value );
  9078. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  9079. setCubeTextureDynamic( texture, value );
  9080. } else {
  9081. _this.setTexture( texture, value );
  9082. }
  9083. // array of THREE.Texture (2d)
  9084. } else if( type === "tv" ) {
  9085. if ( ! uniform._array ) {
  9086. uniform._array = [];
  9087. for( i = 0, il = uniform.texture.length; i < il; i ++ ) {
  9088. uniform._array[ i ] = value + i;
  9089. }
  9090. }
  9091. _gl.uniform1iv( location, uniform._array );
  9092. for( i = 0, il = uniform.texture.length; i < il; i ++ ) {
  9093. texture = uniform.texture[ i ];
  9094. if ( !texture ) continue;
  9095. _this.setTexture( texture, uniform._array[ i ] );
  9096. }
  9097. }
  9098. }
  9099. };
  9100. function setupMatrices ( object, camera ) {
  9101. object._modelViewMatrix.multiplyToArray( camera.matrixWorldInverse, object.matrixWorld, object._modelViewMatrixArray );
  9102. object._normalMatrix.getInverse( object._modelViewMatrix );
  9103. object._normalMatrix.transposeIntoArray( object._normalMatrixArray );
  9104. };
  9105. function setupLights ( program, lights ) {
  9106. var l, ll, light, n,
  9107. r = 0, g = 0, b = 0,
  9108. color, position, intensity, distance,
  9109. zlights = _lights,
  9110. dcolors = zlights.directional.colors,
  9111. dpositions = zlights.directional.positions,
  9112. pcolors = zlights.point.colors,
  9113. ppositions = zlights.point.positions,
  9114. pdistances = zlights.point.distances,
  9115. dlength = 0,
  9116. plength = 0,
  9117. doffset = 0,
  9118. poffset = 0;
  9119. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  9120. light = lights[ l ];
  9121. if ( light.onlyShadow ) continue;
  9122. color = light.color;
  9123. intensity = light.intensity;
  9124. distance = light.distance;
  9125. if ( light instanceof THREE.AmbientLight ) {
  9126. if ( _this.gammaInput ) {
  9127. r += color.r * color.r;
  9128. g += color.g * color.g;
  9129. b += color.b * color.b;
  9130. } else {
  9131. r += color.r;
  9132. g += color.g;
  9133. b += color.b;
  9134. }
  9135. } else if ( light instanceof THREE.DirectionalLight ) {
  9136. doffset = dlength * 3;
  9137. if ( _this.gammaInput ) {
  9138. dcolors[ doffset ] = color.r * color.r * intensity * intensity;
  9139. dcolors[ doffset + 1 ] = color.g * color.g * intensity * intensity;
  9140. dcolors[ doffset + 2 ] = color.b * color.b * intensity * intensity;
  9141. } else {
  9142. dcolors[ doffset ] = color.r * intensity;
  9143. dcolors[ doffset + 1 ] = color.g * intensity;
  9144. dcolors[ doffset + 2 ] = color.b * intensity;
  9145. }
  9146. _direction.copy( light.matrixWorld.getPosition() );
  9147. _direction.subSelf( light.target.matrixWorld.getPosition() );
  9148. _direction.normalize();
  9149. dpositions[ doffset ] = _direction.x;
  9150. dpositions[ doffset + 1 ] = _direction.y;
  9151. dpositions[ doffset + 2 ] = _direction.z;
  9152. dlength += 1;
  9153. } else if( light instanceof THREE.PointLight || light instanceof THREE.SpotLight ) {
  9154. poffset = plength * 3;
  9155. if ( _this.gammaInput ) {
  9156. pcolors[ poffset ] = color.r * color.r * intensity * intensity;
  9157. pcolors[ poffset + 1 ] = color.g * color.g * intensity * intensity;
  9158. pcolors[ poffset + 2 ] = color.b * color.b * intensity * intensity;
  9159. } else {
  9160. pcolors[ poffset ] = color.r * intensity;
  9161. pcolors[ poffset + 1 ] = color.g * intensity;
  9162. pcolors[ poffset + 2 ] = color.b * intensity;
  9163. }
  9164. position = light.matrixWorld.getPosition();
  9165. ppositions[ poffset ] = position.x;
  9166. ppositions[ poffset + 1 ] = position.y;
  9167. ppositions[ poffset + 2 ] = position.z;
  9168. pdistances[ plength ] = distance;
  9169. plength += 1;
  9170. }
  9171. }
  9172. // null eventual remains from removed lights
  9173. // (this is to avoid if in shader)
  9174. for ( l = dlength * 3, ll = dcolors.length; l < ll; l ++ ) dcolors[ l ] = 0.0;
  9175. for ( l = plength * 3, ll = pcolors.length; l < ll; l ++ ) pcolors[ l ] = 0.0;
  9176. zlights.point.length = plength;
  9177. zlights.directional.length = dlength;
  9178. zlights.ambient[ 0 ] = r;
  9179. zlights.ambient[ 1 ] = g;
  9180. zlights.ambient[ 2 ] = b;
  9181. };
  9182. // GL state setting
  9183. this.setFaceCulling = function ( cullFace, frontFace ) {
  9184. if ( cullFace ) {
  9185. if ( !frontFace || frontFace === "ccw" ) {
  9186. _gl.frontFace( _gl.CCW );
  9187. } else {
  9188. _gl.frontFace( _gl.CW );
  9189. }
  9190. if( cullFace === "back" ) {
  9191. _gl.cullFace( _gl.BACK );
  9192. } else if( cullFace === "front" ) {
  9193. _gl.cullFace( _gl.FRONT );
  9194. } else {
  9195. _gl.cullFace( _gl.FRONT_AND_BACK );
  9196. }
  9197. _gl.enable( _gl.CULL_FACE );
  9198. } else {
  9199. _gl.disable( _gl.CULL_FACE );
  9200. }
  9201. };
  9202. this.setObjectFaces = function ( object ) {
  9203. if ( _oldDoubleSided !== object.doubleSided ) {
  9204. if( object.doubleSided ) {
  9205. _gl.disable( _gl.CULL_FACE );
  9206. } else {
  9207. _gl.enable( _gl.CULL_FACE );
  9208. }
  9209. _oldDoubleSided = object.doubleSided;
  9210. }
  9211. if ( _oldFlipSided !== object.flipSided ) {
  9212. if( object.flipSided ) {
  9213. _gl.frontFace( _gl.CW );
  9214. } else {
  9215. _gl.frontFace( _gl.CCW );
  9216. }
  9217. _oldFlipSided = object.flipSided;
  9218. }
  9219. };
  9220. this.setDepthTest = function ( depthTest ) {
  9221. if ( _oldDepthTest !== depthTest ) {
  9222. if ( depthTest ) {
  9223. _gl.enable( _gl.DEPTH_TEST );
  9224. } else {
  9225. _gl.disable( _gl.DEPTH_TEST );
  9226. }
  9227. _oldDepthTest = depthTest;
  9228. }
  9229. };
  9230. this.setDepthWrite = function ( depthWrite ) {
  9231. if ( _oldDepthWrite !== depthWrite ) {
  9232. _gl.depthMask( depthWrite );
  9233. _oldDepthWrite = depthWrite;
  9234. }
  9235. };
  9236. function setLineWidth ( width ) {
  9237. if ( width !== _oldLineWidth ) {
  9238. _gl.lineWidth( width );
  9239. _oldLineWidth = width;
  9240. }
  9241. };
  9242. function setPolygonOffset ( polygonoffset, factor, units ) {
  9243. if ( _oldPolygonOffset !== polygonoffset ) {
  9244. if ( polygonoffset ) {
  9245. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  9246. } else {
  9247. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  9248. }
  9249. _oldPolygonOffset = polygonoffset;
  9250. }
  9251. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  9252. _gl.polygonOffset( factor, units );
  9253. _oldPolygonOffsetFactor = factor;
  9254. _oldPolygonOffsetUnits = units;
  9255. }
  9256. };
  9257. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  9258. if ( blending !== _oldBlending ) {
  9259. switch ( blending ) {
  9260. case THREE.NoBlending:
  9261. _gl.disable( _gl.BLEND );
  9262. break;
  9263. case THREE.AdditiveBlending:
  9264. _gl.enable( _gl.BLEND );
  9265. _gl.blendEquation( _gl.FUNC_ADD );
  9266. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  9267. break;
  9268. case THREE.SubtractiveBlending:
  9269. // TODO: Find blendFuncSeparate() combination
  9270. _gl.enable( _gl.BLEND );
  9271. _gl.blendEquation( _gl.FUNC_ADD );
  9272. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  9273. break;
  9274. case THREE.MultiplyBlending:
  9275. // TODO: Find blendFuncSeparate() combination
  9276. _gl.enable( _gl.BLEND );
  9277. _gl.blendEquation( _gl.FUNC_ADD );
  9278. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  9279. break;
  9280. case THREE.CustomBlending:
  9281. _gl.enable( _gl.BLEND );
  9282. break;
  9283. default:
  9284. _gl.enable( _gl.BLEND );
  9285. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  9286. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  9287. break;
  9288. }
  9289. _oldBlending = blending;
  9290. }
  9291. if ( blending === THREE.CustomBlending ) {
  9292. if ( blendEquation !== _oldBlendEquation ) {
  9293. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  9294. _oldBlendEquation = blendEquation;
  9295. }
  9296. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  9297. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  9298. _oldBlendSrc = blendSrc;
  9299. _oldBlendDst = blendDst;
  9300. }
  9301. } else {
  9302. _oldBlendEquation = null;
  9303. _oldBlendSrc = null;
  9304. _oldBlendDst = null;
  9305. }
  9306. };
  9307. // Shaders
  9308. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, parameters ) {
  9309. var p, pl, program, code;
  9310. var chunks = [];
  9311. // Generate code
  9312. if ( shaderID ) {
  9313. chunks.push( shaderID );
  9314. } else {
  9315. chunks.push( fragmentShader );
  9316. chunks.push( vertexShader );
  9317. }
  9318. for ( p in parameters ) {
  9319. chunks.push( p );
  9320. chunks.push( parameters[ p ] );
  9321. }
  9322. code = chunks.join();
  9323. // Check if code has been already compiled
  9324. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  9325. if ( _programs[ p ].code === code ) {
  9326. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  9327. return _programs[ p ].program;
  9328. }
  9329. }
  9330. //console.log( "building new program " );
  9331. //
  9332. program = _gl.createProgram();
  9333. var prefix_vertex = [
  9334. "precision " + _precision + " float;",
  9335. ( _maxVertexTextures > 0 ) ? "#define VERTEX_TEXTURES" : "",
  9336. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  9337. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  9338. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  9339. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  9340. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  9341. "#define MAX_SHADOWS " + parameters.maxShadows,
  9342. "#define MAX_BONES " + parameters.maxBones,
  9343. parameters.map ? "#define USE_MAP" : "",
  9344. parameters.envMap ? "#define USE_ENVMAP" : "",
  9345. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  9346. parameters.vertexColors ? "#define USE_COLOR" : "",
  9347. parameters.skinning ? "#define USE_SKINNING" : "",
  9348. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  9349. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  9350. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  9351. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  9352. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  9353. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  9354. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  9355. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  9356. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  9357. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  9358. "uniform mat4 objectMatrix;",
  9359. "uniform mat4 modelViewMatrix;",
  9360. "uniform mat4 projectionMatrix;",
  9361. "uniform mat4 viewMatrix;",
  9362. "uniform mat3 normalMatrix;",
  9363. "uniform vec3 cameraPosition;",
  9364. "attribute vec3 position;",
  9365. "attribute vec3 normal;",
  9366. "attribute vec2 uv;",
  9367. "attribute vec2 uv2;",
  9368. "#ifdef USE_COLOR",
  9369. "attribute vec3 color;",
  9370. "#endif",
  9371. "#ifdef USE_MORPHTARGETS",
  9372. "attribute vec3 morphTarget0;",
  9373. "attribute vec3 morphTarget1;",
  9374. "attribute vec3 morphTarget2;",
  9375. "attribute vec3 morphTarget3;",
  9376. "#ifdef USE_MORPHNORMALS",
  9377. "attribute vec3 morphNormal0;",
  9378. "attribute vec3 morphNormal1;",
  9379. "attribute vec3 morphNormal2;",
  9380. "attribute vec3 morphNormal3;",
  9381. "#else",
  9382. "attribute vec3 morphTarget4;",
  9383. "attribute vec3 morphTarget5;",
  9384. "attribute vec3 morphTarget6;",
  9385. "attribute vec3 morphTarget7;",
  9386. "#endif",
  9387. "#endif",
  9388. "#ifdef USE_SKINNING",
  9389. "attribute vec4 skinVertexA;",
  9390. "attribute vec4 skinVertexB;",
  9391. "attribute vec4 skinIndex;",
  9392. "attribute vec4 skinWeight;",
  9393. "#endif",
  9394. ""
  9395. ].join("\n");
  9396. var prefix_fragment = [
  9397. "precision " + _precision + " float;",
  9398. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  9399. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  9400. "#define MAX_SHADOWS " + parameters.maxShadows,
  9401. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  9402. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  9403. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  9404. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  9405. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  9406. ( parameters.useFog && parameters.fog instanceof THREE.FogExp2 ) ? "#define FOG_EXP2" : "",
  9407. parameters.map ? "#define USE_MAP" : "",
  9408. parameters.envMap ? "#define USE_ENVMAP" : "",
  9409. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  9410. parameters.vertexColors ? "#define USE_COLOR" : "",
  9411. parameters.metal ? "#define METAL" : "",
  9412. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  9413. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  9414. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  9415. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  9416. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  9417. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  9418. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  9419. "uniform mat4 viewMatrix;",
  9420. "uniform vec3 cameraPosition;",
  9421. ""
  9422. ].join("\n");
  9423. _gl.attachShader( program, getShader( "fragment", prefix_fragment + fragmentShader ) );
  9424. _gl.attachShader( program, getShader( "vertex", prefix_vertex + vertexShader ) );
  9425. _gl.linkProgram( program );
  9426. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  9427. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  9428. }
  9429. //console.log( prefix_fragment + fragmentShader );
  9430. //console.log( prefix_vertex + vertexShader );
  9431. program.uniforms = {};
  9432. program.attributes = {};
  9433. var identifiers, u, a, i;
  9434. // cache uniform locations
  9435. identifiers = [
  9436. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'objectMatrix', 'cameraPosition',
  9437. 'boneGlobalMatrices', 'morphTargetInfluences'
  9438. ];
  9439. for ( u in uniforms ) {
  9440. identifiers.push( u );
  9441. }
  9442. cacheUniformLocations( program, identifiers );
  9443. // cache attributes locations
  9444. identifiers = [
  9445. "position", "normal", "uv", "uv2", "tangent", "color",
  9446. "skinVertexA", "skinVertexB", "skinIndex", "skinWeight"
  9447. ];
  9448. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  9449. identifiers.push( "morphTarget" + i );
  9450. }
  9451. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  9452. identifiers.push( "morphNormal" + i );
  9453. }
  9454. for ( a in attributes ) {
  9455. identifiers.push( a );
  9456. }
  9457. cacheAttributeLocations( program, identifiers );
  9458. program.id = _programs.length;
  9459. _programs.push( { program: program, code: code } );
  9460. _this.info.memory.programs = _programs.length;
  9461. return program;
  9462. };
  9463. // Shader parameters cache
  9464. function cacheUniformLocations ( program, identifiers ) {
  9465. var i, l, id;
  9466. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  9467. id = identifiers[ i ];
  9468. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  9469. }
  9470. };
  9471. function cacheAttributeLocations ( program, identifiers ) {
  9472. var i, l, id;
  9473. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  9474. id = identifiers[ i ];
  9475. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  9476. }
  9477. };
  9478. function getShader ( type, string ) {
  9479. var shader;
  9480. if ( type === "fragment" ) {
  9481. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  9482. } else if ( type === "vertex" ) {
  9483. shader = _gl.createShader( _gl.VERTEX_SHADER );
  9484. }
  9485. _gl.shaderSource( shader, string );
  9486. _gl.compileShader( shader );
  9487. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  9488. console.error( _gl.getShaderInfoLog( shader ) );
  9489. console.error( string );
  9490. return null;
  9491. }
  9492. return shader;
  9493. };
  9494. // Textures
  9495. function isPowerOfTwo ( value ) {
  9496. return ( value & ( value - 1 ) ) === 0;
  9497. };
  9498. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  9499. if ( isImagePowerOfTwo ) {
  9500. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  9501. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  9502. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  9503. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  9504. } else {
  9505. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  9506. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  9507. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  9508. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  9509. }
  9510. };
  9511. this.setTexture = function ( texture, slot ) {
  9512. if ( texture.needsUpdate ) {
  9513. if ( ! texture.__webglInit ) {
  9514. texture.__webglInit = true;
  9515. texture.__webglTexture = _gl.createTexture();
  9516. _this.info.memory.textures ++;
  9517. }
  9518. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9519. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  9520. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  9521. var image = texture.image,
  9522. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  9523. glFormat = paramThreeToGL( texture.format ),
  9524. glType = paramThreeToGL( texture.type );
  9525. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  9526. if ( texture instanceof THREE.DataTexture ) {
  9527. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  9528. } else {
  9529. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  9530. }
  9531. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  9532. texture.needsUpdate = false;
  9533. if ( texture.onUpdate ) texture.onUpdate();
  9534. } else {
  9535. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9536. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  9537. }
  9538. };
  9539. function clampToMaxSize ( image, maxSize ) {
  9540. if ( image.width <= maxSize && image.height <= maxSize ) {
  9541. return image;
  9542. }
  9543. // Warning: Scaling through the canvas will only work with images that use
  9544. // premultiplied alpha.
  9545. var maxDimension = Math.max( image.width, image.height );
  9546. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  9547. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  9548. var canvas = document.createElement( 'canvas' );
  9549. canvas.width = newWidth;
  9550. canvas.height = newHeight;
  9551. var ctx = canvas.getContext( "2d" );
  9552. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  9553. return canvas;
  9554. }
  9555. function setCubeTexture ( texture, slot ) {
  9556. if ( texture.image.length === 6 ) {
  9557. if ( texture.needsUpdate ) {
  9558. if ( ! texture.image.__webglTextureCube ) {
  9559. texture.image.__webglTextureCube = _gl.createTexture();
  9560. }
  9561. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9562. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  9563. var cubeImage = [];
  9564. for ( var i = 0; i < 6; i ++ ) {
  9565. if ( _this.autoScaleCubemaps ) {
  9566. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  9567. } else {
  9568. cubeImage[ i ] = texture.image[ i ];
  9569. }
  9570. }
  9571. var image = cubeImage[ 0 ],
  9572. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  9573. glFormat = paramThreeToGL( texture.format ),
  9574. glType = paramThreeToGL( texture.type );
  9575. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  9576. for ( var i = 0; i < 6; i ++ ) {
  9577. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  9578. }
  9579. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  9580. texture.needsUpdate = false;
  9581. if ( texture.onUpdate ) texture.onUpdate();
  9582. } else {
  9583. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9584. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  9585. }
  9586. }
  9587. };
  9588. function setCubeTextureDynamic ( texture, slot ) {
  9589. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9590. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  9591. };
  9592. // Render targets
  9593. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  9594. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  9595. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  9596. };
  9597. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  9598. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  9599. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  9600. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  9601. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  9602. /* For some reason this is not working. Defaulting to RGBA4.
  9603. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  9604. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  9605. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  9606. */
  9607. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  9608. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  9609. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  9610. } else {
  9611. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  9612. }
  9613. };
  9614. this.setRenderTarget = function ( renderTarget ) {
  9615. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  9616. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  9617. if( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  9618. if( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  9619. renderTarget.__webglTexture = _gl.createTexture();
  9620. // Setup texture, create render and frame buffers
  9621. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  9622. glFormat = paramThreeToGL( renderTarget.format ),
  9623. glType = paramThreeToGL( renderTarget.type );
  9624. if ( isCube ) {
  9625. renderTarget.__webglFramebuffer = [];
  9626. renderTarget.__webglRenderbuffer = [];
  9627. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  9628. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  9629. for ( var i = 0; i < 6; i ++ ) {
  9630. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  9631. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  9632. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  9633. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  9634. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  9635. }
  9636. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  9637. } else {
  9638. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  9639. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  9640. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  9641. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  9642. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  9643. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  9644. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  9645. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  9646. }
  9647. // Release everything
  9648. if ( isCube ) {
  9649. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  9650. } else {
  9651. _gl.bindTexture( _gl.TEXTURE_2D, null );
  9652. }
  9653. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  9654. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  9655. }
  9656. var framebuffer, width, height, vx, vy;
  9657. if ( renderTarget ) {
  9658. if ( isCube ) {
  9659. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  9660. } else {
  9661. framebuffer = renderTarget.__webglFramebuffer;
  9662. }
  9663. width = renderTarget.width;
  9664. height = renderTarget.height;
  9665. vx = 0;
  9666. vy = 0;
  9667. } else {
  9668. framebuffer = null;
  9669. width = _viewportWidth;
  9670. height = _viewportHeight;
  9671. vx = _viewportX;
  9672. vy = _viewportY;
  9673. }
  9674. if ( framebuffer !== _currentFramebuffer ) {
  9675. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  9676. _gl.viewport( vx, vy, width, height );
  9677. _currentFramebuffer = framebuffer;
  9678. }
  9679. _currentWidth = width;
  9680. _currentHeight = height;
  9681. };
  9682. function updateRenderTargetMipmap ( renderTarget ) {
  9683. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9684. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  9685. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  9686. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  9687. } else {
  9688. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  9689. _gl.generateMipmap( _gl.TEXTURE_2D );
  9690. _gl.bindTexture( _gl.TEXTURE_2D, null );
  9691. }
  9692. };
  9693. // Fallback filters for non-power-of-2 textures
  9694. function filterFallback ( f ) {
  9695. switch ( f ) {
  9696. case THREE.NearestFilter:
  9697. case THREE.NearestMipMapNearestFilter:
  9698. case THREE.NearestMipMapLinearFilter: return _gl.NEAREST; break;
  9699. case THREE.LinearFilter:
  9700. case THREE.LinearMipMapNearestFilter:
  9701. case THREE.LinearMipMapLinearFilter:
  9702. default:
  9703. return _gl.LINEAR; break;
  9704. }
  9705. };
  9706. // Map three.js constants to WebGL constants
  9707. function paramThreeToGL ( p ) {
  9708. switch ( p ) {
  9709. case THREE.RepeatWrapping: return _gl.REPEAT; break;
  9710. case THREE.ClampToEdgeWrapping: return _gl.CLAMP_TO_EDGE; break;
  9711. case THREE.MirroredRepeatWrapping: return _gl.MIRRORED_REPEAT; break;
  9712. case THREE.NearestFilter: return _gl.NEAREST; break;
  9713. case THREE.NearestMipMapNearestFilter: return _gl.NEAREST_MIPMAP_NEAREST; break;
  9714. case THREE.NearestMipMapLinearFilter: return _gl.NEAREST_MIPMAP_LINEAR; break;
  9715. case THREE.LinearFilter: return _gl.LINEAR; break;
  9716. case THREE.LinearMipMapNearestFilter: return _gl.LINEAR_MIPMAP_NEAREST; break;
  9717. case THREE.LinearMipMapLinearFilter: return _gl.LINEAR_MIPMAP_LINEAR; break;
  9718. case THREE.ByteType: return _gl.BYTE; break;
  9719. case THREE.UnsignedByteType: return _gl.UNSIGNED_BYTE; break;
  9720. case THREE.ShortType: return _gl.SHORT; break;
  9721. case THREE.UnsignedShortType: return _gl.UNSIGNED_SHORT; break;
  9722. case THREE.IntType: return _gl.INT; break;
  9723. case THREE.UnsignedIntType: return _gl.UNSIGNED_INT; break;
  9724. case THREE.FloatType: return _gl.FLOAT; break;
  9725. case THREE.AlphaFormat: return _gl.ALPHA; break;
  9726. case THREE.RGBFormat: return _gl.RGB; break;
  9727. case THREE.RGBAFormat: return _gl.RGBA; break;
  9728. case THREE.LuminanceFormat: return _gl.LUMINANCE; break;
  9729. case THREE.LuminanceAlphaFormat: return _gl.LUMINANCE_ALPHA; break;
  9730. case THREE.AddEquation: return _gl.FUNC_ADD; break;
  9731. case THREE.SubtractEquation: return _gl.FUNC_SUBTRACT; break;
  9732. case THREE.ReverseSubtractEquation: return _gl.FUNC_REVERSE_SUBTRACT; break;
  9733. case THREE.ZeroFactor: return _gl.ZERO; break;
  9734. case THREE.OneFactor: return _gl.ONE; break;
  9735. case THREE.SrcColorFactor: return _gl.SRC_COLOR; break;
  9736. case THREE.OneMinusSrcColorFactor: return _gl.ONE_MINUS_SRC_COLOR; break;
  9737. case THREE.SrcAlphaFactor: return _gl.SRC_ALPHA; break;
  9738. case THREE.OneMinusSrcAlphaFactor: return _gl.ONE_MINUS_SRC_ALPHA; break;
  9739. case THREE.DstAlphaFactor: return _gl.DST_ALPHA; break;
  9740. case THREE.OneMinusDstAlphaFactor: return _gl.ONE_MINUS_DST_ALPHA; break;
  9741. case THREE.DstColorFactor: return _gl.DST_COLOR; break;
  9742. case THREE.OneMinusDstColorFactor: return _gl.ONE_MINUS_DST_COLOR; break;
  9743. case THREE.SrcAlphaSaturateFactor: return _gl.SRC_ALPHA_SATURATE; break;
  9744. }
  9745. return 0;
  9746. };
  9747. // Allocations
  9748. function allocateBones ( object ) {
  9749. // default for when object is not specified
  9750. // ( for example when prebuilding shader
  9751. // to be used with multiple objects )
  9752. //
  9753. // - leave some extra space for other uniforms
  9754. // - limit here is ANGLE's 254 max uniform vectors
  9755. // (up to 54 should be safe)
  9756. var maxBones = 50;
  9757. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  9758. maxBones = object.bones.length;
  9759. }
  9760. return maxBones;
  9761. };
  9762. function allocateLights ( lights ) {
  9763. var l, ll, light, dirLights, pointLights, maxDirLights, maxPointLights;
  9764. dirLights = pointLights = maxDirLights = maxPointLights = 0;
  9765. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  9766. light = lights[ l ];
  9767. if ( light.onlyShadow ) continue;
  9768. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  9769. if ( light instanceof THREE.PointLight ) pointLights ++;
  9770. if ( light instanceof THREE.SpotLight ) pointLights ++;
  9771. }
  9772. if ( ( pointLights + dirLights ) <= _maxLights ) {
  9773. maxDirLights = dirLights;
  9774. maxPointLights = pointLights;
  9775. } else {
  9776. maxDirLights = Math.ceil( _maxLights * dirLights / ( pointLights + dirLights ) );
  9777. maxPointLights = _maxLights - maxDirLights;
  9778. }
  9779. return { 'directional' : maxDirLights, 'point' : maxPointLights };
  9780. };
  9781. function allocateShadows ( lights ) {
  9782. var l, ll, light, maxShadows = 0;
  9783. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  9784. light = lights[ l ];
  9785. if ( ! light.castShadow ) continue;
  9786. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  9787. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  9788. }
  9789. return maxShadows;
  9790. };
  9791. // Initialization
  9792. function initGL () {
  9793. var gl;
  9794. try {
  9795. if ( ! ( gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  9796. throw 'Error creating WebGL context.';
  9797. }
  9798. console.log(
  9799. navigator.userAgent + " | " +
  9800. gl.getParameter( gl.VERSION ) + " | " +
  9801. gl.getParameter( gl.VENDOR ) + " | " +
  9802. gl.getParameter( gl.RENDERER ) + " | " +
  9803. gl.getParameter( gl.SHADING_LANGUAGE_VERSION )
  9804. );
  9805. } catch ( error ) {
  9806. console.error( error );
  9807. }
  9808. return gl;
  9809. };
  9810. function setDefaultGLState () {
  9811. _gl.clearColor( 0, 0, 0, 1 );
  9812. _gl.clearDepth( 1 );
  9813. _gl.clearStencil( 0 );
  9814. _gl.enable( _gl.DEPTH_TEST );
  9815. _gl.depthFunc( _gl.LEQUAL );
  9816. _gl.frontFace( _gl.CCW );
  9817. _gl.cullFace( _gl.BACK );
  9818. _gl.enable( _gl.CULL_FACE );
  9819. _gl.enable( _gl.BLEND );
  9820. _gl.blendEquation( _gl.FUNC_ADD );
  9821. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  9822. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9823. };
  9824. // default plugins (order is important)
  9825. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  9826. this.addPrePlugin( this.shadowMapPlugin );
  9827. this.addPostPlugin( new THREE.SpritePlugin() );
  9828. this.addPostPlugin( new THREE.LensFlarePlugin() );
  9829. };
  9830. /**
  9831. * @author szimek / https://github.com/szimek/
  9832. */
  9833. THREE.WebGLRenderTarget = function ( width, height, options ) {
  9834. this.width = width;
  9835. this.height = height;
  9836. options = options || {};
  9837. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  9838. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  9839. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  9840. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  9841. this.offset = new THREE.Vector2( 0, 0 );
  9842. this.repeat = new THREE.Vector2( 1, 1 );
  9843. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  9844. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  9845. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  9846. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  9847. this.generateMipmaps = true;
  9848. };
  9849. THREE.WebGLRenderTarget.prototype.clone = function() {
  9850. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  9851. tmp.wrapS = this.wrapS;
  9852. tmp.wrapT = this.wrapT;
  9853. tmp.magFilter = this.magFilter;
  9854. tmp.minFilter = this.minFilter;
  9855. tmp.offset.copy( this.offset );
  9856. tmp.repeat.copy( this.repeat );
  9857. tmp.format = this.format;
  9858. tmp.type = this.type;
  9859. tmp.depthBuffer = this.depthBuffer;
  9860. tmp.stencilBuffer = this.stencilBuffer;
  9861. return tmp;
  9862. };
  9863. /**
  9864. * @author alteredq / http://alteredqualia.com
  9865. */
  9866. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  9867. THREE.WebGLRenderTarget.call( this, width, height, options );
  9868. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  9869. };
  9870. THREE.WebGLRenderTargetCube.prototype = new THREE.WebGLRenderTarget();
  9871. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  9872. /**
  9873. * @author mr.doob / http://mrdoob.com/
  9874. */
  9875. THREE.RenderableVertex = function () {
  9876. this.positionWorld = new THREE.Vector3();
  9877. this.positionScreen = new THREE.Vector4();
  9878. this.visible = true;
  9879. };
  9880. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  9881. this.positionWorld.copy( vertex.positionWorld );
  9882. this.positionScreen.copy( vertex.positionScreen );
  9883. }
  9884. /**
  9885. * @author mr.doob / http://mrdoob.com/
  9886. */
  9887. THREE.RenderableFace3 = function () {
  9888. this.v1 = new THREE.RenderableVertex();
  9889. this.v2 = new THREE.RenderableVertex();
  9890. this.v3 = new THREE.RenderableVertex();
  9891. this.centroidWorld = new THREE.Vector3();
  9892. this.centroidScreen = new THREE.Vector3();
  9893. this.normalWorld = new THREE.Vector3();
  9894. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  9895. this.material = null;
  9896. this.faceMaterial = null;
  9897. this.uvs = [[]];
  9898. this.z = null;
  9899. };
  9900. /**
  9901. * @author mr.doob / http://mrdoob.com/
  9902. */
  9903. THREE.RenderableFace4 = function () {
  9904. this.v1 = new THREE.RenderableVertex();
  9905. this.v2 = new THREE.RenderableVertex();
  9906. this.v3 = new THREE.RenderableVertex();
  9907. this.v4 = new THREE.RenderableVertex();
  9908. this.centroidWorld = new THREE.Vector3();
  9909. this.centroidScreen = new THREE.Vector3();
  9910. this.normalWorld = new THREE.Vector3();
  9911. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  9912. this.material = null;
  9913. this.faceMaterial = null;
  9914. this.uvs = [[]];
  9915. this.z = null;
  9916. };
  9917. /**
  9918. * @author mr.doob / http://mrdoob.com/
  9919. */
  9920. THREE.RenderableObject = function () {
  9921. this.object = null;
  9922. this.z = null;
  9923. };
  9924. /**
  9925. * @author mr.doob / http://mrdoob.com/
  9926. */
  9927. THREE.RenderableParticle = function () {
  9928. this.x = null;
  9929. this.y = null;
  9930. this.z = null;
  9931. this.rotation = null;
  9932. this.scale = new THREE.Vector2();
  9933. this.material = null;
  9934. };
  9935. /**
  9936. * @author mr.doob / http://mrdoob.com/
  9937. */
  9938. THREE.RenderableLine = function () {
  9939. this.z = null;
  9940. this.v1 = new THREE.RenderableVertex();
  9941. this.v2 = new THREE.RenderableVertex();
  9942. this.material = null;
  9943. };
  9944. /**
  9945. * @author alteredq / http://alteredqualia.com/
  9946. */
  9947. THREE.ColorUtils = {
  9948. adjustHSV : function ( color, h, s, v ) {
  9949. var hsv = THREE.ColorUtils.__hsv;
  9950. THREE.ColorUtils.rgbToHsv( color, hsv );
  9951. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  9952. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  9953. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  9954. color.setHSV( hsv.h, hsv.s, hsv.v );
  9955. },
  9956. // based on MochiKit implementation by Bob Ippolito
  9957. rgbToHsv : function ( color, hsv ) {
  9958. var r = color.r;
  9959. var g = color.g;
  9960. var b = color.b;
  9961. var max = Math.max( Math.max( r, g ), b );
  9962. var min = Math.min( Math.min( r, g ), b );
  9963. var hue;
  9964. var saturation;
  9965. var value = max;
  9966. if ( min === max ) {
  9967. hue = 0;
  9968. saturation = 0;
  9969. } else {
  9970. var delta = ( max - min );
  9971. saturation = delta / max;
  9972. if ( r === max ) {
  9973. hue = ( g - b ) / delta;
  9974. } else if ( g === max ) {
  9975. hue = 2 + ( ( b - r ) / delta );
  9976. } else {
  9977. hue = 4 + ( ( r - g ) / delta );
  9978. }
  9979. hue /= 6;
  9980. if ( hue < 0 ) {
  9981. hue += 1;
  9982. }
  9983. if ( hue > 1 ) {
  9984. hue -= 1;
  9985. }
  9986. }
  9987. if ( hsv === undefined ) {
  9988. hsv = { h: 0, s: 0, v: 0 };
  9989. }
  9990. hsv.h = hue;
  9991. hsv.s = saturation;
  9992. hsv.v = value;
  9993. return hsv;
  9994. }
  9995. };
  9996. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  9997. * @author mrdoob / http://mrdoob.com/
  9998. * @author alteredq / http://alteredqualia.com/
  9999. */
  10000. THREE.GeometryUtils = {
  10001. // Merge two geometries or geometry and geometry from object (using object's transform)
  10002. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  10003. var matrix, matrixRotation,
  10004. vertexOffset = geometry1.vertices.length,
  10005. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  10006. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  10007. vertices1 = geometry1.vertices,
  10008. vertices2 = geometry2.vertices,
  10009. faces1 = geometry1.faces,
  10010. faces2 = geometry2.faces,
  10011. uvs1 = geometry1.faceVertexUvs[ 0 ],
  10012. uvs2 = geometry2.faceVertexUvs[ 0 ];
  10013. var geo1MaterialsMap = {};
  10014. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  10015. var id = geometry1.materials[ i ].id;
  10016. geo1MaterialsMap[ id ] = i;
  10017. }
  10018. if ( object2 instanceof THREE.Mesh ) {
  10019. object2.matrixAutoUpdate && object2.updateMatrix();
  10020. matrix = object2.matrix;
  10021. matrixRotation = new THREE.Matrix4();
  10022. matrixRotation.extractRotation( matrix, object2.scale );
  10023. }
  10024. // vertices
  10025. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  10026. var vertex = vertices2[ i ];
  10027. var vertexCopy = vertex.clone();
  10028. if ( matrix ) matrix.multiplyVector3( vertexCopy.position );
  10029. vertices1.push( vertexCopy );
  10030. }
  10031. // faces
  10032. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  10033. var face = faces2[ i ], faceCopy, normal, color,
  10034. faceVertexNormals = face.vertexNormals,
  10035. faceVertexColors = face.vertexColors;
  10036. if ( face instanceof THREE.Face3 ) {
  10037. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  10038. } else if ( face instanceof THREE.Face4 ) {
  10039. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  10040. }
  10041. faceCopy.normal.copy( face.normal );
  10042. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  10043. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  10044. normal = faceVertexNormals[ j ].clone();
  10045. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  10046. faceCopy.vertexNormals.push( normal );
  10047. }
  10048. faceCopy.color.copy( face.color );
  10049. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  10050. color = faceVertexColors[ j ];
  10051. faceCopy.vertexColors.push( color.clone() );
  10052. }
  10053. if ( face.materialIndex !== undefined ) {
  10054. var material2 = geometry2.materials[ face.materialIndex ];
  10055. var materialId2 = material2.id;
  10056. var materialIndex = geo1MaterialsMap[ materialId2 ];
  10057. if ( materialIndex === undefined ) {
  10058. materialIndex = geometry1.materials.length;
  10059. geo1MaterialsMap[ materialId2 ] = materialIndex;
  10060. geometry1.materials.push( material2 );
  10061. }
  10062. faceCopy.materialIndex = materialIndex;
  10063. }
  10064. faceCopy.centroid.copy( face.centroid );
  10065. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  10066. faces1.push( faceCopy );
  10067. }
  10068. // uvs
  10069. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  10070. var uv = uvs2[ i ], uvCopy = [];
  10071. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  10072. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  10073. }
  10074. uvs1.push( uvCopy );
  10075. }
  10076. },
  10077. clone: function ( geometry ) {
  10078. var cloneGeo = new THREE.Geometry();
  10079. var i, il;
  10080. var vertices = geometry.vertices,
  10081. faces = geometry.faces,
  10082. uvs = geometry.faceVertexUvs[ 0 ];
  10083. // materials
  10084. if ( geometry.materials ) {
  10085. cloneGeo.materials = geometry.materials.slice();
  10086. }
  10087. // vertices
  10088. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  10089. var vertex = vertices[ i ];
  10090. cloneGeo.vertices.push( vertex.clone() );
  10091. }
  10092. // faces
  10093. for ( i = 0, il = faces.length; i < il; i ++ ) {
  10094. var face = faces[ i ];
  10095. cloneGeo.faces.push( face.clone() );
  10096. }
  10097. // uvs
  10098. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  10099. var uv = uvs[ i ], uvCopy = [];
  10100. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  10101. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  10102. }
  10103. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  10104. }
  10105. return cloneGeo;
  10106. },
  10107. // Get random point in triangle (via barycentric coordinates)
  10108. // (uniform distribution)
  10109. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  10110. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  10111. var a, b, c,
  10112. point = new THREE.Vector3(),
  10113. tmp = THREE.GeometryUtils.__v1;
  10114. a = THREE.GeometryUtils.random();
  10115. b = THREE.GeometryUtils.random();
  10116. if ( ( a + b ) > 1 ) {
  10117. a = 1 - a;
  10118. b = 1 - b;
  10119. }
  10120. c = 1 - a - b;
  10121. point.copy( vectorA );
  10122. point.multiplyScalar( a );
  10123. tmp.copy( vectorB );
  10124. tmp.multiplyScalar( b );
  10125. point.addSelf( tmp );
  10126. tmp.copy( vectorC );
  10127. tmp.multiplyScalar( c );
  10128. point.addSelf( tmp );
  10129. return point;
  10130. },
  10131. // Get random point in face (triangle / quad)
  10132. // (uniform distribution)
  10133. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  10134. var vA, vB, vC, vD;
  10135. if ( face instanceof THREE.Face3 ) {
  10136. vA = geometry.vertices[ face.a ].position;
  10137. vB = geometry.vertices[ face.b ].position;
  10138. vC = geometry.vertices[ face.c ].position;
  10139. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  10140. } else if ( face instanceof THREE.Face4 ) {
  10141. vA = geometry.vertices[ face.a ].position;
  10142. vB = geometry.vertices[ face.b ].position;
  10143. vC = geometry.vertices[ face.c ].position;
  10144. vD = geometry.vertices[ face.d ].position;
  10145. var area1, area2;
  10146. if ( useCachedAreas ) {
  10147. if ( face._area1 && face._area2 ) {
  10148. area1 = face._area1;
  10149. area2 = face._area2;
  10150. } else {
  10151. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  10152. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  10153. face._area1 = area1;
  10154. face._area2 = area2;
  10155. }
  10156. } else {
  10157. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  10158. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  10159. }
  10160. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  10161. if ( r < area1 ) {
  10162. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  10163. } else {
  10164. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  10165. }
  10166. }
  10167. },
  10168. // Get uniformly distributed random points in mesh
  10169. // - create array with cumulative sums of face areas
  10170. // - pick random number from 0 to total area
  10171. // - find corresponding place in area array by binary search
  10172. // - get random point in face
  10173. randomPointsInGeometry: function ( geometry, n ) {
  10174. var face, i,
  10175. faces = geometry.faces,
  10176. vertices = geometry.vertices,
  10177. il = faces.length,
  10178. totalArea = 0,
  10179. cumulativeAreas = [],
  10180. vA, vB, vC, vD;
  10181. // precompute face areas
  10182. for ( i = 0; i < il; i ++ ) {
  10183. face = faces[ i ];
  10184. if ( face instanceof THREE.Face3 ) {
  10185. vA = vertices[ face.a ].position;
  10186. vB = vertices[ face.b ].position;
  10187. vC = vertices[ face.c ].position;
  10188. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  10189. } else if ( face instanceof THREE.Face4 ) {
  10190. vA = vertices[ face.a ].position;
  10191. vB = vertices[ face.b ].position;
  10192. vC = vertices[ face.c ].position;
  10193. vD = vertices[ face.d ].position;
  10194. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  10195. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  10196. face._area = face._area1 + face._area2;
  10197. }
  10198. totalArea += face._area;
  10199. cumulativeAreas[ i ] = totalArea;
  10200. }
  10201. // binary search cumulative areas array
  10202. function binarySearchIndices( value ) {
  10203. function binarySearch( start, end ) {
  10204. // return closest larger index
  10205. // if exact number is not found
  10206. if ( end < start )
  10207. return start;
  10208. var mid = start + Math.floor( ( end - start ) / 2 );
  10209. if ( cumulativeAreas[ mid ] > value ) {
  10210. return binarySearch( start, mid - 1 );
  10211. } else if ( cumulativeAreas[ mid ] < value ) {
  10212. return binarySearch( mid + 1, end );
  10213. } else {
  10214. return mid;
  10215. }
  10216. }
  10217. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  10218. return result;
  10219. }
  10220. // pick random face weighted by face area
  10221. var r, index,
  10222. result = [];
  10223. var stats = {};
  10224. for ( i = 0; i < n; i ++ ) {
  10225. r = THREE.GeometryUtils.random() * totalArea;
  10226. index = binarySearchIndices( r );
  10227. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  10228. if ( ! stats[ index ] ) {
  10229. stats[ index ] = 1;
  10230. } else {
  10231. stats[ index ] += 1;
  10232. }
  10233. }
  10234. return result;
  10235. },
  10236. // Get triangle area (by Heron's formula)
  10237. // http://en.wikipedia.org/wiki/Heron%27s_formula
  10238. triangleArea: function ( vectorA, vectorB, vectorC ) {
  10239. var s, a, b, c,
  10240. tmp = THREE.GeometryUtils.__v1;
  10241. tmp.sub( vectorA, vectorB );
  10242. a = tmp.length();
  10243. tmp.sub( vectorA, vectorC );
  10244. b = tmp.length();
  10245. tmp.sub( vectorB, vectorC );
  10246. c = tmp.length();
  10247. s = 0.5 * ( a + b + c );
  10248. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  10249. },
  10250. // Center geometry so that 0,0,0 is in center of bounding box
  10251. center: function ( geometry ) {
  10252. geometry.computeBoundingBox();
  10253. var bb = geometry.boundingBox;
  10254. var offset = new THREE.Vector3();
  10255. offset.add( bb.min, bb.max );
  10256. offset.multiplyScalar( -0.5 );
  10257. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  10258. geometry.computeBoundingBox();
  10259. return offset;
  10260. },
  10261. // Normalize UVs to be from <0,1>
  10262. // (for now just the first set of UVs)
  10263. normalizeUVs: function ( geometry ) {
  10264. var uvSet = geometry.faceVertexUvs[ 0 ];
  10265. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  10266. var uvs = uvSet[ i ];
  10267. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  10268. // texture repeat
  10269. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  10270. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  10271. }
  10272. }
  10273. },
  10274. triangulateQuads: function ( geometry ) {
  10275. var i, il, j, jl;
  10276. var faces = [];
  10277. var faceUvs = [];
  10278. var faceVertexUvs = [];
  10279. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  10280. faceUvs[ i ] = [];
  10281. }
  10282. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  10283. faceVertexUvs[ i ] = [];
  10284. }
  10285. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  10286. var face = geometry.faces[ i ];
  10287. if ( face instanceof THREE.Face4 ) {
  10288. var a = face.a;
  10289. var b = face.b;
  10290. var c = face.c;
  10291. var d = face.d;
  10292. var triA = new THREE.Face3();
  10293. var triB = new THREE.Face3();
  10294. triA.color.copy( face.color );
  10295. triB.color.copy( face.color );
  10296. triA.materialIndex = face.materialIndex;
  10297. triB.materialIndex = face.materialIndex;
  10298. triA.a = a;
  10299. triA.b = b;
  10300. triA.c = d;
  10301. triB.a = b;
  10302. triB.b = c;
  10303. triB.c = d;
  10304. if ( face.vertexColors.length === 4 ) {
  10305. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  10306. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  10307. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  10308. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  10309. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  10310. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  10311. }
  10312. faces.push( triA, triB );
  10313. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10314. if ( geometry.faceVertexUvs[ j ].length ) {
  10315. var uvs = geometry.faceVertexUvs[ j ][ i ];
  10316. var uvA = uvs[ 0 ];
  10317. var uvB = uvs[ 1 ];
  10318. var uvC = uvs[ 2 ];
  10319. var uvD = uvs[ 3 ];
  10320. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  10321. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  10322. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  10323. }
  10324. }
  10325. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  10326. if ( geometry.faceUvs[ j ].length ) {
  10327. var faceUv = geometry.faceUvs[ j ][ i ];
  10328. faceUvs[ j ].push( faceUv, faceUv );
  10329. }
  10330. }
  10331. } else {
  10332. faces.push( face );
  10333. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  10334. faceUvs[ j ].push( geometry.faceUvs[ j ] );
  10335. }
  10336. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10337. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  10338. }
  10339. }
  10340. }
  10341. geometry.faces = faces;
  10342. geometry.faceUvs = faceUvs;
  10343. geometry.faceVertexUvs = faceVertexUvs;
  10344. geometry.computeCentroids();
  10345. geometry.computeFaceNormals();
  10346. geometry.computeVertexNormals();
  10347. if ( geometry.hasTangents ) geometry.computeTangents();
  10348. },
  10349. // Make all faces use unique vertices
  10350. // so that each face can be separated from others
  10351. explode: function( geometry ) {
  10352. var vertices = [];
  10353. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  10354. var n = vertices.length;
  10355. var face = geometry.faces[ i ];
  10356. if ( face instanceof THREE.Face4 ) {
  10357. var a = face.a;
  10358. var b = face.b;
  10359. var c = face.c;
  10360. var d = face.d;
  10361. var va = geometry.vertices[ a ];
  10362. var vb = geometry.vertices[ b ];
  10363. var vc = geometry.vertices[ c ];
  10364. var vd = geometry.vertices[ d ];
  10365. vertices.push( va.clone() );
  10366. vertices.push( vb.clone() );
  10367. vertices.push( vc.clone() );
  10368. vertices.push( vd.clone() );
  10369. face.a = n;
  10370. face.b = n + 1;
  10371. face.c = n + 2;
  10372. face.d = n + 3;
  10373. } else {
  10374. var a = face.a;
  10375. var b = face.b;
  10376. var c = face.c;
  10377. var va = geometry.vertices[ a ];
  10378. var vb = geometry.vertices[ b ];
  10379. var vc = geometry.vertices[ c ];
  10380. vertices.push( va.clone() );
  10381. vertices.push( vb.clone() );
  10382. vertices.push( vc.clone() );
  10383. face.a = n;
  10384. face.b = n + 1;
  10385. face.c = n + 2;
  10386. }
  10387. }
  10388. geometry.vertices = vertices;
  10389. delete geometry.__tmpVertices;
  10390. },
  10391. // Break faces with edges longer than maxEdgeLength
  10392. // - not recursive
  10393. tessellate: function ( geometry, maxEdgeLength ) {
  10394. var i, il, face,
  10395. a, b, c, d,
  10396. va, vb, vc, vd,
  10397. dab, dbc, dac, dcd, dad,
  10398. m, m1, m2,
  10399. vm, vm1, vm2,
  10400. vnm, vnm1, vnm2,
  10401. vcm, vcm1, vcm2,
  10402. triA, triB,
  10403. quadA, quadB,
  10404. edge;
  10405. var faces = [];
  10406. var faceVertexUvs = [];
  10407. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  10408. faceVertexUvs[ i ] = [];
  10409. }
  10410. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  10411. face = geometry.faces[ i ];
  10412. if ( face instanceof THREE.Face3 ) {
  10413. a = face.a;
  10414. b = face.b;
  10415. c = face.c;
  10416. va = geometry.vertices[ a ];
  10417. vb = geometry.vertices[ b ];
  10418. vc = geometry.vertices[ c ];
  10419. dab = va.position.distanceTo( vb.position );
  10420. dbc = vb.position.distanceTo( vc.position );
  10421. dac = va.position.distanceTo( vc.position );
  10422. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  10423. m = geometry.vertices.length;
  10424. triA = face.clone();
  10425. triB = face.clone();
  10426. if ( dab >= dbc && dab >= dac ) {
  10427. vm = va.clone();
  10428. vm.position.lerpSelf( vb.position, 0.5 );
  10429. triA.a = a;
  10430. triA.b = m;
  10431. triA.c = c;
  10432. triB.a = m;
  10433. triB.b = b;
  10434. triB.c = c;
  10435. if ( face.vertexNormals.length === 3 ) {
  10436. vnm = face.vertexNormals[ 0 ].clone();
  10437. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  10438. triA.vertexNormals[ 1 ].copy( vnm );
  10439. triB.vertexNormals[ 0 ].copy( vnm );
  10440. }
  10441. if ( face.vertexColors.length === 3 ) {
  10442. vcm = face.vertexColors[ 0 ].clone();
  10443. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  10444. triA.vertexColors[ 1 ].copy( vcm );
  10445. triB.vertexColors[ 0 ].copy( vcm );
  10446. }
  10447. edge = 0;
  10448. } else if ( dbc >= dab && dbc >= dac ) {
  10449. vm = vb.clone();
  10450. vm.position.lerpSelf( vc.position, 0.5 );
  10451. triA.a = a;
  10452. triA.b = b;
  10453. triA.c = m;
  10454. triB.a = m;
  10455. triB.b = c;
  10456. triB.c = a;
  10457. if ( face.vertexNormals.length === 3 ) {
  10458. vnm = face.vertexNormals[ 1 ].clone();
  10459. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  10460. triA.vertexNormals[ 2 ].copy( vnm );
  10461. triB.vertexNormals[ 0 ].copy( vnm );
  10462. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  10463. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  10464. }
  10465. if ( face.vertexColors.length === 3 ) {
  10466. vcm = face.vertexColors[ 1 ].clone();
  10467. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  10468. triA.vertexColors[ 2 ].copy( vcm );
  10469. triB.vertexColors[ 0 ].copy( vcm );
  10470. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  10471. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  10472. }
  10473. edge = 1;
  10474. } else {
  10475. vm = va.clone();
  10476. vm.position.lerpSelf( vc.position, 0.5 );
  10477. triA.a = a;
  10478. triA.b = b;
  10479. triA.c = m;
  10480. triB.a = m;
  10481. triB.b = b;
  10482. triB.c = c;
  10483. if ( face.vertexNormals.length === 3 ) {
  10484. vnm = face.vertexNormals[ 0 ].clone();
  10485. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  10486. triA.vertexNormals[ 2 ].copy( vnm );
  10487. triB.vertexNormals[ 0 ].copy( vnm );
  10488. }
  10489. if ( face.vertexColors.length === 3 ) {
  10490. vcm = face.vertexColors[ 0 ].clone();
  10491. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  10492. triA.vertexColors[ 2 ].copy( vcm );
  10493. triB.vertexColors[ 0 ].copy( vcm );
  10494. }
  10495. edge = 2;
  10496. }
  10497. faces.push( triA, triB );
  10498. geometry.vertices.push( vm );
  10499. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  10500. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10501. if ( geometry.faceVertexUvs[ j ].length ) {
  10502. uvs = geometry.faceVertexUvs[ j ][ i ];
  10503. uvA = uvs[ 0 ];
  10504. uvB = uvs[ 1 ];
  10505. uvC = uvs[ 2 ];
  10506. // AB
  10507. if ( edge === 0 ) {
  10508. uvM = uvA.clone();
  10509. uvM.lerpSelf( uvB, 0.5 );
  10510. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  10511. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  10512. // BC
  10513. } else if ( edge === 1 ) {
  10514. uvM = uvB.clone();
  10515. uvM.lerpSelf( uvC, 0.5 );
  10516. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  10517. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  10518. // AC
  10519. } else {
  10520. uvM = uvA.clone();
  10521. uvM.lerpSelf( uvC, 0.5 );
  10522. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  10523. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  10524. }
  10525. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  10526. }
  10527. }
  10528. } else {
  10529. faces.push( face );
  10530. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10531. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  10532. }
  10533. }
  10534. } else {
  10535. a = face.a;
  10536. b = face.b;
  10537. c = face.c;
  10538. d = face.d;
  10539. va = geometry.vertices[ a ];
  10540. vb = geometry.vertices[ b ];
  10541. vc = geometry.vertices[ c ];
  10542. vd = geometry.vertices[ d ];
  10543. dab = va.position.distanceTo( vb.position );
  10544. dbc = vb.position.distanceTo( vc.position );
  10545. dcd = vc.position.distanceTo( vd.position );
  10546. dad = va.position.distanceTo( vd.position );
  10547. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  10548. m1 = geometry.vertices.length;
  10549. m2 = geometry.vertices.length + 1;
  10550. quadA = face.clone();
  10551. quadB = face.clone();
  10552. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  10553. vm1 = va.clone();
  10554. vm1.position.lerpSelf( vb.position, 0.5 );
  10555. vm2 = vc.clone();
  10556. vm2.position.lerpSelf( vd.position, 0.5 );
  10557. quadA.a = a;
  10558. quadA.b = m1;
  10559. quadA.c = m2;
  10560. quadA.d = d;
  10561. quadB.a = m1;
  10562. quadB.b = b;
  10563. quadB.c = c;
  10564. quadB.d = m2;
  10565. if ( face.vertexNormals.length === 4 ) {
  10566. vnm1 = face.vertexNormals[ 0 ].clone();
  10567. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  10568. vnm2 = face.vertexNormals[ 2 ].clone();
  10569. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  10570. quadA.vertexNormals[ 1 ].copy( vnm1 );
  10571. quadA.vertexNormals[ 2 ].copy( vnm2 );
  10572. quadB.vertexNormals[ 0 ].copy( vnm1 );
  10573. quadB.vertexNormals[ 3 ].copy( vnm2 );
  10574. }
  10575. if ( face.vertexColors.length === 4 ) {
  10576. vcm1 = face.vertexColors[ 0 ].clone();
  10577. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  10578. vcm2 = face.vertexColors[ 2 ].clone();
  10579. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  10580. quadA.vertexColors[ 1 ].copy( vcm1 );
  10581. quadA.vertexColors[ 2 ].copy( vcm2 );
  10582. quadB.vertexColors[ 0 ].copy( vcm1 );
  10583. quadB.vertexColors[ 3 ].copy( vcm2 );
  10584. }
  10585. edge = 0;
  10586. } else {
  10587. vm1 = vb.clone();
  10588. vm1.position.lerpSelf( vc.position, 0.5 );
  10589. vm2 = vd.clone();
  10590. vm2.position.lerpSelf( va.position, 0.5 );
  10591. quadA.a = a;
  10592. quadA.b = b;
  10593. quadA.c = m1;
  10594. quadA.d = m2;
  10595. quadB.a = m2;
  10596. quadB.b = m1;
  10597. quadB.c = c;
  10598. quadB.d = d;
  10599. if ( face.vertexNormals.length === 4 ) {
  10600. vnm1 = face.vertexNormals[ 1 ].clone();
  10601. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  10602. vnm2 = face.vertexNormals[ 3 ].clone();
  10603. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  10604. quadA.vertexNormals[ 2 ].copy( vnm1 );
  10605. quadA.vertexNormals[ 3 ].copy( vnm2 );
  10606. quadB.vertexNormals[ 0 ].copy( vnm2 );
  10607. quadB.vertexNormals[ 1 ].copy( vnm1 );
  10608. }
  10609. if ( face.vertexColors.length === 4 ) {
  10610. vcm1 = face.vertexColors[ 1 ].clone();
  10611. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  10612. vcm2 = face.vertexColors[ 3 ].clone();
  10613. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  10614. quadA.vertexColors[ 2 ].copy( vcm1 );
  10615. quadA.vertexColors[ 3 ].copy( vcm2 );
  10616. quadB.vertexColors[ 0 ].copy( vcm2 );
  10617. quadB.vertexColors[ 1 ].copy( vcm1 );
  10618. }
  10619. edge = 1;
  10620. }
  10621. faces.push( quadA, quadB );
  10622. geometry.vertices.push( vm1, vm2 );
  10623. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  10624. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10625. if ( geometry.faceVertexUvs[ j ].length ) {
  10626. uvs = geometry.faceVertexUvs[ j ][ i ];
  10627. uvA = uvs[ 0 ];
  10628. uvB = uvs[ 1 ];
  10629. uvC = uvs[ 2 ];
  10630. uvD = uvs[ 3 ];
  10631. // AB + CD
  10632. if ( edge === 0 ) {
  10633. uvM1 = uvA.clone();
  10634. uvM1.lerpSelf( uvB, 0.5 );
  10635. uvM2 = uvC.clone();
  10636. uvM2.lerpSelf( uvD, 0.5 );
  10637. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  10638. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  10639. // BC + AD
  10640. } else {
  10641. uvM1 = uvB.clone();
  10642. uvM1.lerpSelf( uvC, 0.5 );
  10643. uvM2 = uvD.clone();
  10644. uvM2.lerpSelf( uvA, 0.5 );
  10645. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  10646. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  10647. }
  10648. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  10649. }
  10650. }
  10651. } else {
  10652. faces.push( face );
  10653. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10654. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  10655. }
  10656. }
  10657. }
  10658. }
  10659. geometry.faces = faces;
  10660. geometry.faceVertexUvs = faceVertexUvs;
  10661. }
  10662. };
  10663. THREE.GeometryUtils.random = THREE.Math.random16;
  10664. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  10665. /**
  10666. * @author alteredq / http://alteredqualia.com/
  10667. * @author mrdoob / http://mrdoob.com/
  10668. */
  10669. THREE.ImageUtils = {
  10670. crossOrigin: 'anonymous',
  10671. loadTexture: function ( path, mapping, callback ) {
  10672. var image = new Image(), texture = new THREE.Texture( image, mapping );
  10673. image.onload = function () { texture.needsUpdate = true; if ( callback ) callback( this ); };
  10674. image.crossOrigin = this.crossOrigin;
  10675. image.src = path;
  10676. return texture;
  10677. },
  10678. loadTextureCube: function ( array, mapping, callback ) {
  10679. var i, l, images = [], texture = new THREE.Texture( images, mapping );
  10680. images.loadCount = 0;
  10681. for ( i = 0, l = array.length; i < l; ++ i ) {
  10682. images[ i ] = new Image();
  10683. images[ i ].onload = function () {
  10684. images.loadCount += 1;
  10685. if ( images.loadCount === 6 ) texture.needsUpdate = true;
  10686. if ( callback ) callback( this );
  10687. };
  10688. images[ i ].crossOrigin = this.crossOrigin;
  10689. images[ i ].src = array[ i ];
  10690. }
  10691. return texture;
  10692. },
  10693. getNormalMap: function ( image, depth ) {
  10694. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  10695. var cross = function ( a, b ) {
  10696. 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 ] ];
  10697. }
  10698. var subtract = function ( a, b ) {
  10699. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  10700. }
  10701. var normalize = function ( a ) {
  10702. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  10703. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  10704. }
  10705. depth = depth | 1;
  10706. var width = image.width;
  10707. var height = image.height;
  10708. var canvas = document.createElement( 'canvas' );
  10709. canvas.width = width;
  10710. canvas.height = height;
  10711. var context = canvas.getContext( '2d' );
  10712. context.drawImage( image, 0, 0 );
  10713. var data = context.getImageData( 0, 0, width, height ).data;
  10714. var imageData = context.createImageData( width, height );
  10715. var output = imageData.data;
  10716. for ( var x = 0; x < width; x ++ ) {
  10717. for ( var y = 1; y < height; y ++ ) {
  10718. var ly = y - 1 < 0 ? height - 1 : y - 1;
  10719. var uy = ( y + 1 ) % height;
  10720. var lx = x - 1 < 0 ? width - 1 : x - 1;
  10721. var ux = ( x + 1 ) % width;
  10722. var points = [];
  10723. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  10724. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  10725. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  10726. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  10727. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  10728. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  10729. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  10730. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  10731. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  10732. var normals = [];
  10733. var num_points = points.length;
  10734. for ( var i = 0; i < num_points; i ++ ) {
  10735. var v1 = points[ i ];
  10736. var v2 = points[ ( i + 1 ) % num_points ];
  10737. v1 = subtract( v1, origin );
  10738. v2 = subtract( v2, origin );
  10739. normals.push( normalize( cross( v1, v2 ) ) );
  10740. }
  10741. var normal = [ 0, 0, 0 ];
  10742. for ( var i = 0; i < normals.length; i ++ ) {
  10743. normal[ 0 ] += normals[ i ][ 0 ];
  10744. normal[ 1 ] += normals[ i ][ 1 ];
  10745. normal[ 2 ] += normals[ i ][ 2 ];
  10746. }
  10747. normal[ 0 ] /= normals.length;
  10748. normal[ 1 ] /= normals.length;
  10749. normal[ 2 ] /= normals.length;
  10750. var idx = ( y * width + x ) * 4;
  10751. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  10752. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 / 2.0 ) * 255 ) | 0;
  10753. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  10754. output[ idx + 3 ] = 255;
  10755. }
  10756. }
  10757. context.putImageData( imageData, 0, 0 );
  10758. return canvas;
  10759. },
  10760. generateDataTexture: function ( width, height, color ) {
  10761. var size = width * height;
  10762. var data = new Uint8Array( 3 * size );
  10763. var r = Math.floor( color.r * 255 );
  10764. var g = Math.floor( color.g * 255 );
  10765. var b = Math.floor( color.b * 255 );
  10766. for ( var i = 0; i < size; i ++ ) {
  10767. data[ i * 3 ] = r;
  10768. data[ i * 3 + 1 ] = g;
  10769. data[ i * 3 + 2 ] = b;
  10770. }
  10771. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  10772. texture.needsUpdate = true;
  10773. return texture;
  10774. }
  10775. };
  10776. /**
  10777. * @author alteredq / http://alteredqualia.com/
  10778. */
  10779. THREE.SceneUtils = {
  10780. showHierarchy : function ( root, visible ) {
  10781. THREE.SceneUtils.traverseHierarchy( root, function( node ) { node.visible = visible; } );
  10782. },
  10783. traverseHierarchy : function ( root, callback ) {
  10784. var n, i, l = root.children.length;
  10785. for ( i = 0; i < l; i ++ ) {
  10786. n = root.children[ i ];
  10787. callback( n );
  10788. THREE.SceneUtils.traverseHierarchy( n, callback );
  10789. }
  10790. },
  10791. createMultiMaterialObject : function ( geometry, materials ) {
  10792. var i, il = materials.length,
  10793. group = new THREE.Object3D();
  10794. for ( i = 0; i < il; i ++ ) {
  10795. var object = new THREE.Mesh( geometry, materials[ i ] );
  10796. group.add( object );
  10797. }
  10798. return group;
  10799. },
  10800. cloneObject: function ( source ) {
  10801. var object;
  10802. // subclass specific properties
  10803. // (must process in order from more specific subclasses to more abstract classes)
  10804. if ( source instanceof THREE.MorphAnimMesh ) {
  10805. object = new THREE.MorphAnimMesh( source.geometry, source.material );
  10806. object.duration = source.duration;
  10807. object.mirroredLoop = source.mirroredLoop;
  10808. object.time = source.time;
  10809. object.lastKeyframe = source.lastKeyframe;
  10810. object.currentKeyframe = source.currentKeyframe;
  10811. object.direction = source.direction;
  10812. object.directionBackwards = source.directionBackwards;
  10813. } else if ( source instanceof THREE.SkinnedMesh ) {
  10814. object = new THREE.SkinnedMesh( source.geometry, source.material );
  10815. } else if ( source instanceof THREE.Mesh ) {
  10816. object = new THREE.Mesh( source.geometry, source.material );
  10817. } else if ( source instanceof THREE.Line ) {
  10818. object = new THREE.Line( source.geometry, source.material, source.type );
  10819. } else if ( source instanceof THREE.Ribbon ) {
  10820. object = new THREE.Ribbon( source.geometry, source.material );
  10821. } else if ( source instanceof THREE.ParticleSystem ) {
  10822. object = new THREE.ParticleSystem( source.geometry, source.material );
  10823. object.sortParticles = source.sortParticles;
  10824. } else if ( source instanceof THREE.Particle ) {
  10825. object = new THREE.Particle( source.material );
  10826. } else if ( source instanceof THREE.Sprite ) {
  10827. object = new THREE.Sprite( {} );
  10828. object.color.copy( source.color );
  10829. object.map = source.map;
  10830. object.blending = source.blending;
  10831. object.useScreenCoordinates = source.useScreenCoordinates;
  10832. object.mergeWith3D = source.mergeWith3D;
  10833. object.affectedByDistance = source.affectedByDistance;
  10834. object.scaleByViewport = source.scaleByViewport;
  10835. object.alignment = source.alignment;
  10836. object.rotation3d.copy( source.rotation3d );
  10837. object.rotation = source.rotation;
  10838. object.opacity = source.opacity;
  10839. object.uvOffset.copy( source.uvOffset );
  10840. object.uvScale.copy( source.uvScale);
  10841. } else if ( source instanceof THREE.LOD ) {
  10842. object = new THREE.LOD();
  10843. } else if ( source instanceof THREE.MarchingCubes ) {
  10844. object = new THREE.MarchingCubes( source.resolution, source.material );
  10845. object.field.set( source.field );
  10846. object.isolation = source.isolation;
  10847. } else if ( source instanceof THREE.Object3D ) {
  10848. object = new THREE.Object3D();
  10849. }
  10850. // base class properties
  10851. object.name = source.name;
  10852. object.parent = source.parent;
  10853. object.up.copy( source.up );
  10854. object.position.copy( source.position );
  10855. // because of Sprite madness
  10856. if ( object.rotation instanceof THREE.Vector3 )
  10857. object.rotation.copy( source.rotation );
  10858. object.eulerOrder = source.eulerOrder;
  10859. object.scale.copy( source.scale );
  10860. object.dynamic = source.dynamic;
  10861. object.doubleSided = source.doubleSided;
  10862. object.flipSided = source.flipSided;
  10863. object.renderDepth = source.renderDepth;
  10864. object.rotationAutoUpdate = source.rotationAutoUpdate;
  10865. object.matrix.copy( source.matrix );
  10866. object.matrixWorld.copy( source.matrixWorld );
  10867. object.matrixRotationWorld.copy( source.matrixRotationWorld );
  10868. object.matrixAutoUpdate = source.matrixAutoUpdate;
  10869. object.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10870. object.quaternion.copy( source.quaternion );
  10871. object.useQuaternion = source.useQuaternion;
  10872. object.boundRadius = source.boundRadius;
  10873. object.boundRadiusScale = source.boundRadiusScale;
  10874. object.visible = source.visible;
  10875. object.castShadow = source.castShadow;
  10876. object.receiveShadow = source.receiveShadow;
  10877. object.frustumCulled = source.frustumCulled;
  10878. // children
  10879. for ( var i = 0; i < source.children.length; i ++ ) {
  10880. var child = THREE.SceneUtils.cloneObject( source.children[ i ] );
  10881. object.children[ i ] = child;
  10882. child.parent = object;
  10883. }
  10884. // LODs need to be patched separately to use cloned children
  10885. if ( source instanceof THREE.LOD ) {
  10886. for ( var i = 0; i < source.LODs.length; i ++ ) {
  10887. var lod = source.LODs[ i ];
  10888. object.LODs[ i ] = { visibleAtDistance: lod.visibleAtDistance, object3D: object.children[ i ] };
  10889. }
  10890. }
  10891. return object;
  10892. },
  10893. detach : function ( child, parent, scene ) {
  10894. child.applyMatrix( parent.matrixWorld );
  10895. parent.remove( child );
  10896. scene.add( child );
  10897. },
  10898. attach: function ( child, scene, parent ) {
  10899. var matrixWorldInverse = new THREE.Matrix4();
  10900. matrixWorldInverse.getInverse( parent.matrixWorld );
  10901. child.applyMatrix( matrixWorldInverse );
  10902. scene.remove( child );
  10903. parent.add( child );
  10904. }
  10905. };
  10906. /**
  10907. * @author alteredq / http://alteredqualia.com/
  10908. * @author mr.doob / http://mrdoob.com/
  10909. *
  10910. * ShaderUtils currently contains:
  10911. *
  10912. * fresnel
  10913. * normal
  10914. * cube
  10915. *
  10916. */
  10917. if ( THREE.WebGLRenderer ) {
  10918. THREE.ShaderUtils = {
  10919. lib: {
  10920. /* -------------------------------------------------------------------------
  10921. // Fresnel shader
  10922. // - based on Nvidia Cg tutorial
  10923. ------------------------------------------------------------------------- */
  10924. 'fresnel': {
  10925. uniforms: {
  10926. "mRefractionRatio": { type: "f", value: 1.02 },
  10927. "mFresnelBias": { type: "f", value: 0.1 },
  10928. "mFresnelPower": { type: "f", value: 2.0 },
  10929. "mFresnelScale": { type: "f", value: 1.0 },
  10930. "tCube": { type: "t", value: 1, texture: null }
  10931. },
  10932. fragmentShader: [
  10933. "uniform samplerCube tCube;",
  10934. "varying vec3 vReflect;",
  10935. "varying vec3 vRefract[3];",
  10936. "varying float vReflectionFactor;",
  10937. "void main() {",
  10938. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  10939. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  10940. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  10941. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  10942. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  10943. "refractedColor.a = 1.0;",
  10944. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  10945. "}"
  10946. ].join("\n"),
  10947. vertexShader: [
  10948. "uniform float mRefractionRatio;",
  10949. "uniform float mFresnelBias;",
  10950. "uniform float mFresnelScale;",
  10951. "uniform float mFresnelPower;",
  10952. "varying vec3 vReflect;",
  10953. "varying vec3 vRefract[3];",
  10954. "varying float vReflectionFactor;",
  10955. "void main() {",
  10956. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10957. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  10958. "vec3 nWorld = normalize ( mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal );",
  10959. "vec3 I = mPosition.xyz - cameraPosition;",
  10960. "vReflect = reflect( I, nWorld );",
  10961. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  10962. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  10963. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  10964. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  10965. "gl_Position = projectionMatrix * mvPosition;",
  10966. "}"
  10967. ].join("\n")
  10968. },
  10969. /* -------------------------------------------------------------------------
  10970. // Normal map shader
  10971. // - Blinn-Phong
  10972. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10973. // - point and directional lights (use with "lights: true" material option)
  10974. ------------------------------------------------------------------------- */
  10975. 'normal' : {
  10976. uniforms: THREE.UniformsUtils.merge( [
  10977. THREE.UniformsLib[ "fog" ],
  10978. THREE.UniformsLib[ "lights" ],
  10979. THREE.UniformsLib[ "shadowmap" ],
  10980. {
  10981. "enableAO" : { type: "i", value: 0 },
  10982. "enableDiffuse" : { type: "i", value: 0 },
  10983. "enableSpecular" : { type: "i", value: 0 },
  10984. "enableReflection": { type: "i", value: 0 },
  10985. "tDiffuse" : { type: "t", value: 0, texture: null },
  10986. "tCube" : { type: "t", value: 1, texture: null },
  10987. "tNormal" : { type: "t", value: 2, texture: null },
  10988. "tSpecular" : { type: "t", value: 3, texture: null },
  10989. "tAO" : { type: "t", value: 4, texture: null },
  10990. "tDisplacement": { type: "t", value: 5, texture: null },
  10991. "uNormalScale": { type: "f", value: 1.0 },
  10992. "uDisplacementBias": { type: "f", value: 0.0 },
  10993. "uDisplacementScale": { type: "f", value: 1.0 },
  10994. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10995. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  10996. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10997. "uShininess": { type: "f", value: 30 },
  10998. "uOpacity": { type: "f", value: 1 },
  10999. "uReflectivity": { type: "f", value: 0.5 },
  11000. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11001. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11002. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11003. }
  11004. ] ),
  11005. fragmentShader: [
  11006. "uniform vec3 uAmbientColor;",
  11007. "uniform vec3 uDiffuseColor;",
  11008. "uniform vec3 uSpecularColor;",
  11009. "uniform float uShininess;",
  11010. "uniform float uOpacity;",
  11011. "uniform bool enableDiffuse;",
  11012. "uniform bool enableSpecular;",
  11013. "uniform bool enableAO;",
  11014. "uniform bool enableReflection;",
  11015. "uniform sampler2D tDiffuse;",
  11016. "uniform sampler2D tNormal;",
  11017. "uniform sampler2D tSpecular;",
  11018. "uniform sampler2D tAO;",
  11019. "uniform samplerCube tCube;",
  11020. "uniform float uNormalScale;",
  11021. "uniform float uReflectivity;",
  11022. "varying vec3 vTangent;",
  11023. "varying vec3 vBinormal;",
  11024. "varying vec3 vNormal;",
  11025. "varying vec2 vUv;",
  11026. "uniform vec3 ambientLightColor;",
  11027. "#if MAX_DIR_LIGHTS > 0",
  11028. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11029. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11030. "#endif",
  11031. "#if MAX_POINT_LIGHTS > 0",
  11032. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11033. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  11034. "#endif",
  11035. "#ifdef WRAP_AROUND",
  11036. "uniform vec3 wrapRGB;",
  11037. "#endif",
  11038. "varying vec3 vViewPosition;",
  11039. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11040. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11041. "void main() {",
  11042. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11043. "vec3 specularTex = vec3( 1.0 );",
  11044. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11045. "normalTex.xy *= uNormalScale;",
  11046. "normalTex = normalize( normalTex );",
  11047. "if( enableDiffuse ) {",
  11048. "#ifdef GAMMA_INPUT",
  11049. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11050. "texelColor.xyz *= texelColor.xyz;",
  11051. "gl_FragColor = gl_FragColor * texelColor;",
  11052. "#else",
  11053. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11054. "#endif",
  11055. "}",
  11056. "if( enableAO ) {",
  11057. "#ifdef GAMMA_INPUT",
  11058. "vec4 aoColor = texture2D( tAO, vUv );",
  11059. "aoColor.xyz *= aoColor.xyz;",
  11060. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11061. "#else",
  11062. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11063. "#endif",
  11064. "}",
  11065. "if( enableSpecular )",
  11066. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11067. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11068. "vec3 finalNormal = tsb * normalTex;",
  11069. "vec3 normal = normalize( finalNormal );",
  11070. "vec3 viewPosition = normalize( vViewPosition );",
  11071. // point lights
  11072. "#if MAX_POINT_LIGHTS > 0",
  11073. "vec3 pointDiffuse = vec3( 0.0 );",
  11074. "vec3 pointSpecular = vec3( 0.0 );",
  11075. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11076. "vec3 pointVector = normalize( vPointLight[ i ].xyz );",
  11077. "float pointDistance = vPointLight[ i ].w;",
  11078. // diffuse
  11079. "#ifdef WRAP_AROUND",
  11080. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11081. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11082. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11083. "#else",
  11084. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11085. "#endif",
  11086. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11087. // specular
  11088. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11089. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11090. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11091. "#ifdef PHYSICALLY_BASED_SHADING",
  11092. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11093. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11094. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11095. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11096. "#else",
  11097. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11098. "#endif",
  11099. "}",
  11100. "#endif",
  11101. // directional lights
  11102. "#if MAX_DIR_LIGHTS > 0",
  11103. "vec3 dirDiffuse = vec3( 0.0 );",
  11104. "vec3 dirSpecular = vec3( 0.0 );",
  11105. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11106. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11107. "vec3 dirVector = normalize( lDirection.xyz );",
  11108. // diffuse
  11109. "#ifdef WRAP_AROUND",
  11110. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11111. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11112. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11113. "#else",
  11114. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11115. "#endif",
  11116. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11117. // specular
  11118. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11119. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11120. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11121. "#ifdef PHYSICALLY_BASED_SHADING",
  11122. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11123. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11124. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11125. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11126. "#else",
  11127. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11128. "#endif",
  11129. "}",
  11130. "#endif",
  11131. // all lights contribution summation
  11132. "vec3 totalDiffuse = vec3( 0.0 );",
  11133. "vec3 totalSpecular = vec3( 0.0 );",
  11134. "#if MAX_DIR_LIGHTS > 0",
  11135. "totalDiffuse += dirDiffuse;",
  11136. "totalSpecular += dirSpecular;",
  11137. "#endif",
  11138. "#if MAX_POINT_LIGHTS > 0",
  11139. "totalDiffuse += pointDiffuse;",
  11140. "totalSpecular += pointSpecular;",
  11141. "#endif",
  11142. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor) + totalSpecular;",
  11143. "if ( enableReflection ) {",
  11144. "vec3 wPos = cameraPosition - vViewPosition;",
  11145. "vec3 vReflect = reflect( normalize( wPos ), normal );",
  11146. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11147. "#ifdef GAMMA_INPUT",
  11148. "cubeColor.xyz *= cubeColor.xyz;",
  11149. "#endif",
  11150. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11151. "}",
  11152. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11153. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11154. THREE.ShaderChunk[ "fog_fragment" ],
  11155. "}"
  11156. ].join("\n"),
  11157. vertexShader: [
  11158. "attribute vec4 tangent;",
  11159. "uniform vec2 uOffset;",
  11160. "uniform vec2 uRepeat;",
  11161. "#ifdef VERTEX_TEXTURES",
  11162. "uniform sampler2D tDisplacement;",
  11163. "uniform float uDisplacementScale;",
  11164. "uniform float uDisplacementBias;",
  11165. "#endif",
  11166. "varying vec3 vTangent;",
  11167. "varying vec3 vBinormal;",
  11168. "varying vec3 vNormal;",
  11169. "varying vec2 vUv;",
  11170. "#if MAX_POINT_LIGHTS > 0",
  11171. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11172. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11173. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  11174. "#endif",
  11175. "varying vec3 vViewPosition;",
  11176. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11177. "void main() {",
  11178. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11179. "vViewPosition = -mvPosition.xyz;",
  11180. // normal, tangent and binormal vectors
  11181. "vNormal = normalMatrix * normal;",
  11182. "vTangent = normalMatrix * tangent.xyz;",
  11183. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  11184. "vUv = uv * uRepeat + uOffset;",
  11185. // point lights
  11186. "#if MAX_POINT_LIGHTS > 0",
  11187. "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {",
  11188. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11189. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  11190. "float lDistance = 1.0;",
  11191. "if ( pointLightDistance[ i ] > 0.0 )",
  11192. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  11193. "lVector = normalize( lVector );",
  11194. "vPointLight[ i ] = vec4( lVector, lDistance );",
  11195. "}",
  11196. "#endif",
  11197. // displacement mapping
  11198. "#ifdef VERTEX_TEXTURES",
  11199. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11200. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11201. "vec4 displacedPosition = vec4( normalize( vNormal.xyz ) * df, 0.0 ) + mvPosition;",
  11202. "gl_Position = projectionMatrix * displacedPosition;",
  11203. "#else",
  11204. "gl_Position = projectionMatrix * mvPosition;",
  11205. "#endif",
  11206. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11207. "}"
  11208. ].join("\n")
  11209. },
  11210. /* -------------------------------------------------------------------------
  11211. // Cube map shader
  11212. ------------------------------------------------------------------------- */
  11213. 'cube': {
  11214. uniforms: { "tCube": { type: "t", value: 1, texture: null },
  11215. "tFlip": { type: "f", value: -1 } },
  11216. vertexShader: [
  11217. "varying vec3 vViewPosition;",
  11218. "void main() {",
  11219. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  11220. "vViewPosition = cameraPosition - mPosition.xyz;",
  11221. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11222. "}"
  11223. ].join("\n"),
  11224. fragmentShader: [
  11225. "uniform samplerCube tCube;",
  11226. "uniform float tFlip;",
  11227. "varying vec3 vViewPosition;",
  11228. "void main() {",
  11229. "vec3 wPos = cameraPosition - vViewPosition;",
  11230. "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
  11231. "}"
  11232. ].join("\n")
  11233. }
  11234. }
  11235. };
  11236. };/**
  11237. * @author alteredq / http://alteredqualia.com/
  11238. */
  11239. THREE.BufferGeometry = function () {
  11240. this.id = THREE.GeometryCount ++;
  11241. // GL buffers
  11242. this.vertexIndexBuffer = null;
  11243. this.vertexPositionBuffer = null;
  11244. this.vertexNormalBuffer = null;
  11245. this.vertexUvBuffer = null;
  11246. this.vertexColorBuffer = null;
  11247. // typed arrays (kept only if dynamic flag is set)
  11248. this.vertexIndexArray = null;
  11249. this.vertexPositionArray = null;
  11250. this.vertexNormalArray = null;
  11251. this.vertexUvArray = null;
  11252. this.vertexColorArray = null;
  11253. this.dynamic = false;
  11254. // boundings
  11255. this.boundingBox = null;
  11256. this.boundingSphere = null;
  11257. // for compatibility
  11258. this.morphTargets = [];
  11259. };
  11260. THREE.BufferGeometry.prototype = {
  11261. constructor : THREE.BufferGeometry,
  11262. // for compatibility
  11263. computeBoundingBox: function () {
  11264. },
  11265. // for compatibility
  11266. computeBoundingSphere: function () {
  11267. }
  11268. };
  11269. /**
  11270. * @author zz85 / http://www.lab4games.net/zz85/blog
  11271. * Extensible curve object
  11272. *
  11273. * Some common of Curve methods
  11274. * .getPoint(t), getTangent(t)
  11275. * .getPointAt(u), getTagentAt(u)
  11276. * .getPoints(), .getSpacedPoints()
  11277. * .getLength()
  11278. *
  11279. * This file contains following classes:
  11280. *
  11281. * -- 2d classes --
  11282. * THREE.Curve
  11283. * THREE.LineCurve
  11284. * THREE.QuadraticBezierCurve
  11285. * THREE.CubicBezierCurve
  11286. * THREE.SplineCurve
  11287. * THREE.ArcCurve
  11288. *
  11289. * -- 3d classes --
  11290. * THREE.LineCurve3
  11291. * THREE.QuadraticBezierCurve3
  11292. * THREE.CubicBezierCurve3
  11293. * THREE.SplineCurve3
  11294. * THREE.ClosedSplineCurve3
  11295. *
  11296. **/
  11297. /**************************************************************
  11298. * Abstract Curve base class
  11299. **************************************************************/
  11300. THREE.Curve = function () {
  11301. };
  11302. // Virtual base class method to overwrite and implement in subclasses
  11303. // - t [0 .. 1]
  11304. THREE.Curve.prototype.getPoint = function ( t ) {
  11305. console.log( "Warning, getPoint() not implemented!" );
  11306. return null;
  11307. };
  11308. // Get point at relative position in curve according to arc length
  11309. // - u [0 .. 1]
  11310. THREE.Curve.prototype.getPointAt = function ( u ) {
  11311. var t = this.getUtoTmapping( u );
  11312. return this.getPoint( t );
  11313. };
  11314. // Get sequence of points using getPoint( t )
  11315. THREE.Curve.prototype.getPoints = function ( divisions ) {
  11316. if ( !divisions ) divisions = 5;
  11317. var d, pts = [];
  11318. for ( d = 0; d <= divisions; d ++ ) {
  11319. pts.push( this.getPoint( d / divisions ) );
  11320. };
  11321. return pts;
  11322. };
  11323. // Get sequence of points using getPointAt( u )
  11324. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  11325. if ( !divisions ) divisions = 5;
  11326. var d, pts = [];
  11327. for ( d = 0; d <= divisions; d ++ ) {
  11328. pts.push( this.getPointAt( d / divisions ) );
  11329. };
  11330. return pts;
  11331. };
  11332. // Get total curve length
  11333. THREE.Curve.prototype.getLength = function () {
  11334. var lengths = this.getLengths();
  11335. return lengths[ lengths.length - 1 ];
  11336. };
  11337. // Get list of cumulative segment lengths
  11338. THREE.Curve.prototype.getLengths = function ( divisions ) {
  11339. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  11340. if ( this.cacheArcLengths
  11341. && ( this.cacheArcLengths.length == divisions + 1 )
  11342. && !this.needsUpdate) {
  11343. //console.log( "cached", this.cacheArcLengths );
  11344. return this.cacheArcLengths;
  11345. }
  11346. this.needsUpdate = false;
  11347. var cache = [];
  11348. var current, last = this.getPoint( 0 );
  11349. var p, sum = 0;
  11350. cache.push( 0 );
  11351. for ( p = 1; p <= divisions; p ++ ) {
  11352. current = this.getPoint ( p / divisions );
  11353. sum += current.distanceTo( last );
  11354. cache.push( sum );
  11355. last = current;
  11356. }
  11357. this.cacheArcLengths = cache;
  11358. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  11359. };
  11360. THREE.Curve.prototype.updateArcLengths = function() {
  11361. this.needsUpdate = true;
  11362. this.getLengths();
  11363. };
  11364. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  11365. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  11366. var arcLengths = this.getLengths();
  11367. var i = 0, il = arcLengths.length;
  11368. var targetArcLength; // The targeted u distance value to get
  11369. if ( distance ) {
  11370. targetArcLength = distance;
  11371. } else {
  11372. targetArcLength = u * arcLengths[ il - 1 ];
  11373. }
  11374. //var time = Date.now();
  11375. // binary search for the index with largest value smaller than target u distance
  11376. var low = 0, high = il - 1, comparison;
  11377. while ( low <= high ) {
  11378. 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
  11379. comparison = arcLengths[ i ] - targetArcLength;
  11380. if ( comparison < 0 ) {
  11381. low = i + 1;
  11382. continue;
  11383. } else if ( comparison > 0 ) {
  11384. high = i - 1;
  11385. continue;
  11386. } else {
  11387. high = i;
  11388. break;
  11389. // DONE
  11390. }
  11391. }
  11392. i = high;
  11393. //console.log('b' , i, low, high, Date.now()- time);
  11394. if ( arcLengths[ i ] == targetArcLength ) {
  11395. var t = i / ( il - 1 );
  11396. return t;
  11397. }
  11398. // we could get finer grain at lengths, or use simple interpolatation between two points
  11399. var lengthBefore = arcLengths[ i ];
  11400. var lengthAfter = arcLengths[ i + 1 ];
  11401. var segmentLength = lengthAfter - lengthBefore;
  11402. // determine where we are between the 'before' and 'after' points
  11403. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  11404. // add that fractional amount to t
  11405. t = ( i + segmentFraction ) / ( il -1 );
  11406. return t;
  11407. };
  11408. // In case any sub curve does not implement its tangent / normal finding,
  11409. // we get 2 points with a small delta and find a gradient of the 2 points
  11410. // which seems to make a reasonable approximation
  11411. THREE.Curve.prototype.getNormalVector = function( t ) {
  11412. var vec = this.getTangent( t );
  11413. return new THREE.Vector2( -vec.y , vec.x );
  11414. };
  11415. // Returns a unit vector tangent at t
  11416. THREE.Curve.prototype.getTangent = function( t ) {
  11417. var delta = 0.0001;
  11418. var t1 = t - delta;
  11419. var t2 = t + delta;
  11420. // Capping in case of danger
  11421. if ( t1 < 0 ) t1 = 0;
  11422. if ( t2 > 1 ) t2 = 1;
  11423. var pt1 = this.getPoint( t1 );
  11424. var pt2 = this.getPoint( t2 );
  11425. var vec = pt2.clone().subSelf(pt1);
  11426. return vec.normalize();
  11427. };
  11428. THREE.Curve.prototype.getTangentAt = function ( u ) {
  11429. var t = this.getUtoTmapping( u );
  11430. return this.getTangent( t );
  11431. };
  11432. /**************************************************************
  11433. * Line
  11434. **************************************************************/
  11435. THREE.LineCurve = function ( v1, v2 ) {
  11436. if ( ! ( v1 instanceof THREE.Vector2 ) ) {
  11437. // Fall back for old constuctor signature - should be removed over time
  11438. THREE.LineCurve.oldConstructor.apply( this, arguments );
  11439. return;
  11440. }
  11441. this.v1 = v1;
  11442. this.v2 = v2;
  11443. };
  11444. THREE.LineCurve.oldConstructor = function ( x1, y1, x2, y2 ) {
  11445. this.constructor( new THREE.Vector2( x1, y1 ), new THREE.Vector2( x2, y2 ) );
  11446. };
  11447. THREE.LineCurve.prototype = new THREE.Curve();
  11448. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  11449. THREE.LineCurve.prototype.getPoint = function ( t ) {
  11450. var point = new THREE.Vector2();
  11451. point.sub( this.v2, this.v1 );
  11452. point.multiplyScalar( t ).addSelf( this.v1 );
  11453. return point;
  11454. };
  11455. // Line curve is linear, so we can overwrite default getPointAt
  11456. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  11457. return this.getPoint( u );
  11458. };
  11459. THREE.LineCurve.prototype.getTangent = function( t ) {
  11460. var tangent = new THREE.Vector2();
  11461. tangent.sub( this.v2, this.v1 );
  11462. tangent.normalize();
  11463. return tangent;
  11464. };
  11465. /**************************************************************
  11466. * Quadratic Bezier curve
  11467. **************************************************************/
  11468. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  11469. if ( !( v1 instanceof THREE.Vector2 ) ) {
  11470. var args = Array.prototype.slice.call( arguments );
  11471. v0 = new THREE.Vector2( args[ 0 ], args[ 1 ] );
  11472. v1 = new THREE.Vector2( args[ 2 ], args[ 3 ] );
  11473. v2 = new THREE.Vector2( args[ 4 ], args[ 5 ] );
  11474. }
  11475. this.v0 = v0;
  11476. this.v1 = v1;
  11477. this.v2 = v2;
  11478. };
  11479. THREE.QuadraticBezierCurve.prototype = new THREE.Curve();
  11480. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  11481. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  11482. var tx, ty;
  11483. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  11484. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  11485. return new THREE.Vector2( tx, ty );
  11486. };
  11487. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  11488. // iterate sub segments
  11489. // get lengths for sub segments
  11490. // if segment is bezier
  11491. // perform subdivisions
  11492. var tx, ty;
  11493. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  11494. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  11495. // returns unit vector
  11496. var tangent = new THREE.Vector2( tx, ty );
  11497. tangent.normalize();
  11498. return tangent;
  11499. };
  11500. /**************************************************************
  11501. * Cubic Bezier curve
  11502. **************************************************************/
  11503. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  11504. if ( ! ( v1 instanceof THREE.Vector2 ) ) {
  11505. var args = Array.prototype.slice.call( arguments );
  11506. v0 = new THREE.Vector2( args[ 0 ], args[ 1 ] );
  11507. v1 = new THREE.Vector2( args[ 2 ], args[ 3 ] );
  11508. v2 = new THREE.Vector2( args[ 4 ], args[ 5 ] );
  11509. v3 = new THREE.Vector2( args[ 6 ], args[ 7 ] );
  11510. }
  11511. this.v0 = v0;
  11512. this.v1 = v1;
  11513. this.v2 = v2;
  11514. this.v3 = v3;
  11515. };
  11516. THREE.CubicBezierCurve.prototype = new THREE.Curve();
  11517. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  11518. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  11519. var tx, ty;
  11520. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  11521. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  11522. return new THREE.Vector2( tx, ty );
  11523. };
  11524. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  11525. var tx, ty;
  11526. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  11527. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  11528. // return normal unit vector
  11529. var tangent = new THREE.Vector2( tx, ty );
  11530. tangent.normalize();
  11531. return tangent;
  11532. };
  11533. /**************************************************************
  11534. * Spline curve
  11535. **************************************************************/
  11536. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  11537. this.points = (points == undefined) ? [] : points;
  11538. };
  11539. THREE.SplineCurve.prototype = new THREE.Curve();
  11540. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  11541. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  11542. var v = new THREE.Vector2();
  11543. var c = [];
  11544. var points = this.points, point, intPoint, weight;
  11545. point = ( points.length - 1 ) * t;
  11546. intPoint = Math.floor( point );
  11547. weight = point - intPoint;
  11548. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  11549. c[ 1 ] = intPoint;
  11550. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  11551. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  11552. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  11553. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  11554. return v;
  11555. };
  11556. /**************************************************************
  11557. * Arc curve
  11558. **************************************************************/
  11559. THREE.ArcCurve = function ( aX, aY, aRadius,
  11560. aStartAngle, aEndAngle,
  11561. aClockwise ) {
  11562. this.aX = aX;
  11563. this.aY = aY;
  11564. this.aRadius = aRadius;
  11565. this.aStartAngle = aStartAngle;
  11566. this.aEndAngle = aEndAngle;
  11567. this.aClockwise = aClockwise;
  11568. };
  11569. THREE.ArcCurve.prototype = new THREE.Curve();
  11570. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  11571. THREE.ArcCurve.prototype.getPoint = function ( t ) {
  11572. var deltaAngle = this.aEndAngle - this.aStartAngle;
  11573. if ( !this.aClockwise ) {
  11574. t = 1 - t;
  11575. }
  11576. var angle = this.aStartAngle + t * deltaAngle;
  11577. var tx = this.aX + this.aRadius * Math.cos( angle );
  11578. var ty = this.aY + this.aRadius * Math.sin( angle );
  11579. return new THREE.Vector2( tx, ty );
  11580. };
  11581. /**************************************************************
  11582. * Utils
  11583. **************************************************************/
  11584. THREE.Curve.Utils = {
  11585. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  11586. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  11587. },
  11588. // Puay Bing, thanks for helping with this derivative!
  11589. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  11590. return -3 * p0 * (1 - t) * (1 - t) +
  11591. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  11592. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  11593. 3 * t * t * p3;
  11594. },
  11595. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  11596. // To check if my formulas are correct
  11597. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  11598. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  11599. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  11600. var h11 = 3 * t * t - 2 * t; // t3 − t2
  11601. return h00 + h10 + h01 + h11;
  11602. },
  11603. // Catmull-Rom
  11604. interpolate: function( p0, p1, p2, p3, t ) {
  11605. var v0 = ( p2 - p0 ) * 0.5;
  11606. var v1 = ( p3 - p1 ) * 0.5;
  11607. var t2 = t * t;
  11608. var t3 = t * t2;
  11609. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  11610. }
  11611. };
  11612. /*
  11613. getPoint DONE
  11614. getLength DONE
  11615. getLengths DONE
  11616. curve.getPoints(); DONE
  11617. curve.getPointAtArcLength(t); DONE
  11618. curve.transform(params);
  11619. curve.getTangentAt(t); DONE
  11620. */
  11621. /**************************************************************
  11622. * 3D Curves
  11623. **************************************************************/
  11624. // A Factory method for creating new curve subclasses
  11625. THREE.Curve.create = function( constructor, getPointFunc ) {
  11626. var subClass = constructor;
  11627. subClass.prototype = new THREE.Curve();
  11628. subClass.prototype.constructor = constructor;
  11629. subClass.prototype.getPoint = getPointFunc;
  11630. return subClass;
  11631. };
  11632. /**************************************************************
  11633. * Line3D
  11634. **************************************************************/
  11635. THREE.LineCurve3 = THREE.Curve.create(
  11636. function ( v1, v2 ) {
  11637. this.v1 = v1;
  11638. this.v2 = v2;
  11639. },
  11640. function ( t ) {
  11641. var r = new THREE.Vector3();
  11642. r.sub( this.v2, this.v1 ); // diff
  11643. r.multiplyScalar( t );
  11644. r.addSelf( this.v1 );
  11645. return r;
  11646. }
  11647. );
  11648. /**************************************************************
  11649. * Quadratic Bezier 3D curve
  11650. **************************************************************/
  11651. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  11652. function ( v0, v1, v2 ) {
  11653. this.v0 = v0;
  11654. this.v1 = v1;
  11655. this.v2 = v2;
  11656. },
  11657. function ( t ) {
  11658. var tx, ty, tz;
  11659. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  11660. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  11661. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  11662. return new THREE.Vector3( tx, ty, tz );
  11663. }
  11664. );
  11665. /**************************************************************
  11666. * Cubic Bezier 3D curve
  11667. **************************************************************/
  11668. THREE.CubicBezierCurve3 = THREE.Curve.create(
  11669. function ( v0, v1, v2, v3 ) {
  11670. this.v0 = v0;
  11671. this.v1 = v1;
  11672. this.v2 = v2;
  11673. this.v3 = v3;
  11674. },
  11675. function ( t ) {
  11676. var tx, ty, tz;
  11677. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  11678. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  11679. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  11680. return new THREE.Vector3( tx, ty, tz );
  11681. }
  11682. );
  11683. /**************************************************************
  11684. * Spline 3D curve
  11685. **************************************************************/
  11686. THREE.SplineCurve3 = THREE.Curve.create(
  11687. function ( points /* array of Vector3 */) {
  11688. this.points = (points == undefined) ? [] : points;
  11689. },
  11690. function ( t ) {
  11691. var v = new THREE.Vector3();
  11692. var c = [];
  11693. var points = this.points, point, intPoint, weight;
  11694. point = ( points.length - 1 ) * t;
  11695. intPoint = Math.floor( point );
  11696. weight = point - intPoint;
  11697. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  11698. c[ 1 ] = intPoint;
  11699. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  11700. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  11701. var pt0 = points[ c[0] ],
  11702. pt1 = points[ c[1] ],
  11703. pt2 = points[ c[2] ],
  11704. pt3 = points[ c[3] ];
  11705. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  11706. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  11707. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  11708. return v;
  11709. }
  11710. );
  11711. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  11712. // var v = new THREE.Vector3();
  11713. // var c = [];
  11714. // var points = this.points, point, intPoint, weight;
  11715. // point = ( points.length - 1 ) * t;
  11716. // intPoint = Math.floor( point );
  11717. // weight = point - intPoint;
  11718. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  11719. // c[ 1 ] = intPoint;
  11720. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  11721. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  11722. // var pt0 = points[ c[0] ],
  11723. // pt1 = points[ c[1] ],
  11724. // pt2 = points[ c[2] ],
  11725. // pt3 = points[ c[3] ];
  11726. // // t = weight;
  11727. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  11728. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  11729. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  11730. // return v;
  11731. // }
  11732. /**************************************************************
  11733. * Closed Spline 3D curve
  11734. **************************************************************/
  11735. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  11736. function ( points /* array of Vector3 */) {
  11737. this.points = (points == undefined) ? [] : points;
  11738. },
  11739. function ( t ) {
  11740. var v = new THREE.Vector3();
  11741. var c = [];
  11742. var points = this.points, point, intPoint, weight;
  11743. point = ( points.length - 0 ) * t;
  11744. // This needs to be from 0-length +1
  11745. intPoint = Math.floor( point );
  11746. weight = point - intPoint;
  11747. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  11748. c[ 0 ] = ( intPoint - 1 ) % points.length;
  11749. c[ 1 ] = ( intPoint ) % points.length;
  11750. c[ 2 ] = ( intPoint + 1 ) % points.length;
  11751. c[ 3 ] = ( intPoint + 2 ) % points.length;
  11752. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  11753. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  11754. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  11755. return v;
  11756. }
  11757. );/**
  11758. * @author zz85 / http://www.lab4games.net/zz85/blog
  11759. *
  11760. **/
  11761. /**************************************************************
  11762. * Curved Path - a curve path is simply a array of connected
  11763. * curves, but retains the api of a curve
  11764. **************************************************************/
  11765. THREE.CurvePath = function () {
  11766. this.curves = [];
  11767. this.bends = [];
  11768. this.autoClose = false; // Automatically closes the path
  11769. };
  11770. THREE.CurvePath.prototype = new THREE.Curve();
  11771. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  11772. THREE.CurvePath.prototype.add = function ( curve ) {
  11773. this.curves.push( curve );
  11774. };
  11775. THREE.CurvePath.prototype.checkConnection = function() {
  11776. // TODO
  11777. // If the ending of curve is not connected to the starting
  11778. // or the next curve, then, this is not a real path
  11779. };
  11780. THREE.CurvePath.prototype.closePath = function() {
  11781. // TODO Test
  11782. // and verify for vector3 (needs to implement equals)
  11783. // Add a line curve if start and end of lines are not connected
  11784. var startPoint = this.curves[0].getPoint(0);
  11785. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  11786. if (!startPoint.equals(endPoint)) {
  11787. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  11788. }
  11789. };
  11790. // To get accurate point with reference to
  11791. // entire path distance at time t,
  11792. // following has to be done:
  11793. // 1. Length of each sub path have to be known
  11794. // 2. Locate and identify type of curve
  11795. // 3. Get t for the curve
  11796. // 4. Return curve.getPointAt(t')
  11797. THREE.CurvePath.prototype.getPoint = function( t ) {
  11798. var d = t * this.getLength();
  11799. var curveLengths = this.getCurveLengths();
  11800. var i = 0, diff, curve;
  11801. // To think about boundaries points.
  11802. while ( i < curveLengths.length ) {
  11803. if ( curveLengths[ i ] >= d ) {
  11804. diff = curveLengths[ i ] - d;
  11805. curve = this.curves[ i ];
  11806. var u = 1 - diff / curve.getLength();
  11807. return curve.getPointAt( u );
  11808. break;
  11809. }
  11810. i ++;
  11811. }
  11812. return null;
  11813. // loop where sum != 0, sum > d , sum+1 <d
  11814. };
  11815. /*
  11816. THREE.CurvePath.prototype.getTangent = function( t ) {
  11817. };*/
  11818. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11819. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11820. // getPoint() depends on getLength
  11821. THREE.CurvePath.prototype.getLength = function() {
  11822. var lens = this.getCurveLengths();
  11823. return lens[ lens.length - 1 ];
  11824. };
  11825. // Compute lengths and cache them
  11826. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11827. THREE.CurvePath.prototype.getCurveLengths = function() {
  11828. // We use cache values if curves and cache array are same length
  11829. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  11830. return this.cacheLengths;
  11831. };
  11832. // Get length of subsurve
  11833. // Push sums into cached array
  11834. var lengths = [], sums = 0;
  11835. var i, il = this.curves.length;
  11836. for ( i = 0; i < il; i ++ ) {
  11837. sums += this.curves[ i ].getLength();
  11838. lengths.push( sums );
  11839. }
  11840. this.cacheLengths = lengths;
  11841. return lengths;
  11842. };
  11843. // Returns min and max coordinates, as well as centroid
  11844. THREE.CurvePath.prototype.getBoundingBox = function () {
  11845. var points = this.getPoints();
  11846. var maxX, maxY;
  11847. var minX, minY;
  11848. maxX = maxY = Number.NEGATIVE_INFINITY;
  11849. minX = minY = Number.POSITIVE_INFINITY;
  11850. var p, i, il, sum;
  11851. sum = new THREE.Vector2();
  11852. for ( i = 0, il = points.length; i < il; i ++ ) {
  11853. p = points[ i ];
  11854. if ( p.x > maxX ) maxX = p.x;
  11855. else if ( p.x < minX ) minX = p.x;
  11856. if ( p.y > maxY ) maxY = p.y;
  11857. else if ( p.y < maxY ) minY = p.y;
  11858. sum.addSelf( p.x, p.y );
  11859. }
  11860. return {
  11861. minX: minX,
  11862. minY: minY,
  11863. maxX: maxX,
  11864. maxY: maxY,
  11865. centroid: sum.divideScalar( il )
  11866. };
  11867. };
  11868. /**************************************************************
  11869. * Create Geometries Helpers
  11870. **************************************************************/
  11871. /// Generate geometry from path points (for Line or ParticleSystem objects)
  11872. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  11873. var pts = this.getPoints( divisions, true );
  11874. return this.createGeometry( pts );
  11875. };
  11876. // Generate geometry from equidistance sampling along the path
  11877. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  11878. var pts = this.getSpacedPoints( divisions, true );
  11879. return this.createGeometry( pts );
  11880. };
  11881. THREE.CurvePath.prototype.createGeometry = function( points ) {
  11882. var geometry = new THREE.Geometry();
  11883. for( var i = 0; i < points.length; i ++ ) {
  11884. geometry.vertices.push( new THREE.Vertex( new THREE.Vector3( points[ i ].x, points[ i ].y, 0 ) ) );
  11885. }
  11886. return geometry;
  11887. };
  11888. /**************************************************************
  11889. * Bend / Wrap Helper Methods
  11890. **************************************************************/
  11891. // Wrap path / Bend modifiers?
  11892. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  11893. this.bends.push( bendpath );
  11894. };
  11895. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  11896. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  11897. var i, il;
  11898. if ( !bends ) {
  11899. bends = this.bends;
  11900. }
  11901. for ( i = 0, il = bends.length; i < il; i ++ ) {
  11902. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  11903. }
  11904. return oldPts;
  11905. };
  11906. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  11907. var oldPts = this.getSpacedPoints( segments );
  11908. var i, il;
  11909. if ( !bends ) {
  11910. bends = this.bends;
  11911. }
  11912. for ( i = 0, il = bends.length; i < il; i ++ ) {
  11913. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  11914. }
  11915. return oldPts;
  11916. };
  11917. // This returns getPoints() bend/wrapped around the contour of a path.
  11918. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  11919. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  11920. var bounds = this.getBoundingBox();
  11921. var i, il, p, oldX, oldY, xNorm;
  11922. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  11923. p = oldPts[ i ];
  11924. oldX = p.x;
  11925. oldY = p.y;
  11926. xNorm = oldX / bounds.maxX;
  11927. // If using actual distance, for length > path, requires line extrusions
  11928. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  11929. xNorm = path.getUtoTmapping( xNorm, oldX );
  11930. // check for out of bounds?
  11931. var pathPt = path.getPoint( xNorm );
  11932. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  11933. p.x = pathPt.x + normal.x;
  11934. p.y = pathPt.y + normal.y;
  11935. }
  11936. return oldPts;
  11937. };
  11938. /**
  11939. * https://github.com/mrdoob/eventtarget.js/
  11940. */
  11941. THREE.EventTarget = function () {
  11942. var listeners = {};
  11943. this.addEventListener = function ( type, listener ) {
  11944. if ( listeners[ type ] == undefined ) {
  11945. listeners[ type ] = [];
  11946. }
  11947. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  11948. listeners[ type ].push( listener );
  11949. }
  11950. };
  11951. this.dispatchEvent = function ( event ) {
  11952. for ( var listener in listeners[ event.type ] ) {
  11953. listeners[ event.type ][ listener ]( event );
  11954. }
  11955. };
  11956. this.removeEventListener = function ( type, listener ) {
  11957. var index = listeners[ type ].indexOf( listener );
  11958. if ( index !== - 1 ) {
  11959. listeners[ type ].splice( index, 1 );
  11960. }
  11961. };
  11962. };
  11963. /**
  11964. * @author alteredq / http://alteredqualia.com/
  11965. */
  11966. THREE.Gyroscope = function () {
  11967. THREE.Object3D.call( this );
  11968. };
  11969. THREE.Gyroscope.prototype = new THREE.Object3D();
  11970. THREE.Gyroscope.prototype.constructor = THREE.Gyroscope;
  11971. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  11972. this.matrixAutoUpdate && this.updateMatrix();
  11973. // update matrixWorld
  11974. if ( this.matrixWorldNeedsUpdate || force ) {
  11975. if ( this.parent ) {
  11976. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  11977. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  11978. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  11979. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  11980. } else {
  11981. this.matrixWorld.copy( this.matrix );
  11982. }
  11983. this.matrixWorldNeedsUpdate = false;
  11984. force = true;
  11985. }
  11986. // update children
  11987. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  11988. this.children[ i ].updateMatrixWorld( force );
  11989. }
  11990. };
  11991. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  11992. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  11993. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  11994. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  11995. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  11996. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  11997. /**
  11998. * @author zz85 / http://www.lab4games.net/zz85/blog
  11999. * Creates free form 2d path using series of points, lines or curves.
  12000. *
  12001. **/
  12002. THREE.Path = function ( points ) {
  12003. THREE.CurvePath.call(this);
  12004. this.actions = [];
  12005. if ( points ) {
  12006. this.fromPoints( points );
  12007. }
  12008. };
  12009. THREE.Path.prototype = new THREE.CurvePath();
  12010. THREE.Path.prototype.constructor = THREE.Path;
  12011. THREE.PathActions = {
  12012. MOVE_TO: 'moveTo',
  12013. LINE_TO: 'lineTo',
  12014. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  12015. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  12016. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  12017. ARC: 'arc' // Circle
  12018. };
  12019. // TODO Clean up PATH API
  12020. // Create path using straight lines to connect all points
  12021. // - vectors: array of Vector2
  12022. THREE.Path.prototype.fromPoints = function ( vectors ) {
  12023. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  12024. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  12025. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  12026. };
  12027. };
  12028. // startPath() endPath()?
  12029. THREE.Path.prototype.moveTo = function ( x, y ) {
  12030. var args = Array.prototype.slice.call( arguments );
  12031. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  12032. };
  12033. THREE.Path.prototype.lineTo = function ( x, y ) {
  12034. var args = Array.prototype.slice.call( arguments );
  12035. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12036. var x0 = lastargs[ lastargs.length - 2 ];
  12037. var y0 = lastargs[ lastargs.length - 1 ];
  12038. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  12039. this.curves.push( curve );
  12040. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  12041. };
  12042. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  12043. var args = Array.prototype.slice.call( arguments );
  12044. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12045. var x0 = lastargs[ lastargs.length - 2 ];
  12046. var y0 = lastargs[ lastargs.length - 1 ];
  12047. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  12048. new THREE.Vector2( aCPx, aCPy ),
  12049. new THREE.Vector2( aX, aY ) );
  12050. this.curves.push( curve );
  12051. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  12052. };
  12053. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  12054. aCP2x, aCP2y,
  12055. aX, aY ) {
  12056. var args = Array.prototype.slice.call( arguments );
  12057. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12058. var x0 = lastargs[ lastargs.length - 2 ];
  12059. var y0 = lastargs[ lastargs.length - 1 ];
  12060. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  12061. new THREE.Vector2( aCP1x, aCP1y ),
  12062. new THREE.Vector2( aCP2x, aCP2y ),
  12063. new THREE.Vector2( aX, aY ) );
  12064. this.curves.push( curve );
  12065. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  12066. };
  12067. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  12068. var args = Array.prototype.slice.call( arguments );
  12069. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12070. var x0 = lastargs[ lastargs.length - 2 ];
  12071. var y0 = lastargs[ lastargs.length - 1 ];
  12072. //---
  12073. var npts = [ new THREE.Vector2( x0, y0 ) ];
  12074. Array.prototype.push.apply( npts, pts );
  12075. var curve = new THREE.SplineCurve( npts );
  12076. this.curves.push( curve );
  12077. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  12078. };
  12079. // FUTURE: Change the API or follow canvas API?
  12080. // TODO ARC ( x, y, x - radius, y - radius, startAngle, endAngle )
  12081. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  12082. aStartAngle, aEndAngle, aClockwise ) {
  12083. var args = Array.prototype.slice.call( arguments );
  12084. var laste = this.actions[ this.actions.length - 1];
  12085. var curve = new THREE.ArcCurve( laste.x + aX, laste.y + aY, aRadius,
  12086. aStartAngle, aEndAngle, aClockwise );
  12087. this.curves.push( curve );
  12088. // All of the other actions look to the last two elements in the list to
  12089. // find the ending point, so we need to append them.
  12090. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  12091. args.push(lastPoint.x);
  12092. args.push(lastPoint.y);
  12093. this.actions.push( { action: THREE.PathActions.ARC, args: args } );
  12094. };
  12095. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  12096. aStartAngle, aEndAngle, aClockwise ) {
  12097. var args = Array.prototype.slice.call( arguments );
  12098. var curve = new THREE.ArcCurve( aX, aY, aRadius,
  12099. aStartAngle, aEndAngle, aClockwise );
  12100. this.curves.push( curve );
  12101. // console.log( 'arc', args );
  12102. // All of the other actions look to the last two elements in the list to
  12103. // find the ending point, so we need to append them.
  12104. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  12105. args.push(lastPoint.x);
  12106. args.push(lastPoint.y);
  12107. this.actions.push( { action: THREE.PathActions.ARC, args: args } );
  12108. };
  12109. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  12110. if ( ! divisions ) divisions = 40;
  12111. var points = [];
  12112. for ( var i = 0; i < divisions; i ++ ) {
  12113. points.push( this.getPoint( i / divisions ) );
  12114. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  12115. }
  12116. // if ( closedPath ) {
  12117. //
  12118. // points.push( points[ 0 ] );
  12119. //
  12120. // }
  12121. return points;
  12122. };
  12123. /* Return an array of vectors based on contour of the path */
  12124. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  12125. if (this.useSpacedPoints) {
  12126. console.log('tata');
  12127. return this.getSpacedPoints( divisions, closedPath );
  12128. }
  12129. divisions = divisions || 12;
  12130. var points = [];
  12131. var i, il, item, action, args;
  12132. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  12133. laste, j,
  12134. t, tx, ty;
  12135. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  12136. item = this.actions[ i ];
  12137. action = item.action;
  12138. args = item.args;
  12139. switch( action ) {
  12140. case THREE.PathActions.MOVE_TO:
  12141. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  12142. break;
  12143. case THREE.PathActions.LINE_TO:
  12144. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  12145. break;
  12146. case THREE.PathActions.QUADRATIC_CURVE_TO:
  12147. cpx = args[ 2 ];
  12148. cpy = args[ 3 ];
  12149. cpx1 = args[ 0 ];
  12150. cpy1 = args[ 1 ];
  12151. if ( points.length > 0 ) {
  12152. laste = points[ points.length - 1 ];
  12153. cpx0 = laste.x;
  12154. cpy0 = laste.y;
  12155. } else {
  12156. laste = this.actions[ i - 1 ].args;
  12157. cpx0 = laste[ laste.length - 2 ];
  12158. cpy0 = laste[ laste.length - 1 ];
  12159. }
  12160. for ( j = 1; j <= divisions; j ++ ) {
  12161. t = j / divisions;
  12162. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  12163. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  12164. points.push( new THREE.Vector2( tx, ty ) );
  12165. }
  12166. break;
  12167. case THREE.PathActions.BEZIER_CURVE_TO:
  12168. cpx = args[ 4 ];
  12169. cpy = args[ 5 ];
  12170. cpx1 = args[ 0 ];
  12171. cpy1 = args[ 1 ];
  12172. cpx2 = args[ 2 ];
  12173. cpy2 = args[ 3 ];
  12174. if ( points.length > 0 ) {
  12175. laste = points[ points.length - 1 ];
  12176. cpx0 = laste.x;
  12177. cpy0 = laste.y;
  12178. } else {
  12179. laste = this.actions[ i - 1 ].args;
  12180. cpx0 = laste[ laste.length - 2 ];
  12181. cpy0 = laste[ laste.length - 1 ];
  12182. }
  12183. for ( j = 1; j <= divisions; j ++ ) {
  12184. t = j / divisions;
  12185. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  12186. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  12187. points.push( new THREE.Vector2( tx, ty ) );
  12188. }
  12189. break;
  12190. case THREE.PathActions.CSPLINE_THRU:
  12191. laste = this.actions[ i - 1 ].args;
  12192. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  12193. var spts = [ last ];
  12194. var n = divisions * args[ 0 ].length;
  12195. spts = spts.concat( args[ 0 ] );
  12196. var spline = new THREE.SplineCurve( spts );
  12197. for ( j = 1; j <= n; j ++ ) {
  12198. points.push( spline.getPointAt( j / n ) ) ;
  12199. }
  12200. break;
  12201. case THREE.PathActions.ARC:
  12202. laste = this.actions[ i - 1 ].args;
  12203. var aX = args[ 0 ], aY = args[ 1 ],
  12204. aRadius = args[ 2 ],
  12205. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  12206. aClockwise = !!args[ 5 ];
  12207. var deltaAngle = aEndAngle - aStartAngle;
  12208. var angle;
  12209. var tdivisions = divisions * 2;
  12210. for ( j = 1; j <= tdivisions; j ++ ) {
  12211. t = j / tdivisions;
  12212. if ( ! aClockwise ) {
  12213. t = 1 - t;
  12214. }
  12215. angle = aStartAngle + t * deltaAngle;
  12216. tx = aX + aRadius * Math.cos( angle );
  12217. ty = aY + aRadius * Math.sin( angle );
  12218. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  12219. points.push( new THREE.Vector2( tx, ty ) );
  12220. }
  12221. //console.log(points);
  12222. break;
  12223. } // end switch
  12224. }
  12225. // Normalize to remove the closing point by default.
  12226. var lastPoint = points[ points.length - 1];
  12227. var EPSILON = 0.0000000001;
  12228. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  12229. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  12230. points.splice( points.length - 1, 1);
  12231. if ( closedPath ) {
  12232. points.push( points[ 0 ] );
  12233. }
  12234. return points;
  12235. };
  12236. // This was used for testing purposes. Should be removed soon.
  12237. THREE.Path.prototype.transform = function( path, segments ) {
  12238. var bounds = this.getBoundingBox();
  12239. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  12240. //console.log( path.cacheArcLengths() );
  12241. //path.getLengths(400);
  12242. //segments = 40;
  12243. return this.getWrapPoints( oldPts, path );
  12244. };
  12245. // Read http://www.tinaja.com/glib/nonlingr.pdf
  12246. // nonlinear transforms
  12247. THREE.Path.prototype.nltransform = function( a, b, c, d, e, f ) {
  12248. // a - horizontal size
  12249. // b - lean
  12250. // c - x offset
  12251. // d - vertical size
  12252. // e - climb
  12253. // f - y offset
  12254. var oldPts = this.getPoints();
  12255. var i, il, p, oldX, oldY;
  12256. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  12257. p = oldPts[i];
  12258. oldX = p.x;
  12259. oldY = p.y;
  12260. p.x = a * oldX + b * oldY + c;
  12261. p.y = d * oldY + e * oldX + f;
  12262. }
  12263. return oldPts;
  12264. };
  12265. // FUTURE Export JSON Format
  12266. /* Draws this path onto a 2d canvas easily */
  12267. THREE.Path.prototype.debug = function( canvas ) {
  12268. var bounds = this.getBoundingBox();
  12269. if ( !canvas ) {
  12270. canvas = document.createElement( "canvas" );
  12271. canvas.setAttribute( 'width', bounds.maxX + 100 );
  12272. canvas.setAttribute( 'height', bounds.maxY + 100 );
  12273. document.body.appendChild( canvas );
  12274. }
  12275. var ctx = canvas.getContext( "2d" );
  12276. ctx.fillStyle = "white";
  12277. ctx.fillRect( 0, 0, canvas.width, canvas.height );
  12278. ctx.strokeStyle = "black";
  12279. ctx.beginPath();
  12280. var i, il, item, action, args;
  12281. // Debug Path
  12282. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  12283. item = this.actions[ i ];
  12284. args = item.args;
  12285. action = item.action;
  12286. // Short hand for now
  12287. if ( action != THREE.PathActions.CSPLINE_THRU ) {
  12288. ctx[ action ].apply( ctx, args );
  12289. }
  12290. /*
  12291. switch ( action ) {
  12292. case THREE.PathActions.MOVE_TO:
  12293. ctx[ action ]( args[ 0 ], args[ 1 ] );
  12294. break;
  12295. case THREE.PathActions.LINE_TO:
  12296. ctx[ action ]( args[ 0 ], args[ 1 ] );
  12297. break;
  12298. case THREE.PathActions.QUADRATIC_CURVE_TO:
  12299. ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ] );
  12300. break;
  12301. case THREE.PathActions.CUBIC_CURVE_TO:
  12302. ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ], args[ 4 ], args[ 5 ] );
  12303. break;
  12304. }
  12305. */
  12306. }
  12307. ctx.stroke();
  12308. ctx.closePath();
  12309. // Debug Points
  12310. ctx.strokeStyle = "red";
  12311. /* TO CLEAN UP */
  12312. var p, points = this.getPoints();
  12313. for ( i = 0, il = points.length; i < il; i ++ ) {
  12314. p = points[ i ];
  12315. ctx.beginPath();
  12316. ctx.arc( p.x, p.y, 1.5, 0, Math.PI * 2, false );
  12317. ctx.stroke();
  12318. ctx.closePath();
  12319. }
  12320. };
  12321. // Breaks path into shapes
  12322. THREE.Path.prototype.toShapes = function() {
  12323. var i, il, item, action, args;
  12324. var subPaths = [], lastPath = new THREE.Path();
  12325. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  12326. item = this.actions[ i ];
  12327. args = item.args;
  12328. action = item.action;
  12329. if ( action == THREE.PathActions.MOVE_TO ) {
  12330. if ( lastPath.actions.length != 0 ) {
  12331. subPaths.push( lastPath );
  12332. lastPath = new THREE.Path();
  12333. }
  12334. }
  12335. lastPath[ action ].apply( lastPath, args );
  12336. }
  12337. if ( lastPath.actions.length != 0 ) {
  12338. subPaths.push( lastPath );
  12339. }
  12340. // console.log(subPaths);
  12341. if ( subPaths.length == 0 ) return [];
  12342. var tmpPath, tmpShape, shapes = [];
  12343. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  12344. // console.log("Holes first", holesFirst);
  12345. if ( subPaths.length == 1) {
  12346. tmpPath = subPaths[0];
  12347. tmpShape = new THREE.Shape();
  12348. tmpShape.actions = tmpPath.actions;
  12349. tmpShape.curves = tmpPath.curves;
  12350. shapes.push( tmpShape );
  12351. return shapes;
  12352. };
  12353. if ( holesFirst ) {
  12354. tmpShape = new THREE.Shape();
  12355. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  12356. tmpPath = subPaths[ i ];
  12357. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  12358. tmpShape.actions = tmpPath.actions;
  12359. tmpShape.curves = tmpPath.curves;
  12360. shapes.push( tmpShape );
  12361. tmpShape = new THREE.Shape();
  12362. //console.log('cw', i);
  12363. } else {
  12364. tmpShape.holes.push( tmpPath );
  12365. //console.log('ccw', i);
  12366. }
  12367. }
  12368. } else {
  12369. // Shapes first
  12370. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  12371. tmpPath = subPaths[ i ];
  12372. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  12373. if ( tmpShape ) shapes.push( tmpShape );
  12374. tmpShape = new THREE.Shape();
  12375. tmpShape.actions = tmpPath.actions;
  12376. tmpShape.curves = tmpPath.curves;
  12377. } else {
  12378. tmpShape.holes.push( tmpPath );
  12379. }
  12380. }
  12381. shapes.push( tmpShape );
  12382. }
  12383. //console.log("shape", shapes);
  12384. return shapes;
  12385. };
  12386. /**
  12387. * @author zz85 / http://www.lab4games.net/zz85/blog
  12388. * Defines a 2d shape plane using paths.
  12389. **/
  12390. // STEP 1 Create a path.
  12391. // STEP 2 Turn path into shape.
  12392. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  12393. // STEP 3a - Extract points from each shape, turn to vertices
  12394. // STEP 3b - Triangulate each shape, add faces.
  12395. THREE.Shape = function ( ) {
  12396. THREE.Path.apply( this, arguments );
  12397. this.holes = [];
  12398. };
  12399. THREE.Shape.prototype = new THREE.Path();
  12400. THREE.Shape.prototype.constructor = THREE.Path;
  12401. // Convenience method to return ExtrudeGeometry
  12402. THREE.Shape.prototype.extrude = function ( options ) {
  12403. var extruded = new THREE.ExtrudeGeometry( this, options );
  12404. return extruded;
  12405. };
  12406. // Get points of holes
  12407. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  12408. var i, il = this.holes.length, holesPts = [];
  12409. for ( i = 0; i < il; i ++ ) {
  12410. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  12411. }
  12412. return holesPts;
  12413. };
  12414. // Get points of holes (spaced by regular distance)
  12415. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  12416. var i, il = this.holes.length, holesPts = [];
  12417. for ( i = 0; i < il; i ++ ) {
  12418. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  12419. }
  12420. return holesPts;
  12421. };
  12422. // Get points of shape and holes (keypoints based on segments parameter)
  12423. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  12424. return {
  12425. shape: this.getTransformedPoints( divisions ),
  12426. holes: this.getPointsHoles( divisions )
  12427. };
  12428. };
  12429. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  12430. if (this.useSpacedPoints) {
  12431. return this.extractAllSpacedPoints(divisions);
  12432. }
  12433. return this.extractAllPoints(divisions);
  12434. };
  12435. //
  12436. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  12437. //
  12438. // return {
  12439. //
  12440. // shape: this.transform( bend, divisions ),
  12441. // holes: this.getPointsHoles( divisions, bend )
  12442. //
  12443. // };
  12444. //
  12445. // };
  12446. // Get points of shape and holes (spaced by regular distance)
  12447. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  12448. return {
  12449. shape: this.getTransformedSpacedPoints( divisions ),
  12450. holes: this.getSpacedPointsHoles( divisions )
  12451. };
  12452. };
  12453. /**************************************************************
  12454. * Utils
  12455. **************************************************************/
  12456. THREE.Shape.Utils = {
  12457. /*
  12458. contour - array of vector2 for contour
  12459. holes - array of array of vector2
  12460. */
  12461. removeHoles: function ( contour, holes ) {
  12462. var shape = contour.concat(); // work on this shape
  12463. var allpoints = shape.concat();
  12464. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  12465. var prevShapeVert, nextShapeVert,
  12466. prevHoleVert, nextHoleVert,
  12467. holeIndex, shapeIndex,
  12468. shapeId, shapeGroup,
  12469. h, h2,
  12470. hole, shortest, d,
  12471. p, pts1, pts2,
  12472. tmpShape1, tmpShape2,
  12473. tmpHole1, tmpHole2,
  12474. verts = [];
  12475. for ( h = 0; h < holes.length; h ++ ) {
  12476. hole = holes[ h ];
  12477. /*
  12478. shapeholes[ h ].concat(); // preserves original
  12479. holes.push( hole );
  12480. */
  12481. Array.prototype.push.apply( allpoints, hole );
  12482. shortest = Number.POSITIVE_INFINITY;
  12483. // Find the shortest pair of pts between shape and hole
  12484. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  12485. // Using distanceToSquared() intead of distanceTo() should speed a little
  12486. // since running square roots operations are reduced.
  12487. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  12488. pts1 = hole[ h2 ];
  12489. var dist = [];
  12490. for ( p = 0; p < shape.length; p++ ) {
  12491. pts2 = shape[ p ];
  12492. d = pts1.distanceToSquared( pts2 );
  12493. dist.push( d );
  12494. if ( d < shortest ) {
  12495. shortest = d;
  12496. holeIndex = h2;
  12497. shapeIndex = p;
  12498. }
  12499. }
  12500. }
  12501. //console.log("shortest", shortest, dist);
  12502. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  12503. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  12504. var areaapts = [
  12505. hole[ holeIndex ],
  12506. shape[ shapeIndex ],
  12507. shape[ prevShapeVert ]
  12508. ];
  12509. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  12510. var areabpts = [
  12511. hole[ holeIndex ],
  12512. hole[ prevHoleVert ],
  12513. shape[ shapeIndex ]
  12514. ];
  12515. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  12516. var shapeOffset = 1;
  12517. var holeOffset = -1;
  12518. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  12519. shapeIndex += shapeOffset;
  12520. holeIndex += holeOffset;
  12521. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  12522. shapeIndex %= shape.length;
  12523. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  12524. holeIndex %= hole.length;
  12525. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  12526. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  12527. areaapts = [
  12528. hole[ holeIndex ],
  12529. shape[ shapeIndex ],
  12530. shape[ prevShapeVert ]
  12531. ];
  12532. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  12533. areabpts = [
  12534. hole[ holeIndex ],
  12535. hole[ prevHoleVert ],
  12536. shape[ shapeIndex ]
  12537. ];
  12538. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  12539. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  12540. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  12541. // In case areas are not correct.
  12542. //console.log("USE THIS");
  12543. shapeIndex = oldShapeIndex;
  12544. holeIndex = oldHoleIndex ;
  12545. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  12546. shapeIndex %= shape.length;
  12547. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  12548. holeIndex %= hole.length;
  12549. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  12550. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  12551. } else {
  12552. //console.log("USE THAT ")
  12553. }
  12554. tmpShape1 = shape.slice( 0, shapeIndex );
  12555. tmpShape2 = shape.slice( shapeIndex );
  12556. tmpHole1 = hole.slice( holeIndex );
  12557. tmpHole2 = hole.slice( 0, holeIndex );
  12558. // Should check orders here again?
  12559. var trianglea = [
  12560. hole[ holeIndex ],
  12561. shape[ shapeIndex ],
  12562. shape[ prevShapeVert ]
  12563. ];
  12564. var triangleb = [
  12565. hole[ holeIndex ] ,
  12566. hole[ prevHoleVert ],
  12567. shape[ shapeIndex ]
  12568. ];
  12569. verts.push( trianglea );
  12570. verts.push( triangleb );
  12571. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  12572. }
  12573. return {
  12574. shape:shape, /* shape with no holes */
  12575. isolatedPts: verts, /* isolated faces */
  12576. allpoints: allpoints
  12577. }
  12578. },
  12579. triangulateShape: function ( contour, holes ) {
  12580. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  12581. var shape = shapeWithoutHoles.shape,
  12582. allpoints = shapeWithoutHoles.allpoints,
  12583. isolatedPts = shapeWithoutHoles.isolatedPts;
  12584. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  12585. // 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.
  12586. //console.log( "triangles",triangles, triangles.length );
  12587. //console.log( "allpoints",allpoints, allpoints.length );
  12588. var i, il, f, face,
  12589. key, index,
  12590. allPointsMap = {},
  12591. isolatedPointsMap = {};
  12592. // prepare all points map
  12593. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  12594. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  12595. if ( allPointsMap[ key ] !== undefined ) {
  12596. console.log( "Duplicate point", key );
  12597. }
  12598. allPointsMap[ key ] = i;
  12599. }
  12600. // check all face vertices against all points map
  12601. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  12602. face = triangles[ i ];
  12603. for ( f = 0; f < 3; f ++ ) {
  12604. key = face[ f ].x + ":" + face[ f ].y;
  12605. index = allPointsMap[ key ];
  12606. if ( index !== undefined ) {
  12607. face[ f ] = index;
  12608. }
  12609. }
  12610. }
  12611. // check isolated points vertices against all points map
  12612. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  12613. face = isolatedPts[ i ];
  12614. for ( f = 0; f < 3; f ++ ) {
  12615. key = face[ f ].x + ":" + face[ f ].y;
  12616. index = allPointsMap[ key ];
  12617. if ( index !== undefined ) {
  12618. face[ f ] = index;
  12619. }
  12620. }
  12621. }
  12622. return triangles.concat( isolatedPts );
  12623. }, // end triangulate shapes
  12624. /*
  12625. triangulate2 : function( pts, holes ) {
  12626. // For use with Poly2Tri.js
  12627. var allpts = pts.concat();
  12628. var shape = [];
  12629. for (var p in pts) {
  12630. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  12631. }
  12632. var swctx = new js.poly2tri.SweepContext(shape);
  12633. for (var h in holes) {
  12634. var aHole = holes[h];
  12635. var newHole = []
  12636. for (i in aHole) {
  12637. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  12638. allpts.push(aHole[i]);
  12639. }
  12640. swctx.AddHole(newHole);
  12641. }
  12642. var find;
  12643. var findIndexForPt = function (pt) {
  12644. find = new THREE.Vector2(pt.x, pt.y);
  12645. var p;
  12646. for (p=0, pl = allpts.length; p<pl; p++) {
  12647. if (allpts[p].equals(find)) return p;
  12648. }
  12649. return -1;
  12650. };
  12651. // triangulate
  12652. js.poly2tri.sweep.Triangulate(swctx);
  12653. var triangles = swctx.GetTriangles();
  12654. var tr ;
  12655. var facesPts = [];
  12656. for (var t in triangles) {
  12657. tr = triangles[t];
  12658. facesPts.push([
  12659. findIndexForPt(tr.GetPoint(0)),
  12660. findIndexForPt(tr.GetPoint(1)),
  12661. findIndexForPt(tr.GetPoint(2))
  12662. ]);
  12663. }
  12664. // console.log(facesPts);
  12665. // console.log("triangles", triangles.length, triangles);
  12666. // Returns array of faces with 3 element each
  12667. return facesPts;
  12668. },
  12669. */
  12670. isClockWise: function ( pts ) {
  12671. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  12672. },
  12673. // Bezier Curves formulas obtained from
  12674. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  12675. // Quad Bezier Functions
  12676. b2p0: function ( t, p ) {
  12677. var k = 1 - t;
  12678. return k * k * p;
  12679. },
  12680. b2p1: function ( t, p ) {
  12681. return 2 * ( 1 - t ) * t * p;
  12682. },
  12683. b2p2: function ( t, p ) {
  12684. return t * t * p;
  12685. },
  12686. b2: function ( t, p0, p1, p2 ) {
  12687. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  12688. },
  12689. // Cubic Bezier Functions
  12690. b3p0: function ( t, p ) {
  12691. var k = 1 - t;
  12692. return k * k * k * p;
  12693. },
  12694. b3p1: function ( t, p ) {
  12695. var k = 1 - t;
  12696. return 3 * k * k * t * p;
  12697. },
  12698. b3p2: function ( t, p ) {
  12699. var k = 1 - t;
  12700. return 3 * k * t * t * p;
  12701. },
  12702. b3p3: function ( t, p ) {
  12703. return t * t * t * p;
  12704. },
  12705. b3: function ( t, p0, p1, p2, p3 ) {
  12706. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  12707. }
  12708. };
  12709. /**
  12710. * @author zz85 / http://www.lab4games.net/zz85/blog
  12711. *
  12712. * TextPath
  12713. *
  12714. **/
  12715. THREE.TextPath = function ( text, parameters ) {
  12716. THREE.Path.call( this );
  12717. this.parameters = parameters || {};
  12718. this.set( text );
  12719. };
  12720. THREE.TextPath.prototype.set = function ( text, parameters ) {
  12721. parameters = parameters || this.parameters;
  12722. this.text = text;
  12723. var size = parameters.size !== undefined ? parameters.size : 100;
  12724. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  12725. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  12726. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  12727. var style = parameters.style !== undefined ? parameters.style : "normal";
  12728. THREE.FontUtils.size = size;
  12729. THREE.FontUtils.divisions = curveSegments;
  12730. THREE.FontUtils.face = font;
  12731. THREE.FontUtils.weight = weight;
  12732. THREE.FontUtils.style = style;
  12733. };
  12734. THREE.TextPath.prototype.toShapes = function () {
  12735. // Get a Font data json object
  12736. var data = THREE.FontUtils.drawText( this.text );
  12737. var paths = data.paths;
  12738. var shapes = [];
  12739. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  12740. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  12741. }
  12742. return shapes;
  12743. //console.log(path);
  12744. //console.log(fontShapes);
  12745. // Either find actions or curves.
  12746. //var text3d = new THREE.ExtrudeGeometry( shapes , { amount: 20, bevelEnabled:true, bevelThickness:3 } );
  12747. //return text3d;
  12748. };
  12749. /**
  12750. * @author mikael emtinger / http://gomo.se/
  12751. */
  12752. THREE.AnimationHandler = (function() {
  12753. var playing = [];
  12754. var library = {};
  12755. var that = {};
  12756. //--- update ---
  12757. that.update = function( deltaTimeMS ) {
  12758. for( var i = 0; i < playing.length; i++ )
  12759. playing[ i ].update( deltaTimeMS );
  12760. };
  12761. //--- add ---
  12762. that.addToUpdate = function( animation ) {
  12763. if( playing.indexOf( animation ) === -1 )
  12764. playing.push( animation );
  12765. };
  12766. //--- remove ---
  12767. that.removeFromUpdate = function( animation ) {
  12768. var index = playing.indexOf( animation );
  12769. if( index !== -1 )
  12770. playing.splice( index, 1 );
  12771. };
  12772. //--- add ---
  12773. that.add = function( data ) {
  12774. if( library[ data.name ] !== undefined )
  12775. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  12776. library[ data.name ] = data;
  12777. initData( data );
  12778. };
  12779. //--- get ---
  12780. that.get = function( name ) {
  12781. if( typeof name === "string" ) {
  12782. if( library[ name ] ) {
  12783. return library[ name ];
  12784. } else {
  12785. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  12786. return null;
  12787. }
  12788. } else {
  12789. // todo: add simple tween library
  12790. }
  12791. };
  12792. //--- parse ---
  12793. that.parse = function( root ) {
  12794. // setup hierarchy
  12795. var hierarchy = [];
  12796. if ( root instanceof THREE.SkinnedMesh ) {
  12797. for( var b = 0; b < root.bones.length; b++ ) {
  12798. hierarchy.push( root.bones[ b ] );
  12799. }
  12800. } else {
  12801. parseRecurseHierarchy( root, hierarchy );
  12802. }
  12803. return hierarchy;
  12804. };
  12805. var parseRecurseHierarchy = function( root, hierarchy ) {
  12806. hierarchy.push( root );
  12807. for( var c = 0; c < root.children.length; c++ )
  12808. parseRecurseHierarchy( root.children[ c ], hierarchy );
  12809. }
  12810. //--- init data ---
  12811. var initData = function( data ) {
  12812. if( data.initialized === true )
  12813. return;
  12814. // loop through all keys
  12815. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  12816. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12817. // remove minus times
  12818. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  12819. data.hierarchy[ h ].keys[ k ].time = 0;
  12820. // create quaternions
  12821. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  12822. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  12823. var quat = data.hierarchy[ h ].keys[ k ].rot;
  12824. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  12825. }
  12826. }
  12827. // prepare morph target keys
  12828. if( data.hierarchy[h].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  12829. // get all used
  12830. var usedMorphTargets = {};
  12831. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12832. for( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  12833. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  12834. usedMorphTargets[ morphTargetName ] = -1;
  12835. }
  12836. }
  12837. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  12838. // set all used on all frames
  12839. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12840. var influences = {};
  12841. for( var morphTargetName in usedMorphTargets ) {
  12842. for( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  12843. if( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  12844. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  12845. break;
  12846. }
  12847. }
  12848. if( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  12849. influences[ morphTargetName ] = 0;
  12850. }
  12851. }
  12852. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  12853. }
  12854. }
  12855. // remove all keys that are on the same time
  12856. for( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12857. if( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  12858. data.hierarchy[ h ].keys.splice( k, 1 );
  12859. k --;
  12860. }
  12861. }
  12862. // set index
  12863. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12864. data.hierarchy[ h ].keys[ k ].index = k;
  12865. }
  12866. }
  12867. // JIT
  12868. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  12869. data.JIT = {};
  12870. data.JIT.hierarchy = [];
  12871. for( var h = 0; h < data.hierarchy.length; h ++ )
  12872. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  12873. // done
  12874. data.initialized = true;
  12875. };
  12876. // interpolation types
  12877. that.LINEAR = 0;
  12878. that.CATMULLROM = 1;
  12879. that.CATMULLROM_FORWARD = 2;
  12880. return that;
  12881. }());
  12882. /**
  12883. * @author mikael emtinger / http://gomo.se/
  12884. * @author mrdoob / http://mrdoob.com/
  12885. * @author alteredq / http://alteredqualia.com/
  12886. */
  12887. THREE.Animation = function( root, data, interpolationType, JITCompile ) {
  12888. this.root = root;
  12889. this.data = THREE.AnimationHandler.get( data );
  12890. this.hierarchy = THREE.AnimationHandler.parse( root );
  12891. this.currentTime = 0;
  12892. this.timeScale = 1;
  12893. this.isPlaying = false;
  12894. this.isPaused = true;
  12895. this.loop = true;
  12896. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  12897. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  12898. this.points = [];
  12899. this.target = new THREE.Vector3();
  12900. };
  12901. // Play
  12902. THREE.Animation.prototype.play = function( loop, startTimeMS ) {
  12903. if( !this.isPlaying ) {
  12904. this.isPlaying = true;
  12905. this.loop = loop !== undefined ? loop : true;
  12906. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  12907. // reset key cache
  12908. var h, hl = this.hierarchy.length,
  12909. object;
  12910. for ( h = 0; h < hl; h++ ) {
  12911. object = this.hierarchy[ h ];
  12912. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  12913. object.useQuaternion = true;
  12914. }
  12915. object.matrixAutoUpdate = true;
  12916. if ( object.animationCache === undefined ) {
  12917. object.animationCache = {};
  12918. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  12919. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  12920. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  12921. }
  12922. var prevKey = object.animationCache.prevKey;
  12923. var nextKey = object.animationCache.nextKey;
  12924. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  12925. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  12926. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  12927. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  12928. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  12929. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  12930. }
  12931. this.update( 0 );
  12932. }
  12933. this.isPaused = false;
  12934. THREE.AnimationHandler.addToUpdate( this );
  12935. };
  12936. // Pause
  12937. THREE.Animation.prototype.pause = function() {
  12938. if( this.isPaused ) {
  12939. THREE.AnimationHandler.addToUpdate( this );
  12940. } else {
  12941. THREE.AnimationHandler.removeFromUpdate( this );
  12942. }
  12943. this.isPaused = !this.isPaused;
  12944. };
  12945. // Stop
  12946. THREE.Animation.prototype.stop = function() {
  12947. this.isPlaying = false;
  12948. this.isPaused = false;
  12949. THREE.AnimationHandler.removeFromUpdate( this );
  12950. // reset JIT matrix and remove cache
  12951. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  12952. if ( this.hierarchy[ h ].animationCache !== undefined ) {
  12953. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  12954. this.hierarchy[ h ].skinMatrix = this.hierarchy[ h ].animationCache.originalMatrix;
  12955. } else {
  12956. this.hierarchy[ h ].matrix = this.hierarchy[ h ].animationCache.originalMatrix;
  12957. }
  12958. delete this.hierarchy[ h ].animationCache;
  12959. }
  12960. }
  12961. };
  12962. // Update
  12963. THREE.Animation.prototype.update = function( deltaTimeMS ) {
  12964. // early out
  12965. if( !this.isPlaying ) return;
  12966. // vars
  12967. var types = [ "pos", "rot", "scl" ];
  12968. var type;
  12969. var scale;
  12970. var vector;
  12971. var prevXYZ, nextXYZ;
  12972. var prevKey, nextKey;
  12973. var object;
  12974. var animationCache;
  12975. var frame;
  12976. var JIThierarchy = this.data.JIT.hierarchy;
  12977. var currentTime, unloopedCurrentTime;
  12978. var currentPoint, forwardPoint, angle;
  12979. // update
  12980. this.currentTime += deltaTimeMS * this.timeScale;
  12981. unloopedCurrentTime = this.currentTime;
  12982. currentTime = this.currentTime = this.currentTime % this.data.length;
  12983. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  12984. // update
  12985. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  12986. object = this.hierarchy[ h ];
  12987. animationCache = object.animationCache;
  12988. // use JIT?
  12989. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  12990. if( object instanceof THREE.Bone ) {
  12991. object.skinMatrix = JIThierarchy[ h ][ frame ];
  12992. object.matrixAutoUpdate = false;
  12993. object.matrixWorldNeedsUpdate = false;
  12994. } else {
  12995. object.matrix = JIThierarchy[ h ][ frame ];
  12996. object.matrixAutoUpdate = false;
  12997. object.matrixWorldNeedsUpdate = true;
  12998. }
  12999. // use interpolation
  13000. } else {
  13001. // make sure so original matrix and not JIT matrix is set
  13002. if ( this.JITCompile ) {
  13003. if( object instanceof THREE.Bone ) {
  13004. object.skinMatrix = object.animationCache.originalMatrix;
  13005. } else {
  13006. object.matrix = object.animationCache.originalMatrix;
  13007. }
  13008. }
  13009. // loop through pos/rot/scl
  13010. for ( var t = 0; t < 3; t++ ) {
  13011. // get keys
  13012. type = types[ t ];
  13013. prevKey = animationCache.prevKey[ type ];
  13014. nextKey = animationCache.nextKey[ type ];
  13015. // switch keys?
  13016. if ( nextKey.time <= unloopedCurrentTime ) {
  13017. // did we loop?
  13018. if ( currentTime < unloopedCurrentTime ) {
  13019. if ( this.loop ) {
  13020. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  13021. nextKey = this.getNextKeyWith( type, h, 1 );
  13022. while( nextKey.time < currentTime ) {
  13023. prevKey = nextKey;
  13024. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  13025. }
  13026. } else {
  13027. this.stop();
  13028. return;
  13029. }
  13030. } else {
  13031. do {
  13032. prevKey = nextKey;
  13033. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  13034. } while( nextKey.time < currentTime )
  13035. }
  13036. animationCache.prevKey[ type ] = prevKey;
  13037. animationCache.nextKey[ type ] = nextKey;
  13038. }
  13039. object.matrixAutoUpdate = true;
  13040. object.matrixWorldNeedsUpdate = true;
  13041. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  13042. prevXYZ = prevKey[ type ];
  13043. nextXYZ = nextKey[ type ];
  13044. // check scale error
  13045. if ( scale < 0 || scale > 1 ) {
  13046. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  13047. scale = scale < 0 ? 0 : 1;
  13048. }
  13049. // interpolate
  13050. if ( type === "pos" ) {
  13051. vector = object.position;
  13052. if( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  13053. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  13054. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  13055. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  13056. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  13057. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13058. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  13059. this.points[ 1 ] = prevXYZ;
  13060. this.points[ 2 ] = nextXYZ;
  13061. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  13062. scale = scale * 0.33 + 0.33;
  13063. currentPoint = this.interpolateCatmullRom( this.points, scale );
  13064. vector.x = currentPoint[ 0 ];
  13065. vector.y = currentPoint[ 1 ];
  13066. vector.z = currentPoint[ 2 ];
  13067. if( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13068. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  13069. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  13070. this.target.subSelf( vector );
  13071. this.target.y = 0;
  13072. this.target.normalize();
  13073. angle = Math.atan2( this.target.x, this.target.z );
  13074. object.rotation.set( 0, angle, 0 );
  13075. }
  13076. }
  13077. } else if ( type === "rot" ) {
  13078. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  13079. } else if( type === "scl" ) {
  13080. vector = object.scale;
  13081. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  13082. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  13083. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  13084. }
  13085. }
  13086. }
  13087. }
  13088. // update JIT?
  13089. if ( this.JITCompile ) {
  13090. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  13091. this.hierarchy[ 0 ].updateMatrixWorld( true );
  13092. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  13093. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  13094. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  13095. } else {
  13096. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  13097. }
  13098. }
  13099. }
  13100. }
  13101. };
  13102. // Catmull-Rom spline
  13103. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  13104. var c = [], v3 = [],
  13105. point, intPoint, weight, w2, w3,
  13106. pa, pb, pc, pd;
  13107. point = ( points.length - 1 ) * scale;
  13108. intPoint = Math.floor( point );
  13109. weight = point - intPoint;
  13110. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  13111. c[ 1 ] = intPoint;
  13112. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  13113. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  13114. pa = points[ c[ 0 ] ];
  13115. pb = points[ c[ 1 ] ];
  13116. pc = points[ c[ 2 ] ];
  13117. pd = points[ c[ 3 ] ];
  13118. w2 = weight * weight;
  13119. w3 = weight * w2;
  13120. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  13121. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  13122. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  13123. return v3;
  13124. };
  13125. THREE.Animation.prototype.interpolate = function( p0, p1, p2, p3, t, t2, t3 ) {
  13126. var v0 = ( p2 - p0 ) * 0.5,
  13127. v1 = ( p3 - p1 ) * 0.5;
  13128. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  13129. };
  13130. // Get next key with
  13131. THREE.Animation.prototype.getNextKeyWith = function( type, h, key ) {
  13132. var keys = this.data.hierarchy[ h ].keys;
  13133. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  13134. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13135. key = key < keys.length - 1 ? key : keys.length - 1;
  13136. } else {
  13137. key = key % keys.length;
  13138. }
  13139. for ( ; key < keys.length; key++ ) {
  13140. if ( keys[ key ][ type ] !== undefined ) {
  13141. return keys[ key ];
  13142. }
  13143. }
  13144. return this.data.hierarchy[ h ].keys[ 0 ];
  13145. };
  13146. // Get previous key with
  13147. THREE.Animation.prototype.getPrevKeyWith = function( type, h, key ) {
  13148. var keys = this.data.hierarchy[ h ].keys;
  13149. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  13150. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13151. key = key > 0 ? key : 0;
  13152. } else {
  13153. key = key >= 0 ? key : key + keys.length;
  13154. }
  13155. for ( ; key >= 0; key-- ) {
  13156. if ( keys[ key ][ type ] !== undefined ) {
  13157. return keys[ key ];
  13158. }
  13159. }
  13160. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  13161. };/**
  13162. * @author mikael emtinger / http://gomo.se/
  13163. * @author mrdoob / http://mrdoob.com/
  13164. * @author alteredq / http://alteredqualia.com/
  13165. * @author khang duong
  13166. * @author erik kitson
  13167. */
  13168. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  13169. this.root = root;
  13170. this.data = THREE.AnimationHandler.get( data );
  13171. this.hierarchy = THREE.AnimationHandler.parse( root );
  13172. this.currentTime = 0;
  13173. this.timeScale = 0.001;
  13174. this.isPlaying = false;
  13175. this.isPaused = true;
  13176. this.loop = true;
  13177. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  13178. // initialize to first keyframes
  13179. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  13180. var keys = this.data.hierarchy[h].keys,
  13181. sids = this.data.hierarchy[h].sids,
  13182. obj = this.hierarchy[h];
  13183. if ( keys.length && sids ) {
  13184. for ( var s = 0; s < sids.length; s++ ) {
  13185. var sid = sids[ s ],
  13186. next = this.getNextKeyWith( sid, h, 0 );
  13187. if ( next ) {
  13188. next.apply( sid );
  13189. }
  13190. }
  13191. obj.matrixAutoUpdate = false;
  13192. this.data.hierarchy[h].node.updateMatrix();
  13193. obj.matrixWorldNeedsUpdate = true;
  13194. }
  13195. }
  13196. };
  13197. // Play
  13198. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  13199. if( !this.isPlaying ) {
  13200. this.isPlaying = true;
  13201. this.loop = loop !== undefined ? loop : true;
  13202. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  13203. this.startTimeMs = startTimeMS;
  13204. this.startTime = 10000000;
  13205. this.endTime = -this.startTime;
  13206. // reset key cache
  13207. var h, hl = this.hierarchy.length,
  13208. object,
  13209. node;
  13210. for ( h = 0; h < hl; h++ ) {
  13211. object = this.hierarchy[ h ];
  13212. node = this.data.hierarchy[ h ];
  13213. object.useQuaternion = true;
  13214. if ( node.animationCache === undefined ) {
  13215. node.animationCache = {};
  13216. node.animationCache.prevKey = null;
  13217. node.animationCache.nextKey = null;
  13218. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  13219. }
  13220. var keys = this.data.hierarchy[h].keys;
  13221. if (keys.length) {
  13222. node.animationCache.prevKey = keys[ 0 ];
  13223. node.animationCache.nextKey = keys[ 1 ];
  13224. this.startTime = Math.min( keys[0].time, this.startTime );
  13225. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  13226. }
  13227. }
  13228. this.update( 0 );
  13229. }
  13230. this.isPaused = false;
  13231. THREE.AnimationHandler.addToUpdate( this );
  13232. };
  13233. // Pause
  13234. THREE.KeyFrameAnimation.prototype.pause = function() {
  13235. if( this.isPaused ) {
  13236. THREE.AnimationHandler.addToUpdate( this );
  13237. } else {
  13238. THREE.AnimationHandler.removeFromUpdate( this );
  13239. }
  13240. this.isPaused = !this.isPaused;
  13241. };
  13242. // Stop
  13243. THREE.KeyFrameAnimation.prototype.stop = function() {
  13244. this.isPlaying = false;
  13245. this.isPaused = false;
  13246. THREE.AnimationHandler.removeFromUpdate( this );
  13247. // reset JIT matrix and remove cache
  13248. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  13249. var obj = this.hierarchy[ h ];
  13250. var node = this.data.hierarchy[ h ];
  13251. if ( node.animationCache !== undefined ) {
  13252. var original = node.animationCache.originalMatrix;
  13253. if( obj instanceof THREE.Bone ) {
  13254. original.copy( obj.skinMatrix );
  13255. obj.skinMatrix = original;
  13256. } else {
  13257. original.copy( obj.matrix );
  13258. obj.matrix = original;
  13259. }
  13260. delete node.animationCache;
  13261. }
  13262. }
  13263. };
  13264. // Update
  13265. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  13266. // early out
  13267. if( !this.isPlaying ) return;
  13268. // vars
  13269. var prevKey, nextKey;
  13270. var object;
  13271. var node;
  13272. var frame;
  13273. var JIThierarchy = this.data.JIT.hierarchy;
  13274. var currentTime, unloopedCurrentTime;
  13275. var looped;
  13276. // update
  13277. this.currentTime += deltaTimeMS * this.timeScale;
  13278. unloopedCurrentTime = this.currentTime;
  13279. currentTime = this.currentTime = this.currentTime % this.data.length;
  13280. // if looped around, the current time should be based on the startTime
  13281. if ( currentTime < this.startTimeMs ) {
  13282. currentTime = this.currentTime = this.startTimeMs + currentTime;
  13283. }
  13284. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  13285. looped = currentTime < unloopedCurrentTime;
  13286. if ( looped && !this.loop ) {
  13287. // Set the animation to the last keyframes and stop
  13288. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  13289. var keys = this.data.hierarchy[h].keys,
  13290. sids = this.data.hierarchy[h].sids,
  13291. end = keys.length-1,
  13292. obj = this.hierarchy[h];
  13293. if ( keys.length ) {
  13294. for ( var s = 0; s < sids.length; s++ ) {
  13295. var sid = sids[ s ],
  13296. prev = this.getPrevKeyWith( sid, h, end );
  13297. if ( prev ) {
  13298. prev.apply( sid );
  13299. }
  13300. }
  13301. this.data.hierarchy[h].node.updateMatrix();
  13302. obj.matrixWorldNeedsUpdate = true;
  13303. }
  13304. }
  13305. this.stop();
  13306. return;
  13307. }
  13308. // check pre-infinity
  13309. if ( currentTime < this.startTime ) {
  13310. return;
  13311. }
  13312. // update
  13313. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  13314. object = this.hierarchy[ h ];
  13315. node = this.data.hierarchy[ h ];
  13316. var keys = node.keys,
  13317. animationCache = node.animationCache;
  13318. // use JIT?
  13319. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  13320. if( object instanceof THREE.Bone ) {
  13321. object.skinMatrix = JIThierarchy[ h ][ frame ];
  13322. object.matrixWorldNeedsUpdate = false;
  13323. } else {
  13324. object.matrix = JIThierarchy[ h ][ frame ];
  13325. object.matrixWorldNeedsUpdate = true;
  13326. }
  13327. // use interpolation
  13328. } else if ( keys.length ) {
  13329. // make sure so original matrix and not JIT matrix is set
  13330. if ( this.JITCompile && animationCache ) {
  13331. if( object instanceof THREE.Bone ) {
  13332. object.skinMatrix = animationCache.originalMatrix;
  13333. } else {
  13334. object.matrix = animationCache.originalMatrix;
  13335. }
  13336. }
  13337. prevKey = animationCache.prevKey;
  13338. nextKey = animationCache.nextKey;
  13339. if ( prevKey && nextKey ) {
  13340. // switch keys?
  13341. if ( nextKey.time <= unloopedCurrentTime ) {
  13342. // did we loop?
  13343. if ( looped && this.loop ) {
  13344. prevKey = keys[ 0 ];
  13345. nextKey = keys[ 1 ];
  13346. while ( nextKey.time < currentTime ) {
  13347. prevKey = nextKey;
  13348. nextKey = keys[ prevKey.index + 1 ];
  13349. }
  13350. } else if ( !looped ) {
  13351. var lastIndex = keys.length - 1;
  13352. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  13353. prevKey = nextKey;
  13354. nextKey = keys[ prevKey.index + 1 ];
  13355. }
  13356. }
  13357. animationCache.prevKey = prevKey;
  13358. animationCache.nextKey = nextKey;
  13359. }
  13360. if(nextKey.time >= currentTime)
  13361. prevKey.interpolate( nextKey, currentTime );
  13362. else
  13363. prevKey.interpolate( nextKey, nextKey.time);
  13364. }
  13365. this.data.hierarchy[h].node.updateMatrix();
  13366. object.matrixWorldNeedsUpdate = true;
  13367. }
  13368. }
  13369. // update JIT?
  13370. if ( this.JITCompile ) {
  13371. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  13372. this.hierarchy[ 0 ].updateMatrixWorld( true );
  13373. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  13374. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  13375. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  13376. } else {
  13377. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  13378. }
  13379. }
  13380. }
  13381. }
  13382. };
  13383. // Get next key with
  13384. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  13385. var keys = this.data.hierarchy[ h ].keys;
  13386. key = key % keys.length;
  13387. for ( ; key < keys.length; key++ ) {
  13388. if ( keys[ key ].hasTarget( sid ) ) {
  13389. return keys[ key ];
  13390. }
  13391. }
  13392. return keys[ 0 ];
  13393. };
  13394. // Get previous key with
  13395. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  13396. var keys = this.data.hierarchy[ h ].keys;
  13397. key = key >= 0 ? key : key + keys.length;
  13398. for ( ; key >= 0; key-- ) {
  13399. if ( keys[ key ].hasTarget( sid ) ) {
  13400. return keys[ key ];
  13401. }
  13402. }
  13403. return keys[ keys.length - 1 ];
  13404. };
  13405. /**
  13406. * Camera for rendering cube maps
  13407. * - renders scene into axis-aligned cube
  13408. *
  13409. * @author alteredq / http://alteredqualia.com/
  13410. */
  13411. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  13412. this.position = new THREE.Vector3();
  13413. var fov = 90, aspect = 1;
  13414. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13415. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13416. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13417. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13418. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13419. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13420. cameraPX.position = this.position;
  13421. cameraPX.up.set( 0, -1, 0 );
  13422. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  13423. cameraNX.position = this.position;
  13424. cameraNX.up.set( 0, -1, 0 );
  13425. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  13426. cameraPY.position = this.position;
  13427. cameraPY.up.set( 0, 0, 1 );
  13428. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  13429. cameraNY.position = this.position;
  13430. cameraNY.up.set( 0, 0, -1 );
  13431. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  13432. cameraPZ.position = this.position;
  13433. cameraPZ.up.set( 0, -1, 0 );
  13434. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  13435. cameraNZ.position = this.position;
  13436. cameraNZ.up.set( 0, -1, 0 );
  13437. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  13438. // cube render target
  13439. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  13440. this.updateCubeMap = function ( renderer, scene ) {
  13441. var cubeTarget = this.renderTarget;
  13442. var oldGenerateMipmaps = cubeTarget.generateMipmaps;
  13443. cubeTarget.generateMipmaps = false;
  13444. cubeTarget.activeCubeFace = 0;
  13445. renderer.render( scene, cameraPX, cubeTarget );
  13446. cubeTarget.activeCubeFace = 1;
  13447. renderer.render( scene, cameraNX, cubeTarget );
  13448. cubeTarget.activeCubeFace = 2;
  13449. renderer.render( scene, cameraPY, cubeTarget );
  13450. cubeTarget.activeCubeFace = 3;
  13451. renderer.render( scene, cameraNY, cubeTarget );
  13452. cubeTarget.activeCubeFace = 4;
  13453. renderer.render( scene, cameraPZ, cubeTarget );
  13454. cubeTarget.generateMipmaps = oldGenerateMipmaps;
  13455. cubeTarget.activeCubeFace = 5;
  13456. renderer.render( scene, cameraNZ, cubeTarget );
  13457. };
  13458. };
  13459. /*
  13460. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  13461. *
  13462. * A handy general perpose camera, for setting FOV, Lens Focal Length,
  13463. * and switching between perspective and orthographic views easily.
  13464. *
  13465. */
  13466. THREE.CombinedCamera = function ( width, height, fov, near, far, orthonear, orthofar ) {
  13467. THREE.Camera.call( this );
  13468. this.fov = fov;
  13469. this.left = -width / 2;
  13470. this.right = width / 2
  13471. this.top = height / 2;
  13472. this.bottom = -height / 2;
  13473. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  13474. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthonear, orthofar );
  13475. this.cameraP = new THREE.PerspectiveCamera( fov, width/height, near, far );
  13476. this.zoom = 1;
  13477. this.toPerspective();
  13478. var aspect = width/height;
  13479. };
  13480. THREE.CombinedCamera.prototype = new THREE.Camera();
  13481. THREE.CombinedCamera.prototype.constructor = THREE.CoolCamera;
  13482. THREE.CombinedCamera.prototype.toPerspective = function () {
  13483. this.near = this.cameraP.near;
  13484. this.far = this.cameraP.far;
  13485. this.cameraP.fov = this.fov / this.zoom ;
  13486. this.cameraP.updateProjectionMatrix();
  13487. this.projectionMatrix = this.cameraP.projectionMatrix;
  13488. this.inPersepectiveMode = true;
  13489. this.inOrthographicMode = false;
  13490. };
  13491. THREE.CombinedCamera.prototype.toOrthographic = function () {
  13492. // Orthographic from Perspective
  13493. var fov = this.fov;
  13494. var aspect = this.cameraP.aspect;
  13495. var near = this.cameraP.near;
  13496. var far = this.cameraP.far;
  13497. // Just pretend we want the mid plane of the viewing frustum
  13498. var hyperfocus = ( near + far ) / 2;
  13499. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  13500. var planeHeight = 2 * halfHeight;
  13501. var planeWidth = planeHeight * aspect;
  13502. var halfWidth = planeWidth / 2;
  13503. halfHeight /= this.zoom;
  13504. halfWidth /= this.zoom;
  13505. this.cameraO.left = -halfWidth;
  13506. this.cameraO.right = halfWidth;
  13507. this.cameraO.top = halfHeight;
  13508. this.cameraO.bottom = -halfHeight;
  13509. // this.cameraO.left = -farHalfWidth;
  13510. // this.cameraO.right = farHalfWidth;
  13511. // this.cameraO.top = farHalfHeight;
  13512. // this.cameraO.bottom = -farHalfHeight;
  13513. // this.cameraO.left = this.left / this.zoom;
  13514. // this.cameraO.right = this.right / this.zoom;
  13515. // this.cameraO.top = this.top / this.zoom;
  13516. // this.cameraO.bottom = this.bottom / this.zoom;
  13517. this.cameraO.updateProjectionMatrix();
  13518. this.near = this.cameraO.near;
  13519. this.far = this.cameraO.far;
  13520. this.projectionMatrix = this.cameraO.projectionMatrix;
  13521. this.inPersepectiveMode = false;
  13522. this.inOrthographicMode = true;
  13523. };
  13524. THREE.CombinedCamera.prototype.setFov = function(fov) {
  13525. this.fov = fov;
  13526. if (this.inPersepectiveMode) {
  13527. this.toPerspective();
  13528. } else {
  13529. this.toOrthographic();
  13530. }
  13531. };
  13532. /*
  13533. * Uses Focal Length (in mm) to estimate and set FOV
  13534. * 35mm (fullframe) camera is used if frame size is not specified;
  13535. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  13536. */
  13537. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  13538. frameHeight = frameHeight !== undefined ? frameHeight : 24;
  13539. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  13540. this.setFov( fov );
  13541. return fov;
  13542. };
  13543. THREE.CombinedCamera.prototype.setZoom = function(zoom) {
  13544. this.zoom = zoom;
  13545. if (this.inPersepectiveMode) {
  13546. this.toPerspective();
  13547. } else {
  13548. this.toOrthographic();
  13549. }
  13550. };
  13551. THREE.CombinedCamera.prototype.toFrontView = function() {
  13552. this.rotation.x = 0;
  13553. this.rotation.y = 0;
  13554. this.rotation.z = 0;
  13555. //TODO: Better way to disable camera.lookAt()?
  13556. this.rotationAutoUpdate = false;
  13557. };
  13558. THREE.CombinedCamera.prototype.toBackView = function() {
  13559. this.rotation.x = 0;
  13560. this.rotation.y = Math.PI;
  13561. this.rotation.z = 0;
  13562. this.rotationAutoUpdate = false;
  13563. };
  13564. THREE.CombinedCamera.prototype.toLeftView = function() {
  13565. this.rotation.x = 0;
  13566. this.rotation.y = - Math.PI / 2;
  13567. this.rotation.z = 0;
  13568. this.rotationAutoUpdate = false;
  13569. };
  13570. THREE.CombinedCamera.prototype.toRightView = function() {
  13571. this.rotation.x = 0;
  13572. this.rotation.y = Math.PI / 2;
  13573. this.rotation.z = 0;
  13574. this.rotationAutoUpdate = false;
  13575. };
  13576. THREE.CombinedCamera.prototype.toTopView = function() {
  13577. this.rotation.x = - Math.PI / 2;
  13578. this.rotation.y = 0;
  13579. this.rotation.z = 0;
  13580. this.rotationAutoUpdate = false;
  13581. };
  13582. THREE.CombinedCamera.prototype.toBottomView = function() {
  13583. this.rotation.x = Math.PI / 2;
  13584. this.rotation.y = 0;
  13585. this.rotation.z = 0;
  13586. this.rotationAutoUpdate = false;
  13587. };
  13588. /**
  13589. * @author mrdoob / http://mrdoob.com/
  13590. * @author alteredq / http://alteredqualia.com/
  13591. * @author paulirish / http://paulirish.com/
  13592. */
  13593. THREE.FirstPersonControls = function ( object, domElement ) {
  13594. this.object = object;
  13595. this.target = new THREE.Vector3( 0, 0, 0 );
  13596. this.domElement = ( domElement !== undefined ) ? domElement : document;
  13597. this.movementSpeed = 1.0;
  13598. this.lookSpeed = 0.005;
  13599. this.noFly = false;
  13600. this.lookVertical = true;
  13601. this.autoForward = false;
  13602. this.activeLook = true;
  13603. this.heightSpeed = false;
  13604. this.heightCoef = 1.0;
  13605. this.heightMin = 0.0;
  13606. this.constrainVertical = false;
  13607. this.verticalMin = 0;
  13608. this.verticalMax = Math.PI;
  13609. this.autoSpeedFactor = 0.0;
  13610. this.mouseX = 0;
  13611. this.mouseY = 0;
  13612. this.lat = 0;
  13613. this.lon = 0;
  13614. this.phi = 0;
  13615. this.theta = 0;
  13616. this.moveForward = false;
  13617. this.moveBackward = false;
  13618. this.moveLeft = false;
  13619. this.moveRight = false;
  13620. this.freeze = false;
  13621. this.mouseDragOn = false;
  13622. if ( this.domElement === document ) {
  13623. this.viewHalfX = window.innerWidth / 2;
  13624. this.viewHalfY = window.innerHeight / 2;
  13625. } else {
  13626. this.viewHalfX = this.domElement.offsetWidth / 2;
  13627. this.viewHalfY = this.domElement.offsetHeight / 2;
  13628. this.domElement.setAttribute( 'tabindex', -1 );
  13629. }
  13630. this.onMouseDown = function ( event ) {
  13631. if ( this.domElement !== document ) {
  13632. this.domElement.focus();
  13633. }
  13634. event.preventDefault();
  13635. event.stopPropagation();
  13636. if ( this.activeLook ) {
  13637. switch ( event.button ) {
  13638. case 0: this.moveForward = true; break;
  13639. case 2: this.moveBackward = true; break;
  13640. }
  13641. }
  13642. this.mouseDragOn = true;
  13643. };
  13644. this.onMouseUp = function ( event ) {
  13645. event.preventDefault();
  13646. event.stopPropagation();
  13647. if ( this.activeLook ) {
  13648. switch ( event.button ) {
  13649. case 0: this.moveForward = false; break;
  13650. case 2: this.moveBackward = false; break;
  13651. }
  13652. }
  13653. this.mouseDragOn = false;
  13654. };
  13655. this.onMouseMove = function ( event ) {
  13656. if ( this.domElement === document ) {
  13657. this.mouseX = event.pageX - this.viewHalfX;
  13658. this.mouseY = event.pageY - this.viewHalfY;
  13659. } else {
  13660. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  13661. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  13662. }
  13663. };
  13664. this.onKeyDown = function ( event ) {
  13665. switch( event.keyCode ) {
  13666. case 38: /*up*/
  13667. case 87: /*W*/ this.moveForward = true; break;
  13668. case 37: /*left*/
  13669. case 65: /*A*/ this.moveLeft = true; break;
  13670. case 40: /*down*/
  13671. case 83: /*S*/ this.moveBackward = true; break;
  13672. case 39: /*right*/
  13673. case 68: /*D*/ this.moveRight = true; break;
  13674. case 82: /*R*/ this.moveUp = true; break;
  13675. case 70: /*F*/ this.moveDown = true; break;
  13676. case 81: /*Q*/ this.freeze = !this.freeze; break;
  13677. }
  13678. };
  13679. this.onKeyUp = function ( event ) {
  13680. switch( event.keyCode ) {
  13681. case 38: /*up*/
  13682. case 87: /*W*/ this.moveForward = false; break;
  13683. case 37: /*left*/
  13684. case 65: /*A*/ this.moveLeft = false; break;
  13685. case 40: /*down*/
  13686. case 83: /*S*/ this.moveBackward = false; break;
  13687. case 39: /*right*/
  13688. case 68: /*D*/ this.moveRight = false; break;
  13689. case 82: /*R*/ this.moveUp = false; break;
  13690. case 70: /*F*/ this.moveDown = false; break;
  13691. }
  13692. };
  13693. this.update = function( delta ) {
  13694. var actualMoveSpeed = 0;
  13695. if ( this.freeze ) {
  13696. return;
  13697. } else {
  13698. if ( this.heightSpeed ) {
  13699. var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
  13700. var heightDelta = y - this.heightMin;
  13701. this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );
  13702. } else {
  13703. this.autoSpeedFactor = 0.0;
  13704. }
  13705. actualMoveSpeed = delta * this.movementSpeed;
  13706. if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
  13707. if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed );
  13708. if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed );
  13709. if ( this.moveRight ) this.object.translateX( actualMoveSpeed );
  13710. if ( this.moveUp ) this.object.translateY( actualMoveSpeed );
  13711. if ( this.moveDown ) this.object.translateY( - actualMoveSpeed );
  13712. var actualLookSpeed = delta * this.lookSpeed;
  13713. if ( !this.activeLook ) {
  13714. actualLookSpeed = 0;
  13715. }
  13716. this.lon += this.mouseX * actualLookSpeed;
  13717. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed;
  13718. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  13719. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  13720. this.theta = this.lon * Math.PI / 180;
  13721. var targetPosition = this.target,
  13722. position = this.object.position;
  13723. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  13724. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  13725. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  13726. }
  13727. var verticalLookRatio = 1;
  13728. if ( this.constrainVertical ) {
  13729. verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );
  13730. }
  13731. this.lon += this.mouseX * actualLookSpeed;
  13732. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;
  13733. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  13734. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  13735. this.theta = this.lon * Math.PI / 180;
  13736. if ( this.constrainVertical ) {
  13737. this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );
  13738. }
  13739. var targetPosition = this.target,
  13740. position = this.object.position;
  13741. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  13742. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  13743. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  13744. this.object.lookAt( targetPosition );
  13745. };
  13746. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  13747. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  13748. this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
  13749. this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
  13750. this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
  13751. this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
  13752. function bind( scope, fn ) {
  13753. return function () {
  13754. fn.apply( scope, arguments );
  13755. };
  13756. };
  13757. };
  13758. /**
  13759. * @author alteredq / http://alteredqualia.com/
  13760. */
  13761. THREE.PathControls = function ( object, domElement ) {
  13762. this.object = object;
  13763. this.domElement = ( domElement !== undefined ) ? domElement : document;
  13764. this.id = "PathControls" + THREE.PathControlsIdCounter ++;
  13765. // API
  13766. this.duration = 10 * 1000; // milliseconds
  13767. this.waypoints = [];
  13768. this.useConstantSpeed = true;
  13769. this.resamplingCoef = 50;
  13770. this.debugPath = new THREE.Object3D();
  13771. this.debugDummy = new THREE.Object3D();
  13772. this.animationParent = new THREE.Object3D();
  13773. this.lookSpeed = 0.005;
  13774. this.lookVertical = true;
  13775. this.lookHorizontal = true;
  13776. this.verticalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  13777. this.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  13778. // internals
  13779. this.target = new THREE.Object3D();
  13780. this.mouseX = 0;
  13781. this.mouseY = 0;
  13782. this.lat = 0;
  13783. this.lon = 0;
  13784. this.phi = 0;
  13785. this.theta = 0;
  13786. if ( this.domElement === document ) {
  13787. this.viewHalfX = window.innerWidth / 2;
  13788. this.viewHalfY = window.innerHeight / 2;
  13789. } else {
  13790. this.viewHalfX = this.domElement.offsetWidth / 2;
  13791. this.viewHalfY = this.domElement.offsetHeight / 2;
  13792. this.domElement.setAttribute( 'tabindex', -1 );
  13793. }
  13794. var PI2 = Math.PI * 2,
  13795. PI180 = Math.PI / 180;
  13796. // methods
  13797. this.update = function ( delta ) {
  13798. var srcRange, dstRange;
  13799. if( this.lookHorizontal ) this.lon += this.mouseX * this.lookSpeed * delta;
  13800. if( this.lookVertical ) this.lat -= this.mouseY * this.lookSpeed * delta;
  13801. this.lon = Math.max( 0, Math.min( 360, this.lon ) );
  13802. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  13803. this.phi = ( 90 - this.lat ) * PI180;
  13804. this.theta = this.lon * PI180;
  13805. this.phi = normalize_angle_rad( this.phi );
  13806. // constrain vertical look angle
  13807. srcRange = this.verticalAngleMap.srcRange;
  13808. dstRange = this.verticalAngleMap.dstRange;
  13809. var tmpPhi = THREE.Math.mapLinear( this.phi, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  13810. var tmpPhiFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  13811. var tmpPhiNormalized = ( tmpPhi - dstRange[ 0 ] ) / tmpPhiFullRange;
  13812. this.phi = QuadraticEaseInOut( tmpPhiNormalized ) * tmpPhiFullRange + dstRange[ 0 ];
  13813. // constrain horizontal look angle
  13814. srcRange = this.horizontalAngleMap.srcRange;
  13815. dstRange = this.horizontalAngleMap.dstRange;
  13816. var tmpTheta = THREE.Math.mapLinear( this.theta, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  13817. var tmpThetaFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  13818. var tmpThetaNormalized = ( tmpTheta - dstRange[ 0 ] ) / tmpThetaFullRange;
  13819. this.theta = QuadraticEaseInOut( tmpThetaNormalized ) * tmpThetaFullRange + dstRange[ 0 ];
  13820. var targetPosition = this.target.position,
  13821. position = this.object.position;
  13822. targetPosition.x = 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  13823. targetPosition.y = 100 * Math.cos( this.phi );
  13824. targetPosition.z = 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  13825. this.object.lookAt( this.target.position );
  13826. };
  13827. this.onMouseMove = function ( event ) {
  13828. if ( this.domElement === document ) {
  13829. this.mouseX = event.pageX - this.viewHalfX;
  13830. this.mouseY = event.pageY - this.viewHalfY;
  13831. } else {
  13832. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  13833. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  13834. }
  13835. };
  13836. // utils
  13837. function normalize_angle_rad( a ) {
  13838. var b = a % PI2;
  13839. return b >= 0 ? b : b + PI2;
  13840. };
  13841. function distance( a, b ) {
  13842. var dx = a[ 0 ] - b[ 0 ],
  13843. dy = a[ 1 ] - b[ 1 ],
  13844. dz = a[ 2 ] - b[ 2 ];
  13845. return Math.sqrt( dx * dx + dy * dy + dz * dz );
  13846. };
  13847. function QuadraticEaseInOut ( k ) {
  13848. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  13849. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  13850. };
  13851. function bind( scope, fn ) {
  13852. return function () {
  13853. fn.apply( scope, arguments );
  13854. };
  13855. };
  13856. function initAnimationPath( parent, spline, name, duration ) {
  13857. var animationData = {
  13858. name: name,
  13859. fps: 0.6,
  13860. length: duration,
  13861. hierarchy: []
  13862. };
  13863. var i,
  13864. parentAnimation, childAnimation,
  13865. path = spline.getControlPointsArray(),
  13866. sl = spline.getLength(),
  13867. pl = path.length,
  13868. t = 0,
  13869. first = 0,
  13870. last = pl - 1;
  13871. parentAnimation = { parent: -1, keys: [] };
  13872. parentAnimation.keys[ first ] = { time: 0, pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  13873. parentAnimation.keys[ last ] = { time: duration, pos: path[ last ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  13874. for ( i = 1; i < pl - 1; i++ ) {
  13875. // real distance (approximation via linear segments)
  13876. t = duration * sl.chunks[ i ] / sl.total;
  13877. // equal distance
  13878. //t = duration * ( i / pl );
  13879. // linear distance
  13880. //t += duration * distance( path[ i ], path[ i - 1 ] ) / sl.total;
  13881. parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };
  13882. }
  13883. animationData.hierarchy[ 0 ] = parentAnimation;
  13884. THREE.AnimationHandler.add( animationData );
  13885. return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );
  13886. };
  13887. function createSplineGeometry( spline, n_sub ) {
  13888. var i, index, position,
  13889. geometry = new THREE.Geometry();
  13890. for ( i = 0; i < spline.points.length * n_sub; i ++ ) {
  13891. index = i / ( spline.points.length * n_sub );
  13892. position = spline.getPoint( index );
  13893. geometry.vertices[ i ] = new THREE.Vertex( new THREE.Vector3( position.x, position.y, position.z ) );
  13894. }
  13895. return geometry;
  13896. };
  13897. function createPath( parent, spline ) {
  13898. var lineGeo = createSplineGeometry( spline, 10 ),
  13899. particleGeo = createSplineGeometry( spline, 10 ),
  13900. lineMat = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 3 } ),
  13901. lineObj = new THREE.Line( lineGeo, lineMat ),
  13902. particleObj = new THREE.ParticleSystem( particleGeo, new THREE.ParticleBasicMaterial( { color: 0xffaa00, size: 3 } ) );
  13903. lineObj.scale.set( 1, 1, 1 );
  13904. parent.add( lineObj );
  13905. particleObj.scale.set( 1, 1, 1 );
  13906. parent.add( particleObj );
  13907. var waypoint,
  13908. geo = new THREE.SphereGeometry( 1, 16, 8 ),
  13909. mat = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  13910. for ( var i = 0; i < spline.points.length; i ++ ) {
  13911. waypoint = new THREE.Mesh( geo, mat );
  13912. waypoint.position.copy( spline.points[ i ] );
  13913. parent.add( waypoint );
  13914. }
  13915. };
  13916. this.init = function ( ) {
  13917. // constructor
  13918. this.spline = new THREE.Spline();
  13919. this.spline.initFromArray( this.waypoints );
  13920. if ( this.useConstantSpeed ) {
  13921. this.spline.reparametrizeByArcLength( this.resamplingCoef );
  13922. }
  13923. if ( this.createDebugDummy ) {
  13924. var dummyParentMaterial = new THREE.MeshLambertMaterial( { color: 0x0077ff } ),
  13925. dummyChildMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ),
  13926. dummyParentGeo = new THREE.CubeGeometry( 10, 10, 20 ),
  13927. dummyChildGeo = new THREE.CubeGeometry( 2, 2, 10 );
  13928. this.animationParent = new THREE.Mesh( dummyParentGeo, dummyParentMaterial );
  13929. var dummyChild = new THREE.Mesh( dummyChildGeo, dummyChildMaterial );
  13930. dummyChild.position.set( 0, 10, 0 );
  13931. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  13932. this.animationParent.add( this.object );
  13933. this.animationParent.add( this.target );
  13934. this.animationParent.add( dummyChild );
  13935. } else {
  13936. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  13937. this.animationParent.add( this.target );
  13938. this.animationParent.add( this.object );
  13939. }
  13940. if ( this.createDebugPath ) {
  13941. createPath( this.debugPath, this.spline );
  13942. }
  13943. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  13944. };
  13945. };
  13946. THREE.PathControlsIdCounter = 0;
  13947. /**
  13948. * @author James Baicoianu / http://www.baicoianu.com/
  13949. */
  13950. THREE.FlyControls = function ( object, domElement ) {
  13951. this.object = object;
  13952. this.domElement = ( domElement !== undefined ) ? domElement : document;
  13953. if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );
  13954. // API
  13955. this.movementSpeed = 1.0;
  13956. this.rollSpeed = 0.005;
  13957. this.dragToLook = false;
  13958. this.autoForward = false;
  13959. // disable default target object behavior
  13960. this.object.useQuaternion = true;
  13961. // internals
  13962. this.tmpQuaternion = new THREE.Quaternion();
  13963. this.mouseStatus = 0;
  13964. 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 };
  13965. this.moveVector = new THREE.Vector3( 0, 0, 0 );
  13966. this.rotationVector = new THREE.Vector3( 0, 0, 0 );
  13967. this.handleEvent = function ( event ) {
  13968. if ( typeof this[ event.type ] == 'function' ) {
  13969. this[ event.type ]( event );
  13970. }
  13971. };
  13972. this.keydown = function( event ) {
  13973. if ( event.altKey ) {
  13974. return;
  13975. }
  13976. switch( event.keyCode ) {
  13977. case 16: /* shift */ this.movementSpeedMultiplier = .1; break;
  13978. case 87: /*W*/ this.moveState.forward = 1; break;
  13979. case 83: /*S*/ this.moveState.back = 1; break;
  13980. case 65: /*A*/ this.moveState.left = 1; break;
  13981. case 68: /*D*/ this.moveState.right = 1; break;
  13982. case 82: /*R*/ this.moveState.up = 1; break;
  13983. case 70: /*F*/ this.moveState.down = 1; break;
  13984. case 38: /*up*/ this.moveState.pitchUp = 1; break;
  13985. case 40: /*down*/ this.moveState.pitchDown = 1; break;
  13986. case 37: /*left*/ this.moveState.yawLeft = 1; break;
  13987. case 39: /*right*/ this.moveState.yawRight = 1; break;
  13988. case 81: /*Q*/ this.moveState.rollLeft = 1; break;
  13989. case 69: /*E*/ this.moveState.rollRight = 1; break;
  13990. }
  13991. this.updateMovementVector();
  13992. this.updateRotationVector();
  13993. };
  13994. this.keyup = function( event ) {
  13995. switch( event.keyCode ) {
  13996. case 16: /* shift */ this.movementSpeedMultiplier = 1; break;
  13997. case 87: /*W*/ this.moveState.forward = 0; break;
  13998. case 83: /*S*/ this.moveState.back = 0; break;
  13999. case 65: /*A*/ this.moveState.left = 0; break;
  14000. case 68: /*D*/ this.moveState.right = 0; break;
  14001. case 82: /*R*/ this.moveState.up = 0; break;
  14002. case 70: /*F*/ this.moveState.down = 0; break;
  14003. case 38: /*up*/ this.moveState.pitchUp = 0; break;
  14004. case 40: /*down*/ this.moveState.pitchDown = 0; break;
  14005. case 37: /*left*/ this.moveState.yawLeft = 0; break;
  14006. case 39: /*right*/ this.moveState.yawRight = 0; break;
  14007. case 81: /*Q*/ this.moveState.rollLeft = 0; break;
  14008. case 69: /*E*/ this.moveState.rollRight = 0; break;
  14009. }
  14010. this.updateMovementVector();
  14011. this.updateRotationVector();
  14012. };
  14013. this.mousedown = function( event ) {
  14014. if ( this.domElement !== document ) {
  14015. this.domElement.focus();
  14016. }
  14017. event.preventDefault();
  14018. event.stopPropagation();
  14019. if ( this.dragToLook ) {
  14020. this.mouseStatus ++;
  14021. } else {
  14022. switch ( event.button ) {
  14023. case 0: this.object.moveForward = true; break;
  14024. case 2: this.object.moveBackward = true; break;
  14025. }
  14026. }
  14027. };
  14028. this.mousemove = function( event ) {
  14029. if ( !this.dragToLook || this.mouseStatus > 0 ) {
  14030. var container = this.getContainerDimensions();
  14031. var halfWidth = container.size[ 0 ] / 2;
  14032. var halfHeight = container.size[ 1 ] / 2;
  14033. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  14034. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  14035. this.updateRotationVector();
  14036. }
  14037. };
  14038. this.mouseup = function( event ) {
  14039. event.preventDefault();
  14040. event.stopPropagation();
  14041. if ( this.dragToLook ) {
  14042. this.mouseStatus --;
  14043. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  14044. } else {
  14045. switch ( event.button ) {
  14046. case 0: this.moveForward = false; break;
  14047. case 2: this.moveBackward = false; break;
  14048. }
  14049. }
  14050. this.updateRotationVector();
  14051. };
  14052. this.update = function( delta ) {
  14053. var moveMult = delta * this.movementSpeed;
  14054. var rotMult = delta * this.rollSpeed;
  14055. this.object.translateX( this.moveVector.x * moveMult );
  14056. this.object.translateY( this.moveVector.y * moveMult );
  14057. this.object.translateZ( this.moveVector.z * moveMult );
  14058. this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
  14059. this.object.quaternion.multiplySelf( this.tmpQuaternion );
  14060. this.object.matrix.setPosition( this.object.position );
  14061. this.object.matrix.setRotationFromQuaternion( this.object.quaternion );
  14062. this.object.matrixWorldNeedsUpdate = true;
  14063. };
  14064. this.updateMovementVector = function() {
  14065. var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;
  14066. this.moveVector.x = ( -this.moveState.left + this.moveState.right );
  14067. this.moveVector.y = ( -this.moveState.down + this.moveState.up );
  14068. this.moveVector.z = ( -forward + this.moveState.back );
  14069. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  14070. };
  14071. this.updateRotationVector = function() {
  14072. this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
  14073. this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
  14074. this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
  14075. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  14076. };
  14077. this.getContainerDimensions = function() {
  14078. if ( this.domElement != document ) {
  14079. return {
  14080. size : [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  14081. offset : [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  14082. };
  14083. } else {
  14084. return {
  14085. size : [ window.innerWidth, window.innerHeight ],
  14086. offset : [ 0, 0 ]
  14087. };
  14088. }
  14089. };
  14090. function bind( scope, fn ) {
  14091. return function () {
  14092. fn.apply( scope, arguments );
  14093. };
  14094. };
  14095. this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
  14096. this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
  14097. this.domElement.addEventListener( 'mouseup', bind( this, this.mouseup ), false );
  14098. this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
  14099. this.domElement.addEventListener( 'keyup', bind( this, this.keyup ), false );
  14100. this.updateMovementVector();
  14101. this.updateRotationVector();
  14102. };
  14103. /**
  14104. * @author mikael emtinger / http://gomo.se/
  14105. * @author alteredq / http://alteredqualia.com/
  14106. */
  14107. THREE.RollControls = function ( object, domElement ) {
  14108. this.object = object;
  14109. this.domElement = ( domElement !== undefined ) ? domElement : document;
  14110. // API
  14111. this.mouseLook = true;
  14112. this.autoForward = false;
  14113. this.lookSpeed = 1;
  14114. this.movementSpeed = 1;
  14115. this.rollSpeed = 1;
  14116. this.constrainVertical = [ -0.9, 0.9 ];
  14117. // disable default target object behavior
  14118. this.object.matrixAutoUpdate = false;
  14119. // internals
  14120. this.forward = new THREE.Vector3( 0, 0, 1 );
  14121. this.roll = 0;
  14122. var xTemp = new THREE.Vector3();
  14123. var yTemp = new THREE.Vector3();
  14124. var zTemp = new THREE.Vector3();
  14125. var rollMatrix = new THREE.Matrix4();
  14126. var doRoll = false, rollDirection = 1, forwardSpeed = 0, sideSpeed = 0, upSpeed = 0;
  14127. var mouseX = 0, mouseY = 0;
  14128. var windowHalfX = window.innerWidth / 2;
  14129. var windowHalfY = window.innerHeight / 2;
  14130. // custom update
  14131. this.update = function ( delta ) {
  14132. if ( this.mouseLook ) {
  14133. var actualLookSpeed = delta * this.lookSpeed;
  14134. this.rotateHorizontally( actualLookSpeed * mouseX );
  14135. this.rotateVertically( actualLookSpeed * mouseY );
  14136. }
  14137. var actualSpeed = delta * this.movementSpeed;
  14138. var forwardOrAuto = ( forwardSpeed > 0 || ( this.autoForward && ! ( forwardSpeed < 0 ) ) ) ? 1 : forwardSpeed;
  14139. this.object.translateZ( -actualSpeed * forwardOrAuto );
  14140. this.object.translateX( actualSpeed * sideSpeed );
  14141. this.object.translateY( actualSpeed * upSpeed );
  14142. if( doRoll ) {
  14143. this.roll += this.rollSpeed * delta * rollDirection;
  14144. }
  14145. // cap forward up / down
  14146. if( this.forward.y > this.constrainVertical[ 1 ] ) {
  14147. this.forward.y = this.constrainVertical[ 1 ];
  14148. this.forward.normalize();
  14149. } else if( this.forward.y < this.constrainVertical[ 0 ] ) {
  14150. this.forward.y = this.constrainVertical[ 0 ];
  14151. this.forward.normalize();
  14152. }
  14153. // construct unrolled camera matrix
  14154. zTemp.copy( this.forward );
  14155. yTemp.set( 0, 1, 0 );
  14156. xTemp.cross( yTemp, zTemp ).normalize();
  14157. yTemp.cross( zTemp, xTemp ).normalize();
  14158. this.object.matrix.elements[0] = xTemp.x; this.object.matrix.elements[4] = yTemp.x; this.object.matrix.elements[8] = zTemp.x;
  14159. this.object.matrix.elements[1] = xTemp.y; this.object.matrix.elements[5] = yTemp.y; this.object.matrix.elements[9] = zTemp.y;
  14160. this.object.matrix.elements[2] = xTemp.z; this.object.matrix.elements[6] = yTemp.z; this.object.matrix.elements[10] = zTemp.z;
  14161. // calculate roll matrix
  14162. rollMatrix.identity();
  14163. rollMatrix.elements[0] = Math.cos( this.roll ); rollMatrix.elements[4] = -Math.sin( this.roll );
  14164. rollMatrix.elements[1] = Math.sin( this.roll ); rollMatrix.elements[5] = Math.cos( this.roll );
  14165. // multiply camera with roll
  14166. this.object.matrix.multiplySelf( rollMatrix );
  14167. this.object.matrixWorldNeedsUpdate = true;
  14168. // set position
  14169. this.object.matrix.elements[12] = this.object.position.x;
  14170. this.object.matrix.elements[13] = this.object.position.y;
  14171. this.object.matrix.elements[14] = this.object.position.z;
  14172. };
  14173. this.translateX = function ( distance ) {
  14174. this.object.position.x += this.object.matrix.elements[0] * distance;
  14175. this.object.position.y += this.object.matrix.elements[1] * distance;
  14176. this.object.position.z += this.object.matrix.elements[2] * distance;
  14177. };
  14178. this.translateY = function ( distance ) {
  14179. this.object.position.x += this.object.matrix.elements[4] * distance;
  14180. this.object.position.y += this.object.matrix.elements[5] * distance;
  14181. this.object.position.z += this.object.matrix.elements[6] * distance;
  14182. };
  14183. this.translateZ = function ( distance ) {
  14184. this.object.position.x -= this.object.matrix.elements[8] * distance;
  14185. this.object.position.y -= this.object.matrix.elements[9] * distance;
  14186. this.object.position.z -= this.object.matrix.elements[10] * distance;
  14187. };
  14188. this.rotateHorizontally = function ( amount ) {
  14189. // please note that the amount is NOT degrees, but a scale value
  14190. xTemp.set( this.object.matrix.elements[0], this.object.matrix.elements[1], this.object.matrix.elements[2] );
  14191. xTemp.multiplyScalar( amount );
  14192. this.forward.subSelf( xTemp );
  14193. this.forward.normalize();
  14194. };
  14195. this.rotateVertically = function ( amount ) {
  14196. // please note that the amount is NOT degrees, but a scale value
  14197. yTemp.set( this.object.matrix.elements[4], this.object.matrix.elements[5], this.object.matrix.elements[6] );
  14198. yTemp.multiplyScalar( amount );
  14199. this.forward.addSelf( yTemp );
  14200. this.forward.normalize();
  14201. };
  14202. function onKeyDown( event ) {
  14203. switch( event.keyCode ) {
  14204. case 38: /*up*/
  14205. case 87: /*W*/ forwardSpeed = 1; break;
  14206. case 37: /*left*/
  14207. case 65: /*A*/ sideSpeed = -1; break;
  14208. case 40: /*down*/
  14209. case 83: /*S*/ forwardSpeed = -1; break;
  14210. case 39: /*right*/
  14211. case 68: /*D*/ sideSpeed = 1; break;
  14212. case 81: /*Q*/ doRoll = true; rollDirection = 1; break;
  14213. case 69: /*E*/ doRoll = true; rollDirection = -1; break;
  14214. case 82: /*R*/ upSpeed = 1; break;
  14215. case 70: /*F*/ upSpeed = -1; break;
  14216. }
  14217. };
  14218. function onKeyUp( event ) {
  14219. switch( event.keyCode ) {
  14220. case 38: /*up*/
  14221. case 87: /*W*/ forwardSpeed = 0; break;
  14222. case 37: /*left*/
  14223. case 65: /*A*/ sideSpeed = 0; break;
  14224. case 40: /*down*/
  14225. case 83: /*S*/ forwardSpeed = 0; break;
  14226. case 39: /*right*/
  14227. case 68: /*D*/ sideSpeed = 0; break;
  14228. case 81: /*Q*/ doRoll = false; break;
  14229. case 69: /*E*/ doRoll = false; break;
  14230. case 82: /*R*/ upSpeed = 0; break;
  14231. case 70: /*F*/ upSpeed = 0; break;
  14232. }
  14233. };
  14234. function onMouseMove( event ) {
  14235. mouseX = ( event.clientX - windowHalfX ) / window.innerWidth;
  14236. mouseY = ( event.clientY - windowHalfY ) / window.innerHeight;
  14237. };
  14238. function onMouseDown ( event ) {
  14239. event.preventDefault();
  14240. event.stopPropagation();
  14241. switch ( event.button ) {
  14242. case 0: forwardSpeed = 1; break;
  14243. case 2: forwardSpeed = -1; break;
  14244. }
  14245. };
  14246. function onMouseUp ( event ) {
  14247. event.preventDefault();
  14248. event.stopPropagation();
  14249. switch ( event.button ) {
  14250. case 0: forwardSpeed = 0; break;
  14251. case 2: forwardSpeed = 0; break;
  14252. }
  14253. };
  14254. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  14255. this.domElement.addEventListener( 'mousemove', onMouseMove, false );
  14256. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  14257. this.domElement.addEventListener( 'mouseup', onMouseUp, false );
  14258. this.domElement.addEventListener( 'keydown', onKeyDown, false );
  14259. this.domElement.addEventListener( 'keyup', onKeyUp, false );
  14260. };
  14261. /**
  14262. * @author Eberhard Graether / http://egraether.com/
  14263. */
  14264. THREE.TrackballControls = function ( object, domElement ) {
  14265. THREE.EventTarget.call( this );
  14266. var _this = this,
  14267. STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };
  14268. this.object = object;
  14269. this.domElement = ( domElement !== undefined ) ? domElement : document;
  14270. // API
  14271. this.enabled = true;
  14272. this.screen = { width: window.innerWidth, height: window.innerHeight, offsetLeft: 0, offsetTop: 0 };
  14273. this.radius = ( this.screen.width + this.screen.height ) / 4;
  14274. this.rotateSpeed = 1.0;
  14275. this.zoomSpeed = 1.2;
  14276. this.panSpeed = 0.3;
  14277. this.noRotate = false;
  14278. this.noZoom = false;
  14279. this.noPan = false;
  14280. this.staticMoving = false;
  14281. this.dynamicDampingFactor = 0.2;
  14282. this.minDistance = 0;
  14283. this.maxDistance = Infinity;
  14284. this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
  14285. // internals
  14286. this.target = new THREE.Vector3();
  14287. var lastPosition = new THREE.Vector3();
  14288. var _keyPressed = false,
  14289. _state = STATE.NONE,
  14290. _eye = new THREE.Vector3(),
  14291. _rotateStart = new THREE.Vector3(),
  14292. _rotateEnd = new THREE.Vector3(),
  14293. _zoomStart = new THREE.Vector2(),
  14294. _zoomEnd = new THREE.Vector2(),
  14295. _panStart = new THREE.Vector2(),
  14296. _panEnd = new THREE.Vector2();
  14297. // events
  14298. var changeEvent = { type: 'change' };
  14299. // methods
  14300. this.handleEvent = function ( event ) {
  14301. if ( typeof this[ event.type ] == 'function' ) {
  14302. this[ event.type ]( event );
  14303. }
  14304. };
  14305. this.getMouseOnScreen = function ( clientX, clientY ) {
  14306. return new THREE.Vector2(
  14307. ( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
  14308. ( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
  14309. );
  14310. };
  14311. this.getMouseProjectionOnBall = function ( clientX, clientY ) {
  14312. var mouseOnBall = new THREE.Vector3(
  14313. ( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
  14314. ( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
  14315. 0.0
  14316. );
  14317. var length = mouseOnBall.length();
  14318. if ( length > 1.0 ) {
  14319. mouseOnBall.normalize();
  14320. } else {
  14321. mouseOnBall.z = Math.sqrt( 1.0 - length * length );
  14322. }
  14323. _eye.copy( _this.object.position ).subSelf( _this.target );
  14324. var projection = _this.object.up.clone().setLength( mouseOnBall.y );
  14325. projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
  14326. projection.addSelf( _eye.setLength( mouseOnBall.z ) );
  14327. return projection;
  14328. };
  14329. this.rotateCamera = function () {
  14330. var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
  14331. if ( angle ) {
  14332. var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
  14333. quaternion = new THREE.Quaternion();
  14334. angle *= _this.rotateSpeed;
  14335. quaternion.setFromAxisAngle( axis, -angle );
  14336. quaternion.multiplyVector3( _eye );
  14337. quaternion.multiplyVector3( _this.object.up );
  14338. quaternion.multiplyVector3( _rotateEnd );
  14339. if ( _this.staticMoving ) {
  14340. _rotateStart = _rotateEnd;
  14341. } else {
  14342. quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
  14343. quaternion.multiplyVector3( _rotateStart );
  14344. }
  14345. }
  14346. };
  14347. this.zoomCamera = function () {
  14348. var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
  14349. if ( factor !== 1.0 && factor > 0.0 ) {
  14350. _eye.multiplyScalar( factor );
  14351. if ( _this.staticMoving ) {
  14352. _zoomStart = _zoomEnd;
  14353. } else {
  14354. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  14355. }
  14356. }
  14357. };
  14358. this.panCamera = function () {
  14359. var mouseChange = _panEnd.clone().subSelf( _panStart );
  14360. if ( mouseChange.lengthSq() ) {
  14361. mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
  14362. var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
  14363. pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );
  14364. _this.object.position.addSelf( pan );
  14365. _this.target.addSelf( pan );
  14366. if ( _this.staticMoving ) {
  14367. _panStart = _panEnd;
  14368. } else {
  14369. _panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
  14370. }
  14371. }
  14372. };
  14373. this.checkDistances = function () {
  14374. if ( !_this.noZoom || !_this.noPan ) {
  14375. if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {
  14376. _this.object.position.setLength( _this.maxDistance );
  14377. }
  14378. if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
  14379. _this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );
  14380. }
  14381. }
  14382. };
  14383. this.update = function () {
  14384. _eye.copy( _this.object.position ).subSelf( _this.target );
  14385. if ( !_this.noRotate ) {
  14386. _this.rotateCamera();
  14387. }
  14388. if ( !_this.noZoom ) {
  14389. _this.zoomCamera();
  14390. }
  14391. if ( !_this.noPan ) {
  14392. _this.panCamera();
  14393. }
  14394. _this.object.position.add( _this.target, _eye );
  14395. _this.checkDistances();
  14396. _this.object.lookAt( _this.target );
  14397. if ( lastPosition.distanceTo( _this.object.position ) > 0 ) {
  14398. _this.dispatchEvent( changeEvent );
  14399. lastPosition.copy( _this.object.position );
  14400. }
  14401. };
  14402. // listeners
  14403. function keydown( event ) {
  14404. if ( ! _this.enabled ) return;
  14405. if ( _state !== STATE.NONE ) {
  14406. return;
  14407. } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
  14408. _state = STATE.ROTATE;
  14409. } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
  14410. _state = STATE.ZOOM;
  14411. } else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
  14412. _state = STATE.PAN;
  14413. }
  14414. if ( _state !== STATE.NONE ) {
  14415. _keyPressed = true;
  14416. }
  14417. };
  14418. function keyup( event ) {
  14419. if ( ! _this.enabled ) return;
  14420. if ( _state !== STATE.NONE ) {
  14421. _state = STATE.NONE;
  14422. }
  14423. };
  14424. function mousedown( event ) {
  14425. if ( ! _this.enabled ) return;
  14426. event.preventDefault();
  14427. event.stopPropagation();
  14428. if ( _state === STATE.NONE ) {
  14429. _state = event.button;
  14430. if ( _state === STATE.ROTATE && !_this.noRotate ) {
  14431. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  14432. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  14433. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14434. } else if ( !this.noPan ) {
  14435. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14436. }
  14437. }
  14438. };
  14439. function mousemove( event ) {
  14440. if ( ! _this.enabled ) return;
  14441. if ( _keyPressed ) {
  14442. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  14443. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14444. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14445. _keyPressed = false;
  14446. }
  14447. if ( _state === STATE.NONE ) {
  14448. return;
  14449. } else if ( _state === STATE.ROTATE && !_this.noRotate ) {
  14450. _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  14451. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  14452. _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14453. } else if ( _state === STATE.PAN && !_this.noPan ) {
  14454. _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14455. }
  14456. };
  14457. function mouseup( event ) {
  14458. if ( ! _this.enabled ) return;
  14459. event.preventDefault();
  14460. event.stopPropagation();
  14461. _state = STATE.NONE;
  14462. };
  14463. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  14464. this.domElement.addEventListener( 'mousemove', mousemove, false );
  14465. this.domElement.addEventListener( 'mousedown', mousedown, false );
  14466. this.domElement.addEventListener( 'mouseup', mouseup, false );
  14467. window.addEventListener( 'keydown', keydown, false );
  14468. window.addEventListener( 'keyup', keyup, false );
  14469. };
  14470. /**
  14471. * @author mr.doob / http://mrdoob.com/
  14472. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  14473. */
  14474. THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
  14475. THREE.Geometry.call( this );
  14476. var scope = this,
  14477. width_half = width / 2,
  14478. height_half = height / 2,
  14479. depth_half = depth / 2;
  14480. var mpx, mpy, mpz, mnx, mny, mnz;
  14481. if ( materials !== undefined ) {
  14482. if ( materials instanceof Array ) {
  14483. this.materials = materials;
  14484. } else {
  14485. this.materials = [];
  14486. for ( var i = 0; i < 6; i ++ ) {
  14487. this.materials.push( materials );
  14488. }
  14489. }
  14490. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  14491. } else {
  14492. this.materials = [];
  14493. }
  14494. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  14495. if ( sides != undefined ) {
  14496. for ( var s in sides ) {
  14497. if ( this.sides[ s ] !== undefined ) {
  14498. this.sides[ s ] = sides[ s ];
  14499. }
  14500. }
  14501. }
  14502. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
  14503. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, mnx ); // nx
  14504. this.sides.py && buildPlane( 'x', 'z', 1, 1, width, depth, height_half, mpy ); // py
  14505. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, mny ); // ny
  14506. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, mpz ); // pz
  14507. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz
  14508. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  14509. var w, ix, iy,
  14510. gridX = segmentsWidth || 1,
  14511. gridY = segmentsHeight || 1,
  14512. width_half = width / 2,
  14513. height_half = height / 2,
  14514. offset = scope.vertices.length;
  14515. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  14516. w = 'z';
  14517. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  14518. w = 'y';
  14519. gridY = segmentsDepth || 1;
  14520. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  14521. w = 'x';
  14522. gridX = segmentsDepth || 1;
  14523. }
  14524. var gridX1 = gridX + 1,
  14525. gridY1 = gridY + 1,
  14526. segment_width = width / gridX,
  14527. segment_height = height / gridY,
  14528. normal = new THREE.Vector3();
  14529. normal[ w ] = depth > 0 ? 1 : - 1;
  14530. for ( iy = 0; iy < gridY1; iy ++ ) {
  14531. for ( ix = 0; ix < gridX1; ix ++ ) {
  14532. var vector = new THREE.Vector3();
  14533. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  14534. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  14535. vector[ w ] = depth;
  14536. scope.vertices.push( new THREE.Vertex( vector ) );
  14537. }
  14538. }
  14539. for ( iy = 0; iy < gridY; iy++ ) {
  14540. for ( ix = 0; ix < gridX; ix++ ) {
  14541. var a = ix + gridX1 * iy;
  14542. var b = ix + gridX1 * ( iy + 1 );
  14543. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  14544. var d = ( ix + 1 ) + gridX1 * iy;
  14545. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  14546. face.normal.copy( normal );
  14547. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  14548. face.materialIndex = material;
  14549. scope.faces.push( face );
  14550. scope.faceVertexUvs[ 0 ].push( [
  14551. new THREE.UV( ix / gridX, iy / gridY ),
  14552. new THREE.UV( ix / gridX, ( iy + 1 ) / gridY ),
  14553. new THREE.UV( ( ix + 1 ) / gridX, ( iy + 1 ) / gridY ),
  14554. new THREE.UV( ( ix + 1 ) / gridX, iy / gridY )
  14555. ] );
  14556. }
  14557. }
  14558. }
  14559. this.computeCentroids();
  14560. this.mergeVertices();
  14561. };
  14562. THREE.CubeGeometry.prototype = new THREE.Geometry();
  14563. THREE.CubeGeometry.prototype.constructor = THREE.CubeGeometry;
  14564. /**
  14565. * @author mr.doob / http://mrdoob.com/
  14566. */
  14567. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded ) {
  14568. THREE.Geometry.call( this );
  14569. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  14570. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  14571. height = height !== undefined ? height : 100;
  14572. var heightHalf = height / 2;
  14573. var segmentsX = segmentsRadius || 8;
  14574. var segmentsY = segmentsHeight || 1;
  14575. var x, y, vertices = [], uvs = [];
  14576. for ( y = 0; y <= segmentsY; y ++ ) {
  14577. var verticesRow = [];
  14578. var uvsRow = [];
  14579. var v = y / segmentsY;
  14580. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  14581. for ( x = 0; x <= segmentsX; x ++ ) {
  14582. var u = x / segmentsX;
  14583. var xpos = radius * Math.sin( u * Math.PI * 2 );
  14584. var ypos = - v * height + heightHalf;
  14585. var zpos = radius * Math.cos( u * Math.PI * 2 );
  14586. this.vertices.push( new THREE.Vertex( new THREE.Vector3( xpos, ypos, zpos ) ) );
  14587. verticesRow.push( this.vertices.length - 1 );
  14588. uvsRow.push( new THREE.UV( u, v ) );
  14589. }
  14590. vertices.push( verticesRow );
  14591. uvs.push( uvsRow );
  14592. }
  14593. for ( y = 0; y < segmentsY; y ++ ) {
  14594. for ( x = 0; x < segmentsX; x ++ ) {
  14595. var v1 = vertices[ y ][ x ];
  14596. var v2 = vertices[ y + 1 ][ x ];
  14597. var v3 = vertices[ y + 1 ][ x + 1 ];
  14598. var v4 = vertices[ y ][ x + 1 ];
  14599. // FIXME: These normals aren't right for cones.
  14600. var n1 = this.vertices[ v1 ].position.clone().setY( 0 ).normalize();
  14601. var n2 = this.vertices[ v2 ].position.clone().setY( 0 ).normalize();
  14602. var n3 = this.vertices[ v3 ].position.clone().setY( 0 ).normalize();
  14603. var n4 = this.vertices[ v4 ].position.clone().setY( 0 ).normalize();
  14604. var uv1 = uvs[ y ][ x ].clone();
  14605. var uv2 = uvs[ y + 1 ][ x ].clone();
  14606. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  14607. var uv4 = uvs[ y ][ x + 1 ].clone();
  14608. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  14609. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  14610. }
  14611. }
  14612. // top cap
  14613. if ( !openEnded && radiusTop > 0 ) {
  14614. this.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, heightHalf, 0 ) ) );
  14615. for ( x = 0; x < segmentsX; x ++ ) {
  14616. var v1 = vertices[ 0 ][ x ];
  14617. var v2 = vertices[ 0 ][ x + 1 ];
  14618. var v3 = this.vertices.length - 1;
  14619. var n1 = new THREE.Vector3( 0, 1, 0 );
  14620. var n2 = new THREE.Vector3( 0, 1, 0 );
  14621. var n3 = new THREE.Vector3( 0, 1, 0 );
  14622. var uv1 = uvs[ 0 ][ x ].clone();
  14623. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  14624. var uv3 = new THREE.UV( uv2.u, 0 );
  14625. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  14626. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  14627. }
  14628. }
  14629. // bottom cap
  14630. if ( !openEnded && radiusBottom > 0 ) {
  14631. this.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, - heightHalf, 0 ) ) );
  14632. for ( x = 0; x < segmentsX; x ++ ) {
  14633. var v1 = vertices[ y ][ x + 1 ];
  14634. var v2 = vertices[ y ][ x ];
  14635. var v3 = this.vertices.length - 1;
  14636. var n1 = new THREE.Vector3( 0, - 1, 0 );
  14637. var n2 = new THREE.Vector3( 0, - 1, 0 );
  14638. var n3 = new THREE.Vector3( 0, - 1, 0 );
  14639. var uv1 = uvs[ y ][ x + 1 ].clone();
  14640. var uv2 = uvs[ y ][ x ].clone();
  14641. var uv3 = new THREE.UV( uv2.u, 1 );
  14642. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  14643. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  14644. }
  14645. }
  14646. this.computeCentroids();
  14647. this.computeFaceNormals();
  14648. }
  14649. THREE.CylinderGeometry.prototype = new THREE.Geometry();
  14650. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  14651. /**
  14652. * @author zz85 / http://www.lab4games.net/zz85/blog
  14653. *
  14654. * Creates extruded geometry from a path shape.
  14655. *
  14656. * parameters = {
  14657. *
  14658. * size: <float>, // size of the text
  14659. * height: <float>, // thickness to extrude text
  14660. * curveSegments: <int>, // number of points on the curves
  14661. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  14662. amount: <int>, // Amount
  14663. *
  14664. * bevelEnabled: <bool>, // turn on bevel
  14665. * bevelThickness: <float>, // how deep into text bevel goes
  14666. * bevelSize: <float>, // how far from text outline is bevel
  14667. * bevelSegments: <int>, // number of bevel layers
  14668. *
  14669. * extrudePath: <THREE.CurvePath> // 2d/3d spline path to extrude shape orthogonality to
  14670. * bendPath: <THREE.CurvePath> // 2d path for bend the shape around x/y plane
  14671. *
  14672. * material: <int> // material index for front and back faces
  14673. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  14674. *
  14675. * }
  14676. **/
  14677. THREE.ExtrudeGeometry = function( shapes, options ) {
  14678. if ( typeof( shapes ) === "undefined" ) {
  14679. shapes = [];
  14680. return;
  14681. }
  14682. THREE.Geometry.call( this );
  14683. shapes = shapes instanceof Array ? shapes : [ shapes ];
  14684. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  14685. this.addShapeList( shapes, options );
  14686. this.computeCentroids();
  14687. this.computeFaceNormals();
  14688. // can't really use automatic vertex normals
  14689. // as then front and back sides get smoothed too
  14690. // should do separate smoothing just for sides
  14691. //this.computeVertexNormals();
  14692. //console.log( "took", ( Date.now() - startTime ) );
  14693. };
  14694. THREE.ExtrudeGeometry.prototype = new THREE.Geometry();
  14695. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  14696. THREE.ExtrudeGeometry.prototype.addShapeList = function(shapes, options) {
  14697. var sl = shapes.length;
  14698. for ( var s = 0; s < sl; s ++ ) {
  14699. var shape = shapes[ s ];
  14700. this.addShape( shape, options );
  14701. }
  14702. };
  14703. THREE.ExtrudeGeometry.prototype.addShape = function( shape, options ) {
  14704. var amount = options.amount !== undefined ? options.amount : 100;
  14705. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  14706. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  14707. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  14708. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  14709. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  14710. var steps = options.steps !== undefined ? options.steps : 1;
  14711. var bendPath = options.bendPath;
  14712. var extrudePath = options.extrudePath;
  14713. var extrudePts, extrudeByPath = false;
  14714. var material = options.material;
  14715. var extrudeMaterial = options.extrudeMaterial;
  14716. var shapebb = this.shapebb;
  14717. //shapebb = shape.getBoundingBox();
  14718. var splineTube, binormal, normal, position2;
  14719. if ( extrudePath ) {
  14720. extrudePts = extrudePath.getSpacedPoints( steps );
  14721. extrudeByPath = true;
  14722. bevelEnabled = false; // bevels not supported for path extrusion
  14723. // SETUP TNB variables
  14724. // Reuse TNB from TubeGeomtry for now.
  14725. // TODO1 - have a .isClosed in spline?
  14726. // TODO2 - have have TNBs calculation refactored from TubeGeometry?
  14727. splineTube = new THREE.TubeGeometry(extrudePath, steps, 1, 1, false, false);
  14728. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  14729. binormal = new THREE.Vector3();
  14730. normal = new THREE.Vector3();
  14731. position2 = new THREE.Vector3();
  14732. }
  14733. // Safeguards if bevels are not enabled
  14734. if ( ! bevelEnabled ) {
  14735. bevelSegments = 0;
  14736. bevelThickness = 0;
  14737. bevelSize = 0;
  14738. }
  14739. // Variables initalization
  14740. var ahole, h, hl; // looping of holes
  14741. var scope = this;
  14742. var bevelPoints = [];
  14743. var shapesOffset = this.vertices.length;
  14744. if ( bendPath ) {
  14745. shape.addWrapPath( bendPath );
  14746. }
  14747. var shapePoints = shape.extractPoints();
  14748. var vertices = shapePoints.shape;
  14749. var holes = shapePoints.holes;
  14750. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  14751. if ( reverse ) {
  14752. vertices = vertices.reverse();
  14753. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  14754. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14755. ahole = holes[ h ];
  14756. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  14757. holes[ h ] = ahole.reverse();
  14758. }
  14759. }
  14760. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  14761. }
  14762. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  14763. //var faces = THREE.Shape.Utils.triangulate2( vertices, holes );
  14764. // Would it be better to move points after triangulation?
  14765. // shapePoints = shape.extractAllPointsWithBend( curveSegments, bendPath );
  14766. // vertices = shapePoints.shape;
  14767. // holes = shapePoints.holes;
  14768. //console.log(faces);
  14769. ////
  14770. /// Handle Vertices
  14771. ////
  14772. var contour = vertices; // vertices has all points but contour has only points of circumference
  14773. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14774. ahole = holes[ h ];
  14775. vertices = vertices.concat( ahole );
  14776. }
  14777. function scalePt2 ( pt, vec, size ) {
  14778. if ( !vec ) console.log( "die" );
  14779. return vec.clone().multiplyScalar( size ).addSelf( pt );
  14780. }
  14781. var b, bs, t, z,
  14782. vert, vlen = vertices.length,
  14783. face, flen = faces.length,
  14784. cont, clen = contour.length;
  14785. //------
  14786. // Find directions for point movement
  14787. //
  14788. var RAD_TO_DEGREES = 180 / Math.PI;
  14789. function getBevelVec( pt_i, pt_j, pt_k ) {
  14790. // Algorithm 2
  14791. return getBevelVec2( pt_i, pt_j, pt_k );
  14792. }
  14793. function getBevelVec1( pt_i, pt_j, pt_k ) {
  14794. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  14795. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  14796. if ( anglea > angleb ) {
  14797. angleb += Math.PI * 2;
  14798. }
  14799. var anglec = ( anglea + angleb ) / 2;
  14800. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  14801. var x = - Math.cos( anglec );
  14802. var y = - Math.sin( anglec );
  14803. var vec = new THREE.Vector2( x, y ); //.normalize();
  14804. return vec;
  14805. }
  14806. function getBevelVec2( pt_i, pt_j, pt_k ) {
  14807. var a = THREE.ExtrudeGeometry.__v1,
  14808. b = THREE.ExtrudeGeometry.__v2,
  14809. v_hat = THREE.ExtrudeGeometry.__v3,
  14810. w_hat = THREE.ExtrudeGeometry.__v4,
  14811. p = THREE.ExtrudeGeometry.__v5,
  14812. q = THREE.ExtrudeGeometry.__v6,
  14813. v, w,
  14814. v_dot_w_hat, q_sub_p_dot_w_hat,
  14815. s, intersection;
  14816. // good reading for line-line intersection
  14817. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  14818. // define a as vector j->i
  14819. // define b as vectot k->i
  14820. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  14821. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  14822. // get unit vectors
  14823. v = a.normalize();
  14824. w = b.normalize();
  14825. // normals from pt i
  14826. v_hat.set( -v.y, v.x );
  14827. w_hat.set( w.y, -w.x );
  14828. // pts from i
  14829. p.copy( pt_i ).addSelf( v_hat );
  14830. q.copy( pt_i ).addSelf( w_hat );
  14831. if ( p.equals( q ) ) {
  14832. //console.log("Warning: lines are straight");
  14833. return w_hat.clone();
  14834. }
  14835. // Points from j, k. helps prevents points cross overover most of the time
  14836. p.copy( pt_j ).addSelf( v_hat );
  14837. q.copy( pt_k ).addSelf( w_hat );
  14838. v_dot_w_hat = v.dot( w_hat );
  14839. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  14840. // We should not reach these conditions
  14841. if ( v_dot_w_hat === 0 ) {
  14842. console.log( "Either infinite or no solutions!" );
  14843. if ( q_sub_p_dot_w_hat === 0 ) {
  14844. console.log( "Its finite solutions." );
  14845. } else {
  14846. console.log( "Too bad, no solutions." );
  14847. }
  14848. }
  14849. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  14850. if ( s < 0 ) {
  14851. // in case of emergecy, revert to algorithm 1.
  14852. return getBevelVec1( pt_i, pt_j, pt_k );
  14853. }
  14854. intersection = v.multiplyScalar( s ).addSelf( p );
  14855. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  14856. }
  14857. var contourMovements = [];
  14858. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  14859. if ( j === il ) j = 0;
  14860. if ( k === il ) k = 0;
  14861. // (j)---(i)---(k)
  14862. // console.log('i,j,k', i, j , k)
  14863. var pt_i = contour[ i ];
  14864. var pt_j = contour[ j ];
  14865. var pt_k = contour[ k ];
  14866. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  14867. }
  14868. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  14869. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14870. ahole = holes[ h ];
  14871. oneHoleMovements = [];
  14872. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  14873. if ( j === il ) j = 0;
  14874. if ( k === il ) k = 0;
  14875. // (j)---(i)---(k)
  14876. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  14877. }
  14878. holesMovements.push( oneHoleMovements );
  14879. verticesMovements = verticesMovements.concat( oneHoleMovements );
  14880. }
  14881. // Loop bevelSegments, 1 for the front, 1 for the back
  14882. for ( b = 0; b < bevelSegments; b ++ ) {
  14883. //for ( b = bevelSegments; b > 0; b -- ) {
  14884. t = b / bevelSegments;
  14885. z = bevelThickness * ( 1 - t );
  14886. //z = bevelThickness * t;
  14887. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  14888. //bs = bevelSize * t ; // linear
  14889. // contract shape
  14890. for ( i = 0, il = contour.length; i < il; i ++ ) {
  14891. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  14892. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  14893. v( vert.x, vert.y, - z );
  14894. }
  14895. // expand holes
  14896. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  14897. ahole = holes[ h ];
  14898. oneHoleMovements = holesMovements[ h ];
  14899. for ( i = 0, il = ahole.length; i < il; i++ ) {
  14900. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  14901. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  14902. v( vert.x, vert.y, -z );
  14903. }
  14904. }
  14905. }
  14906. bs = bevelSize;
  14907. // Back facing vertices
  14908. for ( i = 0; i < vlen; i ++ ) {
  14909. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  14910. if ( !extrudeByPath ) {
  14911. v( vert.x, vert.y, 0 );
  14912. } else {
  14913. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  14914. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  14915. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  14916. position2.copy(extrudePts[0]).addSelf(normal).addSelf(binormal);
  14917. v(position2.x, position2.y, position2.z);
  14918. }
  14919. }
  14920. // Add stepped vertices...
  14921. // Including front facing vertices
  14922. var s;
  14923. for ( s = 1; s <= steps; s ++ ) {
  14924. for ( i = 0; i < vlen; i ++ ) {
  14925. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  14926. if ( !extrudeByPath ) {
  14927. v( vert.x, vert.y, amount / steps * s );
  14928. } else {
  14929. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  14930. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  14931. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  14932. position2.copy(extrudePts[s]).addSelf(normal).addSelf(binormal);
  14933. v(position2.x, position2.y, position2.z );
  14934. }
  14935. }
  14936. }
  14937. // Add bevel segments planes
  14938. //for ( b = 1; b <= bevelSegments; b ++ ) {
  14939. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  14940. t = b / bevelSegments;
  14941. z = bevelThickness * ( 1 - t );
  14942. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  14943. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  14944. // contract shape
  14945. for ( i = 0, il = contour.length; i < il; i ++ ) {
  14946. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  14947. v( vert.x, vert.y, amount + z );
  14948. }
  14949. // expand holes
  14950. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14951. ahole = holes[ h ];
  14952. oneHoleMovements = holesMovements[ h ];
  14953. for ( i = 0, il = ahole.length; i < il; i++ ) {
  14954. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  14955. if ( !extrudeByPath ) {
  14956. v( vert.x, vert.y, amount + z );
  14957. } else {
  14958. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  14959. }
  14960. }
  14961. }
  14962. }
  14963. // set UV generator
  14964. var uvgen = THREE.ExtrudeGeometry.WorldUVGenerator;
  14965. ////
  14966. /// Handle Faces
  14967. ////
  14968. // Top and bottom faces
  14969. buildLidFaces();
  14970. // Sides faces
  14971. buildSideFaces();
  14972. ///// Internal functions
  14973. function buildLidFaces() {
  14974. if ( bevelEnabled ) {
  14975. var layer = 0 ; // steps + 1
  14976. var offset = vlen * layer;
  14977. // Bottom faces
  14978. for ( i = 0; i < flen; i ++ ) {
  14979. face = faces[ i ];
  14980. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  14981. }
  14982. layer = steps + bevelSegments * 2;
  14983. offset = vlen * layer;
  14984. // Top faces
  14985. for ( i = 0; i < flen; i ++ ) {
  14986. face = faces[ i ];
  14987. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  14988. }
  14989. } else {
  14990. // Bottom faces
  14991. for ( i = 0; i < flen; i++ ) {
  14992. face = faces[ i ];
  14993. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  14994. }
  14995. // Top faces
  14996. for ( i = 0; i < flen; i ++ ) {
  14997. face = faces[ i ];
  14998. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  14999. }
  15000. }
  15001. }
  15002. // Create faces for the z-sides of the shape
  15003. function buildSideFaces() {
  15004. var layeroffset = 0;
  15005. sidewalls( contour, layeroffset );
  15006. layeroffset += contour.length;
  15007. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15008. ahole = holes[ h ];
  15009. sidewalls( ahole, layeroffset );
  15010. //, true
  15011. layeroffset += ahole.length;
  15012. }
  15013. }
  15014. function sidewalls( contour, layeroffset ) {
  15015. var j, k;
  15016. i = contour.length;
  15017. while ( --i >= 0 ) {
  15018. j = i;
  15019. k = i - 1;
  15020. if ( k < 0 ) k = contour.length - 1;
  15021. //console.log('b', i,j, i-1, k,vertices.length);
  15022. var s = 0, sl = steps + bevelSegments * 2;
  15023. for ( s = 0; s < sl; s ++ ) {
  15024. var slen1 = vlen * s;
  15025. var slen2 = vlen * ( s + 1 );
  15026. var a = layeroffset + j + slen1,
  15027. b = layeroffset + k + slen1,
  15028. c = layeroffset + k + slen2,
  15029. d = layeroffset + j + slen2;
  15030. f4( a, b, c, d, contour, s, sl );
  15031. }
  15032. }
  15033. }
  15034. function v( x, y, z ) {
  15035. scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  15036. }
  15037. function f3( a, b, c, isBottom ) {
  15038. a += shapesOffset;
  15039. b += shapesOffset;
  15040. c += shapesOffset;
  15041. // normal, color, material
  15042. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  15043. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c)
  15044. : uvgen.generateTopUV( scope, shape, options, a, b, c);
  15045. scope.faceVertexUvs[ 0 ].push(uvs);
  15046. }
  15047. function f4( a, b, c, d, wallContour, stepIndex, stepsLength ) {
  15048. a += shapesOffset;
  15049. b += shapesOffset;
  15050. c += shapesOffset;
  15051. d += shapesOffset;
  15052. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  15053. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d, stepIndex, stepsLength);
  15054. scope.faceVertexUvs[ 0 ].push(uvs);
  15055. }
  15056. };
  15057. THREE.ExtrudeGeometry.WorldUVGenerator = {
  15058. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  15059. var ax = geometry.vertices[ indexA ].position.x,
  15060. ay = geometry.vertices[ indexA ].position.y,
  15061. bx = geometry.vertices[ indexB ].position.x,
  15062. by = geometry.vertices[ indexB ].position.y,
  15063. cx = geometry.vertices[ indexC ].position.x,
  15064. cy = geometry.vertices[ indexC ].position.y;
  15065. return [
  15066. new THREE.UV( ax, 1 - ay ),
  15067. new THREE.UV( bx, 1 - by ),
  15068. new THREE.UV( cx, 1 - cy )
  15069. ];
  15070. },
  15071. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  15072. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  15073. },
  15074. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  15075. indexA, indexB, indexC, indexD, stepIndex, stepsLength) {
  15076. var ax = geometry.vertices[ indexA ].position.x,
  15077. ay = geometry.vertices[ indexA ].position.y,
  15078. az = geometry.vertices[ indexA ].position.z,
  15079. bx = geometry.vertices[ indexB ].position.x,
  15080. by = geometry.vertices[ indexB ].position.y,
  15081. bz = geometry.vertices[ indexB ].position.z,
  15082. cx = geometry.vertices[ indexC ].position.x,
  15083. cy = geometry.vertices[ indexC ].position.y,
  15084. cz = geometry.vertices[ indexC ].position.z,
  15085. dx = geometry.vertices[ indexD ].position.x,
  15086. dy = geometry.vertices[ indexD ].position.y,
  15087. dz = geometry.vertices[ indexD ].position.z;
  15088. if ( Math.abs( ay - by ) < 0.01 ) {
  15089. return [
  15090. new THREE.UV( ax, az ),
  15091. new THREE.UV( bx, bz ),
  15092. new THREE.UV( cx, cz ),
  15093. new THREE.UV( dx, dz )
  15094. ];
  15095. } else {
  15096. return [
  15097. new THREE.UV( ay, az ),
  15098. new THREE.UV( by, bz ),
  15099. new THREE.UV( cy, cz ),
  15100. new THREE.UV( dy, dz )
  15101. ];
  15102. }
  15103. }
  15104. };
  15105. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  15106. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  15107. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  15108. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  15109. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  15110. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  15111. /**
  15112. * @author astrodud / http://astrodud.isgreat.org/
  15113. */
  15114. THREE.LatheGeometry = function ( points, steps, angle ) {
  15115. THREE.Geometry.call( this );
  15116. this.steps = steps || 12;
  15117. this.angle = angle || 2 * Math.PI;
  15118. var stepSize = this.angle / this.steps,
  15119. newV = [], oldInds = [], newInds = [], startInds = [],
  15120. matrix = new THREE.Matrix4().makeRotationZ( stepSize );
  15121. for ( var j = 0; j < points.length; j ++ ) {
  15122. this.vertices.push( new THREE.Vertex( points[ j ] ) );
  15123. newV[ j ] = points[ j ].clone();
  15124. oldInds[ j ] = this.vertices.length - 1;
  15125. }
  15126. for ( var r = 0; r <= this.angle + 0.001; r += stepSize ) { // need the +0.001 for it go up to angle
  15127. for ( var j = 0; j < newV.length; j ++ ) {
  15128. if ( r < this.angle ) {
  15129. newV[ j ] = matrix.multiplyVector3( newV[ j ].clone() );
  15130. this.vertices.push( new THREE.Vertex( newV[ j ] ) );
  15131. newInds[ j ] = this.vertices.length - 1;
  15132. } else {
  15133. newInds = startInds; // wrap it up!
  15134. }
  15135. }
  15136. if ( r == 0 ) startInds = oldInds;
  15137. for ( var j = 0; j < oldInds.length - 1; j ++ ) {
  15138. this.faces.push( new THREE.Face4( newInds[ j ], newInds[ j + 1 ], oldInds[ j + 1 ], oldInds[ j ] ) );
  15139. this.faceVertexUvs[ 0 ].push( [
  15140. new THREE.UV( 1 - r / this.angle, j / points.length ),
  15141. new THREE.UV( 1 - r / this.angle, ( j + 1 ) / points.length ),
  15142. new THREE.UV( 1 - ( r - stepSize ) / this.angle, ( j + 1 ) / points.length ),
  15143. new THREE.UV( 1 - ( r - stepSize ) / this.angle, j / points.length )
  15144. ] );
  15145. }
  15146. oldInds = newInds;
  15147. newInds = [];
  15148. }
  15149. this.computeCentroids();
  15150. this.computeFaceNormals();
  15151. this.computeVertexNormals();
  15152. };
  15153. THREE.LatheGeometry.prototype = new THREE.Geometry();
  15154. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  15155. /**
  15156. * @author mr.doob / http://mrdoob.com/
  15157. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  15158. */
  15159. THREE.PlaneGeometry = function ( width, depth, segmentsWidth, segmentsDepth ) {
  15160. THREE.Geometry.call( this );
  15161. var ix, iz,
  15162. width_half = width / 2,
  15163. depth_half = depth / 2,
  15164. gridX = segmentsWidth || 1,
  15165. gridZ = segmentsDepth || 1,
  15166. gridX1 = gridX + 1,
  15167. gridZ1 = gridZ + 1,
  15168. segment_width = width / gridX,
  15169. segment_depth = depth / gridZ,
  15170. normal = new THREE.Vector3( 0, 1, 0 );
  15171. for ( iz = 0; iz < gridZ1; iz ++ ) {
  15172. for ( ix = 0; ix < gridX1; ix ++ ) {
  15173. var x = ix * segment_width - width_half;
  15174. var z = iz * segment_depth - depth_half;
  15175. this.vertices.push( new THREE.Vertex( new THREE.Vector3( x, 0, z ) ) );
  15176. }
  15177. }
  15178. for ( iz = 0; iz < gridZ; iz ++ ) {
  15179. for ( ix = 0; ix < gridX; ix ++ ) {
  15180. var a = ix + gridX1 * iz;
  15181. var b = ix + gridX1 * ( iz + 1 );
  15182. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  15183. var d = ( ix + 1 ) + gridX1 * iz;
  15184. var face = new THREE.Face4( a, b, c, d );
  15185. face.normal.copy( normal );
  15186. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  15187. this.faces.push( face );
  15188. this.faceVertexUvs[ 0 ].push( [
  15189. new THREE.UV( ix / gridX, iz / gridZ ),
  15190. new THREE.UV( ix / gridX, ( iz + 1 ) / gridZ ),
  15191. new THREE.UV( ( ix + 1 ) / gridX, ( iz + 1 ) / gridZ ),
  15192. new THREE.UV( ( ix + 1 ) / gridX, iz / gridZ )
  15193. ] );
  15194. }
  15195. }
  15196. this.computeCentroids();
  15197. };
  15198. THREE.PlaneGeometry.prototype = new THREE.Geometry();
  15199. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  15200. /**
  15201. * @author mr.doob / http://mrdoob.com/
  15202. */
  15203. THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength ) {
  15204. THREE.Geometry.call( this );
  15205. radius = radius || 50;
  15206. phiStart = phiStart !== undefined ? phiStart : 0;
  15207. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  15208. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  15209. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  15210. var segmentsX = Math.max( 3, Math.floor( segmentsWidth ) || 8 );
  15211. var segmentsY = Math.max( 2, Math.floor( segmentsHeight ) || 6 );
  15212. var x, y, vertices = [], uvs = [];
  15213. for ( y = 0; y <= segmentsY; y ++ ) {
  15214. var verticesRow = [];
  15215. var uvsRow = [];
  15216. for ( x = 0; x <= segmentsX; x ++ ) {
  15217. var u = x / segmentsX;
  15218. var v = y / segmentsY;
  15219. var xpos = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15220. var ypos = radius * Math.cos( thetaStart + v * thetaLength );
  15221. var zpos = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15222. this.vertices.push( new THREE.Vertex( new THREE.Vector3( xpos, ypos, zpos ) ) );
  15223. verticesRow.push( this.vertices.length - 1 );
  15224. uvsRow.push( new THREE.UV( u, v ) );
  15225. }
  15226. vertices.push( verticesRow );
  15227. uvs.push( uvsRow );
  15228. }
  15229. for ( y = 0; y < segmentsY; y ++ ) {
  15230. for ( x = 0; x < segmentsX; x ++ ) {
  15231. var v1 = vertices[ y ][ x + 1 ];
  15232. var v2 = vertices[ y ][ x ];
  15233. var v3 = vertices[ y + 1 ][ x ];
  15234. var v4 = vertices[ y + 1 ][ x + 1 ];
  15235. var n1 = this.vertices[ v1 ].position.clone().normalize();
  15236. var n2 = this.vertices[ v2 ].position.clone().normalize();
  15237. var n3 = this.vertices[ v3 ].position.clone().normalize();
  15238. var n4 = this.vertices[ v4 ].position.clone().normalize();
  15239. var uv1 = uvs[ y ][ x + 1 ].clone();
  15240. var uv2 = uvs[ y ][ x ].clone();
  15241. var uv3 = uvs[ y + 1 ][ x ].clone();
  15242. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  15243. if ( Math.abs( this.vertices[ v1 ].position.y ) == radius ) {
  15244. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  15245. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  15246. } else if ( Math.abs( this.vertices[ v3 ].position.y ) == radius ) {
  15247. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  15248. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  15249. } else {
  15250. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  15251. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  15252. }
  15253. }
  15254. }
  15255. this.computeCentroids();
  15256. this.computeFaceNormals();
  15257. this.boundingSphere = { radius: radius };
  15258. };
  15259. THREE.SphereGeometry.prototype = new THREE.Geometry();
  15260. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  15261. /**
  15262. * @author zz85 / http://www.lab4games.net/zz85/blog
  15263. * @author alteredq / http://alteredqualia.com/
  15264. *
  15265. * For creating 3D text geometry in three.js
  15266. *
  15267. * Text = 3D Text
  15268. *
  15269. * parameters = {
  15270. * size: <float>, // size of the text
  15271. * height: <float>, // thickness to extrude text
  15272. * curveSegments: <int>, // number of points on the curves
  15273. *
  15274. * font: <string>, // font name
  15275. * weight: <string>, // font weight (normal, bold)
  15276. * style: <string>, // font style (normal, italics)
  15277. *
  15278. * bevelEnabled: <bool>, // turn on bevel
  15279. * bevelThickness: <float>, // how deep into text bevel goes
  15280. * bevelSize: <float>, // how far from text outline is bevel
  15281. *
  15282. * bend: <bool> // bend according to hardcoded curve (generates bendPath)
  15283. * bendPath: <curve> // wraps text according to bend Path
  15284. * }
  15285. *
  15286. * It uses techniques used in:
  15287. *
  15288. * typeface.js and canvastext
  15289. * For converting fonts and rendering with javascript
  15290. * http://typeface.neocracy.org
  15291. *
  15292. * Triangulation ported from AS3
  15293. * Simple Polygon Triangulation
  15294. * http://actionsnippet.com/?p=1462
  15295. *
  15296. * A Method to triangulate shapes with holes
  15297. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15298. *
  15299. */
  15300. /* Usage Examples
  15301. // TextGeometry wrapper
  15302. var text3d = new TextGeometry( text, options );
  15303. // Complete manner
  15304. var textPath = new THREE.TextPath( text, options );
  15305. var textShapes = textPath.toShapes();
  15306. var text3d = new ExtrudeGeometry( textShapes, options );
  15307. */
  15308. THREE.TextGeometry = function ( text, parameters ) {
  15309. var textPath = new THREE.TextPath( text, parameters );
  15310. var textShapes = textPath.toShapes();
  15311. // translate parameters to ExtrudeGeometry API
  15312. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  15313. // defaults
  15314. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  15315. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  15316. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  15317. if ( parameters.bend ) {
  15318. var b = textShapes[ textShapes.length - 1 ].getBoundingBox();
  15319. var max = b.maxX;
  15320. parameters.bendPath = new THREE.QuadraticBezierCurve( new THREE.Vector2( 0, 0 ),
  15321. new THREE.Vector2( max / 2, 120 ),
  15322. new THREE.Vector2( max, 0 ) );
  15323. }
  15324. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  15325. };
  15326. THREE.TextGeometry.prototype = new THREE.ExtrudeGeometry();
  15327. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  15328. THREE.FontUtils = {
  15329. faces : {},
  15330. // Just for now. face[weight][style]
  15331. face : "helvetiker",
  15332. weight: "normal",
  15333. style : "normal",
  15334. size : 150,
  15335. divisions : 10,
  15336. getFace : function() {
  15337. return this.faces[ this.face ][ this.weight ][ this.style ];
  15338. },
  15339. loadFace : function( data ) {
  15340. var family = data.familyName.toLowerCase();
  15341. var ThreeFont = this;
  15342. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15343. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15344. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15345. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15346. return data;
  15347. },
  15348. drawText : function( text ) {
  15349. var characterPts = [], allPts = [];
  15350. // RenderText
  15351. var i, p,
  15352. face = this.getFace(),
  15353. scale = this.size / face.resolution,
  15354. offset = 0,
  15355. chars = String( text ).split( '' ),
  15356. length = chars.length;
  15357. var fontPaths = [];
  15358. for ( i = 0; i < length; i ++ ) {
  15359. var path = new THREE.Path();
  15360. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15361. offset += ret.offset;
  15362. //characterPts.push( ret.points );
  15363. //allPts = allPts.concat( ret.points );
  15364. fontPaths.push( ret.path );
  15365. }
  15366. // get the width
  15367. var width = offset / 2;
  15368. //
  15369. // for ( p = 0; p < allPts.length; p++ ) {
  15370. //
  15371. // allPts[ p ].x -= width;
  15372. //
  15373. // }
  15374. //var extract = this.extractPoints( allPts, characterPts );
  15375. //extract.contour = allPts;
  15376. //extract.paths = fontPaths;
  15377. //extract.offset = width;
  15378. return { paths : fontPaths, offset : width };
  15379. },
  15380. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15381. var pts = [];
  15382. var i, i2, divisions,
  15383. outline, action, length,
  15384. scaleX, scaleY,
  15385. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15386. laste,
  15387. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15388. if ( !glyph ) return;
  15389. if ( glyph.o ) {
  15390. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15391. length = outline.length;
  15392. scaleX = scale;
  15393. scaleY = scale;
  15394. for ( i = 0; i < length; ) {
  15395. action = outline[ i ++ ];
  15396. //console.log( action );
  15397. switch( action ) {
  15398. case 'm':
  15399. // Move To
  15400. x = outline[ i++ ] * scaleX + offset;
  15401. y = outline[ i++ ] * scaleY;
  15402. pts.push( new THREE.Vector2( x, y ) );
  15403. path.moveTo( x, y );
  15404. break;
  15405. case 'l':
  15406. // Line To
  15407. x = outline[ i++ ] * scaleX + offset;
  15408. y = outline[ i++ ] * scaleY;
  15409. pts.push( new THREE.Vector2( x, y ) );
  15410. path.lineTo(x,y);
  15411. break;
  15412. case 'q':
  15413. // QuadraticCurveTo
  15414. cpx = outline[ i++ ] * scaleX + offset;
  15415. cpy = outline[ i++ ] * scaleY;
  15416. cpx1 = outline[ i++ ] * scaleX + offset;
  15417. cpy1 = outline[ i++ ] * scaleY;
  15418. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15419. laste = pts[ pts.length - 1 ];
  15420. if ( laste ) {
  15421. cpx0 = laste.x;
  15422. cpy0 = laste.y;
  15423. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15424. var t = i2 / divisions;
  15425. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15426. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15427. pts.push( new THREE.Vector2( tx, ty ) );
  15428. }
  15429. }
  15430. break;
  15431. case 'b':
  15432. // Cubic Bezier Curve
  15433. cpx = outline[ i++ ] * scaleX + offset;
  15434. cpy = outline[ i++ ] * scaleY;
  15435. cpx1 = outline[ i++ ] * scaleX + offset;
  15436. cpy1 = outline[ i++ ] * -scaleY;
  15437. cpx2 = outline[ i++ ] * scaleX + offset;
  15438. cpy2 = outline[ i++ ] * -scaleY;
  15439. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15440. laste = pts[ pts.length - 1 ];
  15441. if ( laste ) {
  15442. cpx0 = laste.x;
  15443. cpy0 = laste.y;
  15444. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15445. var t = i2 / divisions;
  15446. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15447. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15448. pts.push( new THREE.Vector2( tx, ty ) );
  15449. }
  15450. }
  15451. break;
  15452. }
  15453. }
  15454. }
  15455. return { offset: glyph.ha*scale, points:pts, path:path};
  15456. }
  15457. };
  15458. /**
  15459. * This code is a quick port of code written in C++ which was submitted to
  15460. * flipcode.com by John W. Ratcliff // July 22, 2000
  15461. * See original code and more information here:
  15462. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15463. *
  15464. * ported to actionscript by Zevan Rosser
  15465. * www.actionsnippet.com
  15466. *
  15467. * ported to javascript by Joshua Koo
  15468. * http://www.lab4games.net/zz85/blog
  15469. *
  15470. */
  15471. ( function( namespace ) {
  15472. var EPSILON = 0.0000000001;
  15473. // takes in an contour array and returns
  15474. var process = function( contour, indices ) {
  15475. var n = contour.length;
  15476. if ( n < 3 ) return null;
  15477. var result = [],
  15478. verts = [],
  15479. vertIndices = [];
  15480. /* we want a counter-clockwise polygon in verts */
  15481. var u, v, w;
  15482. if ( area( contour ) > 0.0 ) {
  15483. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15484. } else {
  15485. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15486. }
  15487. var nv = n;
  15488. /* remove nv - 2 vertices, creating 1 triangle every time */
  15489. var count = 2 * nv; /* error detection */
  15490. for( v = nv - 1; nv > 2; ) {
  15491. /* if we loop, it is probably a non-simple polygon */
  15492. if ( ( count-- ) <= 0 ) {
  15493. //** Triangulate: ERROR - probable bad polygon!
  15494. //throw ( "Warning, unable to triangulate polygon!" );
  15495. //return null;
  15496. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15497. console.log( "Warning, unable to triangulate polygon!" );
  15498. if ( indices ) return vertIndices;
  15499. return result;
  15500. }
  15501. /* three consecutive vertices in current polygon, <u,v,w> */
  15502. u = v; if ( nv <= u ) u = 0; /* previous */
  15503. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15504. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15505. if ( snip( contour, u, v, w, nv, verts ) ) {
  15506. var a, b, c, s, t;
  15507. /* true names of the vertices */
  15508. a = verts[ u ];
  15509. b = verts[ v ];
  15510. c = verts[ w ];
  15511. /* output Triangle */
  15512. /*
  15513. result.push( contour[ a ] );
  15514. result.push( contour[ b ] );
  15515. result.push( contour[ c ] );
  15516. */
  15517. result.push( [ contour[ a ],
  15518. contour[ b ],
  15519. contour[ c ] ] );
  15520. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15521. /* remove v from the remaining polygon */
  15522. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15523. verts[ s ] = verts[ t ];
  15524. }
  15525. nv--;
  15526. /* reset error detection counter */
  15527. count = 2 * nv;
  15528. }
  15529. }
  15530. if ( indices ) return vertIndices;
  15531. return result;
  15532. };
  15533. // calculate area of the contour polygon
  15534. var area = function ( contour ) {
  15535. var n = contour.length;
  15536. var a = 0.0;
  15537. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15538. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15539. }
  15540. return a * 0.5;
  15541. };
  15542. // see if p is inside triangle abc
  15543. var insideTriangle = function( ax, ay,
  15544. bx, by,
  15545. cx, cy,
  15546. px, py ) {
  15547. var aX, aY, bX, bY;
  15548. var cX, cY, apx, apy;
  15549. var bpx, bpy, cpx, cpy;
  15550. var cCROSSap, bCROSScp, aCROSSbp;
  15551. aX = cx - bx; aY = cy - by;
  15552. bX = ax - cx; bY = ay - cy;
  15553. cX = bx - ax; cY = by - ay;
  15554. apx= px -ax; apy= py - ay;
  15555. bpx= px - bx; bpy= py - by;
  15556. cpx= px - cx; cpy= py - cy;
  15557. aCROSSbp = aX*bpy - aY*bpx;
  15558. cCROSSap = cX*apy - cY*apx;
  15559. bCROSScp = bX*cpy - bY*cpx;
  15560. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  15561. };
  15562. var snip = function ( contour, u, v, w, n, verts ) {
  15563. var p;
  15564. var ax, ay, bx, by;
  15565. var cx, cy, px, py;
  15566. ax = contour[ verts[ u ] ].x;
  15567. ay = contour[ verts[ u ] ].y;
  15568. bx = contour[ verts[ v ] ].x;
  15569. by = contour[ verts[ v ] ].y;
  15570. cx = contour[ verts[ w ] ].x;
  15571. cy = contour[ verts[ w ] ].y;
  15572. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  15573. for ( p = 0; p < n; p++ ) {
  15574. if( (p == u) || (p == v) || (p == w) ) continue;
  15575. px = contour[ verts[ p ] ].x
  15576. py = contour[ verts[ p ] ].y
  15577. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  15578. }
  15579. return true;
  15580. };
  15581. namespace.Triangulate = process;
  15582. namespace.Triangulate.area = area;
  15583. return namespace;
  15584. })(THREE.FontUtils);
  15585. // To use the typeface.js face files, hook up the API
  15586. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  15587. /**
  15588. * @author oosmoxiecode
  15589. * @author mr.doob / http://mrdoob.com/
  15590. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  15591. */
  15592. THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {
  15593. THREE.Geometry.call( this );
  15594. var scope = this;
  15595. this.radius = radius || 100;
  15596. this.tube = tube || 40;
  15597. this.segmentsR = segmentsR || 8;
  15598. this.segmentsT = segmentsT || 6;
  15599. this.arc = arc || Math.PI * 2;
  15600. var center = new THREE.Vector3(), uvs = [], normals = [];
  15601. for ( var j = 0; j <= this.segmentsR; j ++ ) {
  15602. for ( var i = 0; i <= this.segmentsT; i ++ ) {
  15603. var u = i / this.segmentsT * this.arc;
  15604. var v = j / this.segmentsR * Math.PI * 2;
  15605. center.x = this.radius * Math.cos( u );
  15606. center.y = this.radius * Math.sin( u );
  15607. var vector = new THREE.Vector3();
  15608. vector.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  15609. vector.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  15610. vector.z = this.tube * Math.sin( v );
  15611. this.vertices.push( new THREE.Vertex( vector ) );
  15612. uvs.push( new THREE.UV( i / this.segmentsT, 1 - j / this.segmentsR ) );
  15613. normals.push( vector.clone().subSelf( center ).normalize() );
  15614. }
  15615. }
  15616. for ( var j = 1; j <= this.segmentsR; j ++ ) {
  15617. for ( var i = 1; i <= this.segmentsT; i ++ ) {
  15618. var a = ( this.segmentsT + 1 ) * j + i - 1;
  15619. var b = ( this.segmentsT + 1 ) * ( j - 1 ) + i - 1;
  15620. var c = ( this.segmentsT + 1 ) * ( j - 1 ) + i;
  15621. var d = ( this.segmentsT + 1 ) * j + i;
  15622. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  15623. face.normal.addSelf( normals[ a ] );
  15624. face.normal.addSelf( normals[ b ] );
  15625. face.normal.addSelf( normals[ c ] );
  15626. face.normal.addSelf( normals[ d ] );
  15627. face.normal.normalize();
  15628. this.faces.push( face );
  15629. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  15630. }
  15631. }
  15632. this.computeCentroids();
  15633. };
  15634. THREE.TorusGeometry.prototype = new THREE.Geometry();
  15635. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  15636. /**
  15637. * @author oosmoxiecode
  15638. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  15639. */
  15640. THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {
  15641. THREE.Geometry.call( this );
  15642. var scope = this;
  15643. this.radius = radius || 200;
  15644. this.tube = tube || 40;
  15645. this.segmentsR = segmentsR || 64;
  15646. this.segmentsT = segmentsT || 8;
  15647. this.p = p || 2;
  15648. this.q = q || 3;
  15649. this.heightScale = heightScale || 1;
  15650. this.grid = new Array(this.segmentsR);
  15651. var tang = new THREE.Vector3();
  15652. var n = new THREE.Vector3();
  15653. var bitan = new THREE.Vector3();
  15654. for ( var i = 0; i < this.segmentsR; ++ i ) {
  15655. this.grid[ i ] = new Array( this.segmentsT );
  15656. for ( var j = 0; j < this.segmentsT; ++ j ) {
  15657. var u = i / this.segmentsR * 2 * this.p * Math.PI;
  15658. var v = j / this.segmentsT * 2 * Math.PI;
  15659. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  15660. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  15661. var cx, cy;
  15662. tang.sub( p2, p1 );
  15663. n.add( p2, p1 );
  15664. bitan.cross( tang, n );
  15665. n.cross( bitan, tang );
  15666. bitan.normalize();
  15667. n.normalize();
  15668. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  15669. cy = this.tube * Math.sin( v );
  15670. p1.x += cx * n.x + cy * bitan.x;
  15671. p1.y += cx * n.y + cy * bitan.y;
  15672. p1.z += cx * n.z + cy * bitan.z;
  15673. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  15674. }
  15675. }
  15676. for ( var i = 0; i < this.segmentsR; ++ i ) {
  15677. for ( var j = 0; j < this.segmentsT; ++ j ) {
  15678. var ip = ( i + 1 ) % this.segmentsR;
  15679. var jp = ( j + 1 ) % this.segmentsT;
  15680. var a = this.grid[ i ][ j ];
  15681. var b = this.grid[ ip ][ j ];
  15682. var c = this.grid[ ip ][ jp ];
  15683. var d = this.grid[ i ][ jp ];
  15684. var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
  15685. var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
  15686. var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
  15687. var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );
  15688. this.faces.push( new THREE.Face4( a, b, c, d ) );
  15689. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  15690. }
  15691. }
  15692. this.computeCentroids();
  15693. this.computeFaceNormals();
  15694. this.computeVertexNormals();
  15695. function vert( x, y, z ) {
  15696. return scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) ) - 1;
  15697. }
  15698. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  15699. var cu = Math.cos( u );
  15700. var cv = Math.cos( v );
  15701. var su = Math.sin( u );
  15702. var quOverP = in_q / in_p * u;
  15703. var cs = Math.cos( quOverP );
  15704. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  15705. var ty = radius * ( 2 + cs ) * su * 0.5;
  15706. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  15707. return new THREE.Vector3( tx, ty, tz );
  15708. }
  15709. };
  15710. THREE.TorusKnotGeometry.prototype = new THREE.Geometry();
  15711. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  15712. /**
  15713. * @author WestLangley / https://github.com/WestLangley
  15714. * @author zz85 / https://github.com/zz85
  15715. * @author miningold / https://github.com/miningold
  15716. *
  15717. * Modified from the TorusKnotGeometry by @oosmoxiecode
  15718. *
  15719. * Creates a tube which extrudes along a 3d spline
  15720. *
  15721. * Uses parallel transport frames as described in
  15722. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  15723. */
  15724. THREE.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {
  15725. THREE.Geometry.call( this );
  15726. this.path = path;
  15727. this.segments = segments || 64;
  15728. this.radius = radius || 1;
  15729. this.segmentsRadius = segmentsRadius || 8;
  15730. this.closed = closed || false;
  15731. if ( debug ) this.debug = new THREE.Object3D();
  15732. this.grid = [];
  15733. var scope = this,
  15734. tangent = new THREE.Vector3(),
  15735. normal = new THREE.Vector3(),
  15736. binormal = new THREE.Vector3(),
  15737. vec = new THREE.Vector3(),
  15738. mat = new THREE.Matrix4(),
  15739. tangents = [],
  15740. normals = [],
  15741. binormals = [],
  15742. numpoints = this.segments + 1,
  15743. theta,
  15744. epsilon = 0.0001,
  15745. smallest,
  15746. x, y, z,
  15747. tx, ty, tz,
  15748. u, v,
  15749. p1, p2,
  15750. cx, cy,
  15751. pos, pos2,
  15752. i, j,
  15753. ip, jp,
  15754. a, b, c, d,
  15755. uva, uvb, uvc, uvd;
  15756. // expose internals
  15757. this.tangents = tangents;
  15758. this.normals = normals;
  15759. this.binormals = binormals;
  15760. function vert( x, y, z ) {
  15761. return scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) ) - 1;
  15762. }
  15763. // compute the tangent vectors for each segment on the path
  15764. for ( i = 0; i < numpoints; i++ ) {
  15765. u = i / ( numpoints - 1 );
  15766. tangents[ i ] = this.path.getTangentAt( u );
  15767. tangents[ i ].normalize();
  15768. }
  15769. initialNormal3();
  15770. function initialNormal1() {
  15771. // fixed start binormal. Has dangers of 0 vectors
  15772. normals[ 0 ] = new THREE.Vector3();
  15773. binormals[ 0 ] = new THREE.Vector3();
  15774. var lastBinormal = new THREE.Vector3( 0, 0, 1 );
  15775. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  15776. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  15777. }
  15778. function initialNormal2() {
  15779. // This uses the Frenet-Serret formula for deriving binormal
  15780. var t2 = path.getTangentAt( epsilon );
  15781. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize()
  15782. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  15783. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  15784. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  15785. }
  15786. function initialNormal3() {
  15787. // select an initial normal vector perpenicular to the first tangent vector,
  15788. // and in the direction of the smallest tangent xyz component
  15789. normals[ 0 ] = new THREE.Vector3();
  15790. binormals[ 0 ] = new THREE.Vector3();
  15791. smallest = Number.MAX_VALUE;
  15792. tx = Math.abs( tangents[ 0 ].x );
  15793. ty = Math.abs( tangents[ 0 ].y );
  15794. tz = Math.abs( tangents[ 0 ].z );
  15795. if ( tx <= smallest ) {
  15796. smallest = tx;
  15797. vec.set( 1, 0, 0 );
  15798. }
  15799. if ( ty <= smallest ) {
  15800. smallest = ty;
  15801. vec.set( 0, 1, 0 );
  15802. }
  15803. if ( tz <= smallest ) {
  15804. vec.set( 0, 0, 1 );
  15805. }
  15806. // vec.cross( tangents[ 0 ], normal ).normalize();
  15807. normals[ 0 ].cross( tangents[ 0 ], vec );
  15808. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  15809. }
  15810. // compute the slowly-varying normal and binormal vectors for each segment on the path
  15811. for ( i = 1; i < numpoints; i++ ) {
  15812. normals[ i ] = normals[ i-1 ].clone();
  15813. binormals[ i ] = binormals[ i-1 ].clone();
  15814. vec.cross( tangents[ i-1 ], tangents[ i ] );
  15815. if ( vec.length() > epsilon ) {
  15816. vec.normalize();
  15817. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  15818. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  15819. }
  15820. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  15821. }
  15822. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  15823. if ( this.closed ) {
  15824. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  15825. theta /= ( numpoints - 1 );
  15826. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  15827. theta = -theta;
  15828. }
  15829. for ( i = 1; i < numpoints; i++ ) {
  15830. // twist a little...
  15831. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  15832. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  15833. }
  15834. }
  15835. // consruct the grid
  15836. for ( i = 0; i < numpoints; i++ ) {
  15837. this.grid[ i ] = [];
  15838. u = i / ( numpoints - 1 );
  15839. pos = this.path.getPointAt( u );
  15840. tangent = tangents[ i ];
  15841. normal = normals[ i ];
  15842. binormal = binormals[ i ];
  15843. if ( this.debug ) {
  15844. this.debug.add(new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff));
  15845. this.debug.add(new THREE.ArrowHelper(normal, pos, radius, 0xff0000));
  15846. this.debug.add(new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00));
  15847. }
  15848. for ( j = 0; j < this.segmentsRadius; j++ ) {
  15849. v = j / this.segmentsRadius * 2 * Math.PI;
  15850. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  15851. cy = this.radius * Math.sin( v );
  15852. pos2 = new THREE.Vector3().copy( pos );
  15853. pos2.x += cx * normal.x + cy * binormal.x;
  15854. pos2.y += cx * normal.y + cy * binormal.y;
  15855. pos2.z += cx * normal.z + cy * binormal.z;
  15856. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  15857. }
  15858. }
  15859. // construct the mesh
  15860. for ( i = 0; i < this.segments; i++ ) {
  15861. for ( j = 0; j < this.segmentsRadius; j++ ) {
  15862. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  15863. jp = (j + 1) % this.segmentsRadius;
  15864. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  15865. b = this.grid[ ip ][ j ];
  15866. c = this.grid[ ip ][ jp ];
  15867. d = this.grid[ i ][ jp ];
  15868. uva = new THREE.UV( i / this.segments, j / this.segmentsRadius );
  15869. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.segmentsRadius );
  15870. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.segmentsRadius );
  15871. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.segmentsRadius );
  15872. this.faces.push( new THREE.Face4( a, b, c, d ) );
  15873. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  15874. }
  15875. }
  15876. this.computeCentroids();
  15877. this.computeFaceNormals();
  15878. this.computeVertexNormals();
  15879. };
  15880. THREE.TubeGeometry.prototype = new THREE.Geometry();
  15881. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  15882. /**
  15883. * @author clockworkgeek / https://github.com/clockworkgeek
  15884. * @author timothypratley / https://github.com/timothypratley
  15885. */
  15886. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  15887. THREE.Geometry.call( this );
  15888. radius = radius || 1;
  15889. detail = detail || 0;
  15890. var that = this;
  15891. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  15892. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  15893. }
  15894. var midpoints = [], p = this.vertices;
  15895. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  15896. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  15897. }
  15898. this.mergeVertices();
  15899. // Apply radius
  15900. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  15901. this.vertices[ i ].position.multiplyScalar( radius );
  15902. }
  15903. /**
  15904. * Project vector onto sphere's surface
  15905. */
  15906. function prepare( vector ) {
  15907. var vertex = new THREE.Vertex( vector.normalize() );
  15908. vertex.index = that.vertices.push( vertex ) - 1;
  15909. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  15910. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  15911. var v = inclination( vector ) / Math.PI + 0.5;
  15912. vertex.uv = new THREE.UV( u, v );
  15913. return vertex;
  15914. }
  15915. /**
  15916. * Approximate a curved face with recursively sub-divided triangles.
  15917. */
  15918. function make( v1, v2, v3, detail ) {
  15919. if ( detail < 1 ) {
  15920. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.position.clone(), v2.position.clone(), v3.position.clone() ] );
  15921. face.centroid.addSelf( v1.position ).addSelf( v2.position ).addSelf( v3.position ).divideScalar( 3 );
  15922. face.normal = face.centroid.clone().normalize();
  15923. that.faces.push( face );
  15924. var azi = azimuth( face.centroid );
  15925. that.faceVertexUvs[ 0 ].push( [
  15926. correctUV( v1.uv, v1.position, azi ),
  15927. correctUV( v2.uv, v2.position, azi ),
  15928. correctUV( v3.uv, v3.position, azi )
  15929. ] );
  15930. }
  15931. else {
  15932. detail -= 1;
  15933. // split triangle into 4 smaller triangles
  15934. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  15935. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  15936. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  15937. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  15938. }
  15939. }
  15940. function midpoint( v1, v2 ) {
  15941. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  15942. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  15943. var mid = midpoints[ v1.index ][ v2.index ];
  15944. if ( mid === undefined ) {
  15945. // generate mean point and project to surface with prepare()
  15946. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  15947. new THREE.Vector3().add( v1.position, v2.position ).divideScalar( 2 )
  15948. );
  15949. }
  15950. return mid;
  15951. }
  15952. /**
  15953. * Angle around the Y axis, counter-clockwise when looking from above.
  15954. */
  15955. function azimuth( vector ) {
  15956. return Math.atan2( vector.z, -vector.x );
  15957. }
  15958. /**
  15959. * Angle above the XZ plane.
  15960. */
  15961. function inclination( vector ) {
  15962. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  15963. }
  15964. /**
  15965. * Texture fixing helper. Spheres have some odd behaviours.
  15966. */
  15967. function correctUV( uv, vector, azimuth ) {
  15968. if ( (azimuth < 0) && (uv.u === 1) ) uv = new THREE.UV( uv.u - 1, uv.v );
  15969. if ( (vector.x === 0) && (vector.z === 0) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  15970. return uv;
  15971. }
  15972. this.computeCentroids();
  15973. this.boundingSphere = { radius: radius };
  15974. };
  15975. THREE.PolyhedronGeometry.prototype = new THREE.Geometry();
  15976. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  15977. /**
  15978. * @author timothypratley / https://github.com/timothypratley
  15979. */
  15980. THREE.IcosahedronGeometry = function ( radius, detail ) {
  15981. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15982. var vertices = [
  15983. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  15984. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  15985. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  15986. ];
  15987. var faces = [
  15988. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  15989. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  15990. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  15991. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  15992. ];
  15993. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  15994. };
  15995. THREE.IcosahedronGeometry.prototype = new THREE.Geometry();
  15996. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  15997. /**
  15998. * @author timothypratley / https://github.com/timothypratley
  15999. */
  16000. THREE.OctahedronGeometry = function ( radius, detail ) {
  16001. var vertices = [
  16002. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  16003. ];
  16004. var faces = [
  16005. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  16006. ];
  16007. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  16008. };
  16009. THREE.OctahedronGeometry.prototype = new THREE.Geometry();
  16010. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  16011. /**
  16012. * @author timothypratley / https://github.com/timothypratley
  16013. */
  16014. THREE.TetrahedronGeometry = function ( radius, detail ) {
  16015. var vertices = [
  16016. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  16017. ];
  16018. var faces = [
  16019. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  16020. ];
  16021. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  16022. };
  16023. THREE.TetrahedronGeometry.prototype = new THREE.Geometry();
  16024. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  16025. /**
  16026. * @author sroucheray / http://sroucheray.org/
  16027. * @author mr.doob / http://mrdoob.com/
  16028. */
  16029. THREE.AxisHelper = function () {
  16030. THREE.Object3D.call( this );
  16031. var lineGeometry = new THREE.Geometry();
  16032. lineGeometry.vertices.push( new THREE.Vertex() );
  16033. lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 100, 0 ) ) );
  16034. var coneGeometry = new THREE.CylinderGeometry( 0, 5, 25, 5, 1 );
  16035. var line, cone;
  16036. // x
  16037. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
  16038. line.rotation.z = - Math.PI / 2;
  16039. this.add( line );
  16040. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0xff0000 } ) );
  16041. cone.position.x = 100;
  16042. cone.rotation.z = - Math.PI / 2;
  16043. this.add( cone );
  16044. // y
  16045. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x00ff00 } ) );
  16046. this.add( line );
  16047. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x00ff00 } ) );
  16048. cone.position.y = 100;
  16049. this.add( cone );
  16050. // z
  16051. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
  16052. line.rotation.x = Math.PI / 2;
  16053. this.add( line );
  16054. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x0000ff } ) );
  16055. cone.position.z = 100;
  16056. cone.rotation.x = Math.PI / 2;
  16057. this.add( cone );
  16058. };
  16059. THREE.AxisHelper.prototype = new THREE.Object3D();
  16060. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  16061. /**
  16062. * @author WestLangley / https://github.com/WestLangley
  16063. * @author zz85 / https://github.com/zz85
  16064. *
  16065. * Creates an arrow for visualizing directions
  16066. *
  16067. * Parameters:
  16068. * dir - Vector3
  16069. * origin - Vector3
  16070. * length - Number
  16071. * hex - color in hex value
  16072. */
  16073. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  16074. THREE.Object3D.call( this );
  16075. if ( hex === undefined ) hex = 0xffff00;
  16076. if ( length === undefined ) length = 20;
  16077. var lineGeometry = new THREE.Geometry();
  16078. lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 0, 0 ) ) );
  16079. lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 1, 0 ) ) );
  16080. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : hex } ) );
  16081. this.add( this.line );
  16082. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  16083. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : hex } ) );
  16084. this.cone.position.set( 0, 1, 0 );
  16085. this.add( this.cone );
  16086. if ( origin instanceof THREE.Vector3 ) {
  16087. this.position = origin;
  16088. }
  16089. this.setDirection( dir );
  16090. this.setLength( length );
  16091. };
  16092. THREE.ArrowHelper.prototype = new THREE.Object3D();
  16093. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  16094. THREE.ArrowHelper.prototype.setDirection = function( dir ) {
  16095. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  16096. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  16097. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  16098. this.rotation.getRotationFromMatrix( this.matrix, this.scale );
  16099. };
  16100. THREE.ArrowHelper.prototype.setLength = function( length ) {
  16101. this.scale.set( length, length, length );
  16102. };
  16103. THREE.ArrowHelper.prototype.setColor = function( hex ) {
  16104. this.line.material.color.setHex( hex );
  16105. this.cone.material.color.setHex( hex );
  16106. };
  16107. /**
  16108. * @author alteredq / http://alteredqualia.com/
  16109. *
  16110. * - shows frustum, line of sight and up of the camera
  16111. * - suitable for fast updates
  16112. * - based on frustum visualization in lightgl.js shadowmap example
  16113. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  16114. */
  16115. THREE.CameraHelper = function ( camera ) {
  16116. THREE.Object3D.call( this );
  16117. var _this = this;
  16118. this.lineGeometry = new THREE.Geometry();
  16119. this.lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  16120. this.pointMap = {};
  16121. // colors
  16122. var hexFrustum = 0xffaa00,
  16123. hexCone = 0xff0000,
  16124. hexUp = 0x00aaff,
  16125. hexTarget = 0xffffff,
  16126. hexCross = 0x333333;
  16127. // near
  16128. addLine( "n1", "n2", hexFrustum );
  16129. addLine( "n2", "n4", hexFrustum );
  16130. addLine( "n4", "n3", hexFrustum );
  16131. addLine( "n3", "n1", hexFrustum );
  16132. // far
  16133. addLine( "f1", "f2", hexFrustum );
  16134. addLine( "f2", "f4", hexFrustum );
  16135. addLine( "f4", "f3", hexFrustum );
  16136. addLine( "f3", "f1", hexFrustum );
  16137. // sides
  16138. addLine( "n1", "f1", hexFrustum );
  16139. addLine( "n2", "f2", hexFrustum );
  16140. addLine( "n3", "f3", hexFrustum );
  16141. addLine( "n4", "f4", hexFrustum );
  16142. // cone
  16143. addLine( "p", "n1", hexCone );
  16144. addLine( "p", "n2", hexCone );
  16145. addLine( "p", "n3", hexCone );
  16146. addLine( "p", "n4", hexCone );
  16147. // up
  16148. addLine( "u1", "u2", hexUp );
  16149. addLine( "u2", "u3", hexUp );
  16150. addLine( "u3", "u1", hexUp );
  16151. // target
  16152. addLine( "c", "t", hexTarget );
  16153. addLine( "p", "c", hexCross );
  16154. // cross
  16155. addLine( "cn1", "cn2", hexCross );
  16156. addLine( "cn3", "cn4", hexCross );
  16157. addLine( "cf1", "cf2", hexCross );
  16158. addLine( "cf3", "cf4", hexCross );
  16159. this.camera = camera;
  16160. function addLine( a, b, hex ) {
  16161. addPoint( a, hex );
  16162. addPoint( b, hex );
  16163. }
  16164. function addPoint( id, hex ) {
  16165. _this.lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3() ) );
  16166. _this.lineGeometry.colors.push( new THREE.Color( hex ) );
  16167. if ( _this.pointMap[ id ] === undefined ) _this.pointMap[ id ] = [];
  16168. _this.pointMap[ id ].push( _this.lineGeometry.vertices.length - 1 );
  16169. }
  16170. this.update( camera );
  16171. this.lines = new THREE.Line( this.lineGeometry, this.lineMaterial, THREE.LinePieces );
  16172. this.add( this.lines );
  16173. };
  16174. THREE.CameraHelper.prototype = new THREE.Object3D();
  16175. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  16176. THREE.CameraHelper.prototype.update = function () {
  16177. var camera = this.camera;
  16178. var w = 1;
  16179. var h = 1;
  16180. var _this = this;
  16181. // we need just camera projection matrix
  16182. // world matrix must be identity
  16183. THREE.CameraHelper.__c.projectionMatrix.copy( camera.projectionMatrix );
  16184. // center / target
  16185. setPoint( "c", 0, 0, -1 );
  16186. setPoint( "t", 0, 0, 1 );
  16187. // near
  16188. setPoint( "n1", -w, -h, -1 );
  16189. setPoint( "n2", w, -h, -1 );
  16190. setPoint( "n3", -w, h, -1 );
  16191. setPoint( "n4", w, h, -1 );
  16192. // far
  16193. setPoint( "f1", -w, -h, 1 );
  16194. setPoint( "f2", w, -h, 1 );
  16195. setPoint( "f3", -w, h, 1 );
  16196. setPoint( "f4", w, h, 1 );
  16197. // up
  16198. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  16199. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  16200. setPoint( "u3", 0, h * 2, -1 );
  16201. // cross
  16202. setPoint( "cf1", -w, 0, 1 );
  16203. setPoint( "cf2", w, 0, 1 );
  16204. setPoint( "cf3", 0, -h, 1 );
  16205. setPoint( "cf4", 0, h, 1 );
  16206. setPoint( "cn1", -w, 0, -1 );
  16207. setPoint( "cn2", w, 0, -1 );
  16208. setPoint( "cn3", 0, -h, -1 );
  16209. setPoint( "cn4", 0, h, -1 );
  16210. function setPoint( point, x, y, z ) {
  16211. THREE.CameraHelper.__v.set( x, y, z );
  16212. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  16213. var points = _this.pointMap[ point ];
  16214. if ( points !== undefined ) {
  16215. for ( var i = 0, il = points.length; i < il; i ++ ) {
  16216. var j = points[ i ];
  16217. _this.lineGeometry.vertices[ j ].position.copy( THREE.CameraHelper.__v );
  16218. }
  16219. }
  16220. }
  16221. this.lineGeometry.__dirtyVertices = true;
  16222. };
  16223. THREE.CameraHelper.__projector = new THREE.Projector();
  16224. THREE.CameraHelper.__v = new THREE.Vector3();
  16225. THREE.CameraHelper.__c = new THREE.Camera();
  16226. /*
  16227. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  16228. *
  16229. * Subdivision Geometry Modifier
  16230. * using Catmull-Clark Subdivision Surfaces
  16231. * for creating smooth geometry meshes
  16232. *
  16233. * Note: a modifier modifies vertices and faces of geometry,
  16234. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  16235. *
  16236. * Readings:
  16237. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  16238. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  16239. * http://xrt.wikidot.com/blog:31
  16240. * "Subdivision Surfaces in Character Animation"
  16241. *
  16242. * Supports:
  16243. * Closed and Open geometries.
  16244. *
  16245. * TODO:
  16246. * crease vertex and "semi-sharp" features
  16247. * selective subdivision
  16248. */
  16249. THREE.SubdivisionModifier = function( subdivisions ) {
  16250. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  16251. // Settings
  16252. this.useOldVertexColors = false;
  16253. this.supportUVs = true;
  16254. };
  16255. //THREE.SubdivisionModifier.prototype = new THREE.Modifier();
  16256. THREE.SubdivisionModifier.prototype.constructor = THREE.SubdivisionModifier;
  16257. // Applies the "modify" pattern
  16258. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  16259. var repeats = this.subdivisions;
  16260. while ( repeats-- > 0 ) {
  16261. this.smooth( geometry );
  16262. }
  16263. };
  16264. // Performs an iteration of Catmull-Clark Subdivision
  16265. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  16266. //console.log( 'running smooth' );
  16267. // New set of vertices, faces and uvs
  16268. var newVertices = [], newFaces = [], newUVs = [];
  16269. function v( x, y, z ) {
  16270. newVertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  16271. }
  16272. var scope = this;
  16273. function f4( a, b, c, d, oldFace, orders ) {
  16274. // TODO move vertex selection over here!
  16275. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.material );
  16276. if (scope.useOldVertexColors) {
  16277. newFace.vertexColors = [];
  16278. var color, tmpColor, order;
  16279. for (var i=0;i<4;i++) {
  16280. order = orders[i];
  16281. color = new THREE.Color(),
  16282. color.setRGB(0,0,0);
  16283. for (var j=0, jl=0; j<order.length;j++) {
  16284. tmpColor = oldFace.vertexColors[order[j]-1];
  16285. color.r += tmpColor.r;
  16286. color.g += tmpColor.g;
  16287. color.b += tmpColor.b;
  16288. }
  16289. color.r /= order.length;
  16290. color.g /= order.length;
  16291. color.b /= order.length;
  16292. newFace.vertexColors[i] = color;
  16293. }
  16294. }
  16295. newFaces.push( newFace );
  16296. if (!scope.supportUVs || uvForVertices.length!=0) {
  16297. newUVs.push( [
  16298. uvForVertices[a],
  16299. uvForVertices[b],
  16300. uvForVertices[c],
  16301. uvForVertices[d]
  16302. ] );
  16303. }
  16304. }
  16305. function edge_hash( a, b ) {
  16306. return Math.min( a, b ) + "_" + Math.max( a, b );
  16307. };
  16308. function computeEdgeFaces( geometry ) {
  16309. function addToMap( map, hash, i ) {
  16310. if ( map[ hash ] === undefined ) {
  16311. map[ hash ] = [];
  16312. }
  16313. map[ hash ].push( i );
  16314. };
  16315. var i, il, v1, v2, j, k,
  16316. face, faceIndices, faceIndex,
  16317. edge,
  16318. hash,
  16319. vfMap = {};
  16320. // construct vertex -> face map
  16321. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  16322. face = geometry.faces[ i ];
  16323. if ( face instanceof THREE.Face3 ) {
  16324. hash = edge_hash( face.a, face.b );
  16325. addToMap( vfMap, hash, i );
  16326. hash = edge_hash( face.b, face.c );
  16327. addToMap( vfMap, hash, i );
  16328. hash = edge_hash( face.c, face.a );
  16329. addToMap( vfMap, hash, i );
  16330. } else if ( face instanceof THREE.Face4 ) {
  16331. hash = edge_hash( face.a, face.b );
  16332. addToMap( vfMap, hash, i );
  16333. hash = edge_hash( face.b, face.c );
  16334. addToMap( vfMap, hash, i );
  16335. hash = edge_hash( face.c, face.d );
  16336. addToMap( vfMap, hash, i );
  16337. hash = edge_hash( face.d, face.a );
  16338. addToMap( vfMap, hash, i );
  16339. }
  16340. }
  16341. // extract faces
  16342. // var edges = [];
  16343. //
  16344. // var numOfEdges = 0;
  16345. // for (i in vfMap) {
  16346. // numOfEdges++;
  16347. //
  16348. // edge = vfMap[i];
  16349. // edges.push(edge);
  16350. //
  16351. // }
  16352. //console.log('vfMap', vfMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  16353. return vfMap;
  16354. };
  16355. var originalPoints = oldGeometry.vertices;
  16356. var originalFaces = oldGeometry.faces;
  16357. var newPoints = originalPoints.concat(); // Vertices
  16358. var facePoints = [], edgePoints = {};
  16359. var sharpEdges = {}, sharpVertices = [], sharpFaces = [];
  16360. var uvForVertices = [];
  16361. // Step 1
  16362. // For each face, add a face point
  16363. // Set each face point to be the centroid of all original points for the respective face.
  16364. var i, il, j, jl, face;
  16365. // For Uvs
  16366. var uvs = oldGeometry.faceVertexUvs[0];
  16367. var abcd = 'abcd', vertice;
  16368. for (i=0, il = uvs.length; i<il; i++ ) {
  16369. for (j=0,jl=uvs[i].length;j<jl;j++) {
  16370. vertice = originalFaces[i][abcd.charAt(j)];
  16371. if (!uvForVertices[vertice]) {
  16372. uvForVertices[vertice] = uvs[i][j];
  16373. } else {
  16374. //console.log('dup', uvForVertices[vertice]);
  16375. }
  16376. }
  16377. }
  16378. var avgUv ;
  16379. for (i=0, il = originalFaces.length; i<il ;i++) {
  16380. face = originalFaces[i];
  16381. facePoints.push(face.centroid);
  16382. newPoints.push( new THREE.Vertex(face.centroid) );
  16383. if (!scope.supportUVs || uvForVertices.length==0) continue;
  16384. // Prepare subdivided uv
  16385. avgUv = new THREE.UV();
  16386. if ( face instanceof THREE.Face3 ) {
  16387. avgUv.u = uvForVertices[face.a].u + uvForVertices[face.b].u + uvForVertices[face.c].u;
  16388. avgUv.v = uvForVertices[face.a].v + uvForVertices[face.b].v + uvForVertices[face.c].v;
  16389. avgUv.u /= 3;
  16390. avgUv.v /= 3;
  16391. } else if ( face instanceof THREE.Face4 ) {
  16392. avgUv.u = uvForVertices[face.a].u + uvForVertices[face.b].u + uvForVertices[face.c].u + uvForVertices[face.d].u;
  16393. avgUv.v = uvForVertices[face.a].v + uvForVertices[face.b].v + uvForVertices[face.c].v + uvForVertices[face.d].v;
  16394. avgUv.u /= 4;
  16395. avgUv.v /= 4;
  16396. }
  16397. uvForVertices.push(avgUv);
  16398. }
  16399. // Step 2
  16400. // For each edge, add an edge point.
  16401. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  16402. var vfMap = computeEdgeFaces ( oldGeometry );
  16403. var edge, faceIndexA, faceIndexB, avg;
  16404. //console.log('vfMap', vfMap);
  16405. var edgeCount = 0;
  16406. var originalVerticesLength = originalPoints.length;
  16407. var edgeVertex, edgeVertexA, edgeVertexB;
  16408. ////
  16409. var vertexEdgeMap = {};
  16410. var vertexFaceMap = {};
  16411. var addVertexEdgeMap = function(vertex, edge) {
  16412. if (vertexEdgeMap[vertex]===undefined) {
  16413. vertexEdgeMap[vertex] = [];
  16414. }
  16415. vertexEdgeMap[vertex].push(edge);
  16416. };
  16417. var addVertexFaceMap = function(vertex, face, edge) {
  16418. if (vertexFaceMap[vertex]===undefined) {
  16419. vertexFaceMap[vertex] = {};
  16420. }
  16421. //vertexFaceMap[vertex][face] = edge;
  16422. vertexFaceMap[vertex][face] = null;
  16423. };
  16424. // Prepares vertexEdgeMap and vertexFaceMap
  16425. for (i in vfMap) { // This is for every edge
  16426. edge = vfMap[i];
  16427. edgeVertex = i.split('_');
  16428. edgeVertexA = edgeVertex[0];
  16429. edgeVertexB = edgeVertex[1];
  16430. // Maps an edgeVertex to connecting edges
  16431. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  16432. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  16433. // faceIndexA = edge[0]; // face index a
  16434. // faceIndexB = edge[1]; // face index b
  16435. //
  16436. // // Add connecting faces for edge
  16437. // addVertexFaceMap(edgeVertexA, faceIndexA);
  16438. // addVertexFaceMap(edgeVertexB, faceIndexA);
  16439. //
  16440. //
  16441. // if (faceIndexB) {
  16442. // addVertexFaceMap(edgeVertexA, faceIndexB);
  16443. // addVertexFaceMap(edgeVertexB, faceIndexB);
  16444. // } else {
  16445. // addVertexFaceMap(edgeVertexA, faceIndexA);
  16446. // addVertexFaceMap(edgeVertexB, faceIndexA);
  16447. // }
  16448. for (j=0,jl=edge.length;j<jl;j++) {
  16449. face = edge[j];
  16450. addVertexFaceMap(edgeVertexA, face, i);
  16451. addVertexFaceMap(edgeVertexB, face, i);
  16452. }
  16453. if (edge.length < 2) {
  16454. // edge is "sharp";
  16455. sharpEdges[i] = true;
  16456. sharpVertices[edgeVertexA] = true;
  16457. sharpVertices[edgeVertexB] = true;
  16458. }
  16459. }
  16460. //console.log('vertexEdgeMap',vertexEdgeMap, 'vertexFaceMap', vertexFaceMap);
  16461. for (i in vfMap) {
  16462. edge = vfMap[i];
  16463. faceIndexA = edge[0]; // face index a
  16464. faceIndexB = edge[1]; // face index b
  16465. edgeVertex = i.split('_');
  16466. edgeVertexA = edgeVertex[0];
  16467. edgeVertexB = edgeVertex[1];
  16468. avg = new THREE.Vector3();
  16469. //console.log(i, faceIndexB,facePoints[faceIndexB]);
  16470. if (sharpEdges[i]) {
  16471. //console.log('warning, ', i, 'edge has only 1 connecting face', edge);
  16472. // For a sharp edge, average the edge end points.
  16473. avg.addSelf(originalPoints[edgeVertexA].position);
  16474. avg.addSelf(originalPoints[edgeVertexB].position);
  16475. avg.multiplyScalar(0.5);
  16476. sharpVertices[newPoints.length] = true;
  16477. } else {
  16478. avg.addSelf(facePoints[faceIndexA]);
  16479. avg.addSelf(facePoints[faceIndexB]);
  16480. avg.addSelf(originalPoints[edgeVertexA].position);
  16481. avg.addSelf(originalPoints[edgeVertexB].position);
  16482. avg.multiplyScalar(0.25);
  16483. }
  16484. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  16485. //console.log(edgePoints[i], newPoints.length);
  16486. newPoints.push( new THREE.Vertex(avg) );
  16487. edgeCount ++;
  16488. if (!scope.supportUVs || uvForVertices.length==0) continue;
  16489. // Prepare subdivided uv
  16490. avgUv = new THREE.UV();
  16491. avgUv.u = uvForVertices[edgeVertexA].u + uvForVertices[edgeVertexB].u;
  16492. avgUv.v = uvForVertices[edgeVertexA].v + uvForVertices[edgeVertexB].v;
  16493. avgUv.u /= 2;
  16494. avgUv.v /= 2;
  16495. uvForVertices.push(avgUv);
  16496. }
  16497. // Step 3
  16498. // For each face point, add an edge for every edge of the face,
  16499. // connecting the face point to each edge point for the face.
  16500. var facePt, currentVerticeIndex;
  16501. var hashAB, hashBC, hashCD, hashDA, hashCA;
  16502. var abc123 = ['123', '12', '2', '23'];
  16503. var bca123 = ['123', '23', '3', '31'];
  16504. var cab123 = ['123', '31', '1', '12'];
  16505. var abc1234 = ['1234', '12', '2', '23'];
  16506. var bcd1234 = ['1234', '23', '3', '34'];
  16507. var cda1234 = ['1234', '34', '4', '41'];
  16508. var dab1234 = ['1234', '41', '1', '12'];
  16509. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  16510. facePt = facePoints[i];
  16511. face = originalFaces[i];
  16512. currentVerticeIndex = originalVerticesLength+ i;
  16513. if ( face instanceof THREE.Face3 ) {
  16514. // create 3 face4s
  16515. hashAB = edge_hash( face.a, face.b );
  16516. hashBC = edge_hash( face.b, face.c );
  16517. hashCA = edge_hash( face.c, face.a );
  16518. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123 );
  16519. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123 );
  16520. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123 );
  16521. } else if ( face instanceof THREE.Face4 ) {
  16522. // create 4 face4s
  16523. hashAB = edge_hash( face.a, face.b );
  16524. hashBC = edge_hash( face.b, face.c );
  16525. hashCD = edge_hash( face.c, face.d );
  16526. hashDA = edge_hash( face.d, face.a );
  16527. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234 );
  16528. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234 );
  16529. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234 );
  16530. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234 );
  16531. } else {
  16532. console.log('face should be a face!', face);
  16533. }
  16534. }
  16535. newVertices = newPoints;
  16536. // console.log('original ', oldGeometry.vertices.length, oldGeometry.faces.length );
  16537. // console.log('new points', newPoints.length, 'faces', newFaces.length );
  16538. // Step 4
  16539. // For each original point P,
  16540. // take the average F of all n face points for faces touching P,
  16541. // and take the average R of all n edge midpoints for edges touching P,
  16542. // where each edge midpoint is the average of its two endpoint vertices.
  16543. // Move each original point to the point
  16544. var F = new THREE.Vector3();
  16545. var R = new THREE.Vector3();
  16546. var n;
  16547. for (i=0, il = originalPoints.length; i<il; i++) {
  16548. // (F + 2R + (n-3)P) / n
  16549. if (vertexEdgeMap[i]===undefined) continue;
  16550. F.set(0,0,0);
  16551. R.set(0,0,0);
  16552. var newPos = new THREE.Vector3(0,0,0);
  16553. var f =0;
  16554. for (j in vertexFaceMap[i]) {
  16555. F.addSelf(facePoints[j]);
  16556. f++;
  16557. }
  16558. var sharpEdgeCount = 0;
  16559. n = vertexEdgeMap[i].length;
  16560. for (j=0;j<n;j++) {
  16561. if (
  16562. sharpEdges[
  16563. edge_hash(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  16564. ]) {
  16565. sharpEdgeCount++;
  16566. }
  16567. }
  16568. if ( sharpEdgeCount==2 ) {
  16569. continue;
  16570. // Do not move vertex if there's 2 connecting sharp edges.
  16571. }
  16572. /*
  16573. if (sharpEdgeCount>2) {
  16574. // TODO
  16575. }
  16576. */
  16577. F.divideScalar(f);
  16578. for (j=0; j<n;j++) {
  16579. edge = vertexEdgeMap[i][j];
  16580. var midPt = originalPoints[edge[0]].position.clone().addSelf(originalPoints[edge[1]].position).divideScalar(2);
  16581. R.addSelf(midPt);
  16582. // R.addSelf(originalPoints[edge[0]].position);
  16583. // R.addSelf(originalPoints[edge[1]].position);
  16584. }
  16585. R.divideScalar(n)
  16586. newPos.addSelf(originalPoints[i].position);
  16587. newPos.multiplyScalar(n - 3);
  16588. newPos.addSelf(F);
  16589. newPos.addSelf(R.multiplyScalar(2));
  16590. newPos.divideScalar(n);
  16591. newVertices[i].position = newPos;
  16592. }
  16593. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  16594. newGeometry.vertices = newVertices;
  16595. newGeometry.faces = newFaces;
  16596. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  16597. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  16598. newGeometry.computeCentroids();
  16599. newGeometry.computeFaceNormals();
  16600. newGeometry.computeVertexNormals();
  16601. };
  16602. /**
  16603. * @author alteredq / http://alteredqualia.com/
  16604. */
  16605. THREE.Loader = function ( showStatus ) {
  16606. this.showStatus = showStatus;
  16607. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  16608. this.onLoadStart = function () {};
  16609. this.onLoadProgress = function() {};
  16610. this.onLoadComplete = function () {};
  16611. };
  16612. THREE.Loader.prototype = {
  16613. constructor: THREE.Loader,
  16614. crossOrigin: 'anonymous',
  16615. addStatusElement: function () {
  16616. var e = document.createElement( "div" );
  16617. e.style.position = "absolute";
  16618. e.style.right = "0px";
  16619. e.style.top = "0px";
  16620. e.style.fontSize = "0.8em";
  16621. e.style.textAlign = "left";
  16622. e.style.background = "rgba(0,0,0,0.25)";
  16623. e.style.color = "#fff";
  16624. e.style.width = "120px";
  16625. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  16626. e.style.zIndex = 1000;
  16627. e.innerHTML = "Loading ...";
  16628. return e;
  16629. },
  16630. updateProgress: function ( progress ) {
  16631. var message = "Loaded ";
  16632. if ( progress.total ) {
  16633. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  16634. } else {
  16635. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  16636. }
  16637. this.statusDomElement.innerHTML = message;
  16638. },
  16639. extractUrlBase: function ( url ) {
  16640. var parts = url.split( '/' );
  16641. parts.pop();
  16642. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  16643. },
  16644. initMaterials: function ( scope, materials, texturePath ) {
  16645. scope.materials = [];
  16646. for ( var i = 0; i < materials.length; ++ i ) {
  16647. scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  16648. }
  16649. },
  16650. hasNormals: function ( scope ) {
  16651. var m, i, il = scope.materials.length;
  16652. for( i = 0; i < il; i ++ ) {
  16653. m = scope.materials[ i ];
  16654. if ( m instanceof THREE.ShaderMaterial ) return true;
  16655. }
  16656. return false;
  16657. },
  16658. createMaterial: function ( m, texturePath ) {
  16659. var _this = this;
  16660. function is_pow2( n ) {
  16661. var l = Math.log( n ) / Math.LN2;
  16662. return Math.floor( l ) == l;
  16663. }
  16664. function nearest_pow2( n ) {
  16665. var l = Math.log( n ) / Math.LN2;
  16666. return Math.pow( 2, Math.round( l ) );
  16667. }
  16668. function load_image( where, url ) {
  16669. var image = new Image();
  16670. image.onload = function () {
  16671. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  16672. var width = nearest_pow2( this.width );
  16673. var height = nearest_pow2( this.height );
  16674. where.image.width = width;
  16675. where.image.height = height;
  16676. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  16677. } else {
  16678. where.image = this;
  16679. }
  16680. where.needsUpdate = true;
  16681. };
  16682. image.crossOrigin = _this.crossOrigin;
  16683. image.src = url;
  16684. }
  16685. function create_texture( where, name, sourceFile, repeat, offset, wrap ) {
  16686. var texture = document.createElement( 'canvas' );
  16687. where[ name ] = new THREE.Texture( texture );
  16688. where[ name ].sourceFile = sourceFile;
  16689. if( repeat ) {
  16690. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  16691. if ( repeat[ 0 ] != 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  16692. if ( repeat[ 1 ] != 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  16693. }
  16694. if ( offset ) {
  16695. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  16696. }
  16697. if ( wrap ) {
  16698. var wrapMap = {
  16699. "repeat" : THREE.RepeatWrapping,
  16700. "mirror" : THREE.MirroredRepeatWrapping
  16701. }
  16702. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  16703. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  16704. }
  16705. load_image( where[ name ], texturePath + "/" + sourceFile );
  16706. }
  16707. function rgb2hex( rgb ) {
  16708. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  16709. }
  16710. // defaults
  16711. var mtype = "MeshLambertMaterial";
  16712. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, wireframe: m.wireframe };
  16713. // parameters from model file
  16714. if ( m.shading ) {
  16715. var shading = m.shading.toLowerCase();
  16716. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  16717. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  16718. }
  16719. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  16720. mpars.blending = THREE[ m.blending ];
  16721. }
  16722. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  16723. mpars.transparent = m.transparent;
  16724. }
  16725. if ( m.depthTest !== undefined ) {
  16726. mpars.depthTest = m.depthTest;
  16727. }
  16728. if ( m.depthWrite !== undefined ) {
  16729. mpars.depthWrite = m.depthWrite;
  16730. }
  16731. if ( m.vertexColors !== undefined ) {
  16732. if ( m.vertexColors == "face" ) {
  16733. mpars.vertexColors = THREE.FaceColors;
  16734. } else if ( m.vertexColors ) {
  16735. mpars.vertexColors = THREE.VertexColors;
  16736. }
  16737. }
  16738. // colors
  16739. if ( m.colorDiffuse ) {
  16740. mpars.color = rgb2hex( m.colorDiffuse );
  16741. } else if ( m.DbgColor ) {
  16742. mpars.color = m.DbgColor;
  16743. }
  16744. if ( m.colorSpecular ) {
  16745. mpars.specular = rgb2hex( m.colorSpecular );
  16746. }
  16747. if ( m.colorAmbient ) {
  16748. mpars.ambient = rgb2hex( m.colorAmbient );
  16749. }
  16750. // modifiers
  16751. if ( m.transparency ) {
  16752. mpars.opacity = m.transparency;
  16753. }
  16754. if ( m.specularCoef ) {
  16755. mpars.shininess = m.specularCoef;
  16756. }
  16757. // textures
  16758. if ( m.mapDiffuse && texturePath ) {
  16759. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  16760. }
  16761. if ( m.mapLight && texturePath ) {
  16762. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  16763. }
  16764. if ( m.mapNormal && texturePath ) {
  16765. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  16766. }
  16767. if ( m.mapSpecular && texturePath ) {
  16768. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  16769. }
  16770. // special case for normal mapped material
  16771. if ( m.mapNormal ) {
  16772. var shader = THREE.ShaderUtils.lib[ "normal" ];
  16773. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  16774. uniforms[ "tNormal" ].texture = mpars.normalMap;
  16775. if ( m.mapNormalFactor ) {
  16776. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  16777. }
  16778. if ( mpars.map ) {
  16779. uniforms[ "tDiffuse" ].texture = mpars.map;
  16780. uniforms[ "enableDiffuse" ].value = true;
  16781. }
  16782. if ( mpars.specularMap ) {
  16783. uniforms[ "tSpecular" ].texture = mpars.specularMap;
  16784. uniforms[ "enableSpecular" ].value = true;
  16785. }
  16786. if ( mpars.lightMap ) {
  16787. uniforms[ "tAO" ].texture = mpars.lightMap;
  16788. uniforms[ "enableAO" ].value = true;
  16789. }
  16790. // for the moment don't handle displacement texture
  16791. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  16792. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  16793. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  16794. uniforms[ "uShininess" ].value = mpars.shininess;
  16795. if ( mpars.opacity !== undefined ) {
  16796. uniforms[ "uOpacity" ].value = mpars.opacity;
  16797. }
  16798. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  16799. var material = new THREE.ShaderMaterial( parameters );
  16800. } else {
  16801. var material = new THREE[ mtype ]( mpars );
  16802. }
  16803. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  16804. return material;
  16805. }
  16806. };
  16807. /**
  16808. * @author alteredq / http://alteredqualia.com/
  16809. */
  16810. THREE.BinaryLoader = function ( showStatus ) {
  16811. THREE.Loader.call( this, showStatus );
  16812. };
  16813. THREE.BinaryLoader.prototype = new THREE.Loader();
  16814. THREE.BinaryLoader.prototype.constructor = THREE.BinaryLoader;
  16815. THREE.BinaryLoader.prototype.supr = THREE.Loader.prototype;
  16816. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  16817. // - binary models consist of two files: JS and BIN
  16818. // - parameters
  16819. // - url (required)
  16820. // - callback (required)
  16821. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  16822. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  16823. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  16824. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  16825. binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
  16826. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  16827. this.onLoadStart();
  16828. // #1 load JS part via web worker
  16829. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  16830. };
  16831. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  16832. var xhr = new XMLHttpRequest();
  16833. xhr.onreadystatechange = function () {
  16834. if ( xhr.readyState == 4 ) {
  16835. if ( xhr.status == 200 || xhr.status == 0 ) {
  16836. var json = JSON.parse( xhr.responseText );
  16837. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  16838. } else {
  16839. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  16840. }
  16841. }
  16842. };
  16843. xhr.open( "GET", url, true );
  16844. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  16845. xhr.setRequestHeader( "Content-Type", "text/plain" );
  16846. xhr.send( null );
  16847. };
  16848. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  16849. var xhr = new XMLHttpRequest(),
  16850. url = binaryPath + "/" + json.buffers;
  16851. var length = 0;
  16852. xhr.onreadystatechange = function () {
  16853. if ( xhr.readyState == 4 ) {
  16854. if ( xhr.status == 200 || xhr.status == 0 ) {
  16855. THREE.BinaryLoader.prototype.createBinModel( xhr.response, callback, texturePath, json.materials );
  16856. } else {
  16857. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  16858. }
  16859. } else if ( xhr.readyState == 3 ) {
  16860. if ( callbackProgress ) {
  16861. if ( length == 0 ) {
  16862. length = xhr.getResponseHeader( "Content-Length" );
  16863. }
  16864. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  16865. }
  16866. } else if ( xhr.readyState == 2 ) {
  16867. length = xhr.getResponseHeader( "Content-Length" );
  16868. }
  16869. };
  16870. xhr.open( "GET", url, true );
  16871. xhr.responseType = "arraybuffer";
  16872. xhr.send( null );
  16873. };
  16874. // Binary AJAX parser
  16875. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
  16876. var Model = function ( texturePath ) {
  16877. var scope = this,
  16878. currentOffset = 0,
  16879. md,
  16880. normals = [],
  16881. uvs = [],
  16882. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  16883. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  16884. tri_size, quad_size,
  16885. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  16886. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  16887. THREE.Geometry.call( this );
  16888. THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
  16889. md = parseMetaData( data, currentOffset );
  16890. currentOffset += md.header_bytes;
  16891. /*
  16892. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  16893. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  16894. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  16895. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  16896. */
  16897. // buffers sizes
  16898. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  16899. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  16900. len_tri_flat = md.ntri_flat * ( tri_size );
  16901. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  16902. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  16903. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  16904. len_quad_flat = md.nquad_flat * ( quad_size );
  16905. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  16906. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  16907. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  16908. // read buffers
  16909. currentOffset += init_vertices( currentOffset );
  16910. currentOffset += init_normals( currentOffset );
  16911. currentOffset += handlePadding( md.nnormals * 3 );
  16912. currentOffset += init_uvs( currentOffset );
  16913. start_tri_flat = currentOffset;
  16914. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  16915. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  16916. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  16917. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  16918. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  16919. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  16920. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  16921. // have to first process faces with uvs
  16922. // so that face and uv indices match
  16923. init_triangles_flat_uv( start_tri_flat_uv );
  16924. init_triangles_smooth_uv( start_tri_smooth_uv );
  16925. init_quads_flat_uv( start_quad_flat_uv );
  16926. init_quads_smooth_uv( start_quad_smooth_uv );
  16927. // now we can process untextured faces
  16928. init_triangles_flat( start_tri_flat );
  16929. init_triangles_smooth( start_tri_smooth );
  16930. init_quads_flat( start_quad_flat );
  16931. init_quads_smooth( start_quad_smooth );
  16932. this.computeCentroids();
  16933. this.computeFaceNormals();
  16934. if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
  16935. function handlePadding( n ) {
  16936. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  16937. };
  16938. function parseMetaData( data, offset ) {
  16939. var metaData = {
  16940. 'signature' :parseString( data, offset, 12 ),
  16941. 'header_bytes' :parseUChar8( data, offset + 12 ),
  16942. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  16943. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  16944. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  16945. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  16946. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  16947. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  16948. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  16949. 'nvertices' :parseUInt32( data, offset + 20 ),
  16950. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  16951. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  16952. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  16953. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  16954. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  16955. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  16956. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  16957. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  16958. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  16959. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  16960. };
  16961. /*
  16962. console.log( "signature: " + metaData.signature );
  16963. console.log( "header_bytes: " + metaData.header_bytes );
  16964. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  16965. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  16966. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  16967. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  16968. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  16969. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  16970. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  16971. console.log( "nvertices: " + metaData.nvertices );
  16972. console.log( "nnormals: " + metaData.nnormals );
  16973. console.log( "nuvs: " + metaData.nuvs );
  16974. console.log( "ntri_flat: " + metaData.ntri_flat );
  16975. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  16976. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  16977. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  16978. console.log( "nquad_flat: " + metaData.nquad_flat );
  16979. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  16980. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  16981. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  16982. var total = metaData.header_bytes
  16983. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  16984. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  16985. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  16986. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  16987. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  16988. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  16989. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  16990. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  16991. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  16992. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  16993. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  16994. console.log( "total bytes: " + total );
  16995. */
  16996. return metaData;
  16997. };
  16998. function parseString( data, offset, length ) {
  16999. var charArray = new Uint8Array( data, offset, length );
  17000. var text = "";
  17001. for ( var i = 0; i < length; i ++ ) {
  17002. text += String.fromCharCode( charArray[ offset + i ] );
  17003. }
  17004. return text;
  17005. };
  17006. function parseUChar8( data, offset ) {
  17007. var charArray = new Uint8Array( data, offset, 1 );
  17008. return charArray[ 0 ];
  17009. };
  17010. function parseUInt32( data, offset ) {
  17011. var intArray = new Uint32Array( data, offset, 1 );
  17012. return intArray[ 0 ];
  17013. };
  17014. function init_vertices( start ) {
  17015. var nElements = md.nvertices;
  17016. var coordArray = new Float32Array( data, start, nElements * 3 );
  17017. var i, x, y, z;
  17018. for( i = 0; i < nElements; i ++ ) {
  17019. x = coordArray[ i * 3 ];
  17020. y = coordArray[ i * 3 + 1 ];
  17021. z = coordArray[ i * 3 + 2 ];
  17022. vertex( scope, x, y, z );
  17023. }
  17024. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  17025. };
  17026. function init_normals( start ) {
  17027. var nElements = md.nnormals;
  17028. if ( nElements ) {
  17029. var normalArray = new Int8Array( data, start, nElements * 3 );
  17030. var i, x, y, z;
  17031. for( i = 0; i < nElements; i ++ ) {
  17032. x = normalArray[ i * 3 ];
  17033. y = normalArray[ i * 3 + 1 ];
  17034. z = normalArray[ i * 3 + 2 ];
  17035. normals.push( x/127, y/127, z/127 );
  17036. }
  17037. }
  17038. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  17039. };
  17040. function init_uvs( start ) {
  17041. var nElements = md.nuvs;
  17042. if ( nElements ) {
  17043. var uvArray = new Float32Array( data, start, nElements * 2 );
  17044. var i, u, v;
  17045. for( i = 0; i < nElements; i ++ ) {
  17046. u = uvArray[ i * 2 ];
  17047. v = uvArray[ i * 2 + 1 ];
  17048. uvs.push( u, v );
  17049. }
  17050. }
  17051. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  17052. };
  17053. function init_uvs3( nElements, offset ) {
  17054. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  17055. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  17056. for( i = 0; i < nElements; i ++ ) {
  17057. uva = uvIndexBuffer[ i * 3 ];
  17058. uvb = uvIndexBuffer[ i * 3 + 1 ];
  17059. uvc = uvIndexBuffer[ i * 3 + 2 ];
  17060. u1 = uvs[ uva*2 ];
  17061. v1 = uvs[ uva*2 + 1 ];
  17062. u2 = uvs[ uvb*2 ];
  17063. v2 = uvs[ uvb*2 + 1 ];
  17064. u3 = uvs[ uvc*2 ];
  17065. v3 = uvs[ uvc*2 + 1 ];
  17066. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  17067. }
  17068. };
  17069. function init_uvs4( nElements, offset ) {
  17070. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  17071. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  17072. for( i = 0; i < nElements; i ++ ) {
  17073. uva = uvIndexBuffer[ i * 4 ];
  17074. uvb = uvIndexBuffer[ i * 4 + 1 ];
  17075. uvc = uvIndexBuffer[ i * 4 + 2 ];
  17076. uvd = uvIndexBuffer[ i * 4 + 3 ];
  17077. u1 = uvs[ uva*2 ];
  17078. v1 = uvs[ uva*2 + 1 ];
  17079. u2 = uvs[ uvb*2 ];
  17080. v2 = uvs[ uvb*2 + 1 ];
  17081. u3 = uvs[ uvc*2 ];
  17082. v3 = uvs[ uvc*2 + 1 ];
  17083. u4 = uvs[ uvd*2 ];
  17084. v4 = uvs[ uvd*2 + 1 ];
  17085. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  17086. }
  17087. };
  17088. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  17089. var i, a, b, c, m;
  17090. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  17091. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17092. for( i = 0; i < nElements; i ++ ) {
  17093. a = vertexIndexBuffer[ i * 3 ];
  17094. b = vertexIndexBuffer[ i * 3 + 1 ];
  17095. c = vertexIndexBuffer[ i * 3 + 2 ];
  17096. m = materialIndexBuffer[ i ];
  17097. f3( scope, a, b, c, m );
  17098. }
  17099. };
  17100. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  17101. var i, a, b, c, d, m;
  17102. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  17103. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17104. for( i = 0; i < nElements; i ++ ) {
  17105. a = vertexIndexBuffer[ i * 4 ];
  17106. b = vertexIndexBuffer[ i * 4 + 1 ];
  17107. c = vertexIndexBuffer[ i * 4 + 2 ];
  17108. d = vertexIndexBuffer[ i * 4 + 3 ];
  17109. m = materialIndexBuffer[ i ];
  17110. f4( scope, a, b, c, d, m );
  17111. }
  17112. };
  17113. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  17114. var i, a, b, c, m;
  17115. var na, nb, nc;
  17116. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  17117. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  17118. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17119. for( i = 0; i < nElements; i ++ ) {
  17120. a = vertexIndexBuffer[ i * 3 ];
  17121. b = vertexIndexBuffer[ i * 3 + 1 ];
  17122. c = vertexIndexBuffer[ i * 3 + 2 ];
  17123. na = normalIndexBuffer[ i * 3 ];
  17124. nb = normalIndexBuffer[ i * 3 + 1 ];
  17125. nc = normalIndexBuffer[ i * 3 + 2 ];
  17126. m = materialIndexBuffer[ i ];
  17127. f3n( scope, normals, a, b, c, m, na, nb, nc );
  17128. }
  17129. };
  17130. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  17131. var i, a, b, c, d, m;
  17132. var na, nb, nc, nd;
  17133. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  17134. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  17135. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17136. for( i = 0; i < nElements; i ++ ) {
  17137. a = vertexIndexBuffer[ i * 4 ];
  17138. b = vertexIndexBuffer[ i * 4 + 1 ];
  17139. c = vertexIndexBuffer[ i * 4 + 2 ];
  17140. d = vertexIndexBuffer[ i * 4 + 3 ];
  17141. na = normalIndexBuffer[ i * 4 ];
  17142. nb = normalIndexBuffer[ i * 4 + 1 ];
  17143. nc = normalIndexBuffer[ i * 4 + 2 ];
  17144. nd = normalIndexBuffer[ i * 4 + 3 ];
  17145. m = materialIndexBuffer[ i ];
  17146. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  17147. }
  17148. };
  17149. function init_triangles_flat( start ) {
  17150. var nElements = md.ntri_flat;
  17151. if ( nElements ) {
  17152. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17153. init_faces3_flat( nElements, start, offsetMaterials );
  17154. }
  17155. };
  17156. function init_triangles_flat_uv( start ) {
  17157. var nElements = md.ntri_flat_uv;
  17158. if ( nElements ) {
  17159. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17160. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17161. init_faces3_flat( nElements, start, offsetMaterials );
  17162. init_uvs3( nElements, offsetUvs );
  17163. }
  17164. };
  17165. function init_triangles_smooth( start ) {
  17166. var nElements = md.ntri_smooth;
  17167. if ( nElements ) {
  17168. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17169. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17170. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  17171. }
  17172. };
  17173. function init_triangles_smooth_uv( start ) {
  17174. var nElements = md.ntri_smooth_uv;
  17175. if ( nElements ) {
  17176. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17177. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17178. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17179. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  17180. init_uvs3( nElements, offsetUvs );
  17181. }
  17182. };
  17183. function init_quads_flat( start ) {
  17184. var nElements = md.nquad_flat;
  17185. if ( nElements ) {
  17186. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17187. init_faces4_flat( nElements, start, offsetMaterials );
  17188. }
  17189. };
  17190. function init_quads_flat_uv( start ) {
  17191. var nElements = md.nquad_flat_uv;
  17192. if ( nElements ) {
  17193. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17194. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17195. init_faces4_flat( nElements, start, offsetMaterials );
  17196. init_uvs4( nElements, offsetUvs );
  17197. }
  17198. };
  17199. function init_quads_smooth( start ) {
  17200. var nElements = md.nquad_smooth;
  17201. if ( nElements ) {
  17202. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17203. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17204. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  17205. }
  17206. };
  17207. function init_quads_smooth_uv( start ) {
  17208. var nElements = md.nquad_smooth_uv;
  17209. if ( nElements ) {
  17210. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17211. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17212. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17213. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  17214. init_uvs4( nElements, offsetUvs );
  17215. }
  17216. };
  17217. };
  17218. function vertex ( scope, x, y, z ) {
  17219. scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  17220. };
  17221. function f3 ( scope, a, b, c, mi ) {
  17222. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  17223. };
  17224. function f4 ( scope, a, b, c, d, mi ) {
  17225. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  17226. };
  17227. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  17228. var nax = normals[ na*3 ],
  17229. nay = normals[ na*3 + 1 ],
  17230. naz = normals[ na*3 + 2 ],
  17231. nbx = normals[ nb*3 ],
  17232. nby = normals[ nb*3 + 1 ],
  17233. nbz = normals[ nb*3 + 2 ],
  17234. ncx = normals[ nc*3 ],
  17235. ncy = normals[ nc*3 + 1 ],
  17236. ncz = normals[ nc*3 + 2 ];
  17237. scope.faces.push( new THREE.Face3( a, b, c,
  17238. [new THREE.Vector3( nax, nay, naz ),
  17239. new THREE.Vector3( nbx, nby, nbz ),
  17240. new THREE.Vector3( ncx, ncy, ncz )],
  17241. null,
  17242. mi ) );
  17243. };
  17244. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  17245. var nax = normals[ na*3 ],
  17246. nay = normals[ na*3 + 1 ],
  17247. naz = normals[ na*3 + 2 ],
  17248. nbx = normals[ nb*3 ],
  17249. nby = normals[ nb*3 + 1 ],
  17250. nbz = normals[ nb*3 + 2 ],
  17251. ncx = normals[ nc*3 ],
  17252. ncy = normals[ nc*3 + 1 ],
  17253. ncz = normals[ nc*3 + 2 ],
  17254. ndx = normals[ nd*3 ],
  17255. ndy = normals[ nd*3 + 1 ],
  17256. ndz = normals[ nd*3 + 2 ];
  17257. scope.faces.push( new THREE.Face4( a, b, c, d,
  17258. [new THREE.Vector3( nax, nay, naz ),
  17259. new THREE.Vector3( nbx, nby, nbz ),
  17260. new THREE.Vector3( ncx, ncy, ncz ),
  17261. new THREE.Vector3( ndx, ndy, ndz )],
  17262. null,
  17263. mi ) );
  17264. };
  17265. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  17266. var uv = [];
  17267. uv.push( new THREE.UV( u1, v1 ) );
  17268. uv.push( new THREE.UV( u2, v2 ) );
  17269. uv.push( new THREE.UV( u3, v3 ) );
  17270. where.push( uv );
  17271. };
  17272. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  17273. var uv = [];
  17274. uv.push( new THREE.UV( u1, v1 ) );
  17275. uv.push( new THREE.UV( u2, v2 ) );
  17276. uv.push( new THREE.UV( u3, v3 ) );
  17277. uv.push( new THREE.UV( u4, v4 ) );
  17278. where.push( uv );
  17279. };
  17280. Model.prototype = new THREE.Geometry();
  17281. Model.prototype.constructor = Model;
  17282. callback( new Model( texturePath ) );
  17283. };
  17284. /**
  17285. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  17286. */
  17287. THREE.ColladaLoader = function () {
  17288. var COLLADA = null;
  17289. var scene = null;
  17290. var daeScene;
  17291. var readyCallbackFunc = null;
  17292. var sources = {};
  17293. var images = {};
  17294. var animations = {};
  17295. var controllers = {};
  17296. var geometries = {};
  17297. var materials = {};
  17298. var effects = {};
  17299. var cameras = {};
  17300. var animData;
  17301. var visualScenes;
  17302. var baseUrl;
  17303. var morphs;
  17304. var skins;
  17305. var flip_uv = true;
  17306. var preferredShading = THREE.SmoothShading;
  17307. var options = {
  17308. // Force Geometry to always be centered at the local origin of the
  17309. // containing Mesh.
  17310. centerGeometry: false,
  17311. // Axis conversion is done for geometries, animations, and controllers.
  17312. // If we ever pull cameras or lights out of the COLLADA file, they'll
  17313. // need extra work.
  17314. convertUpAxis: false,
  17315. subdivideFaces: true,
  17316. upAxis: 'Y'
  17317. };
  17318. // TODO: support unit conversion as well
  17319. var colladaUnit = 1.0;
  17320. var colladaUp = 'Y';
  17321. var upConversion = null;
  17322. var TO_RADIANS = Math.PI / 180;
  17323. function load ( url, readyCallback, progressCallback ) {
  17324. var length = 0;
  17325. if ( document.implementation && document.implementation.createDocument ) {
  17326. var req = new XMLHttpRequest();
  17327. if ( req.overrideMimeType ) req.overrideMimeType( "text/xml" );
  17328. req.onreadystatechange = function() {
  17329. if( req.readyState == 4 ) {
  17330. if( req.status == 0 || req.status == 200 ) {
  17331. if ( req.responseXML ) {
  17332. readyCallbackFunc = readyCallback;
  17333. parse( req.responseXML, undefined, url );
  17334. } else {
  17335. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  17336. }
  17337. }
  17338. } else if ( req.readyState == 3 ) {
  17339. if ( progressCallback ) {
  17340. if ( length == 0 ) {
  17341. length = req.getResponseHeader( "Content-Length" );
  17342. }
  17343. progressCallback( { total: length, loaded: req.responseText.length } );
  17344. }
  17345. }
  17346. }
  17347. req.open( "GET", url, true );
  17348. req.send( null );
  17349. } else {
  17350. alert( "Don't know how to parse XML!" );
  17351. }
  17352. };
  17353. function parse( doc, callBack, url ) {
  17354. COLLADA = doc;
  17355. callBack = callBack || readyCallbackFunc;
  17356. if ( url !== undefined ) {
  17357. var parts = url.split( '/' );
  17358. parts.pop();
  17359. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  17360. }
  17361. parseAsset();
  17362. setUpConversion();
  17363. images = parseLib( "//dae:library_images/dae:image", _Image, "image" );
  17364. materials = parseLib( "//dae:library_materials/dae:material", Material, "material") ;
  17365. effects = parseLib( "//dae:library_effects/dae:effect", Effect, "effect" );
  17366. geometries = parseLib( "//dae:library_geometries/dae:geometry", Geometry, "geometry" );
  17367. cameras = parseLib( ".//dae:library_cameras/dae:camera", Camera, "camera" );
  17368. controllers = parseLib( "//dae:library_controllers/dae:controller", Controller, "controller" );
  17369. animations = parseLib( "//dae:library_animations/dae:animation", Animation, "animation" );
  17370. visualScenes = parseLib( ".//dae:library_visual_scenes/dae:visual_scene", VisualScene, "visual_scene" );
  17371. morphs = [];
  17372. skins = [];
  17373. daeScene = parseScene();
  17374. scene = new THREE.Object3D();
  17375. for ( var i = 0; i < daeScene.nodes.length; i ++ ) {
  17376. scene.add( createSceneGraph( daeScene.nodes[ i ] ) );
  17377. }
  17378. createAnimations();
  17379. var result = {
  17380. scene: scene,
  17381. morphs: morphs,
  17382. skins: skins,
  17383. animations: animData,
  17384. dae: {
  17385. images: images,
  17386. materials: materials,
  17387. cameras: cameras,
  17388. effects: effects,
  17389. geometries: geometries,
  17390. controllers: controllers,
  17391. animations: animations,
  17392. visualScenes: visualScenes,
  17393. scene: daeScene
  17394. }
  17395. };
  17396. if ( callBack ) {
  17397. callBack( result );
  17398. }
  17399. return result;
  17400. };
  17401. function setPreferredShading ( shading ) {
  17402. preferredShading = shading;
  17403. };
  17404. function parseAsset () {
  17405. var elements = COLLADA.evaluate( '//dae:asset', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  17406. var element = elements.iterateNext();
  17407. if ( element && element.childNodes ) {
  17408. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  17409. var child = element.childNodes[ i ];
  17410. switch ( child.nodeName ) {
  17411. case 'unit':
  17412. var meter = child.getAttribute( 'meter' );
  17413. if ( meter ) {
  17414. colladaUnit = parseFloat( meter );
  17415. }
  17416. break;
  17417. case 'up_axis':
  17418. colladaUp = child.textContent.charAt(0);
  17419. break;
  17420. }
  17421. }
  17422. }
  17423. };
  17424. function parseLib ( q, classSpec, prefix ) {
  17425. var elements = COLLADA.evaluate(q, COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
  17426. var lib = {};
  17427. var element = elements.iterateNext();
  17428. var i = 0;
  17429. while ( element ) {
  17430. var daeElement = ( new classSpec() ).parse( element );
  17431. if ( !daeElement.id || daeElement.id.length == 0 ) daeElement.id = prefix + ( i ++ );
  17432. lib[ daeElement.id ] = daeElement;
  17433. element = elements.iterateNext();
  17434. }
  17435. return lib;
  17436. };
  17437. function parseScene() {
  17438. var sceneElement = COLLADA.evaluate( './/dae:scene/dae:instance_visual_scene', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  17439. if ( sceneElement ) {
  17440. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  17441. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  17442. } else {
  17443. return null;
  17444. }
  17445. };
  17446. function createAnimations() {
  17447. animData = [];
  17448. // fill in the keys
  17449. recurseHierarchy( scene );
  17450. };
  17451. function recurseHierarchy( node ) {
  17452. var n = daeScene.getChildById( node.name, true ),
  17453. newData = null;
  17454. if ( n && n.keys ) {
  17455. newData = {
  17456. fps: 60,
  17457. hierarchy: [ {
  17458. node: n,
  17459. keys: n.keys,
  17460. sids: n.sids
  17461. } ],
  17462. node: node,
  17463. name: 'animation_' + node.name,
  17464. length: 0
  17465. };
  17466. animData.push(newData);
  17467. for ( var i = 0, il = n.keys.length; i < il; i++ ) {
  17468. newData.length = Math.max( newData.length, n.keys[i].time );
  17469. }
  17470. } else {
  17471. newData = {
  17472. hierarchy: [ {
  17473. keys: [],
  17474. sids: []
  17475. } ]
  17476. }
  17477. }
  17478. for ( var i = 0, il = node.children.length; i < il; i++ ) {
  17479. var d = recurseHierarchy( node.children[i] );
  17480. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  17481. newData.hierarchy.push( {
  17482. keys: [],
  17483. sids: []
  17484. } );
  17485. }
  17486. }
  17487. return newData;
  17488. };
  17489. function calcAnimationBounds () {
  17490. var start = 1000000;
  17491. var end = -start;
  17492. var frames = 0;
  17493. for ( var id in animations ) {
  17494. var animation = animations[ id ];
  17495. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  17496. var sampler = animation.sampler[ i ];
  17497. sampler.create();
  17498. start = Math.min( start, sampler.startTime );
  17499. end = Math.max( end, sampler.endTime );
  17500. frames = Math.max( frames, sampler.input.length );
  17501. }
  17502. }
  17503. return { start:start, end:end, frames:frames };
  17504. };
  17505. function createMorph ( geometry, ctrl ) {
  17506. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  17507. if ( !morphCtrl || !morphCtrl.morph ) {
  17508. console.log("could not find morph controller!");
  17509. return;
  17510. }
  17511. var morph = morphCtrl.morph;
  17512. for ( var i = 0; i < morph.targets.length; i ++ ) {
  17513. var target_id = morph.targets[ i ];
  17514. var daeGeometry = geometries[ target_id ];
  17515. if ( !daeGeometry.mesh ||
  17516. !daeGeometry.mesh.primitives ||
  17517. !daeGeometry.mesh.primitives.length ) {
  17518. continue;
  17519. }
  17520. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  17521. if ( target.vertices.length === geometry.vertices.length ) {
  17522. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  17523. }
  17524. }
  17525. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  17526. };
  17527. function createSkin ( geometry, ctrl, applyBindShape ) {
  17528. var skinCtrl = controllers[ ctrl.url ];
  17529. if ( !skinCtrl || !skinCtrl.skin ) {
  17530. console.log( "could not find skin controller!" );
  17531. return;
  17532. }
  17533. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  17534. console.log( "could not find the skeleton for the skin!" );
  17535. return;
  17536. }
  17537. var skin = skinCtrl.skin;
  17538. var skeleton = daeScene.getChildById( ctrl.skeleton[ 0 ] );
  17539. var hierarchy = [];
  17540. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  17541. var bones = [];
  17542. geometry.skinWeights = [];
  17543. geometry.skinIndices = [];
  17544. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  17545. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  17546. /*
  17547. geometry.animation = {
  17548. name: 'take_001',
  17549. fps: 30,
  17550. length: 2,
  17551. JIT: true,
  17552. hierarchy: hierarchy
  17553. };
  17554. */
  17555. if ( applyBindShape ) {
  17556. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  17557. skin.bindShapeMatrix.multiplyVector3( geometry.vertices[ i ].position );
  17558. }
  17559. }
  17560. };
  17561. function setupSkeleton ( node, bones, frame, parent ) {
  17562. node.world = node.world || new THREE.Matrix4();
  17563. node.world.copy( node.matrix );
  17564. if ( node.channels && node.channels.length ) {
  17565. var channel = node.channels[ 0 ];
  17566. var m = channel.sampler.output[ frame ];
  17567. if ( m instanceof THREE.Matrix4 ) {
  17568. node.world.copy( m );
  17569. }
  17570. }
  17571. if ( parent ) {
  17572. node.world.multiply( parent, node.world );
  17573. }
  17574. bones.push( node );
  17575. for ( var i = 0; i < node.nodes.length; i ++ ) {
  17576. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  17577. }
  17578. };
  17579. function setupSkinningMatrices ( bones, skin ) {
  17580. // FIXME: this is dumb...
  17581. for ( var i = 0; i < bones.length; i ++ ) {
  17582. var bone = bones[ i ];
  17583. var found = -1;
  17584. if ( bone.type != 'JOINT' ) continue;
  17585. for ( var j = 0; j < skin.joints.length; j ++ ) {
  17586. if ( bone.sid == skin.joints[ j ] ) {
  17587. found = j;
  17588. break;
  17589. }
  17590. }
  17591. if ( found >= 0 ) {
  17592. var inv = skin.invBindMatrices[ found ];
  17593. bone.invBindMatrix = inv;
  17594. bone.skinningMatrix = new THREE.Matrix4();
  17595. bone.skinningMatrix.multiply(bone.world, inv); // (IBMi * JMi)
  17596. bone.weights = [];
  17597. for ( var j = 0; j < skin.weights.length; j ++ ) {
  17598. for (var k = 0; k < skin.weights[ j ].length; k ++) {
  17599. var w = skin.weights[ j ][ k ];
  17600. if ( w.joint == found ) {
  17601. bone.weights.push( w );
  17602. }
  17603. }
  17604. }
  17605. } else {
  17606. throw 'ColladaLoader: Could not find joint \'' + bone.sid + '\'.';
  17607. }
  17608. }
  17609. };
  17610. function applySkin ( geometry, instanceCtrl, frame ) {
  17611. var skinController = controllers[ instanceCtrl.url ];
  17612. frame = frame !== undefined ? frame : 40;
  17613. if ( !skinController || !skinController.skin ) {
  17614. console.log( 'ColladaLoader: Could not find skin controller.' );
  17615. return;
  17616. }
  17617. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  17618. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  17619. return;
  17620. }
  17621. var animationBounds = calcAnimationBounds();
  17622. var skeleton = daeScene.getChildById( instanceCtrl.skeleton[0], true ) ||
  17623. daeScene.getChildBySid( instanceCtrl.skeleton[0], true );
  17624. var i, j, w, vidx, weight;
  17625. var v = new THREE.Vector3(), o, s;
  17626. // move vertices to bind shape
  17627. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  17628. skinController.skin.bindShapeMatrix.multiplyVector3( geometry.vertices[i].position );
  17629. }
  17630. // process animation, or simply pose the rig if no animation
  17631. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  17632. var bones = [];
  17633. var skinned = [];
  17634. // zero skinned vertices
  17635. for ( i = 0; i < geometry.vertices.length; i++ ) {
  17636. skinned.push( new THREE.Vertex( new THREE.Vector3() ) );
  17637. }
  17638. // process the frame and setup the rig with a fresh
  17639. // transform, possibly from the bone's animation channel(s)
  17640. setupSkeleton( skeleton, bones, frame );
  17641. setupSkinningMatrices( bones, skinController.skin );
  17642. // skin 'm
  17643. for ( i = 0; i < bones.length; i ++ ) {
  17644. if ( bones[ i ].type != 'JOINT' ) continue;
  17645. for ( j = 0; j < bones[ i ].weights.length; j ++ ) {
  17646. w = bones[ i ].weights[ j ];
  17647. vidx = w.index;
  17648. weight = w.weight;
  17649. o = geometry.vertices[vidx];
  17650. s = skinned[vidx];
  17651. v.x = o.position.x;
  17652. v.y = o.position.y;
  17653. v.z = o.position.z;
  17654. bones[i].skinningMatrix.multiplyVector3(v);
  17655. s.position.x += (v.x * weight);
  17656. s.position.y += (v.y * weight);
  17657. s.position.z += (v.z * weight);
  17658. }
  17659. }
  17660. geometry.morphTargets.push( { name: "target_" + frame, vertices: skinned } );
  17661. }
  17662. };
  17663. function createSceneGraph ( node, parent ) {
  17664. var obj = new THREE.Object3D();
  17665. var skinned = false;
  17666. var skinController;
  17667. var morphController;
  17668. var i, j;
  17669. // FIXME: controllers
  17670. for ( i = 0; i < node.controllers.length; i ++ ) {
  17671. var controller = controllers[ node.controllers[ i ].url ];
  17672. switch ( controller.type ) {
  17673. case 'skin':
  17674. if ( geometries[ controller.skin.source ] ) {
  17675. var inst_geom = new InstanceGeometry();
  17676. inst_geom.url = controller.skin.source;
  17677. inst_geom.instance_material = node.controllers[ i ].instance_material;
  17678. node.geometries.push( inst_geom );
  17679. skinned = true;
  17680. skinController = node.controllers[ i ];
  17681. } else if ( controllers[ controller.skin.source ] ) {
  17682. // urgh: controller can be chained
  17683. // handle the most basic case...
  17684. var second = controllers[ controller.skin.source ];
  17685. morphController = second;
  17686. // skinController = node.controllers[i];
  17687. if ( second.morph && geometries[ second.morph.source ] ) {
  17688. var inst_geom = new InstanceGeometry();
  17689. inst_geom.url = second.morph.source;
  17690. inst_geom.instance_material = node.controllers[ i ].instance_material;
  17691. node.geometries.push( inst_geom );
  17692. }
  17693. }
  17694. break;
  17695. case 'morph':
  17696. if ( geometries[ controller.morph.source ] ) {
  17697. var inst_geom = new InstanceGeometry();
  17698. inst_geom.url = controller.morph.source;
  17699. inst_geom.instance_material = node.controllers[ i ].instance_material;
  17700. node.geometries.push( inst_geom );
  17701. morphController = node.controllers[ i ];
  17702. }
  17703. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  17704. default:
  17705. break;
  17706. }
  17707. }
  17708. // FIXME: multi-material mesh?
  17709. // geometries
  17710. for ( i = 0; i < node.geometries.length; i ++ ) {
  17711. var instance_geometry = node.geometries[i];
  17712. var instance_materials = instance_geometry.instance_material;
  17713. var geometry = geometries[instance_geometry.url];
  17714. var used_materials = {};
  17715. var used_materials_array = [];
  17716. var num_materials = 0;
  17717. var first_material;
  17718. if ( geometry ) {
  17719. if ( !geometry.mesh || !geometry.mesh.primitives )
  17720. continue;
  17721. if ( obj.name.length == 0 ) {
  17722. obj.name = geometry.id;
  17723. }
  17724. // collect used fx for this geometry-instance
  17725. if ( instance_materials ) {
  17726. for ( j = 0; j < instance_materials.length; j ++ ) {
  17727. var instance_material = instance_materials[ j ];
  17728. var mat = materials[ instance_material.target ];
  17729. var effect_id = mat.instance_effect.url;
  17730. var shader = effects[ effect_id ].shader;
  17731. shader.material.opacity = !shader.material.opacity ? 1 : shader.material.opacity;
  17732. used_materials[ instance_material.symbol ] = num_materials;
  17733. used_materials_array.push( shader.material )
  17734. first_material = shader.material;
  17735. first_material.name = mat.name == null || mat.name === '' ? mat.id : mat.name;
  17736. num_materials ++;
  17737. }
  17738. }
  17739. var mesh;
  17740. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.FlatShading } );
  17741. var geom = geometry.mesh.geometry3js;
  17742. if ( num_materials > 1 ) {
  17743. material = new THREE.MeshFaceMaterial();
  17744. geom.materials = used_materials_array;
  17745. for ( j = 0; j < geom.faces.length; j ++ ) {
  17746. var face = geom.faces[ j ];
  17747. face.materialIndex = used_materials[ face.daeMaterial ]
  17748. }
  17749. }
  17750. if ( skinController !== undefined) {
  17751. applySkin( geom, skinController );
  17752. material.morphTargets = true;
  17753. mesh = new THREE.SkinnedMesh( geom, material );
  17754. mesh.skeleton = skinController.skeleton;
  17755. mesh.skinController = controllers[ skinController.url ];
  17756. mesh.skinInstanceController = skinController;
  17757. mesh.name = 'skin_' + skins.length;
  17758. skins.push( mesh );
  17759. } else if ( morphController !== undefined ) {
  17760. createMorph( geom, morphController );
  17761. material.morphTargets = true;
  17762. mesh = new THREE.Mesh( geom, material );
  17763. mesh.name = 'morph_' + morphs.length;
  17764. morphs.push( mesh );
  17765. } else {
  17766. mesh = new THREE.Mesh( geom, material );
  17767. // mesh.geom.name = geometry.id;
  17768. }
  17769. node.geometries.length > 1 ? obj.add( mesh ) : obj = mesh;
  17770. }
  17771. }
  17772. for ( i = 0; i < node.cameras.length; i ++ ) {
  17773. var instance_camera = node.cameras[i];
  17774. var cparams = cameras[instance_camera.url];
  17775. obj = new THREE.PerspectiveCamera(cparams.fov, cparams.aspect_ratio, cparams.znear, cparams.zfar);
  17776. }
  17777. obj.name = node.id || "";
  17778. obj.matrix = node.matrix;
  17779. var props = node.matrix.decompose();
  17780. obj.position = props[ 0 ];
  17781. obj.quaternion = props[ 1 ];
  17782. obj.useQuaternion = true;
  17783. obj.scale = props[ 2 ];
  17784. if ( options.centerGeometry && obj.geometry ) {
  17785. var delta = THREE.GeometryUtils.center( obj.geometry );
  17786. obj.quaternion.multiplyVector3( delta.multiplySelf( obj.scale ) );
  17787. obj.position.subSelf( delta );
  17788. }
  17789. for ( i = 0; i < node.nodes.length; i ++ ) {
  17790. obj.add( createSceneGraph( node.nodes[i], node ) );
  17791. }
  17792. return obj;
  17793. };
  17794. function getJointId( skin, id ) {
  17795. for ( var i = 0; i < skin.joints.length; i ++ ) {
  17796. if ( skin.joints[ i ] == id ) {
  17797. return i;
  17798. }
  17799. }
  17800. };
  17801. function getLibraryNode( id ) {
  17802. return COLLADA.evaluate( './/dae:library_nodes//dae:node[@id=\'' + id + '\']', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  17803. };
  17804. function getChannelsForNode (node ) {
  17805. var channels = [];
  17806. var startTime = 1000000;
  17807. var endTime = -1000000;
  17808. for ( var id in animations ) {
  17809. var animation = animations[id];
  17810. for ( var i = 0; i < animation.channel.length; i ++ ) {
  17811. var channel = animation.channel[i];
  17812. var sampler = animation.sampler[i];
  17813. var id = channel.target.split('/')[0];
  17814. if ( id == node.id ) {
  17815. sampler.create();
  17816. channel.sampler = sampler;
  17817. startTime = Math.min(startTime, sampler.startTime);
  17818. endTime = Math.max(endTime, sampler.endTime);
  17819. channels.push(channel);
  17820. }
  17821. }
  17822. }
  17823. if ( channels.length ) {
  17824. node.startTime = startTime;
  17825. node.endTime = endTime;
  17826. }
  17827. return channels;
  17828. };
  17829. function calcFrameDuration( node ) {
  17830. var minT = 10000000;
  17831. for ( var i = 0; i < node.channels.length; i ++ ) {
  17832. var sampler = node.channels[i].sampler;
  17833. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  17834. var t0 = sampler.input[ j ];
  17835. var t1 = sampler.input[ j + 1 ];
  17836. minT = Math.min( minT, t1 - t0 );
  17837. }
  17838. }
  17839. return minT;
  17840. };
  17841. function calcMatrixAt( node, t ) {
  17842. var animated = {};
  17843. var i, j;
  17844. for ( i = 0; i < node.channels.length; i ++ ) {
  17845. var channel = node.channels[ i ];
  17846. animated[ channel.sid ] = channel;
  17847. }
  17848. var matrix = new THREE.Matrix4();
  17849. for ( i = 0; i < node.transforms.length; i ++ ) {
  17850. var transform = node.transforms[ i ];
  17851. var channel = animated[ transform.sid ];
  17852. if ( channel !== undefined ) {
  17853. var sampler = channel.sampler;
  17854. var value;
  17855. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  17856. if ( sampler.input[ j + 1 ] > t ) {
  17857. value = sampler.output[ j ];
  17858. //console.log(value.flatten)
  17859. break;
  17860. }
  17861. }
  17862. if ( value !== undefined ) {
  17863. if ( value instanceof THREE.Matrix4 ) {
  17864. matrix = matrix.multiply( matrix, value );
  17865. } else {
  17866. // FIXME: handle other types
  17867. matrix = matrix.multiply( matrix, transform.matrix );
  17868. }
  17869. } else {
  17870. matrix = matrix.multiply( matrix, transform.matrix );
  17871. }
  17872. } else {
  17873. matrix = matrix.multiply( matrix, transform.matrix );
  17874. }
  17875. }
  17876. return matrix;
  17877. };
  17878. function bakeAnimations ( node ) {
  17879. if ( node.channels && node.channels.length ) {
  17880. var keys = [],
  17881. sids = [];
  17882. for ( var i = 0, il = node.channels.length; i < il; i++ ) {
  17883. var channel = node.channels[i],
  17884. fullSid = channel.fullSid,
  17885. member = getConvertedMember( channel.member ),
  17886. sampler = channel.sampler,
  17887. input = sampler.input,
  17888. transform = node.getTransformBySid( channel.sid );
  17889. if ( transform ) {
  17890. if ( sids.indexOf( fullSid ) === -1 ) {
  17891. sids.push( fullSid );
  17892. }
  17893. for ( var j = 0, jl = input.length; j < jl; j++ ) {
  17894. var time = input[j],
  17895. data = sampler.getData( transform.type, j ),
  17896. key = findKey( keys, time );
  17897. if ( !key ) {
  17898. key = new Key( time );
  17899. var timeNdx = findTimeNdx( keys, time );
  17900. keys.splice( timeNdx == -1 ? keys.length : timeNdx, 0, key );
  17901. }
  17902. key.addTarget( fullSid, transform, member, data );
  17903. }
  17904. } else {
  17905. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  17906. }
  17907. }
  17908. // post process
  17909. for ( var i = 0; i < sids.length; i++ ) {
  17910. var sid = sids[ i ];
  17911. for ( var j = 0; j < keys.length; j++ ) {
  17912. var key = keys[ j ];
  17913. if ( !key.hasTarget( sid ) ) {
  17914. interpolateKeys( keys, key, j, sid );
  17915. }
  17916. }
  17917. }
  17918. node.keys = keys;
  17919. node.sids = sids;
  17920. }
  17921. };
  17922. function findKey ( keys, time) {
  17923. var retVal = null;
  17924. for ( var i = 0, il = keys.length; i < il && retVal == null; i++ ) {
  17925. var key = keys[i];
  17926. if ( key.time === time ) {
  17927. retVal = key;
  17928. } else if ( key.time > time ) {
  17929. break;
  17930. }
  17931. }
  17932. return retVal;
  17933. };
  17934. function findTimeNdx ( keys, time) {
  17935. var ndx = -1;
  17936. for ( var i = 0, il = keys.length; i < il && ndx == -1; i++ ) {
  17937. var key = keys[i];
  17938. if ( key.time >= time ) {
  17939. ndx = i;
  17940. }
  17941. }
  17942. return ndx;
  17943. };
  17944. function interpolateKeys ( keys, key, ndx, fullSid ) {
  17945. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx-1 : 0 ),
  17946. nextKey = getNextKeyWith( keys, fullSid, ndx+1 );
  17947. if ( prevKey && nextKey ) {
  17948. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  17949. prevTarget = prevKey.getTarget( fullSid ),
  17950. nextData = nextKey.getTarget( fullSid ).data,
  17951. prevData = prevTarget.data,
  17952. data;
  17953. if ( prevData.length ) {
  17954. data = [];
  17955. for ( var i = 0; i < prevData.length; ++i ) {
  17956. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  17957. }
  17958. } else {
  17959. data = prevData + ( nextData - prevData ) * scale;
  17960. }
  17961. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  17962. }
  17963. };
  17964. // Get next key with given sid
  17965. function getNextKeyWith( keys, fullSid, ndx ) {
  17966. for ( ; ndx < keys.length; ndx++ ) {
  17967. var key = keys[ ndx ];
  17968. if ( key.hasTarget( fullSid ) ) {
  17969. return key;
  17970. }
  17971. }
  17972. return null;
  17973. };
  17974. // Get previous key with given sid
  17975. function getPrevKeyWith( keys, fullSid, ndx ) {
  17976. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  17977. for ( ; ndx >= 0; ndx-- ) {
  17978. var key = keys[ ndx ];
  17979. if ( key.hasTarget( fullSid ) ) {
  17980. return key;
  17981. }
  17982. }
  17983. return null;
  17984. };
  17985. function _Image() {
  17986. this.id = "";
  17987. this.init_from = "";
  17988. };
  17989. _Image.prototype.parse = function(element) {
  17990. this.id = element.getAttribute('id');
  17991. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  17992. var child = element.childNodes[ i ];
  17993. if ( child.nodeName == 'init_from' ) {
  17994. this.init_from = child.textContent;
  17995. }
  17996. }
  17997. return this;
  17998. };
  17999. function Controller() {
  18000. this.id = "";
  18001. this.name = "";
  18002. this.type = "";
  18003. this.skin = null;
  18004. this.morph = null;
  18005. };
  18006. Controller.prototype.parse = function( element ) {
  18007. this.id = element.getAttribute('id');
  18008. this.name = element.getAttribute('name');
  18009. this.type = "none";
  18010. for ( var i = 0; i < element.childNodes.length; i++ ) {
  18011. var child = element.childNodes[ i ];
  18012. switch ( child.nodeName ) {
  18013. case 'skin':
  18014. this.skin = (new Skin()).parse(child);
  18015. this.type = child.nodeName;
  18016. break;
  18017. case 'morph':
  18018. this.morph = (new Morph()).parse(child);
  18019. this.type = child.nodeName;
  18020. break;
  18021. default:
  18022. break;
  18023. }
  18024. }
  18025. return this;
  18026. };
  18027. function Morph() {
  18028. this.method = null;
  18029. this.source = null;
  18030. this.targets = null;
  18031. this.weights = null;
  18032. };
  18033. Morph.prototype.parse = function( element ) {
  18034. var sources = {};
  18035. var inputs = [];
  18036. var i;
  18037. this.method = element.getAttribute( 'method' );
  18038. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  18039. for ( i = 0; i < element.childNodes.length; i ++ ) {
  18040. var child = element.childNodes[ i ];
  18041. if ( child.nodeType != 1 ) continue;
  18042. switch ( child.nodeName ) {
  18043. case 'source':
  18044. var source = ( new Source() ).parse( child );
  18045. sources[ source.id ] = source;
  18046. break;
  18047. case 'targets':
  18048. inputs = this.parseInputs( child );
  18049. break;
  18050. default:
  18051. console.log( child.nodeName );
  18052. break;
  18053. }
  18054. }
  18055. for ( i = 0; i < inputs.length; i ++ ) {
  18056. var input = inputs[ i ];
  18057. var source = sources[ input.source ];
  18058. switch ( input.semantic ) {
  18059. case 'MORPH_TARGET':
  18060. this.targets = source.read();
  18061. break;
  18062. case 'MORPH_WEIGHT':
  18063. this.weights = source.read();
  18064. break;
  18065. default:
  18066. break;
  18067. }
  18068. }
  18069. return this;
  18070. };
  18071. Morph.prototype.parseInputs = function(element) {
  18072. var inputs = [];
  18073. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18074. var child = element.childNodes[i];
  18075. if ( child.nodeType != 1) continue;
  18076. switch ( child.nodeName ) {
  18077. case 'input':
  18078. inputs.push( (new Input()).parse(child) );
  18079. break;
  18080. default:
  18081. break;
  18082. }
  18083. }
  18084. return inputs;
  18085. };
  18086. function Skin() {
  18087. this.source = "";
  18088. this.bindShapeMatrix = null;
  18089. this.invBindMatrices = [];
  18090. this.joints = [];
  18091. this.weights = [];
  18092. };
  18093. Skin.prototype.parse = function( element ) {
  18094. var sources = {};
  18095. var joints, weights;
  18096. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  18097. this.invBindMatrices = [];
  18098. this.joints = [];
  18099. this.weights = [];
  18100. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18101. var child = element.childNodes[i];
  18102. if ( child.nodeType != 1 ) continue;
  18103. switch ( child.nodeName ) {
  18104. case 'bind_shape_matrix':
  18105. var f = _floats(child.textContent);
  18106. this.bindShapeMatrix = getConvertedMat4( f );
  18107. break;
  18108. case 'source':
  18109. var src = new Source().parse(child);
  18110. sources[ src.id ] = src;
  18111. break;
  18112. case 'joints':
  18113. joints = child;
  18114. break;
  18115. case 'vertex_weights':
  18116. weights = child;
  18117. break;
  18118. default:
  18119. console.log( child.nodeName );
  18120. break;
  18121. }
  18122. }
  18123. this.parseJoints( joints, sources );
  18124. this.parseWeights( weights, sources );
  18125. return this;
  18126. };
  18127. Skin.prototype.parseJoints = function ( element, sources ) {
  18128. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18129. var child = element.childNodes[ i ];
  18130. if ( child.nodeType != 1 ) continue;
  18131. switch ( child.nodeName ) {
  18132. case 'input':
  18133. var input = ( new Input() ).parse( child );
  18134. var source = sources[ input.source ];
  18135. if ( input.semantic == 'JOINT' ) {
  18136. this.joints = source.read();
  18137. } else if ( input.semantic == 'INV_BIND_MATRIX' ) {
  18138. this.invBindMatrices = source.read();
  18139. }
  18140. break;
  18141. default:
  18142. break;
  18143. }
  18144. }
  18145. };
  18146. Skin.prototype.parseWeights = function ( element, sources ) {
  18147. var v, vcount, inputs = [];
  18148. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18149. var child = element.childNodes[ i ];
  18150. if ( child.nodeType != 1 ) continue;
  18151. switch ( child.nodeName ) {
  18152. case 'input':
  18153. inputs.push( ( new Input() ).parse( child ) );
  18154. break;
  18155. case 'v':
  18156. v = _ints( child.textContent );
  18157. break;
  18158. case 'vcount':
  18159. vcount = _ints( child.textContent );
  18160. break;
  18161. default:
  18162. break;
  18163. }
  18164. }
  18165. var index = 0;
  18166. for ( var i = 0; i < vcount.length; i ++ ) {
  18167. var numBones = vcount[i];
  18168. var vertex_weights = [];
  18169. for ( var j = 0; j < numBones; j++ ) {
  18170. var influence = {};
  18171. for ( var k = 0; k < inputs.length; k ++ ) {
  18172. var input = inputs[ k ];
  18173. var value = v[ index + input.offset ];
  18174. switch ( input.semantic ) {
  18175. case 'JOINT':
  18176. influence.joint = value;//this.joints[value];
  18177. break;
  18178. case 'WEIGHT':
  18179. influence.weight = sources[ input.source ].data[ value ];
  18180. break;
  18181. default:
  18182. break;
  18183. }
  18184. }
  18185. vertex_weights.push( influence );
  18186. index += inputs.length;
  18187. }
  18188. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  18189. vertex_weights[ j ].index = i;
  18190. }
  18191. this.weights.push( vertex_weights );
  18192. }
  18193. };
  18194. function VisualScene () {
  18195. this.id = "";
  18196. this.name = "";
  18197. this.nodes = [];
  18198. this.scene = new THREE.Object3D();
  18199. };
  18200. VisualScene.prototype.getChildById = function( id, recursive ) {
  18201. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18202. var node = this.nodes[ i ].getChildById( id, recursive );
  18203. if ( node ) {
  18204. return node;
  18205. }
  18206. }
  18207. return null;
  18208. };
  18209. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  18210. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18211. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  18212. if ( node ) {
  18213. return node;
  18214. }
  18215. }
  18216. return null;
  18217. };
  18218. VisualScene.prototype.parse = function( element ) {
  18219. this.id = element.getAttribute( 'id' );
  18220. this.name = element.getAttribute( 'name' );
  18221. this.nodes = [];
  18222. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18223. var child = element.childNodes[ i ];
  18224. if ( child.nodeType != 1 ) continue;
  18225. switch ( child.nodeName ) {
  18226. case 'node':
  18227. this.nodes.push( ( new Node() ).parse( child ) );
  18228. break;
  18229. default:
  18230. break;
  18231. }
  18232. }
  18233. return this;
  18234. };
  18235. function Node() {
  18236. this.id = "";
  18237. this.name = "";
  18238. this.sid = "";
  18239. this.nodes = [];
  18240. this.controllers = [];
  18241. this.transforms = [];
  18242. this.geometries = [];
  18243. this.channels = [];
  18244. this.matrix = new THREE.Matrix4();
  18245. };
  18246. Node.prototype.getChannelForTransform = function( transformSid ) {
  18247. for ( var i = 0; i < this.channels.length; i ++ ) {
  18248. var channel = this.channels[i];
  18249. var parts = channel.target.split('/');
  18250. var id = parts.shift();
  18251. var sid = parts.shift();
  18252. var dotSyntax = (sid.indexOf(".") >= 0);
  18253. var arrSyntax = (sid.indexOf("(") >= 0);
  18254. var arrIndices;
  18255. var member;
  18256. if ( dotSyntax ) {
  18257. parts = sid.split(".");
  18258. sid = parts.shift();
  18259. member = parts.shift();
  18260. } else if ( arrSyntax ) {
  18261. arrIndices = sid.split("(");
  18262. sid = arrIndices.shift();
  18263. for ( var j = 0; j < arrIndices.length; j ++ ) {
  18264. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  18265. }
  18266. }
  18267. if ( sid == transformSid ) {
  18268. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  18269. return channel;
  18270. }
  18271. }
  18272. return null;
  18273. };
  18274. Node.prototype.getChildById = function ( id, recursive ) {
  18275. if ( this.id == id ) {
  18276. return this;
  18277. }
  18278. if ( recursive ) {
  18279. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18280. var n = this.nodes[ i ].getChildById( id, recursive );
  18281. if ( n ) {
  18282. return n;
  18283. }
  18284. }
  18285. }
  18286. return null;
  18287. };
  18288. Node.prototype.getChildBySid = function ( sid, recursive ) {
  18289. if ( this.sid == sid ) {
  18290. return this;
  18291. }
  18292. if ( recursive ) {
  18293. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18294. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  18295. if ( n ) {
  18296. return n;
  18297. }
  18298. }
  18299. }
  18300. return null;
  18301. };
  18302. Node.prototype.getTransformBySid = function ( sid ) {
  18303. for ( var i = 0; i < this.transforms.length; i ++ ) {
  18304. if ( this.transforms[ i ].sid == sid ) return this.transforms[ i ];
  18305. }
  18306. return null;
  18307. };
  18308. Node.prototype.parse = function( element ) {
  18309. var url;
  18310. this.id = element.getAttribute('id');
  18311. this.sid = element.getAttribute('sid');
  18312. this.name = element.getAttribute('name');
  18313. this.type = element.getAttribute('type');
  18314. this.type = this.type == 'JOINT' ? this.type : 'NODE';
  18315. this.nodes = [];
  18316. this.transforms = [];
  18317. this.geometries = [];
  18318. this.cameras = [];
  18319. this.controllers = [];
  18320. this.matrix = new THREE.Matrix4();
  18321. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18322. var child = element.childNodes[ i ];
  18323. if ( child.nodeType != 1 ) continue;
  18324. switch ( child.nodeName ) {
  18325. case 'node':
  18326. this.nodes.push( ( new Node() ).parse( child ) );
  18327. break;
  18328. case 'instance_camera':
  18329. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  18330. break;
  18331. case 'instance_controller':
  18332. this.controllers.push( ( new InstanceController() ).parse( child ) );
  18333. break;
  18334. case 'instance_geometry':
  18335. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  18336. break;
  18337. case 'instance_light':
  18338. break;
  18339. case 'instance_node':
  18340. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  18341. var iNode = getLibraryNode( url );
  18342. if ( iNode ) {
  18343. this.nodes.push( ( new Node() ).parse( iNode )) ;
  18344. }
  18345. break;
  18346. case 'rotate':
  18347. case 'translate':
  18348. case 'scale':
  18349. case 'matrix':
  18350. case 'lookat':
  18351. case 'skew':
  18352. this.transforms.push( ( new Transform() ).parse( child ) );
  18353. break;
  18354. case 'extra':
  18355. break;
  18356. default:
  18357. console.log( child.nodeName );
  18358. break;
  18359. }
  18360. }
  18361. this.channels = getChannelsForNode( this );
  18362. bakeAnimations( this );
  18363. this.updateMatrix();
  18364. return this;
  18365. };
  18366. Node.prototype.updateMatrix = function () {
  18367. this.matrix.identity();
  18368. for ( var i = 0; i < this.transforms.length; i ++ ) {
  18369. this.transforms[ i ].apply( this.matrix );
  18370. }
  18371. };
  18372. function Transform () {
  18373. this.sid = "";
  18374. this.type = "";
  18375. this.data = [];
  18376. this.obj = null;
  18377. };
  18378. Transform.prototype.parse = function ( element ) {
  18379. this.sid = element.getAttribute( 'sid' );
  18380. this.type = element.nodeName;
  18381. this.data = _floats( element.textContent );
  18382. this.convert();
  18383. return this;
  18384. };
  18385. Transform.prototype.convert = function () {
  18386. switch ( this.type ) {
  18387. case 'matrix':
  18388. this.obj = getConvertedMat4( this.data );
  18389. break;
  18390. case 'rotate':
  18391. this.angle = this.data[3] * TO_RADIANS;
  18392. case 'translate':
  18393. fixCoords( this.data, -1 );
  18394. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  18395. break;
  18396. case 'scale':
  18397. fixCoords( this.data, 1 );
  18398. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  18399. break;
  18400. default:
  18401. console.log( 'Can not convert Transform of type ' + this.type );
  18402. break;
  18403. }
  18404. };
  18405. Transform.prototype.apply = function ( matrix ) {
  18406. switch ( this.type ) {
  18407. case 'matrix':
  18408. matrix.multiplySelf( this.obj );
  18409. break;
  18410. case 'translate':
  18411. matrix.translate( this.obj );
  18412. break;
  18413. case 'rotate':
  18414. matrix.rotateByAxis( this.obj, this.angle );
  18415. break;
  18416. case 'scale':
  18417. matrix.scale( this.obj );
  18418. break;
  18419. }
  18420. };
  18421. Transform.prototype.update = function ( data, member ) {
  18422. switch ( this.type ) {
  18423. case 'matrix':
  18424. console.log( 'Currently not handling matrix transform updates' );
  18425. break;
  18426. case 'translate':
  18427. case 'scale':
  18428. switch ( member ) {
  18429. case 'X':
  18430. this.obj.x = data;
  18431. break;
  18432. case 'Y':
  18433. this.obj.y = data;
  18434. break;
  18435. case 'Z':
  18436. this.obj.z = data;
  18437. break;
  18438. default:
  18439. this.obj.x = data[ 0 ];
  18440. this.obj.y = data[ 1 ];
  18441. this.obj.z = data[ 2 ];
  18442. break;
  18443. }
  18444. break;
  18445. case 'rotate':
  18446. switch ( member ) {
  18447. case 'X':
  18448. this.obj.x = data;
  18449. break;
  18450. case 'Y':
  18451. this.obj.y = data;
  18452. break;
  18453. case 'Z':
  18454. this.obj.z = data;
  18455. break;
  18456. case 'ANGLE':
  18457. this.angle = data * TO_RADIANS;
  18458. break;
  18459. default:
  18460. this.obj.x = data[ 0 ];
  18461. this.obj.y = data[ 1 ];
  18462. this.obj.z = data[ 2 ];
  18463. this.angle = data[ 3 ] * TO_RADIANS;
  18464. break;
  18465. }
  18466. break;
  18467. }
  18468. };
  18469. function InstanceController() {
  18470. this.url = "";
  18471. this.skeleton = [];
  18472. this.instance_material = [];
  18473. };
  18474. InstanceController.prototype.parse = function ( element ) {
  18475. this.url = element.getAttribute('url').replace(/^#/, '');
  18476. this.skeleton = [];
  18477. this.instance_material = [];
  18478. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18479. var child = element.childNodes[i];
  18480. if (child.nodeType != 1) continue;
  18481. switch ( child.nodeName ) {
  18482. case 'skeleton':
  18483. this.skeleton.push( child.textContent.replace(/^#/, '') );
  18484. break;
  18485. case 'bind_material':
  18486. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  18487. if ( instances ) {
  18488. var instance = instances.iterateNext();
  18489. while ( instance ) {
  18490. this.instance_material.push((new InstanceMaterial()).parse(instance));
  18491. instance = instances.iterateNext();
  18492. }
  18493. }
  18494. break;
  18495. case 'extra':
  18496. break;
  18497. default:
  18498. break;
  18499. }
  18500. }
  18501. return this;
  18502. };
  18503. function InstanceMaterial () {
  18504. this.symbol = "";
  18505. this.target = "";
  18506. };
  18507. InstanceMaterial.prototype.parse = function ( element ) {
  18508. this.symbol = element.getAttribute('symbol');
  18509. this.target = element.getAttribute('target').replace(/^#/, '');
  18510. return this;
  18511. };
  18512. function InstanceGeometry() {
  18513. this.url = "";
  18514. this.instance_material = [];
  18515. };
  18516. InstanceGeometry.prototype.parse = function ( element ) {
  18517. this.url = element.getAttribute('url').replace(/^#/, '');
  18518. this.instance_material = [];
  18519. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18520. var child = element.childNodes[i];
  18521. if ( child.nodeType != 1 ) continue;
  18522. if ( child.nodeName == 'bind_material' ) {
  18523. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  18524. if ( instances ) {
  18525. var instance = instances.iterateNext();
  18526. while ( instance ) {
  18527. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  18528. instance = instances.iterateNext();
  18529. }
  18530. }
  18531. break;
  18532. }
  18533. }
  18534. return this;
  18535. };
  18536. function Geometry() {
  18537. this.id = "";
  18538. this.mesh = null;
  18539. };
  18540. Geometry.prototype.parse = function ( element ) {
  18541. this.id = element.getAttribute('id');
  18542. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18543. var child = element.childNodes[i];
  18544. switch ( child.nodeName ) {
  18545. case 'mesh':
  18546. this.mesh = (new Mesh(this)).parse(child);
  18547. break;
  18548. case 'extra':
  18549. // console.log( child );
  18550. break;
  18551. default:
  18552. break;
  18553. }
  18554. }
  18555. return this;
  18556. };
  18557. function Mesh( geometry ) {
  18558. this.geometry = geometry.id;
  18559. this.primitives = [];
  18560. this.vertices = null;
  18561. this.geometry3js = null;
  18562. };
  18563. Mesh.prototype.parse = function( element ) {
  18564. this.primitives = [];
  18565. var i, j;
  18566. for ( i = 0; i < element.childNodes.length; i ++ ) {
  18567. var child = element.childNodes[ i ];
  18568. switch ( child.nodeName ) {
  18569. case 'source':
  18570. _source( child );
  18571. break;
  18572. case 'vertices':
  18573. this.vertices = ( new Vertices() ).parse( child );
  18574. break;
  18575. case 'triangles':
  18576. this.primitives.push( ( new Triangles().parse( child ) ) );
  18577. break;
  18578. case 'polygons':
  18579. this.primitives.push( ( new Polygons().parse( child ) ) );
  18580. break;
  18581. case 'polylist':
  18582. this.primitives.push( ( new Polylist().parse( child ) ) );
  18583. break;
  18584. default:
  18585. break;
  18586. }
  18587. }
  18588. this.geometry3js = new THREE.Geometry();
  18589. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  18590. for ( i = 0; i < vertexData.length; i += 3 ) {
  18591. var v = new THREE.Vertex( getConvertedVec3( vertexData, i ) );
  18592. this.geometry3js.vertices.push( v );
  18593. }
  18594. for ( i = 0; i < this.primitives.length; i ++ ) {
  18595. var primitive = this.primitives[ i ];
  18596. primitive.setVertices( this.vertices );
  18597. this.handlePrimitive( primitive, this.geometry3js );
  18598. }
  18599. this.geometry3js.computeCentroids();
  18600. this.geometry3js.computeFaceNormals();
  18601. if ( this.geometry3js.calcNormals ) {
  18602. this.geometry3js.computeVertexNormals();
  18603. delete this.geometry3js.calcNormals;
  18604. }
  18605. this.geometry3js.computeBoundingBox();
  18606. return this;
  18607. };
  18608. Mesh.prototype.handlePrimitive = function( primitive, geom ) {
  18609. var j, k, pList = primitive.p, inputs = primitive.inputs;
  18610. var input, index, idx32;
  18611. var source, numParams;
  18612. var vcIndex = 0, vcount = 3, maxOffset = 0;
  18613. var texture_sets = [];
  18614. for ( j = 0; j < inputs.length; j ++ ) {
  18615. input = inputs[ j ];
  18616. var offset = input.offset + 1;
  18617. maxOffset = (maxOffset < offset)? offset : maxOffset;
  18618. switch ( input.semantic ) {
  18619. case 'TEXCOORD':
  18620. texture_sets.push( input.set );
  18621. break;
  18622. }
  18623. }
  18624. for ( var pCount = 0; pCount < pList.length; ++pCount ) {
  18625. var p = pList[pCount], i = 0;
  18626. while ( i < p.length ) {
  18627. var vs = [];
  18628. var ns = [];
  18629. var ts = {};
  18630. var cs = [];
  18631. if ( primitive.vcount ) {
  18632. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  18633. } else {
  18634. vcount = p.length / maxOffset;
  18635. }
  18636. for ( j = 0; j < vcount; j ++ ) {
  18637. for ( k = 0; k < inputs.length; k ++ ) {
  18638. input = inputs[ k ];
  18639. source = sources[ input.source ];
  18640. index = p[ i + ( j * maxOffset ) + input.offset ];
  18641. numParams = source.accessor.params.length;
  18642. idx32 = index * numParams;
  18643. switch ( input.semantic ) {
  18644. case 'VERTEX':
  18645. vs.push( index );
  18646. break;
  18647. case 'NORMAL':
  18648. ns.push( getConvertedVec3( source.data, idx32 ) );
  18649. break;
  18650. case 'TEXCOORD':
  18651. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  18652. // invert the V
  18653. ts[ input.set ].push( new THREE.UV( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  18654. break;
  18655. case 'COLOR':
  18656. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  18657. break;
  18658. default:
  18659. break;
  18660. }
  18661. }
  18662. }
  18663. var face = null, faces = [], uv, uvArr;
  18664. if ( ns.length == 0 ) {
  18665. // check the vertices source
  18666. input = this.vertices.input.NORMAL;
  18667. if ( input ) {
  18668. source = sources[ input.source ];
  18669. numParams = source.accessor.params.length;
  18670. for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
  18671. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  18672. }
  18673. }
  18674. else {
  18675. geom.calcNormals = true;
  18676. }
  18677. }
  18678. if ( vcount === 3 ) {
  18679. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  18680. } else if ( vcount === 4 ) {
  18681. faces.push( new THREE.Face4( vs[0], vs[1], vs[2], vs[3], ns, cs.length ? cs : new THREE.Color() ) );
  18682. } else if ( vcount > 4 && options.subdivideFaces ) {
  18683. var clr = cs.length ? cs : new THREE.Color(),
  18684. vec1, vec2, vec3, v1, v2, norm;
  18685. // subdivide into multiple Face3s
  18686. for ( k = 1; k < vcount-1; ) {
  18687. // FIXME: normals don't seem to be quite right
  18688. faces.push( new THREE.Face3( vs[0], vs[k], vs[k+1], [ ns[0], ns[k++], ns[k] ], clr ) );
  18689. }
  18690. }
  18691. if ( faces.length ) {
  18692. for (var ndx = 0, len = faces.length; ndx < len; ndx++) {
  18693. face = faces[ndx];
  18694. face.daeMaterial = primitive.material;
  18695. geom.faces.push( face );
  18696. for ( k = 0; k < texture_sets.length; k++ ) {
  18697. uv = ts[ texture_sets[k] ];
  18698. if ( vcount > 4 ) {
  18699. // Grab the right UVs for the vertices in this face
  18700. uvArr = [ uv[0], uv[ndx+1], uv[ndx+2] ];
  18701. } else if ( vcount === 4 ) {
  18702. uvArr = [ uv[0], uv[1], uv[2], uv[3] ];
  18703. } else {
  18704. uvArr = [ uv[0], uv[1], uv[2] ];
  18705. }
  18706. if ( !geom.faceVertexUvs[k] ) {
  18707. geom.faceVertexUvs[k] = [];
  18708. }
  18709. geom.faceVertexUvs[k].push( uvArr );
  18710. }
  18711. }
  18712. } else {
  18713. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  18714. }
  18715. i += maxOffset * vcount;
  18716. }
  18717. }
  18718. };
  18719. function Polygons () {
  18720. this.material = "";
  18721. this.count = 0;
  18722. this.inputs = [];
  18723. this.vcount = null;
  18724. this.p = [];
  18725. this.geometry = new THREE.Geometry();
  18726. };
  18727. Polygons.prototype.setVertices = function ( vertices ) {
  18728. for ( var i = 0; i < this.inputs.length; i ++ ) {
  18729. if ( this.inputs[ i ].source == vertices.id ) {
  18730. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  18731. }
  18732. }
  18733. };
  18734. Polygons.prototype.parse = function ( element ) {
  18735. this.material = element.getAttribute( 'material' );
  18736. this.count = _attr_as_int( element, 'count', 0 );
  18737. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18738. var child = element.childNodes[ i ];
  18739. switch ( child.nodeName ) {
  18740. case 'input':
  18741. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  18742. break;
  18743. case 'vcount':
  18744. this.vcount = _ints( child.textContent );
  18745. break;
  18746. case 'p':
  18747. this.p.push( _ints( child.textContent ) );
  18748. break;
  18749. case 'ph':
  18750. console.warn( 'polygon holes not yet supported!' );
  18751. break;
  18752. default:
  18753. break;
  18754. }
  18755. }
  18756. return this;
  18757. };
  18758. function Polylist () {
  18759. Polygons.call( this );
  18760. this.vcount = [];
  18761. };
  18762. Polylist.prototype = new Polygons();
  18763. Polylist.prototype.constructor = Polylist;
  18764. function Triangles () {
  18765. Polygons.call( this );
  18766. this.vcount = 3;
  18767. };
  18768. Triangles.prototype = new Polygons();
  18769. Triangles.prototype.constructor = Triangles;
  18770. function Accessor() {
  18771. this.source = "";
  18772. this.count = 0;
  18773. this.stride = 0;
  18774. this.params = [];
  18775. };
  18776. Accessor.prototype.parse = function ( element ) {
  18777. this.params = [];
  18778. this.source = element.getAttribute( 'source' );
  18779. this.count = _attr_as_int( element, 'count', 0 );
  18780. this.stride = _attr_as_int( element, 'stride', 0 );
  18781. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18782. var child = element.childNodes[ i ];
  18783. if ( child.nodeName == 'param' ) {
  18784. var param = {};
  18785. param[ 'name' ] = child.getAttribute( 'name' );
  18786. param[ 'type' ] = child.getAttribute( 'type' );
  18787. this.params.push( param );
  18788. }
  18789. }
  18790. return this;
  18791. };
  18792. function Vertices() {
  18793. this.input = {};
  18794. };
  18795. Vertices.prototype.parse = function ( element ) {
  18796. this.id = element.getAttribute('id');
  18797. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18798. if ( element.childNodes[i].nodeName == 'input' ) {
  18799. var input = ( new Input() ).parse( element.childNodes[ i ] );
  18800. this.input[ input.semantic ] = input;
  18801. }
  18802. }
  18803. return this;
  18804. };
  18805. function Input () {
  18806. this.semantic = "";
  18807. this.offset = 0;
  18808. this.source = "";
  18809. this.set = 0;
  18810. };
  18811. Input.prototype.parse = function ( element ) {
  18812. this.semantic = element.getAttribute('semantic');
  18813. this.source = element.getAttribute('source').replace(/^#/, '');
  18814. this.set = _attr_as_int(element, 'set', -1);
  18815. this.offset = _attr_as_int(element, 'offset', 0);
  18816. if ( this.semantic == 'TEXCOORD' && this.set < 0 ) {
  18817. this.set = 0;
  18818. }
  18819. return this;
  18820. };
  18821. function Source ( id ) {
  18822. this.id = id;
  18823. this.type = null;
  18824. };
  18825. Source.prototype.parse = function ( element ) {
  18826. this.id = element.getAttribute( 'id' );
  18827. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18828. var child = element.childNodes[i];
  18829. switch ( child.nodeName ) {
  18830. case 'bool_array':
  18831. this.data = _bools( child.textContent );
  18832. this.type = child.nodeName;
  18833. break;
  18834. case 'float_array':
  18835. this.data = _floats( child.textContent );
  18836. this.type = child.nodeName;
  18837. break;
  18838. case 'int_array':
  18839. this.data = _ints( child.textContent );
  18840. this.type = child.nodeName;
  18841. break;
  18842. case 'IDREF_array':
  18843. case 'Name_array':
  18844. this.data = _strings( child.textContent );
  18845. this.type = child.nodeName;
  18846. break;
  18847. case 'technique_common':
  18848. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  18849. if ( child.childNodes[ j ].nodeName == 'accessor' ) {
  18850. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  18851. break;
  18852. }
  18853. }
  18854. break;
  18855. default:
  18856. // console.log(child.nodeName);
  18857. break;
  18858. }
  18859. }
  18860. return this;
  18861. };
  18862. Source.prototype.read = function () {
  18863. var result = [];
  18864. //for (var i = 0; i < this.accessor.params.length; i++) {
  18865. var param = this.accessor.params[ 0 ];
  18866. //console.log(param.name + " " + param.type);
  18867. switch ( param.type ) {
  18868. case 'IDREF':
  18869. case 'Name': case 'name':
  18870. case 'float':
  18871. return this.data;
  18872. case 'float4x4':
  18873. for ( var j = 0; j < this.data.length; j += 16 ) {
  18874. var s = this.data.slice( j, j + 16 );
  18875. var m = getConvertedMat4( s );
  18876. result.push( m );
  18877. }
  18878. break;
  18879. default:
  18880. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  18881. break;
  18882. }
  18883. //}
  18884. return result;
  18885. };
  18886. function Material () {
  18887. this.id = "";
  18888. this.name = "";
  18889. this.instance_effect = null;
  18890. };
  18891. Material.prototype.parse = function ( element ) {
  18892. this.id = element.getAttribute( 'id' );
  18893. this.name = element.getAttribute( 'name' );
  18894. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18895. if ( element.childNodes[ i ].nodeName == 'instance_effect' ) {
  18896. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  18897. break;
  18898. }
  18899. }
  18900. return this;
  18901. };
  18902. function ColorOrTexture () {
  18903. this.color = new THREE.Color( 0 );
  18904. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  18905. this.color.a = 1.0;
  18906. this.texture = null;
  18907. this.texcoord = null;
  18908. this.texOpts = null;
  18909. };
  18910. ColorOrTexture.prototype.isColor = function () {
  18911. return ( this.texture == null );
  18912. };
  18913. ColorOrTexture.prototype.isTexture = function () {
  18914. return ( this.texture != null );
  18915. };
  18916. ColorOrTexture.prototype.parse = function ( element ) {
  18917. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18918. var child = element.childNodes[ i ];
  18919. if ( child.nodeType != 1 ) continue;
  18920. switch ( child.nodeName ) {
  18921. case 'color':
  18922. var rgba = _floats( child.textContent );
  18923. this.color = new THREE.Color(0);
  18924. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  18925. this.color.a = rgba[3];
  18926. break;
  18927. case 'texture':
  18928. this.texture = child.getAttribute('texture');
  18929. this.texcoord = child.getAttribute('texcoord');
  18930. // Defaults from:
  18931. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  18932. this.texOpts = {
  18933. offsetU: 0,
  18934. offsetV: 0,
  18935. repeatU: 1,
  18936. repeatV: 1,
  18937. wrapU: 1,
  18938. wrapV: 1,
  18939. };
  18940. this.parseTexture( child );
  18941. break;
  18942. default:
  18943. break;
  18944. }
  18945. }
  18946. return this;
  18947. };
  18948. ColorOrTexture.prototype.parseTexture = function ( element ) {
  18949. if ( ! element.childNodes ) return this;
  18950. // This should be supported by Maya, 3dsMax, and MotionBuilder
  18951. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  18952. element = element.childNodes[1];
  18953. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  18954. element = element.childNodes[1];
  18955. }
  18956. }
  18957. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18958. var child = element.childNodes[ i ];
  18959. switch ( child.nodeName ) {
  18960. case 'offsetU':
  18961. case 'offsetV':
  18962. case 'repeatU':
  18963. case 'repeatV':
  18964. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  18965. break;
  18966. case 'wrapU':
  18967. case 'wrapV':
  18968. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  18969. break;
  18970. default:
  18971. this.texOpts[ child.nodeName ] = child.textContent;
  18972. break;
  18973. }
  18974. }
  18975. return this;
  18976. };
  18977. function Shader ( type, effect ) {
  18978. this.type = type;
  18979. this.effect = effect;
  18980. this.material = null;
  18981. };
  18982. Shader.prototype.parse = function ( element ) {
  18983. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18984. var child = element.childNodes[ i ];
  18985. if ( child.nodeType != 1 ) continue;
  18986. switch ( child.nodeName ) {
  18987. case 'ambient':
  18988. case 'emission':
  18989. case 'diffuse':
  18990. case 'specular':
  18991. case 'transparent':
  18992. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  18993. break;
  18994. case 'shininess':
  18995. case 'reflectivity':
  18996. case 'transparency':
  18997. var f = evaluateXPath( child, './/dae:float' );
  18998. if ( f.length > 0 )
  18999. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  19000. break;
  19001. default:
  19002. break;
  19003. }
  19004. }
  19005. this.create();
  19006. return this;
  19007. };
  19008. Shader.prototype.create = function() {
  19009. var props = {};
  19010. var transparent = ( this['transparency'] !== undefined && this['transparency'] < 1.0 );
  19011. for ( var prop in this ) {
  19012. switch ( prop ) {
  19013. case 'ambient':
  19014. case 'emission':
  19015. case 'diffuse':
  19016. case 'specular':
  19017. var cot = this[prop];
  19018. if ( cot instanceof ColorOrTexture ) {
  19019. if ( cot.isTexture() ) {
  19020. if ( this.effect.sampler && this.effect.surface ) {
  19021. if ( this.effect.sampler.source == this.effect.surface.sid ) {
  19022. var image = images[this.effect.surface.init_from];
  19023. if ( image ) {
  19024. var texture = THREE.ImageUtils.loadTexture(baseUrl + image.init_from);
  19025. texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  19026. texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  19027. texture.offset.x = cot.texOpts.offsetU;
  19028. texture.offset.y = cot.texOpts.offsetV;
  19029. texture.repeat.x = cot.texOpts.repeatU;
  19030. texture.repeat.y = cot.texOpts.repeatV;
  19031. props['map'] = texture;
  19032. }
  19033. }
  19034. }
  19035. } else if ( prop == 'diffuse' || !transparent ) {
  19036. props[ prop ] = cot.color.getHex();
  19037. }
  19038. }
  19039. break;
  19040. case 'shininess':
  19041. case 'reflectivity':
  19042. props[ prop ] = this[ prop ];
  19043. break;
  19044. case 'transparency':
  19045. if ( transparent ) {
  19046. props[ 'transparent' ] = true;
  19047. props[ 'opacity' ] = this[ prop ];
  19048. transparent = true;
  19049. }
  19050. break;
  19051. default:
  19052. break;
  19053. }
  19054. }
  19055. props[ 'shading' ] = preferredShading;
  19056. switch ( this.type ) {
  19057. case 'constant':
  19058. props.color = props.emission;
  19059. this.material = new THREE.MeshBasicMaterial( props );
  19060. break;
  19061. case 'phong':
  19062. case 'blinn':
  19063. props.color = props.diffuse;
  19064. this.material = new THREE.MeshPhongMaterial( props );
  19065. break;
  19066. case 'lambert':
  19067. default:
  19068. props.color = props.diffuse;
  19069. this.material = new THREE.MeshLambertMaterial( props );
  19070. break;
  19071. }
  19072. return this.material;
  19073. };
  19074. function Surface ( effect ) {
  19075. this.effect = effect;
  19076. this.init_from = null;
  19077. this.format = null;
  19078. };
  19079. Surface.prototype.parse = function ( element ) {
  19080. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19081. var child = element.childNodes[ i ];
  19082. if ( child.nodeType != 1 ) continue;
  19083. switch ( child.nodeName ) {
  19084. case 'init_from':
  19085. this.init_from = child.textContent;
  19086. break;
  19087. case 'format':
  19088. this.format = child.textContent;
  19089. break;
  19090. default:
  19091. console.log( "unhandled Surface prop: " + child.nodeName );
  19092. break;
  19093. }
  19094. }
  19095. return this;
  19096. };
  19097. function Sampler2D ( effect ) {
  19098. this.effect = effect;
  19099. this.source = null;
  19100. this.wrap_s = null;
  19101. this.wrap_t = null;
  19102. this.minfilter = null;
  19103. this.magfilter = null;
  19104. this.mipfilter = null;
  19105. };
  19106. Sampler2D.prototype.parse = function ( element ) {
  19107. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19108. var child = element.childNodes[ i ];
  19109. if ( child.nodeType != 1 ) continue;
  19110. switch ( child.nodeName ) {
  19111. case 'source':
  19112. this.source = child.textContent;
  19113. break;
  19114. case 'minfilter':
  19115. this.minfilter = child.textContent;
  19116. break;
  19117. case 'magfilter':
  19118. this.magfilter = child.textContent;
  19119. break;
  19120. case 'mipfilter':
  19121. this.mipfilter = child.textContent;
  19122. break;
  19123. case 'wrap_s':
  19124. this.wrap_s = child.textContent;
  19125. break;
  19126. case 'wrap_t':
  19127. this.wrap_t = child.textContent;
  19128. break;
  19129. default:
  19130. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  19131. break;
  19132. }
  19133. }
  19134. return this;
  19135. };
  19136. function Effect () {
  19137. this.id = "";
  19138. this.name = "";
  19139. this.shader = null;
  19140. this.surface = null;
  19141. this.sampler = null;
  19142. };
  19143. Effect.prototype.create = function () {
  19144. if ( this.shader == null ) {
  19145. return null;
  19146. }
  19147. };
  19148. Effect.prototype.parse = function ( element ) {
  19149. this.id = element.getAttribute( 'id' );
  19150. this.name = element.getAttribute( 'name' );
  19151. this.shader = null;
  19152. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19153. var child = element.childNodes[ i ];
  19154. if ( child.nodeType != 1 ) continue;
  19155. switch ( child.nodeName ) {
  19156. case 'profile_COMMON':
  19157. this.parseTechnique( this.parseProfileCOMMON( child ) );
  19158. break;
  19159. default:
  19160. break;
  19161. }
  19162. }
  19163. return this;
  19164. };
  19165. Effect.prototype.parseNewparam = function ( element ) {
  19166. var sid = element.getAttribute( 'sid' );
  19167. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19168. var child = element.childNodes[ i ];
  19169. if ( child.nodeType != 1 ) continue;
  19170. switch ( child.nodeName ) {
  19171. case 'surface':
  19172. this.surface = ( new Surface( this ) ).parse( child );
  19173. this.surface.sid = sid;
  19174. break;
  19175. case 'sampler2D':
  19176. this.sampler = ( new Sampler2D( this ) ).parse( child );
  19177. this.sampler.sid = sid;
  19178. break;
  19179. case 'extra':
  19180. break;
  19181. default:
  19182. console.log( child.nodeName );
  19183. break;
  19184. }
  19185. }
  19186. };
  19187. Effect.prototype.parseProfileCOMMON = function ( element ) {
  19188. var technique;
  19189. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19190. var child = element.childNodes[ i ];
  19191. if ( child.nodeType != 1 ) continue;
  19192. switch ( child.nodeName ) {
  19193. case 'profile_COMMON':
  19194. this.parseProfileCOMMON( child );
  19195. break;
  19196. case 'technique':
  19197. technique = child;
  19198. break;
  19199. case 'newparam':
  19200. this.parseNewparam( child );
  19201. break;
  19202. case 'image':
  19203. var _image = ( new _Image() ).parse( child );
  19204. images[ _image.id ] = _image;
  19205. break;
  19206. case 'extra':
  19207. break;
  19208. default:
  19209. console.log( child.nodeName );
  19210. break;
  19211. }
  19212. }
  19213. return technique;
  19214. };
  19215. Effect.prototype.parseTechnique= function ( element ) {
  19216. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19217. var child = element.childNodes[i];
  19218. if ( child.nodeType != 1 ) continue;
  19219. switch ( child.nodeName ) {
  19220. case 'constant':
  19221. case 'lambert':
  19222. case 'blinn':
  19223. case 'phong':
  19224. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  19225. break;
  19226. default:
  19227. break;
  19228. }
  19229. }
  19230. };
  19231. function InstanceEffect () {
  19232. this.url = "";
  19233. };
  19234. InstanceEffect.prototype.parse = function ( element ) {
  19235. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  19236. return this;
  19237. };
  19238. function Animation() {
  19239. this.id = "";
  19240. this.name = "";
  19241. this.source = {};
  19242. this.sampler = [];
  19243. this.channel = [];
  19244. };
  19245. Animation.prototype.parse = function ( element ) {
  19246. this.id = element.getAttribute( 'id' );
  19247. this.name = element.getAttribute( 'name' );
  19248. this.source = {};
  19249. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19250. var child = element.childNodes[ i ];
  19251. if ( child.nodeType != 1 ) continue;
  19252. switch ( child.nodeName ) {
  19253. case 'source':
  19254. var src = ( new Source() ).parse( child );
  19255. this.source[ src.id ] = src;
  19256. break;
  19257. case 'sampler':
  19258. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  19259. break;
  19260. case 'channel':
  19261. this.channel.push( ( new Channel( this ) ).parse( child ) );
  19262. break;
  19263. default:
  19264. break;
  19265. }
  19266. }
  19267. return this;
  19268. };
  19269. function Channel( animation ) {
  19270. this.animation = animation;
  19271. this.source = "";
  19272. this.target = "";
  19273. this.fullSid = null;
  19274. this.sid = null;
  19275. this.dotSyntax = null;
  19276. this.arrSyntax = null;
  19277. this.arrIndices = null;
  19278. this.member = null;
  19279. };
  19280. Channel.prototype.parse = function ( element ) {
  19281. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  19282. this.target = element.getAttribute( 'target' );
  19283. var parts = this.target.split( '/' );
  19284. var id = parts.shift();
  19285. var sid = parts.shift();
  19286. var dotSyntax = ( sid.indexOf(".") >= 0 );
  19287. var arrSyntax = ( sid.indexOf("(") >= 0 );
  19288. if ( dotSyntax ) {
  19289. parts = sid.split(".");
  19290. this.sid = parts.shift();
  19291. this.member = parts.shift();
  19292. } else if ( arrSyntax ) {
  19293. var arrIndices = sid.split("(");
  19294. this.sid = arrIndices.shift();
  19295. for (var j = 0; j < arrIndices.length; j ++ ) {
  19296. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  19297. }
  19298. this.arrIndices = arrIndices;
  19299. } else {
  19300. this.sid = sid;
  19301. }
  19302. this.fullSid = sid;
  19303. this.dotSyntax = dotSyntax;
  19304. this.arrSyntax = arrSyntax;
  19305. return this;
  19306. };
  19307. function Sampler ( animation ) {
  19308. this.id = "";
  19309. this.animation = animation;
  19310. this.inputs = [];
  19311. this.input = null;
  19312. this.output = null;
  19313. this.strideOut = null;
  19314. this.interpolation = null;
  19315. this.startTime = null;
  19316. this.endTime = null;
  19317. this.duration = 0;
  19318. };
  19319. Sampler.prototype.parse = function ( element ) {
  19320. this.id = element.getAttribute( 'id' );
  19321. this.inputs = [];
  19322. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19323. var child = element.childNodes[ i ];
  19324. if ( child.nodeType != 1 ) continue;
  19325. switch ( child.nodeName ) {
  19326. case 'input':
  19327. this.inputs.push( (new Input()).parse( child ) );
  19328. break;
  19329. default:
  19330. break;
  19331. }
  19332. }
  19333. return this;
  19334. };
  19335. Sampler.prototype.create = function () {
  19336. for ( var i = 0; i < this.inputs.length; i ++ ) {
  19337. var input = this.inputs[ i ];
  19338. var source = this.animation.source[ input.source ];
  19339. switch ( input.semantic ) {
  19340. case 'INPUT':
  19341. this.input = source.read();
  19342. break;
  19343. case 'OUTPUT':
  19344. this.output = source.read();
  19345. this.strideOut = source.accessor.stride;
  19346. break;
  19347. case 'INTERPOLATION':
  19348. this.interpolation = source.read();
  19349. break;
  19350. case 'IN_TANGENT':
  19351. break;
  19352. case 'OUT_TANGENT':
  19353. break;
  19354. default:
  19355. console.log(input.semantic);
  19356. break;
  19357. }
  19358. }
  19359. this.startTime = 0;
  19360. this.endTime = 0;
  19361. this.duration = 0;
  19362. if ( this.input.length ) {
  19363. this.startTime = 100000000;
  19364. this.endTime = -100000000;
  19365. for ( var i = 0; i < this.input.length; i ++ ) {
  19366. this.startTime = Math.min( this.startTime, this.input[ i ] );
  19367. this.endTime = Math.max( this.endTime, this.input[ i ] );
  19368. }
  19369. this.duration = this.endTime - this.startTime;
  19370. }
  19371. };
  19372. Sampler.prototype.getData = function ( type, ndx ) {
  19373. var data;
  19374. if ( this.strideOut > 1 ) {
  19375. data = [];
  19376. ndx *= this.strideOut;
  19377. for ( var i = 0; i < this.strideOut; ++i ) {
  19378. data[ i ] = this.output[ ndx + i ];
  19379. }
  19380. if ( this.strideOut === 3 ) {
  19381. switch ( type ) {
  19382. case 'rotate':
  19383. case 'translate':
  19384. fixCoords( data, -1 );
  19385. break;
  19386. case 'scale':
  19387. fixCoords( data, 1 );
  19388. break;
  19389. }
  19390. }
  19391. } else {
  19392. data = this.output[ ndx ];
  19393. }
  19394. return data;
  19395. };
  19396. function Key ( time ) {
  19397. this.targets = [];
  19398. this.time = time;
  19399. };
  19400. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  19401. this.targets.push( {
  19402. sid: fullSid,
  19403. member: member,
  19404. transform: transform,
  19405. data: data
  19406. } );
  19407. };
  19408. Key.prototype.apply = function ( opt_sid ) {
  19409. for ( var i = 0; i < this.targets.length; ++i ) {
  19410. var target = this.targets[ i ];
  19411. if ( !opt_sid || target.sid === opt_sid ) {
  19412. target.transform.update( target.data, target.member );
  19413. }
  19414. }
  19415. };
  19416. Key.prototype.getTarget = function ( fullSid ) {
  19417. for ( var i = 0; i < this.targets.length; ++i ) {
  19418. if ( this.targets[ i ].sid === fullSid ) {
  19419. return this.targets[ i ];
  19420. }
  19421. }
  19422. return null;
  19423. };
  19424. Key.prototype.hasTarget = function ( fullSid ) {
  19425. for ( var i = 0; i < this.targets.length; ++i ) {
  19426. if ( this.targets[ i ].sid === fullSid ) {
  19427. return true;
  19428. }
  19429. }
  19430. return false;
  19431. };
  19432. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  19433. Key.prototype.interpolate = function ( nextKey, time ) {
  19434. for ( var i = 0; i < this.targets.length; ++i ) {
  19435. var target = this.targets[ i ],
  19436. nextTarget = nextKey.getTarget( target.sid ),
  19437. data;
  19438. if ( nextTarget ) {
  19439. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  19440. nextData = nextTarget.data,
  19441. prevData = target.data;
  19442. // check scale error
  19443. if ( scale < 0 || scale > 1 ) {
  19444. console.log( "Key.interpolate: Warning! Scale out of bounds:" + scale );
  19445. scale = scale < 0 ? 0 : 1;
  19446. }
  19447. if ( prevData.length ) {
  19448. data = [];
  19449. for ( var j = 0; j < prevData.length; ++j ) {
  19450. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  19451. }
  19452. } else {
  19453. data = prevData + ( nextData - prevData ) * scale;
  19454. }
  19455. } else {
  19456. data = target.data;
  19457. }
  19458. target.transform.update( data, target.member );
  19459. }
  19460. };
  19461. function Camera() {
  19462. this.id = "";
  19463. this.name = "";
  19464. this.technique = "";
  19465. };
  19466. Camera.prototype.parse = function ( element ) {
  19467. this.id = element.getAttribute( 'id' );
  19468. this.name = element.getAttribute( 'name' );
  19469. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19470. var child = element.childNodes[ i ];
  19471. if ( child.nodeType != 1 ) continue;
  19472. switch ( child.nodeName ) {
  19473. case 'optics':
  19474. this.parseOptics( child );
  19475. break;
  19476. default:
  19477. break;
  19478. }
  19479. }
  19480. return this;
  19481. };
  19482. Camera.prototype.parseOptics = function ( element ) {
  19483. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19484. if ( element.childNodes[ i ].nodeName == 'technique_common' ) {
  19485. var technique = element.childNodes[ i ];
  19486. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  19487. this.technique = technique.childNodes[ j ].nodeName;
  19488. if ( this.technique == 'perspective' ) {
  19489. var perspective = technique.childNodes[ j ];
  19490. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  19491. var param = perspective.childNodes[ k ];
  19492. switch ( param.nodeName ) {
  19493. case 'yfov':
  19494. this.yfov = param.textContent;
  19495. break;
  19496. case 'xfov':
  19497. this.xfov = param.textContent;
  19498. break;
  19499. case 'znear':
  19500. this.znear = param.textContent;
  19501. break;
  19502. case 'zfar':
  19503. this.zfar = param.textContent;
  19504. break;
  19505. case 'aspect_ratio':
  19506. this.aspect_ratio = param.textContent;
  19507. break;
  19508. }
  19509. }
  19510. } else if ( this.technique == 'orthographic' ) {
  19511. var orthographic = technique.childNodes[ j ];
  19512. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  19513. var param = orthographic.childNodes[ k ];
  19514. switch ( param.nodeName ) {
  19515. case 'xmag':
  19516. this.xmag = param.textContent;
  19517. break;
  19518. case 'ymag':
  19519. this.ymag = param.textContent;
  19520. break;
  19521. case 'znear':
  19522. this.znear = param.textContent;
  19523. break;
  19524. case 'zfar':
  19525. this.zfar = param.textContent;
  19526. break;
  19527. case 'aspect_ratio':
  19528. this.aspect_ratio = param.textContent;
  19529. break;
  19530. }
  19531. }
  19532. }
  19533. }
  19534. }
  19535. }
  19536. return this;
  19537. };
  19538. function InstanceCamera() {
  19539. this.url = "";
  19540. };
  19541. InstanceCamera.prototype.parse = function ( element ) {
  19542. this.url = element.getAttribute('url').replace(/^#/, '');
  19543. return this;
  19544. };
  19545. function _source( element ) {
  19546. var id = element.getAttribute( 'id' );
  19547. if ( sources[ id ] != undefined ) {
  19548. return sources[ id ];
  19549. }
  19550. sources[ id ] = ( new Source(id )).parse( element );
  19551. return sources[ id ];
  19552. };
  19553. function _nsResolver( nsPrefix ) {
  19554. if ( nsPrefix == "dae" ) {
  19555. return "http://www.collada.org/2005/11/COLLADASchema";
  19556. }
  19557. return null;
  19558. };
  19559. function _bools( str ) {
  19560. var raw = _strings( str );
  19561. var data = [];
  19562. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  19563. data.push( (raw[i] == 'true' || raw[i] == '1') ? true : false );
  19564. }
  19565. return data;
  19566. };
  19567. function _floats( str ) {
  19568. var raw = _strings(str);
  19569. var data = [];
  19570. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  19571. data.push( parseFloat( raw[ i ] ) );
  19572. }
  19573. return data;
  19574. };
  19575. function _ints( str ) {
  19576. var raw = _strings( str );
  19577. var data = [];
  19578. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  19579. data.push( parseInt( raw[ i ], 10 ) );
  19580. }
  19581. return data;
  19582. };
  19583. function _strings( str ) {
  19584. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  19585. };
  19586. function _trimString( str ) {
  19587. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  19588. };
  19589. function _attr_as_float( element, name, defaultValue ) {
  19590. if ( element.hasAttribute( name ) ) {
  19591. return parseFloat( element.getAttribute( name ) );
  19592. } else {
  19593. return defaultValue;
  19594. }
  19595. };
  19596. function _attr_as_int( element, name, defaultValue ) {
  19597. if ( element.hasAttribute( name ) ) {
  19598. return parseInt( element.getAttribute( name ), 10) ;
  19599. } else {
  19600. return defaultValue;
  19601. }
  19602. };
  19603. function _attr_as_string( element, name, defaultValue ) {
  19604. if ( element.hasAttribute( name ) ) {
  19605. return element.getAttribute( name );
  19606. } else {
  19607. return defaultValue;
  19608. }
  19609. };
  19610. function _format_float( f, num ) {
  19611. if ( f === undefined ) {
  19612. var s = '0.';
  19613. while ( s.length < num + 2 ) {
  19614. s += '0';
  19615. }
  19616. return s;
  19617. }
  19618. num = num || 2;
  19619. var parts = f.toString().split( '.' );
  19620. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  19621. while( parts[ 1 ].length < num ) {
  19622. parts[ 1 ] += '0';
  19623. }
  19624. return parts.join( '.' );
  19625. };
  19626. function evaluateXPath( node, query ) {
  19627. var instances = COLLADA.evaluate( query, node, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  19628. var inst = instances.iterateNext();
  19629. var result = [];
  19630. while ( inst ) {
  19631. result.push( inst );
  19632. inst = instances.iterateNext();
  19633. }
  19634. return result;
  19635. };
  19636. // Up axis conversion
  19637. function setUpConversion() {
  19638. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  19639. upConversion = null;
  19640. } else {
  19641. switch ( colladaUp ) {
  19642. case 'X':
  19643. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  19644. break;
  19645. case 'Y':
  19646. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  19647. break;
  19648. case 'Z':
  19649. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  19650. break;
  19651. }
  19652. }
  19653. };
  19654. function fixCoords( data, sign ) {
  19655. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  19656. return;
  19657. }
  19658. switch ( upConversion ) {
  19659. case 'XtoY':
  19660. var tmp = data[ 0 ];
  19661. data[ 0 ] = sign * data[ 1 ];
  19662. data[ 1 ] = tmp;
  19663. break;
  19664. case 'XtoZ':
  19665. var tmp = data[ 2 ];
  19666. data[ 2 ] = data[ 1 ];
  19667. data[ 1 ] = data[ 0 ];
  19668. data[ 0 ] = tmp;
  19669. break;
  19670. case 'YtoX':
  19671. var tmp = data[ 0 ];
  19672. data[ 0 ] = data[ 1 ];
  19673. data[ 1 ] = sign * tmp;
  19674. break;
  19675. case 'YtoZ':
  19676. var tmp = data[ 1 ];
  19677. data[ 1 ] = sign * data[ 2 ];
  19678. data[ 2 ] = tmp;
  19679. break;
  19680. case 'ZtoX':
  19681. var tmp = data[ 0 ];
  19682. data[ 0 ] = data[ 1 ];
  19683. data[ 1 ] = data[ 2 ];
  19684. data[ 2 ] = tmp;
  19685. break;
  19686. case 'ZtoY':
  19687. var tmp = data[ 1 ];
  19688. data[ 1 ] = data[ 2 ];
  19689. data[ 2 ] = sign * tmp;
  19690. break;
  19691. }
  19692. };
  19693. function getConvertedVec3( data, offset ) {
  19694. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  19695. fixCoords( arr, -1 );
  19696. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  19697. };
  19698. function getConvertedMat4( data ) {
  19699. if ( options.convertUpAxis ) {
  19700. // First fix rotation and scale
  19701. // Columns first
  19702. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  19703. fixCoords( arr, -1 );
  19704. data[ 0 ] = arr[ 0 ];
  19705. data[ 4 ] = arr[ 1 ];
  19706. data[ 8 ] = arr[ 2 ];
  19707. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  19708. fixCoords( arr, -1 );
  19709. data[ 1 ] = arr[ 0 ];
  19710. data[ 5 ] = arr[ 1 ];
  19711. data[ 9 ] = arr[ 2 ];
  19712. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  19713. fixCoords( arr, -1 );
  19714. data[ 2 ] = arr[ 0 ];
  19715. data[ 6 ] = arr[ 1 ];
  19716. data[ 10 ] = arr[ 2 ];
  19717. // Rows second
  19718. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  19719. fixCoords( arr, -1 );
  19720. data[ 0 ] = arr[ 0 ];
  19721. data[ 1 ] = arr[ 1 ];
  19722. data[ 2 ] = arr[ 2 ];
  19723. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  19724. fixCoords( arr, -1 );
  19725. data[ 4 ] = arr[ 0 ];
  19726. data[ 5 ] = arr[ 1 ];
  19727. data[ 6 ] = arr[ 2 ];
  19728. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  19729. fixCoords( arr, -1 );
  19730. data[ 8 ] = arr[ 0 ];
  19731. data[ 9 ] = arr[ 1 ];
  19732. data[ 10 ] = arr[ 2 ];
  19733. // Now fix translation
  19734. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  19735. fixCoords( arr, -1 );
  19736. data[ 3 ] = arr[ 0 ];
  19737. data[ 7 ] = arr[ 1 ];
  19738. data[ 11 ] = arr[ 2 ];
  19739. }
  19740. return new THREE.Matrix4(
  19741. data[0], data[1], data[2], data[3],
  19742. data[4], data[5], data[6], data[7],
  19743. data[8], data[9], data[10], data[11],
  19744. data[12], data[13], data[14], data[15]
  19745. );
  19746. };
  19747. function getConvertedMember( member ) {
  19748. if ( options.convertUpAxis ) {
  19749. switch ( member ) {
  19750. case 'X':
  19751. switch ( upConversion ) {
  19752. case 'XtoY':
  19753. case 'XtoZ':
  19754. case 'YtoX':
  19755. member = 'Y';
  19756. break;
  19757. case 'ZtoX':
  19758. member = 'Z';
  19759. break;
  19760. }
  19761. break;
  19762. case 'Y':
  19763. switch ( upConversion ) {
  19764. case 'XtoY':
  19765. case 'YtoX':
  19766. case 'ZtoX':
  19767. member = 'X';
  19768. break;
  19769. case 'XtoZ':
  19770. case 'YtoZ':
  19771. case 'ZtoY':
  19772. member = 'Z';
  19773. break;
  19774. }
  19775. break;
  19776. case 'Z':
  19777. switch ( upConversion ) {
  19778. case 'XtoZ':
  19779. member = 'X';
  19780. break;
  19781. case 'YtoZ':
  19782. case 'ZtoX':
  19783. case 'ZtoY':
  19784. member = 'Y';
  19785. break;
  19786. }
  19787. break;
  19788. }
  19789. }
  19790. return member;
  19791. };
  19792. return {
  19793. load: load,
  19794. parse: parse,
  19795. setPreferredShading: setPreferredShading,
  19796. applySkin: applySkin,
  19797. geometries : geometries,
  19798. options: options
  19799. };
  19800. };
  19801. /**
  19802. * @author mrdoob / http://mrdoob.com/
  19803. * @author alteredq / http://alteredqualia.com/
  19804. */
  19805. THREE.JSONLoader = function ( showStatus ) {
  19806. THREE.Loader.call( this, showStatus );
  19807. };
  19808. THREE.JSONLoader.prototype = new THREE.Loader();
  19809. THREE.JSONLoader.prototype.constructor = THREE.JSONLoader;
  19810. THREE.JSONLoader.prototype.supr = THREE.Loader.prototype;
  19811. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  19812. var worker, scope = this;
  19813. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  19814. this.onLoadStart();
  19815. this.loadAjaxJSON( this, url, callback, texturePath );
  19816. };
  19817. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  19818. var xhr = new XMLHttpRequest();
  19819. var length = 0;
  19820. xhr.onreadystatechange = function () {
  19821. if ( xhr.readyState === xhr.DONE ) {
  19822. if ( xhr.status === 200 || xhr.status === 0 ) {
  19823. if ( xhr.responseText ) {
  19824. var json = JSON.parse( xhr.responseText );
  19825. context.createModel( json, callback, texturePath );
  19826. } else {
  19827. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  19828. }
  19829. // in context of more complex asset initialization
  19830. // do not block on single failed file
  19831. // maybe should go even one more level up
  19832. context.onLoadComplete();
  19833. } else {
  19834. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  19835. }
  19836. } else if ( xhr.readyState === xhr.LOADING ) {
  19837. if ( callbackProgress ) {
  19838. if ( length === 0 ) {
  19839. length = xhr.getResponseHeader( "Content-Length" );
  19840. }
  19841. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  19842. }
  19843. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  19844. length = xhr.getResponseHeader( "Content-Length" );
  19845. }
  19846. };
  19847. xhr.open( "GET", url, true );
  19848. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  19849. xhr.setRequestHeader( "Content-Type", "text/plain" );
  19850. xhr.send( null );
  19851. };
  19852. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  19853. var scope = this,
  19854. geometry = new THREE.Geometry(),
  19855. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  19856. this.initMaterials( geometry, json.materials, texturePath );
  19857. parseModel( scale );
  19858. parseSkin();
  19859. parseMorphing( scale );
  19860. geometry.computeCentroids();
  19861. geometry.computeFaceNormals();
  19862. if ( this.hasNormals( geometry ) ) geometry.computeTangents();
  19863. function parseModel( scale ) {
  19864. function isBitSet( value, position ) {
  19865. return value & ( 1 << position );
  19866. }
  19867. var i, j, fi,
  19868. offset, zLength, nVertices,
  19869. colorIndex, normalIndex, uvIndex, materialIndex,
  19870. type,
  19871. isQuad,
  19872. hasMaterial,
  19873. hasFaceUv, hasFaceVertexUv,
  19874. hasFaceNormal, hasFaceVertexNormal,
  19875. hasFaceColor, hasFaceVertexColor,
  19876. vertex, face, color, normal,
  19877. uvLayer, uvs, u, v,
  19878. faces = json.faces,
  19879. vertices = json.vertices,
  19880. normals = json.normals,
  19881. colors = json.colors,
  19882. nUvLayers = 0;
  19883. // disregard empty arrays
  19884. for ( i = 0; i < json.uvs.length; i++ ) {
  19885. if ( json.uvs[ i ].length ) nUvLayers ++;
  19886. }
  19887. for ( i = 0; i < nUvLayers; i++ ) {
  19888. geometry.faceUvs[ i ] = [];
  19889. geometry.faceVertexUvs[ i ] = [];
  19890. }
  19891. offset = 0;
  19892. zLength = vertices.length;
  19893. while ( offset < zLength ) {
  19894. vertex = new THREE.Vertex();
  19895. vertex.position.x = vertices[ offset ++ ] * scale;
  19896. vertex.position.y = vertices[ offset ++ ] * scale;
  19897. vertex.position.z = vertices[ offset ++ ] * scale;
  19898. geometry.vertices.push( vertex );
  19899. }
  19900. offset = 0;
  19901. zLength = faces.length;
  19902. while ( offset < zLength ) {
  19903. type = faces[ offset ++ ];
  19904. isQuad = isBitSet( type, 0 );
  19905. hasMaterial = isBitSet( type, 1 );
  19906. hasFaceUv = isBitSet( type, 2 );
  19907. hasFaceVertexUv = isBitSet( type, 3 );
  19908. hasFaceNormal = isBitSet( type, 4 );
  19909. hasFaceVertexNormal = isBitSet( type, 5 );
  19910. hasFaceColor = isBitSet( type, 6 );
  19911. hasFaceVertexColor = isBitSet( type, 7 );
  19912. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  19913. if ( isQuad ) {
  19914. face = new THREE.Face4();
  19915. face.a = faces[ offset ++ ];
  19916. face.b = faces[ offset ++ ];
  19917. face.c = faces[ offset ++ ];
  19918. face.d = faces[ offset ++ ];
  19919. nVertices = 4;
  19920. } else {
  19921. face = new THREE.Face3();
  19922. face.a = faces[ offset ++ ];
  19923. face.b = faces[ offset ++ ];
  19924. face.c = faces[ offset ++ ];
  19925. nVertices = 3;
  19926. }
  19927. if ( hasMaterial ) {
  19928. materialIndex = faces[ offset ++ ];
  19929. face.materialIndex = materialIndex;
  19930. }
  19931. // to get face <=> uv index correspondence
  19932. fi = geometry.faces.length;
  19933. if ( hasFaceUv ) {
  19934. for ( i = 0; i < nUvLayers; i++ ) {
  19935. uvLayer = json.uvs[ i ];
  19936. uvIndex = faces[ offset ++ ];
  19937. u = uvLayer[ uvIndex * 2 ];
  19938. v = uvLayer[ uvIndex * 2 + 1 ];
  19939. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  19940. }
  19941. }
  19942. if ( hasFaceVertexUv ) {
  19943. for ( i = 0; i < nUvLayers; i++ ) {
  19944. uvLayer = json.uvs[ i ];
  19945. uvs = [];
  19946. for ( j = 0; j < nVertices; j ++ ) {
  19947. uvIndex = faces[ offset ++ ];
  19948. u = uvLayer[ uvIndex * 2 ];
  19949. v = uvLayer[ uvIndex * 2 + 1 ];
  19950. uvs[ j ] = new THREE.UV( u, v );
  19951. }
  19952. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  19953. }
  19954. }
  19955. if ( hasFaceNormal ) {
  19956. normalIndex = faces[ offset ++ ] * 3;
  19957. normal = new THREE.Vector3();
  19958. normal.x = normals[ normalIndex ++ ];
  19959. normal.y = normals[ normalIndex ++ ];
  19960. normal.z = normals[ normalIndex ];
  19961. face.normal = normal;
  19962. }
  19963. if ( hasFaceVertexNormal ) {
  19964. for ( i = 0; i < nVertices; i++ ) {
  19965. normalIndex = faces[ offset ++ ] * 3;
  19966. normal = new THREE.Vector3();
  19967. normal.x = normals[ normalIndex ++ ];
  19968. normal.y = normals[ normalIndex ++ ];
  19969. normal.z = normals[ normalIndex ];
  19970. face.vertexNormals.push( normal );
  19971. }
  19972. }
  19973. if ( hasFaceColor ) {
  19974. colorIndex = faces[ offset ++ ];
  19975. color = new THREE.Color( colors[ colorIndex ] );
  19976. face.color = color;
  19977. }
  19978. if ( hasFaceVertexColor ) {
  19979. for ( i = 0; i < nVertices; i++ ) {
  19980. colorIndex = faces[ offset ++ ];
  19981. color = new THREE.Color( colors[ colorIndex ] );
  19982. face.vertexColors.push( color );
  19983. }
  19984. }
  19985. geometry.faces.push( face );
  19986. }
  19987. };
  19988. function parseSkin() {
  19989. var i, l, x, y, z, w, a, b, c, d;
  19990. if ( json.skinWeights ) {
  19991. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  19992. x = json.skinWeights[ i ];
  19993. y = json.skinWeights[ i + 1 ];
  19994. z = 0;
  19995. w = 0;
  19996. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  19997. }
  19998. }
  19999. if ( json.skinIndices ) {
  20000. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  20001. a = json.skinIndices[ i ];
  20002. b = json.skinIndices[ i + 1 ];
  20003. c = 0;
  20004. d = 0;
  20005. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  20006. }
  20007. }
  20008. geometry.bones = json.bones;
  20009. geometry.animation = json.animation;
  20010. };
  20011. function parseMorphing( scale ) {
  20012. if ( json.morphTargets !== undefined ) {
  20013. var i, l, v, vl, x, y, z, dstVertices, srcVertices;
  20014. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  20015. geometry.morphTargets[ i ] = {};
  20016. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  20017. geometry.morphTargets[ i ].vertices = [];
  20018. dstVertices = geometry.morphTargets[ i ].vertices;
  20019. srcVertices = json.morphTargets [ i ].vertices;
  20020. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  20021. x = srcVertices[ v ] * scale;
  20022. y = srcVertices[ v + 1 ] * scale;
  20023. z = srcVertices[ v + 2 ] * scale;
  20024. dstVertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  20025. }
  20026. }
  20027. }
  20028. if ( json.morphColors !== undefined ) {
  20029. var i, l, c, cl, dstColors, srcColors, color;
  20030. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  20031. geometry.morphColors[ i ] = {};
  20032. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  20033. geometry.morphColors[ i ].colors = [];
  20034. dstColors = geometry.morphColors[ i ].colors;
  20035. srcColors = json.morphColors [ i ].colors;
  20036. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  20037. color = new THREE.Color( 0xffaa00 );
  20038. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  20039. dstColors.push( color );
  20040. }
  20041. }
  20042. }
  20043. };
  20044. callback( geometry );
  20045. };
  20046. /**
  20047. * @author alteredq / http://alteredqualia.com/
  20048. */
  20049. THREE.SceneLoader = function () {
  20050. this.onLoadStart = function () {};
  20051. this.onLoadProgress = function() {};
  20052. this.onLoadComplete = function () {};
  20053. this.callbackSync = function () {};
  20054. this.callbackProgress = function () {};
  20055. };
  20056. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  20057. THREE.SceneLoader.prototype.load = function( url, callbackFinished ) {
  20058. var context = this;
  20059. var xhr = new XMLHttpRequest();
  20060. xhr.onreadystatechange = function () {
  20061. if ( xhr.readyState == 4 ) {
  20062. if ( xhr.status == 200 || xhr.status == 0 ) {
  20063. var json = JSON.parse( xhr.responseText );
  20064. context.createScene( json, callbackFinished, url );
  20065. } else {
  20066. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  20067. }
  20068. }
  20069. };
  20070. xhr.open( "GET", url, true );
  20071. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  20072. xhr.setRequestHeader( "Content-Type", "text/plain" );
  20073. xhr.send( null );
  20074. };
  20075. THREE.SceneLoader.prototype.createScene = function ( json, callbackFinished, url ) {
  20076. var scope = this;
  20077. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  20078. var dg, dm, dd, dl, dc, df, dt,
  20079. g, o, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  20080. geometry, material, camera, fog,
  20081. texture, images,
  20082. light,
  20083. data, binLoader, jsonLoader,
  20084. counter_models, counter_textures,
  20085. total_models, total_textures,
  20086. result;
  20087. data = json;
  20088. binLoader = new THREE.BinaryLoader();
  20089. jsonLoader = new THREE.JSONLoader();
  20090. counter_models = 0;
  20091. counter_textures = 0;
  20092. result = {
  20093. scene: new THREE.Scene(),
  20094. geometries: {},
  20095. materials: {},
  20096. textures: {},
  20097. objects: {},
  20098. cameras: {},
  20099. lights: {},
  20100. fogs: {},
  20101. empties: {}
  20102. };
  20103. if ( data.transform ) {
  20104. var position = data.transform.position,
  20105. rotation = data.transform.rotation,
  20106. scale = data.transform.scale;
  20107. if ( position )
  20108. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  20109. if ( rotation )
  20110. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  20111. if ( scale )
  20112. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  20113. if ( position || rotation || scale ) {
  20114. result.scene.updateMatrix();
  20115. result.scene.updateMatrixWorld();
  20116. }
  20117. }
  20118. function get_url( source_url, url_type ) {
  20119. if ( url_type == "relativeToHTML" ) {
  20120. return source_url;
  20121. } else {
  20122. return urlBase + "/" + source_url;
  20123. }
  20124. };
  20125. function handle_objects() {
  20126. var object;
  20127. for( dd in data.objects ) {
  20128. if ( !result.objects[ dd ] ) {
  20129. o = data.objects[ dd ];
  20130. if ( o.geometry !== undefined ) {
  20131. geometry = result.geometries[ o.geometry ];
  20132. // geometry already loaded
  20133. if ( geometry ) {
  20134. var hasNormals = false;
  20135. // not anymore support for multiple materials
  20136. // shouldn't really be array
  20137. material = result.materials[ o.materials[ 0 ] ];
  20138. hasNormals = material instanceof THREE.ShaderMaterial;
  20139. if ( hasNormals ) {
  20140. geometry.computeTangents();
  20141. }
  20142. p = o.position;
  20143. r = o.rotation;
  20144. q = o.quaternion;
  20145. s = o.scale;
  20146. // turn off quaternions, for the moment
  20147. q = 0;
  20148. if ( o.materials.length == 0 ) {
  20149. material = new THREE.MeshFaceMaterial();
  20150. }
  20151. // dirty hack to handle meshes with multiple materials
  20152. // just use face materials defined in model
  20153. if ( o.materials.length > 1 ) {
  20154. material = new THREE.MeshFaceMaterial();
  20155. }
  20156. object = new THREE.Mesh( geometry, material );
  20157. object.name = dd;
  20158. object.position.set( p[0], p[1], p[2] );
  20159. if ( q ) {
  20160. object.quaternion.set( q[0], q[1], q[2], q[3] );
  20161. object.useQuaternion = true;
  20162. } else {
  20163. object.rotation.set( r[0], r[1], r[2] );
  20164. }
  20165. object.scale.set( s[0], s[1], s[2] );
  20166. object.visible = o.visible;
  20167. object.doubleSided = o.doubleSided;
  20168. object.castShadow = o.castShadow;
  20169. object.receiveShadow = o.receiveShadow;
  20170. result.scene.add( object );
  20171. result.objects[ dd ] = object;
  20172. }
  20173. // pure Object3D
  20174. } else {
  20175. p = o.position;
  20176. r = o.rotation;
  20177. q = o.quaternion;
  20178. s = o.scale;
  20179. // turn off quaternions, for the moment
  20180. q = 0;
  20181. object = new THREE.Object3D();
  20182. object.name = dd;
  20183. object.position.set( p[0], p[1], p[2] );
  20184. if ( q ) {
  20185. object.quaternion.set( q[0], q[1], q[2], q[3] );
  20186. object.useQuaternion = true;
  20187. } else {
  20188. object.rotation.set( r[0], r[1], r[2] );
  20189. }
  20190. object.scale.set( s[0], s[1], s[2] );
  20191. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  20192. result.scene.add( object );
  20193. result.objects[ dd ] = object;
  20194. result.empties[ dd ] = object;
  20195. }
  20196. }
  20197. }
  20198. };
  20199. function handle_mesh( geo, id ) {
  20200. result.geometries[ id ] = geo;
  20201. handle_objects();
  20202. };
  20203. function create_callback( id ) {
  20204. return function( geo ) {
  20205. handle_mesh( geo, id );
  20206. counter_models -= 1;
  20207. scope.onLoadComplete();
  20208. async_callback_gate();
  20209. }
  20210. };
  20211. function create_callback_embed( id ) {
  20212. return function( geo ) {
  20213. result.geometries[ id ] = geo;
  20214. }
  20215. };
  20216. function async_callback_gate() {
  20217. var progress = {
  20218. totalModels : total_models,
  20219. totalTextures : total_textures,
  20220. loadedModels : total_models - counter_models,
  20221. loadedTextures : total_textures - counter_textures
  20222. };
  20223. scope.callbackProgress( progress, result );
  20224. scope.onLoadProgress();
  20225. if( counter_models == 0 && counter_textures == 0 ) {
  20226. callbackFinished( result );
  20227. }
  20228. };
  20229. var callbackTexture = function( images ) {
  20230. counter_textures -= 1;
  20231. async_callback_gate();
  20232. scope.onLoadComplete();
  20233. };
  20234. // first go synchronous elements
  20235. // cameras
  20236. for( dc in data.cameras ) {
  20237. c = data.cameras[ dc ];
  20238. if ( c.type == "perspective" ) {
  20239. camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );
  20240. } else if ( c.type == "ortho" ) {
  20241. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  20242. }
  20243. p = c.position;
  20244. t = c.target;
  20245. u = c.up;
  20246. camera.position.set( p[0], p[1], p[2] );
  20247. camera.target = new THREE.Vector3( t[0], t[1], t[2] );
  20248. if ( u ) camera.up.set( u[0], u[1], u[2] );
  20249. result.cameras[ dc ] = camera;
  20250. }
  20251. // lights
  20252. var hex, intensity;
  20253. for ( dl in data.lights ) {
  20254. l = data.lights[ dl ];
  20255. hex = ( l.color !== undefined ) ? l.color : 0xffffff;
  20256. intensity = ( l.intensity !== undefined ) ? l.intensity : 1;
  20257. if ( l.type == "directional" ) {
  20258. p = l.direction;
  20259. light = new THREE.DirectionalLight( hex, intensity );
  20260. light.position.set( p[0], p[1], p[2] );
  20261. light.position.normalize();
  20262. } else if ( l.type == "point" ) {
  20263. p = l.position;
  20264. d = l.distance;
  20265. light = new THREE.PointLight( hex, intensity, d );
  20266. light.position.set( p[0], p[1], p[2] );
  20267. } else if ( l.type == "ambient" ) {
  20268. light = new THREE.AmbientLight( hex );
  20269. }
  20270. result.scene.add( light );
  20271. result.lights[ dl ] = light;
  20272. }
  20273. // fogs
  20274. for( df in data.fogs ) {
  20275. f = data.fogs[ df ];
  20276. if ( f.type == "linear" ) {
  20277. fog = new THREE.Fog( 0x000000, f.near, f.far );
  20278. } else if ( f.type == "exp2" ) {
  20279. fog = new THREE.FogExp2( 0x000000, f.density );
  20280. }
  20281. c = f.color;
  20282. fog.color.setRGB( c[0], c[1], c[2] );
  20283. result.fogs[ df ] = fog;
  20284. }
  20285. // defaults
  20286. if ( result.cameras && data.defaults.camera ) {
  20287. result.currentCamera = result.cameras[ data.defaults.camera ];
  20288. }
  20289. if ( result.fogs && data.defaults.fog ) {
  20290. result.scene.fog = result.fogs[ data.defaults.fog ];
  20291. }
  20292. c = data.defaults.bgcolor;
  20293. result.bgColor = new THREE.Color();
  20294. result.bgColor.setRGB( c[0], c[1], c[2] );
  20295. result.bgColorAlpha = data.defaults.bgalpha;
  20296. // now come potentially asynchronous elements
  20297. // geometries
  20298. // count how many models will be loaded asynchronously
  20299. for( dg in data.geometries ) {
  20300. g = data.geometries[ dg ];
  20301. if ( g.type == "bin_mesh" || g.type == "ascii_mesh" ) {
  20302. counter_models += 1;
  20303. scope.onLoadStart();
  20304. }
  20305. }
  20306. total_models = counter_models;
  20307. for ( dg in data.geometries ) {
  20308. g = data.geometries[ dg ];
  20309. if ( g.type == "cube" ) {
  20310. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.segmentsWidth, g.segmentsHeight, g.segmentsDepth, null, g.flipped, g.sides );
  20311. result.geometries[ dg ] = geometry;
  20312. } else if ( g.type == "plane" ) {
  20313. geometry = new THREE.PlaneGeometry( g.width, g.height, g.segmentsWidth, g.segmentsHeight );
  20314. result.geometries[ dg ] = geometry;
  20315. } else if ( g.type == "sphere" ) {
  20316. geometry = new THREE.SphereGeometry( g.radius, g.segmentsWidth, g.segmentsHeight );
  20317. result.geometries[ dg ] = geometry;
  20318. } else if ( g.type == "cylinder" ) {
  20319. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  20320. result.geometries[ dg ] = geometry;
  20321. } else if ( g.type == "torus" ) {
  20322. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  20323. result.geometries[ dg ] = geometry;
  20324. } else if ( g.type == "icosahedron" ) {
  20325. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  20326. result.geometries[ dg ] = geometry;
  20327. } else if ( g.type == "bin_mesh" ) {
  20328. binLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  20329. } else if ( g.type == "ascii_mesh" ) {
  20330. jsonLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  20331. } else if ( g.type == "embedded_mesh" ) {
  20332. var modelJson = data.embeds[ g.id ],
  20333. texture_path = "";
  20334. // Pass metadata along to jsonLoader so it knows the format version.
  20335. modelJson.metadata = data.metadata;
  20336. if ( modelJson ) {
  20337. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  20338. }
  20339. }
  20340. }
  20341. // textures
  20342. // count how many textures will be loaded asynchronously
  20343. for( dt in data.textures ) {
  20344. tt = data.textures[ dt ];
  20345. if( tt.url instanceof Array ) {
  20346. counter_textures += tt.url.length;
  20347. for( var n = 0; n < tt.url.length; n ++ ) {
  20348. scope.onLoadStart();
  20349. }
  20350. } else {
  20351. counter_textures += 1;
  20352. scope.onLoadStart();
  20353. }
  20354. }
  20355. total_textures = counter_textures;
  20356. for( dt in data.textures ) {
  20357. tt = data.textures[ dt ];
  20358. if ( tt.mapping != undefined && THREE[ tt.mapping ] != undefined ) {
  20359. tt.mapping = new THREE[ tt.mapping ]();
  20360. }
  20361. if( tt.url instanceof Array ) {
  20362. var url_array = [];
  20363. for( var i = 0; i < tt.url.length; i ++ ) {
  20364. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  20365. }
  20366. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, callbackTexture );
  20367. } else {
  20368. texture = THREE.ImageUtils.loadTexture( get_url( tt.url, data.urlBaseType ), tt.mapping, callbackTexture );
  20369. if ( THREE[ tt.minFilter ] != undefined )
  20370. texture.minFilter = THREE[ tt.minFilter ];
  20371. if ( THREE[ tt.magFilter ] != undefined )
  20372. texture.magFilter = THREE[ tt.magFilter ];
  20373. if ( tt.repeat ) {
  20374. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  20375. if ( tt.repeat[ 0 ] != 1 ) texture.wrapS = THREE.RepeatWrapping;
  20376. if ( tt.repeat[ 1 ] != 1 ) texture.wrapT = THREE.RepeatWrapping;
  20377. }
  20378. if ( tt.offset ) {
  20379. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  20380. }
  20381. // handle wrap after repeat so that default repeat can be overriden
  20382. if ( tt.wrap ) {
  20383. var wrapMap = {
  20384. "repeat" : THREE.RepeatWrapping,
  20385. "mirror" : THREE.MirroredRepeatWrapping
  20386. }
  20387. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  20388. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  20389. }
  20390. }
  20391. result.textures[ dt ] = texture;
  20392. }
  20393. // materials
  20394. for ( dm in data.materials ) {
  20395. m = data.materials[ dm ];
  20396. for ( pp in m.parameters ) {
  20397. if ( pp == "envMap" || pp == "map" || pp == "lightMap" ) {
  20398. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  20399. } else if ( pp == "shading" ) {
  20400. m.parameters[ pp ] = ( m.parameters[ pp ] == "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  20401. } else if ( pp == "blending" ) {
  20402. m.parameters[ pp ] = THREE[ m.parameters[ pp ] ] ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  20403. } else if ( pp == "combine" ) {
  20404. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  20405. } else if ( pp == "vertexColors" ) {
  20406. if ( m.parameters[ pp ] == "face" ) {
  20407. m.parameters[ pp ] = THREE.FaceColors;
  20408. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  20409. } else if ( m.parameters[ pp ] ) {
  20410. m.parameters[ pp ] = THREE.VertexColors;
  20411. }
  20412. }
  20413. }
  20414. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  20415. m.parameters.transparent = true;
  20416. }
  20417. if ( m.parameters.normalMap ) {
  20418. var shader = THREE.ShaderUtils.lib[ "normal" ];
  20419. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  20420. var diffuse = m.parameters.color;
  20421. var specular = m.parameters.specular;
  20422. var ambient = m.parameters.ambient;
  20423. var shininess = m.parameters.shininess;
  20424. uniforms[ "tNormal" ].texture = result.textures[ m.parameters.normalMap ];
  20425. if ( m.parameters.normalMapFactor ) {
  20426. uniforms[ "uNormalScale" ].value = m.parameters.normalMapFactor;
  20427. }
  20428. if ( m.parameters.map ) {
  20429. uniforms[ "tDiffuse" ].texture = m.parameters.map;
  20430. uniforms[ "enableDiffuse" ].value = true;
  20431. }
  20432. if ( m.parameters.lightMap ) {
  20433. uniforms[ "tAO" ].texture = m.parameters.lightMap;
  20434. uniforms[ "enableAO" ].value = true;
  20435. }
  20436. if ( m.parameters.specularMap ) {
  20437. uniforms[ "tSpecular" ].texture = result.textures[ m.parameters.specularMap ];
  20438. uniforms[ "enableSpecular" ].value = true;
  20439. }
  20440. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  20441. uniforms[ "uSpecularColor" ].value.setHex( specular );
  20442. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  20443. uniforms[ "uShininess" ].value = shininess;
  20444. if ( m.parameters.opacity ) {
  20445. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  20446. }
  20447. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  20448. material = new THREE.ShaderMaterial( parameters );
  20449. } else {
  20450. material = new THREE[ m.type ]( m.parameters );
  20451. }
  20452. result.materials[ dm ] = material;
  20453. }
  20454. // objects ( synchronous init of procedural primitives )
  20455. handle_objects();
  20456. // synchronous callback
  20457. scope.callbackSync( result );
  20458. // just in case there are no async elements:
  20459. async_callback_gate();
  20460. };
  20461. /**
  20462. * Loader for UTF8 encoded models generated by:
  20463. * http://code.google.com/p/webgl-loader/
  20464. *
  20465. * Limitations:
  20466. * - number of vertices < 65536 (this is after optimizations in compressor, input OBJ may have even less)
  20467. * - models must have normals and texture coordinates
  20468. * - texture coordinates must be only from <0,1>
  20469. * - no materials support yet
  20470. * - models are scaled and offset (copy numbers from compressor and use them as parameters in UTF8Loader.load() )
  20471. *
  20472. * @author alteredq / http://alteredqualia.com/
  20473. * @author won3d / http://twitter.com/won3d
  20474. */
  20475. THREE.UTF8Loader = function () {};
  20476. THREE.UTF8Loader.prototype.load = function ( url, callback, metadata ) {
  20477. var xhr = new XMLHttpRequest(),
  20478. callbackProgress = null,
  20479. scale = metadata.scale !== undefined ? metadata.scale : 1,
  20480. offsetX = metadata.offsetX !== undefined ? metadata.offsetX : 0,
  20481. offsetY = metadata.offsetY !== undefined ? metadata.offsetY : 0,
  20482. offsetZ = metadata.offsetZ !== undefined ? metadata.offsetZ : 0;
  20483. var length = 0;
  20484. xhr.onreadystatechange = function() {
  20485. if ( xhr.readyState == 4 ) {
  20486. if ( xhr.status == 200 || xhr.status == 0 ) {
  20487. THREE.UTF8Loader.prototype.createModel( xhr.responseText, callback, scale, offsetX, offsetY, offsetZ );
  20488. } else {
  20489. console.error( "THREE.UTF8Loader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  20490. }
  20491. } else if ( xhr.readyState == 3 ) {
  20492. if ( callbackProgress ) {
  20493. if ( length == 0 ) {
  20494. length = xhr.getResponseHeader( "Content-Length" );
  20495. }
  20496. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  20497. }
  20498. } else if ( xhr.readyState == 2 ) {
  20499. length = xhr.getResponseHeader( "Content-Length" );
  20500. }
  20501. }
  20502. xhr.open( "GET", url, true );
  20503. xhr.send( null );
  20504. };
  20505. // UTF-8 decoder from webgl-loader
  20506. // http://code.google.com/p/webgl-loader/
  20507. // Copyright 2011 Google Inc. All Rights Reserved.
  20508. //
  20509. // Licensed under the Apache License, Version 2.0 (the "License"); you
  20510. // may not use this file except in compliance with the License. You
  20511. // may obtain a copy of the License at
  20512. //
  20513. // http://www.apache.org/licenses/LICENSE-2.0
  20514. //
  20515. // Unless required by applicable law or agreed to in writing, software
  20516. // distributed under the License is distributed on an "AS IS" BASIS,
  20517. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  20518. // implied. See the License for the specific language governing
  20519. // permissions and limitations under the License.
  20520. THREE.UTF8Loader.prototype.decompressMesh = function ( str ) {
  20521. var num_verts = str.charCodeAt( 0 );
  20522. if ( num_verts >= 0xE000 ) {
  20523. num_verts -= 0x0800;
  20524. }
  20525. num_verts ++;
  20526. var attribs_out = new Float32Array( 8 * num_verts );
  20527. var offset = 1;
  20528. for ( var i = 0; i < 8; i ++ ) {
  20529. var prev_attrib = 0;
  20530. for ( var j = 0; j < num_verts; ++ j ) {
  20531. var code = str.charCodeAt( j + offset );
  20532. prev_attrib += ( code >> 1 ) ^ ( - ( code & 1 ) );
  20533. attribs_out[ 8 * j + i ] = prev_attrib;
  20534. }
  20535. offset += num_verts;
  20536. }
  20537. var num_indices = str.length - offset;
  20538. var indices_out = new Uint16Array( num_indices );
  20539. var index_high_water_mark = 0;
  20540. for ( var i = 0; i < num_indices; i ++ ) {
  20541. var code = str.charCodeAt( i + offset );
  20542. indices_out[ i ] = index_high_water_mark - code;
  20543. if ( code == 0 ) {
  20544. index_high_water_mark ++;
  20545. }
  20546. }
  20547. return [ attribs_out, indices_out ];
  20548. };
  20549. THREE.UTF8Loader.prototype.createModel = function ( data, callback, scale, offsetX, offsetY, offsetZ ) {
  20550. var Model = function ( texture_path ) {
  20551. //var s = (new Date).getTime();
  20552. var scope = this;
  20553. scope.materials = [];
  20554. THREE.Geometry.call( this );
  20555. var buffers = THREE.UTF8Loader.prototype.decompressMesh( data );
  20556. var normals = [],
  20557. uvs = [];
  20558. init_vertices( buffers[ 0 ], 8, 0 );
  20559. init_uvs( buffers[ 0 ], 8, 3 );
  20560. init_normals( buffers[ 0 ], 8, 5 );
  20561. init_faces( buffers[ 1 ] );
  20562. this.computeCentroids();
  20563. this.computeFaceNormals();
  20564. //this.computeTangents();
  20565. //var e = (new Date).getTime();
  20566. //console.log( "utf8 data parse time: " + (e-s) + " ms" );
  20567. function init_vertices( data, stride, offset ) {
  20568. var i, x, y, z,
  20569. end = data.length;
  20570. for( i = offset; i < end; i += stride ) {
  20571. x = data[ i ];
  20572. y = data[ i + 1 ];
  20573. z = data[ i + 2 ];
  20574. // fix scale and offsets
  20575. x = ( x / 16383 ) * scale;
  20576. y = ( y / 16383 ) * scale;
  20577. z = ( z / 16383 ) * scale;
  20578. x += offsetX;
  20579. y += offsetY;
  20580. z += offsetZ;
  20581. vertex( scope, x, y, z );
  20582. }
  20583. };
  20584. function init_normals( data, stride, offset ) {
  20585. var i, x, y, z,
  20586. end = data.length;
  20587. for( i = offset; i < end; i += stride ) {
  20588. x = data[ i ];
  20589. y = data[ i + 1 ];
  20590. z = data[ i + 2 ];
  20591. // normalize to <-1,1>
  20592. x = ( x - 512 ) / 511;
  20593. y = ( y - 512 ) / 511;
  20594. z = ( z - 512 ) / 511;
  20595. normals.push( x, y, z );
  20596. }
  20597. };
  20598. function init_uvs( data, stride, offset ) {
  20599. var i, u, v,
  20600. end = data.length;
  20601. for( i = offset; i < end; i += stride ) {
  20602. u = data[ i ];
  20603. v = data[ i + 1 ];
  20604. // normalize to <0,1>
  20605. u /= 1023;
  20606. v /= 1023;
  20607. uvs.push( u, 1 - v );
  20608. }
  20609. };
  20610. function init_faces( indices ) {
  20611. var i,
  20612. a, b, c,
  20613. u1, v1, u2, v2, u3, v3,
  20614. m,
  20615. end = indices.length;
  20616. m = 0; // all faces defaulting to material 0
  20617. for( i = 0; i < end; i += 3 ) {
  20618. a = indices[ i ];
  20619. b = indices[ i + 1 ];
  20620. c = indices[ i + 2 ];
  20621. f3n( scope, normals, a, b, c, m, a, b, c );
  20622. u1 = uvs[ a * 2 ];
  20623. v1 = uvs[ a * 2 + 1 ];
  20624. u2 = uvs[ b * 2 ];
  20625. v2 = uvs[ b * 2 + 1 ];
  20626. u3 = uvs[ c * 2 ];
  20627. v3 = uvs[ c * 2 + 1 ];
  20628. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  20629. }
  20630. }
  20631. };
  20632. function vertex ( scope, x, y, z ) {
  20633. scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  20634. };
  20635. function f3n ( scope, normals, a, b, c, mi, nai, nbi, nci ) {
  20636. var nax = normals[ nai * 3 ],
  20637. nay = normals[ nai * 3 + 1 ],
  20638. naz = normals[ nai * 3 + 2 ],
  20639. nbx = normals[ nbi * 3 ],
  20640. nby = normals[ nbi * 3 + 1 ],
  20641. nbz = normals[ nbi * 3 + 2 ],
  20642. ncx = normals[ nci * 3 ],
  20643. ncy = normals[ nci * 3 + 1 ],
  20644. ncz = normals[ nci * 3 + 2 ];
  20645. var na = new THREE.Vector3( nax, nay, naz ),
  20646. nb = new THREE.Vector3( nbx, nby, nbz ),
  20647. nc = new THREE.Vector3( ncx, ncy, ncz );
  20648. scope.faces.push( new THREE.Face3( a, b, c, [ na, nb, nc ], null, mi ) );
  20649. };
  20650. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  20651. var uv = [];
  20652. uv.push( new THREE.UV( u1, v1 ) );
  20653. uv.push( new THREE.UV( u2, v2 ) );
  20654. uv.push( new THREE.UV( u3, v3 ) );
  20655. where.push( uv );
  20656. };
  20657. Model.prototype = new THREE.Geometry();
  20658. Model.prototype.constructor = Model;
  20659. callback( new Model() );
  20660. };
  20661. /**
  20662. * @author alteredq / http://alteredqualia.com/
  20663. */
  20664. THREE.ImmediateRenderObject = function ( ) {
  20665. THREE.Object3D.call( this );
  20666. this.render = function( renderCallback ) {
  20667. };
  20668. };
  20669. THREE.ImmediateRenderObject.prototype = new THREE.Object3D();
  20670. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  20671. /**
  20672. * @author mikael emtinger / http://gomo.se/
  20673. * @author alteredq / http://alteredqualia.com/
  20674. */
  20675. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20676. THREE.Object3D.call( this );
  20677. this.lensFlares = [];
  20678. this.positionScreen = new THREE.Vector3();
  20679. this.customUpdateCallback = undefined;
  20680. if( texture !== undefined ) {
  20681. this.add( texture, size, distance, blending, color );
  20682. }
  20683. };
  20684. THREE.LensFlare.prototype = new THREE.Object3D();
  20685. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  20686. THREE.LensFlare.prototype.supr = THREE.Object3D.prototype;
  20687. /*
  20688. * Add: adds another flare
  20689. */
  20690. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20691. if( size === undefined ) size = -1;
  20692. if( distance === undefined ) distance = 0;
  20693. if( opacity === undefined ) opacity = 1;
  20694. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20695. if( blending === undefined ) blending = THREE.NormalBlending;
  20696. distance = Math.min( distance, Math.max( 0, distance ) );
  20697. this.lensFlares.push( { texture: texture, // THREE.Texture
  20698. size: size, // size in pixels (-1 = use texture.width)
  20699. distance: distance, // distance (0-1) from light source (0=at light source)
  20700. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20701. scale: 1, // scale
  20702. rotation: 1, // rotation
  20703. opacity: opacity, // opacity
  20704. color: color, // color
  20705. blending: blending } ); // blending
  20706. };
  20707. /*
  20708. * Update lens flares update positions on all flares based on the screen position
  20709. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20710. */
  20711. THREE.LensFlare.prototype.updateLensFlares = function () {
  20712. var f, fl = this.lensFlares.length;
  20713. var flare;
  20714. var vecX = -this.positionScreen.x * 2;
  20715. var vecY = -this.positionScreen.y * 2;
  20716. for( f = 0; f < fl; f ++ ) {
  20717. flare = this.lensFlares[ f ];
  20718. flare.x = this.positionScreen.x + vecX * flare.distance;
  20719. flare.y = this.positionScreen.y + vecY * flare.distance;
  20720. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20721. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20722. }
  20723. };
  20724. /**
  20725. * @author alteredq / http://alteredqualia.com/
  20726. */
  20727. THREE.MorphBlendMesh = function( geometry, material ) {
  20728. THREE.Mesh.call( this, geometry, material );
  20729. this.animationsMap = {};
  20730. this.animationsList = [];
  20731. // prepare default animation
  20732. // (all frames played together in 1 second)
  20733. var numFrames = this.geometry.morphTargets.length;
  20734. var name = "__default";
  20735. var startFrame = 0;
  20736. var endFrame = numFrames - 1;
  20737. var fps = numFrames / 1;
  20738. this.createAnimation( name, startFrame, endFrame, fps );
  20739. this.setAnimationWeight( name, 1 );
  20740. };
  20741. THREE.MorphBlendMesh.prototype = new THREE.Mesh();
  20742. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  20743. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20744. var animation = {
  20745. startFrame: start,
  20746. endFrame: end,
  20747. length: end - start + 1,
  20748. fps: fps,
  20749. duration: ( end - start ) / fps,
  20750. lastFrame: 0,
  20751. currentFrame: 0,
  20752. active: false,
  20753. time: 0,
  20754. direction: 1,
  20755. weight: 1,
  20756. directionBackwards: false,
  20757. mirroredLoop: false
  20758. };
  20759. this.animationsMap[ name ] = animation;
  20760. this.animationsList.push( animation );
  20761. };
  20762. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20763. var pattern = /([a-z]+)(\d+)/;
  20764. var firstAnimation, frameRanges = {};
  20765. var geometry = this.geometry;
  20766. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20767. var morph = geometry.morphTargets[ i ];
  20768. var chunks = morph.name.match( pattern );
  20769. if ( chunks && chunks.length > 1 ) {
  20770. var name = chunks[ 1 ];
  20771. var num = chunks[ 2 ];
  20772. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20773. var range = frameRanges[ name ];
  20774. if ( i < range.start ) range.start = i;
  20775. if ( i > range.end ) range.end = i;
  20776. if ( ! firstAnimation ) firstAnimation = name;
  20777. }
  20778. }
  20779. for ( var name in frameRanges ) {
  20780. var range = frameRanges[ name ];
  20781. this.createAnimation( name, range.start, range.end, fps );
  20782. }
  20783. this.firstAnimation = firstAnimation;
  20784. };
  20785. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20786. var animation = this.animationsMap[ name ];
  20787. if ( animation ) {
  20788. animation.direction = 1;
  20789. animation.directionBackwards = false;
  20790. }
  20791. };
  20792. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20793. var animation = this.animationsMap[ name ];
  20794. if ( animation ) {
  20795. animation.direction = -1;
  20796. animation.directionBackwards = true;
  20797. }
  20798. };
  20799. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20800. var animation = this.animationsMap[ name ];
  20801. if ( animation ) {
  20802. animation.fps = fps;
  20803. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20804. }
  20805. };
  20806. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20807. var animation = this.animationsMap[ name ];
  20808. if ( animation ) {
  20809. animation.duration = duration;
  20810. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20811. }
  20812. };
  20813. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20814. var animation = this.animationsMap[ name ];
  20815. if ( animation ) {
  20816. animation.weight = weight;
  20817. }
  20818. };
  20819. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20820. var animation = this.animationsMap[ name ];
  20821. if ( animation ) {
  20822. animation.time = time;
  20823. }
  20824. };
  20825. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20826. var time = 0;
  20827. var animation = this.animationsMap[ name ];
  20828. if ( animation ) {
  20829. time = animation.time;
  20830. }
  20831. return time;
  20832. };
  20833. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20834. var duration = -1;
  20835. var animation = this.animationsMap[ name ];
  20836. if ( animation ) {
  20837. duration = animation.duration;
  20838. }
  20839. return duration;
  20840. };
  20841. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20842. var animation = this.animationsMap[ name ];
  20843. if ( animation ) {
  20844. animation.time = 0;
  20845. animation.active = true;
  20846. } else {
  20847. console.warn( "animation[" + name + "] undefined" );
  20848. }
  20849. };
  20850. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20851. var animation = this.animationsMap[ name ];
  20852. if ( animation ) {
  20853. animation.active = false;
  20854. }
  20855. };
  20856. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20857. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20858. var animation = this.animationsList[ i ];
  20859. if ( ! animation.active ) continue;
  20860. var frameTime = animation.duration / animation.length;
  20861. animation.time += animation.direction * delta;
  20862. if ( animation.mirroredLoop ) {
  20863. if ( animation.time > animation.duration || animation.time < 0 ) {
  20864. animation.direction *= -1;
  20865. if ( animation.time > animation.duration ) {
  20866. animation.time = animation.duration;
  20867. animation.directionBackwards = true;
  20868. }
  20869. if ( animation.time < 0 ) {
  20870. animation.time = 0;
  20871. animation.directionBackwards = false;
  20872. }
  20873. }
  20874. } else {
  20875. animation.time = animation.time % animation.duration;
  20876. if ( animation.time < 0 ) animation.time += animation.duration;
  20877. }
  20878. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20879. var weight = animation.weight;
  20880. if ( keyframe !== animation.currentFrame ) {
  20881. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20882. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20883. this.morphTargetInfluences[ keyframe ] = 0;
  20884. animation.lastFrame = animation.currentFrame;
  20885. animation.currentFrame = keyframe;
  20886. }
  20887. var mix = ( animation.time % frameTime ) / frameTime;
  20888. if ( animation.directionBackwards ) mix = 1 - mix;
  20889. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20890. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20891. }
  20892. };
  20893. /**
  20894. * @author mikael emtinger / http://gomo.se/
  20895. * @author alteredq / http://alteredqualia.com/
  20896. */
  20897. THREE.LensFlarePlugin = function ( ) {
  20898. var _gl, _renderer, _lensFlare = {};
  20899. this.init = function ( renderer ) {
  20900. _gl = renderer.context;
  20901. _renderer = renderer;
  20902. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20903. _lensFlare.faces = new Uint16Array( 6 );
  20904. var i = 0;
  20905. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20906. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20907. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20908. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20909. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20910. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20911. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20912. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20913. i = 0;
  20914. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20915. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20916. // buffers
  20917. _lensFlare.vertexBuffer = _gl.createBuffer();
  20918. _lensFlare.elementBuffer = _gl.createBuffer();
  20919. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20920. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20921. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20922. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20923. // textures
  20924. _lensFlare.tempTexture = _gl.createTexture();
  20925. _lensFlare.occlusionTexture = _gl.createTexture();
  20926. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20927. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20928. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20929. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20930. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20931. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20932. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20933. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20934. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20935. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20936. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20937. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20938. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20939. _lensFlare.hasVertexTexture = false;
  20940. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20941. } else {
  20942. _lensFlare.hasVertexTexture = true;
  20943. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20944. }
  20945. _lensFlare.attributes = {};
  20946. _lensFlare.uniforms = {};
  20947. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20948. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20949. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20950. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20951. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20952. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20953. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20954. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20955. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20956. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20957. _lensFlare.attributesEnabled = false;
  20958. };
  20959. /*
  20960. * Render lens flares
  20961. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20962. * reads these back and calculates occlusion.
  20963. * Then _lensFlare.update_lensFlares() is called to re-position and
  20964. * update transparency of flares. Then they are rendered.
  20965. *
  20966. */
  20967. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20968. var flares = scene.__webglFlares,
  20969. nFlares = flares.length;
  20970. if ( ! nFlares ) return;
  20971. var tempPosition = new THREE.Vector3();
  20972. var invAspect = viewportHeight / viewportWidth,
  20973. halfViewportWidth = viewportWidth * 0.5,
  20974. halfViewportHeight = viewportHeight * 0.5;
  20975. var size = 16 / viewportHeight,
  20976. scale = new THREE.Vector2( size * invAspect, size );
  20977. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20978. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20979. var uniforms = _lensFlare.uniforms,
  20980. attributes = _lensFlare.attributes;
  20981. // set _lensFlare program and reset blending
  20982. _gl.useProgram( _lensFlare.program );
  20983. if ( ! _lensFlare.attributesEnabled ) {
  20984. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20985. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20986. _lensFlare.attributesEnabled = true;
  20987. }
  20988. // loop through all lens flares to update their occlusion and positions
  20989. // setup gl and common used attribs/unforms
  20990. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20991. _gl.uniform1i( uniforms.map, 1 );
  20992. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20993. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20994. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20995. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20996. _gl.disable( _gl.CULL_FACE );
  20997. _gl.depthMask( false );
  20998. var i, j, jl, flare, sprite;
  20999. for ( i = 0; i < nFlares; i ++ ) {
  21000. size = 16 / viewportHeight;
  21001. scale.set( size * invAspect, size );
  21002. // calc object screen position
  21003. flare = flares[ i ];
  21004. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21005. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  21006. camera.projectionMatrix.multiplyVector3( tempPosition );
  21007. // setup arrays for gl programs
  21008. screenPosition.copy( tempPosition )
  21009. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21010. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21011. // screen cull
  21012. if ( _lensFlare.hasVertexTexture || (
  21013. screenPositionPixels.x > 0 &&
  21014. screenPositionPixels.x < viewportWidth &&
  21015. screenPositionPixels.y > 0 &&
  21016. screenPositionPixels.y < viewportHeight ) ) {
  21017. // save current RGB to temp texture
  21018. _gl.activeTexture( _gl.TEXTURE1 );
  21019. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21020. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21021. // render pink quad
  21022. _gl.uniform1i( uniforms.renderType, 0 );
  21023. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21024. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21025. _gl.disable( _gl.BLEND );
  21026. _gl.enable( _gl.DEPTH_TEST );
  21027. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21028. // copy result to occlusionMap
  21029. _gl.activeTexture( _gl.TEXTURE0 );
  21030. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21031. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21032. // restore graphics
  21033. _gl.uniform1i( uniforms.renderType, 1 );
  21034. _gl.disable( _gl.DEPTH_TEST );
  21035. _gl.activeTexture( _gl.TEXTURE1 );
  21036. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21037. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21038. // update object positions
  21039. flare.positionScreen.copy( screenPosition )
  21040. if ( flare.customUpdateCallback ) {
  21041. flare.customUpdateCallback( flare );
  21042. } else {
  21043. flare.updateLensFlares();
  21044. }
  21045. // render flares
  21046. _gl.uniform1i( uniforms.renderType, 2 );
  21047. _gl.enable( _gl.BLEND );
  21048. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21049. sprite = flare.lensFlares[ j ];
  21050. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21051. screenPosition.x = sprite.x;
  21052. screenPosition.y = sprite.y;
  21053. screenPosition.z = sprite.z;
  21054. size = sprite.size * sprite.scale / viewportHeight;
  21055. scale.x = size * invAspect;
  21056. scale.y = size;
  21057. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21058. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21059. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21060. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21061. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21062. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21063. _renderer.setTexture( sprite.texture, 1 );
  21064. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21065. }
  21066. }
  21067. }
  21068. }
  21069. // restore gl
  21070. _gl.enable( _gl.CULL_FACE );
  21071. _gl.enable( _gl.DEPTH_TEST );
  21072. _gl.depthMask( true );
  21073. };
  21074. function createProgram ( shader ) {
  21075. var program = _gl.createProgram();
  21076. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21077. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21078. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21079. _gl.shaderSource( vertexShader, shader.vertexShader );
  21080. _gl.compileShader( fragmentShader );
  21081. _gl.compileShader( vertexShader );
  21082. _gl.attachShader( program, fragmentShader );
  21083. _gl.attachShader( program, vertexShader );
  21084. _gl.linkProgram( program );
  21085. return program;
  21086. };
  21087. };/**
  21088. * @author alteredq / http://alteredqualia.com/
  21089. */
  21090. THREE.ShadowMapPlugin = function ( ) {
  21091. var _gl,
  21092. _renderer,
  21093. _depthMaterial, _depthMaterialMorph,
  21094. _frustum = new THREE.Frustum(),
  21095. _projScreenMatrix = new THREE.Matrix4(),
  21096. _min = new THREE.Vector3(),
  21097. _max = new THREE.Vector3();
  21098. this.init = function ( renderer ) {
  21099. _gl = renderer.context;
  21100. _renderer = renderer;
  21101. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21102. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21103. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21104. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21105. _depthMaterial._shadowPass = true;
  21106. _depthMaterialMorph._shadowPass = true;
  21107. };
  21108. this.render = function ( scene, camera ) {
  21109. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21110. this.update( scene, camera );
  21111. };
  21112. this.update = function ( scene, camera ) {
  21113. var i, il, j, jl, n,
  21114. shadowMap, shadowMatrix, shadowCamera,
  21115. program, buffer, material,
  21116. webglObject, object, light,
  21117. renderList,
  21118. lights = [],
  21119. k = 0,
  21120. fog = null;
  21121. // set GL state for depth map
  21122. _gl.clearColor( 1, 1, 1, 1 );
  21123. _gl.disable( _gl.BLEND );
  21124. if ( _renderer.shadowMapCullFrontFaces ) _gl.cullFace( _gl.FRONT );
  21125. _renderer.setDepthTest( true );
  21126. // preprocess lights
  21127. // - skip lights that are not casting shadows
  21128. // - create virtual lights for cascaded shadow maps
  21129. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21130. light = scene.__lights[ i ];
  21131. if ( ! light.castShadow ) continue;
  21132. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21133. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21134. var virtualLight;
  21135. if ( ! light.shadowCascadeArray[ n ] ) {
  21136. virtualLight = createVirtualLight( light, n );
  21137. virtualLight.originalCamera = camera;
  21138. var gyro = new THREE.Gyroscope();
  21139. gyro.position = light.shadowCascadeOffset;
  21140. gyro.add( virtualLight );
  21141. gyro.add( virtualLight.target );
  21142. camera.add( gyro );
  21143. light.shadowCascadeArray[ n ] = virtualLight;
  21144. console.log( "Created virtualLight", virtualLight );
  21145. } else {
  21146. virtualLight = light.shadowCascadeArray[ n ];
  21147. }
  21148. updateVirtualLight( light, n );
  21149. lights[ k ] = virtualLight;
  21150. k ++;
  21151. }
  21152. } else {
  21153. lights[ k ] = light;
  21154. k ++;
  21155. }
  21156. }
  21157. // render depth map
  21158. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21159. light = lights[ i ];
  21160. if ( ! light.shadowMap ) {
  21161. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  21162. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21163. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21164. light.shadowMatrix = new THREE.Matrix4();
  21165. }
  21166. if ( ! light.shadowCamera ) {
  21167. if ( light instanceof THREE.SpotLight ) {
  21168. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21169. } else if ( light instanceof THREE.DirectionalLight ) {
  21170. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21171. } else {
  21172. console.error( "Unsupported light type for shadow" );
  21173. continue;
  21174. }
  21175. scene.add( light.shadowCamera );
  21176. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21177. }
  21178. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21179. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21180. light.shadowCamera.add( light.cameraHelper );
  21181. }
  21182. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21183. updateShadowCamera( camera, light );
  21184. }
  21185. shadowMap = light.shadowMap;
  21186. shadowMatrix = light.shadowMatrix;
  21187. shadowCamera = light.shadowCamera;
  21188. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  21189. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  21190. shadowCamera.updateMatrixWorld();
  21191. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21192. if ( light.cameraHelper ) light.cameraHelper.lines.visible = light.shadowCameraVisible;
  21193. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21194. // compute shadow matrix
  21195. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21196. 0.0, 0.5, 0.0, 0.5,
  21197. 0.0, 0.0, 0.5, 0.5,
  21198. 0.0, 0.0, 0.0, 1.0 );
  21199. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  21200. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  21201. // update camera matrices and frustum
  21202. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  21203. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  21204. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  21205. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  21206. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21207. _frustum.setFromMatrix( _projScreenMatrix );
  21208. // render shadow map
  21209. _renderer.setRenderTarget( shadowMap );
  21210. _renderer.clear();
  21211. // set object matrices & frustum culling
  21212. renderList = scene.__webglObjects;
  21213. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21214. webglObject = renderList[ j ];
  21215. object = webglObject.object;
  21216. webglObject.render = false;
  21217. if ( object.visible && object.castShadow ) {
  21218. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21219. object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21220. object._modelViewMatrix.multiplyToArray( shadowCamera.matrixWorldInverse, object.matrixWorld, object._modelViewMatrixArray );
  21221. webglObject.render = true;
  21222. }
  21223. }
  21224. }
  21225. // render regular objects
  21226. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21227. webglObject = renderList[ j ];
  21228. if ( webglObject.render ) {
  21229. object = webglObject.object;
  21230. buffer = webglObject.buffer;
  21231. _renderer.setObjectFaces( object );
  21232. if ( object.customDepthMaterial ) {
  21233. material = object.customDepthMaterial;
  21234. } else if ( object.geometry.morphTargets.length ) {
  21235. material = _depthMaterialMorph;
  21236. } else {
  21237. material = _depthMaterial;
  21238. }
  21239. if ( buffer instanceof THREE.BufferGeometry ) {
  21240. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21241. } else {
  21242. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21243. }
  21244. }
  21245. }
  21246. // set matrices and render immediate objects
  21247. renderList = scene.__webglObjectsImmediate;
  21248. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21249. webglObject = renderList[ j ];
  21250. object = webglObject.object;
  21251. if ( object.visible && object.castShadow ) {
  21252. if( object.matrixAutoUpdate ) {
  21253. object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21254. }
  21255. object._modelViewMatrix.multiplyToArray( shadowCamera.matrixWorldInverse, object.matrixWorld, object._modelViewMatrixArray );
  21256. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21257. }
  21258. }
  21259. }
  21260. // restore GL state
  21261. var clearColor = _renderer.getClearColor(),
  21262. clearAlpha = _renderer.getClearAlpha();
  21263. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21264. _gl.enable( _gl.BLEND );
  21265. if ( _renderer.shadowMapCullFrontFaces ) _gl.cullFace( _gl.BACK );
  21266. };
  21267. function createVirtualLight( light, cascade ) {
  21268. var virtualLight = new THREE.DirectionalLight();
  21269. virtualLight.isVirtual = true;
  21270. virtualLight.onlyShadow = true;
  21271. virtualLight.castShadow = true;
  21272. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21273. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21274. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21275. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21276. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21277. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21278. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21279. virtualLight.shadowDarkness = light.shadowDarkness;
  21280. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21281. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21282. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21283. virtualLight.pointsWorld = [];
  21284. virtualLight.pointsFrustum = [];
  21285. var pointsWorld = virtualLight.pointsWorld,
  21286. pointsFrustum = virtualLight.pointsFrustum;
  21287. for ( var i = 0; i < 8; i ++ ) {
  21288. pointsWorld[ i ] = new THREE.Vector3();
  21289. pointsFrustum[ i ] = new THREE.Vector3();
  21290. }
  21291. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21292. var farZ = light.shadowCascadeFarZ[ cascade ];
  21293. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21294. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21295. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21296. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21297. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21298. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21299. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21300. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21301. return virtualLight;
  21302. }
  21303. // Synchronize virtual light with the original light
  21304. function updateVirtualLight( light, cascade ) {
  21305. var virtualLight = light.shadowCascadeArray[ cascade ];
  21306. virtualLight.position.copy( light.position );
  21307. virtualLight.target.position.copy( light.target.position );
  21308. virtualLight.lookAt( virtualLight.target );
  21309. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21310. virtualLight.shadowDarkness = light.shadowDarkness;
  21311. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21312. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21313. var farZ = light.shadowCascadeFarZ[ cascade ];
  21314. var pointsFrustum = virtualLight.pointsFrustum;
  21315. pointsFrustum[ 0 ].z = nearZ;
  21316. pointsFrustum[ 1 ].z = nearZ;
  21317. pointsFrustum[ 2 ].z = nearZ;
  21318. pointsFrustum[ 3 ].z = nearZ;
  21319. pointsFrustum[ 4 ].z = farZ;
  21320. pointsFrustum[ 5 ].z = farZ;
  21321. pointsFrustum[ 6 ].z = farZ;
  21322. pointsFrustum[ 7 ].z = farZ;
  21323. }
  21324. // Fit shadow camera's ortho frustum to camera frustum
  21325. function updateShadowCamera( camera, light ) {
  21326. var shadowCamera = light.shadowCamera,
  21327. pointsFrustum = light.pointsFrustum,
  21328. pointsWorld = light.pointsWorld;
  21329. _min.set( Infinity, Infinity, Infinity );
  21330. _max.set( -Infinity, -Infinity, -Infinity );
  21331. for ( var i = 0; i < 8; i ++ ) {
  21332. var p = pointsWorld[ i ];
  21333. p.copy( pointsFrustum[ i ] );
  21334. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21335. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  21336. if ( p.x < _min.x ) _min.x = p.x;
  21337. if ( p.x > _max.x ) _max.x = p.x;
  21338. if ( p.y < _min.y ) _min.y = p.y;
  21339. if ( p.y > _max.y ) _max.y = p.y;
  21340. if ( p.z < _min.z ) _min.z = p.z;
  21341. if ( p.z > _max.z ) _max.z = p.z;
  21342. }
  21343. shadowCamera.left = _min.x;
  21344. shadowCamera.right = _max.x;
  21345. shadowCamera.top = _max.y;
  21346. shadowCamera.bottom = _min.y;
  21347. // can't really fit near/far
  21348. //shadowCamera.near = _min.z;
  21349. //shadowCamera.far = _max.z;
  21350. shadowCamera.updateProjectionMatrix();
  21351. }
  21352. };
  21353. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21354. /**
  21355. * @author mikael emtinger / http://gomo.se/
  21356. * @author alteredq / http://alteredqualia.com/
  21357. */
  21358. THREE.SpritePlugin = function ( ) {
  21359. var _gl, _renderer, _sprite = {};
  21360. this.init = function ( renderer ) {
  21361. _gl = renderer.context;
  21362. _renderer = renderer;
  21363. _sprite.vertices = new Float32Array( 8 + 8 );
  21364. _sprite.faces = new Uint16Array( 6 );
  21365. var i = 0;
  21366. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21367. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 0
  21368. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21369. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 1
  21370. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21371. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 2
  21372. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21373. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 3
  21374. i = 0;
  21375. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21376. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21377. _sprite.vertexBuffer = _gl.createBuffer();
  21378. _sprite.elementBuffer = _gl.createBuffer();
  21379. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21380. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21381. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21382. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21383. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  21384. _sprite.attributes = {};
  21385. _sprite.uniforms = {};
  21386. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21387. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21388. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21389. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21390. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21391. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21392. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21393. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21394. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21395. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21396. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21397. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  21398. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21399. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21400. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21401. _sprite.attributesEnabled = false;
  21402. };
  21403. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21404. var sprites = scene.__webglSprites,
  21405. nSprites = sprites.length;
  21406. if ( ! nSprites ) return;
  21407. var attributes = _sprite.attributes,
  21408. uniforms = _sprite.uniforms;
  21409. var invAspect = viewportHeight / viewportWidth;
  21410. var halfViewportWidth = viewportWidth * 0.5,
  21411. halfViewportHeight = viewportHeight * 0.5;
  21412. var mergeWith3D = true;
  21413. // setup gl
  21414. _gl.useProgram( _sprite.program );
  21415. if ( ! _sprite.attributesEnabled ) {
  21416. _gl.enableVertexAttribArray( attributes.position );
  21417. _gl.enableVertexAttribArray( attributes.uv );
  21418. _sprite.attributesEnabled = true;
  21419. }
  21420. _gl.disable( _gl.CULL_FACE );
  21421. _gl.enable( _gl.BLEND );
  21422. _gl.depthMask( true );
  21423. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21424. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21425. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21426. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21427. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  21428. _gl.activeTexture( _gl.TEXTURE0 );
  21429. _gl.uniform1i( uniforms.map, 0 );
  21430. // update positions and sort
  21431. var i, sprite, screenPosition, size, scale = [];
  21432. for( i = 0; i < nSprites; i ++ ) {
  21433. sprite = sprites[ i ];
  21434. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  21435. if( ! sprite.useScreenCoordinates ) {
  21436. sprite._modelViewMatrix.multiplyToArray( camera.matrixWorldInverse, sprite.matrixWorld, sprite._modelViewMatrixArray );
  21437. sprite.z = - sprite._modelViewMatrix.elements[14];
  21438. } else {
  21439. sprite.z = - sprite.position.z;
  21440. }
  21441. }
  21442. sprites.sort( painterSort );
  21443. // render all sprites
  21444. for( i = 0; i < nSprites; i ++ ) {
  21445. sprite = sprites[ i ];
  21446. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  21447. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  21448. if ( sprite.useScreenCoordinates ) {
  21449. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21450. _gl.uniform3f( uniforms.screenPosition, ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21451. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21452. Math.max( 0, Math.min( 1, sprite.position.z ) ) );
  21453. } else {
  21454. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21455. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  21456. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrixArray );
  21457. }
  21458. size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
  21459. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21460. scale[ 1 ] = size * sprite.scale.y;
  21461. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  21462. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  21463. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  21464. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21465. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21466. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21467. _gl.uniform2fv( uniforms.scale, scale );
  21468. if ( sprite.mergeWith3D && !mergeWith3D ) {
  21469. _gl.enable( _gl.DEPTH_TEST );
  21470. mergeWith3D = true;
  21471. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  21472. _gl.disable( _gl.DEPTH_TEST );
  21473. mergeWith3D = false;
  21474. }
  21475. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21476. _renderer.setTexture( sprite.map, 0 );
  21477. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21478. }
  21479. }
  21480. // restore gl
  21481. _gl.enable( _gl.CULL_FACE );
  21482. _gl.enable( _gl.DEPTH_TEST );
  21483. _gl.depthMask( true );
  21484. };
  21485. function createProgram ( shader ) {
  21486. var program = _gl.createProgram();
  21487. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21488. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21489. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21490. _gl.shaderSource( vertexShader, shader.vertexShader );
  21491. _gl.compileShader( fragmentShader );
  21492. _gl.compileShader( vertexShader );
  21493. _gl.attachShader( program, fragmentShader );
  21494. _gl.attachShader( program, vertexShader );
  21495. _gl.linkProgram( program );
  21496. return program;
  21497. };
  21498. function painterSort ( a, b ) {
  21499. return b.z - a.z;
  21500. };
  21501. };/**
  21502. * @author alteredq / http://alteredqualia.com/
  21503. */
  21504. THREE.DepthPassPlugin = function ( ) {
  21505. this.enabled = false;
  21506. this.renderTarget = null;
  21507. var _gl,
  21508. _renderer,
  21509. _depthMaterial, _depthMaterialMorph,
  21510. _frustum = new THREE.Frustum(),
  21511. _projScreenMatrix = new THREE.Matrix4();
  21512. this.init = function ( renderer ) {
  21513. _gl = renderer.context;
  21514. _renderer = renderer;
  21515. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21516. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21517. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21518. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21519. _depthMaterial._shadowPass = true;
  21520. _depthMaterialMorph._shadowPass = true;
  21521. };
  21522. this.render = function ( scene, camera ) {
  21523. if ( ! this.enabled ) return;
  21524. this.update( scene, camera );
  21525. };
  21526. this.update = function ( scene, camera ) {
  21527. var i, il, j, jl, n,
  21528. program, buffer, material,
  21529. webglObject, object, light,
  21530. renderList,
  21531. fog = null;
  21532. // set GL state for depth map
  21533. _gl.clearColor( 1, 1, 1, 1 );
  21534. _gl.disable( _gl.BLEND );
  21535. _renderer.setDepthTest( true );
  21536. // update scene
  21537. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21538. // update camera matrices and frustum
  21539. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  21540. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  21541. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21542. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  21543. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  21544. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21545. _frustum.setFromMatrix( _projScreenMatrix );
  21546. // render depth map
  21547. _renderer.setRenderTarget( this.renderTarget );
  21548. _renderer.clear();
  21549. // set object matrices & frustum culling
  21550. renderList = scene.__webglObjects;
  21551. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21552. webglObject = renderList[ j ];
  21553. object = webglObject.object;
  21554. webglObject.render = false;
  21555. if ( object.visible ) {
  21556. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21557. object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21558. object._modelViewMatrix.multiplyToArray( camera.matrixWorldInverse, object.matrixWorld, object._modelViewMatrixArray );
  21559. webglObject.render = true;
  21560. }
  21561. }
  21562. }
  21563. // render regular objects
  21564. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21565. webglObject = renderList[ j ];
  21566. if ( webglObject.render ) {
  21567. object = webglObject.object;
  21568. buffer = webglObject.buffer;
  21569. _renderer.setObjectFaces( object );
  21570. if ( object.customDepthMaterial ) {
  21571. material = object.customDepthMaterial;
  21572. } else if ( object.geometry.morphTargets.length ) {
  21573. material = _depthMaterialMorph;
  21574. } else {
  21575. material = _depthMaterial;
  21576. }
  21577. if ( buffer instanceof THREE.BufferGeometry ) {
  21578. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21579. } else {
  21580. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21581. }
  21582. }
  21583. }
  21584. // set matrices and render immediate objects
  21585. renderList = scene.__webglObjectsImmediate;
  21586. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21587. webglObject = renderList[ j ];
  21588. object = webglObject.object;
  21589. if ( object.visible && object.castShadow ) {
  21590. if( object.matrixAutoUpdate ) {
  21591. object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21592. }
  21593. object._modelViewMatrix.multiplyToArray( camera.matrixWorldInverse, object.matrixWorld, object._modelViewMatrixArray );
  21594. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21595. }
  21596. }
  21597. // restore GL state
  21598. var clearColor = _renderer.getClearColor(),
  21599. clearAlpha = _renderer.getClearAlpha();
  21600. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21601. _gl.enable( _gl.BLEND );
  21602. };
  21603. };
  21604. /**
  21605. * @author mrdoob / http://mrdoob.com/
  21606. * @author marklundin / http://mark-lundin.com/
  21607. * @author alteredq / http://alteredqualia.com/
  21608. */
  21609. if ( THREE.WebGLRenderer ) {
  21610. THREE.AnaglyphWebGLRenderer = function ( parameters ) {
  21611. THREE.WebGLRenderer.call( this, parameters );
  21612. this.autoUpdateScene = false;
  21613. var _this = this, _setSize = this.setSize, _render = this.render;
  21614. var _cameraL = new THREE.PerspectiveCamera(),
  21615. _cameraR = new THREE.PerspectiveCamera();
  21616. var eyeRight = new THREE.Matrix4(),
  21617. eyeLeft = new THREE.Matrix4(),
  21618. focalLength = 125,
  21619. _aspect, _near, _far, _fov;
  21620. _cameraL.matrixAutoUpdate = _cameraR.matrixAutoUpdate = false;
  21621. var _params = { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };
  21622. var _renderTargetL = new THREE.WebGLRenderTarget( 512, 512, _params ),
  21623. _renderTargetR = new THREE.WebGLRenderTarget( 512, 512, _params );
  21624. var _camera = new THREE.PerspectiveCamera( 53, 1, 1, 10000 );
  21625. _camera.position.z = 2;
  21626. var _material = new THREE.ShaderMaterial( {
  21627. uniforms: {
  21628. "mapLeft": { type: "t", value: 0, texture: _renderTargetL },
  21629. "mapRight": { type: "t", value: 1, texture: _renderTargetR }
  21630. },
  21631. vertexShader: [
  21632. "varying vec2 vUv;",
  21633. "void main() {",
  21634. "vUv = vec2( uv.x, 1.0 - uv.y );",
  21635. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  21636. "}"
  21637. ].join("\n"),
  21638. fragmentShader: [
  21639. "uniform sampler2D mapLeft;",
  21640. "uniform sampler2D mapRight;",
  21641. "varying vec2 vUv;",
  21642. "void main() {",
  21643. "vec4 colorL, colorR;",
  21644. "vec2 uv = vUv;",
  21645. "colorL = texture2D( mapLeft, uv );",
  21646. "colorR = texture2D( mapRight, uv );",
  21647. // http://3dtv.at/Knowhow/AnaglyphComparison_en.aspx
  21648. "gl_FragColor = vec4( colorL.g * 0.7 + colorL.b * 0.3, colorR.g, colorR.b, colorL.a + colorR.a ) * 1.1;",
  21649. "}"
  21650. ].join("\n")
  21651. } );
  21652. var _scene = new THREE.Scene();
  21653. var mesh = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), _material );
  21654. mesh.rotation.x = Math.PI / 2;
  21655. _scene.add( mesh );
  21656. _scene.add( _camera );
  21657. this.setSize = function ( width, height ) {
  21658. _setSize.call( _this, width, height );
  21659. _renderTargetL.width = width;
  21660. _renderTargetL.height = height;
  21661. _renderTargetR.width = width;
  21662. _renderTargetR.height = height;
  21663. };
  21664. /*
  21665. * Renderer now uses an asymmetric perspective projection (http://paulbourke.net/miscellaneous/stereographics/stereorender/).
  21666. * Each camera is offset by the eye seperation and its projection matrix is also skewed asymetrically back to converge on the same
  21667. * projection plane. Added a focal length parameter to, this is where the parallax is equal to 0.
  21668. */
  21669. this.render = function ( scene, camera, renderTarget, forceClear ) {
  21670. scene.updateMatrixWorld();
  21671. var hasCameraChanged = ( _aspect !== camera.aspect ) || ( _near !== camera.near ) || ( _far !== camera.far ) || ( _fov !== camera.fov );
  21672. if( hasCameraChanged ) {
  21673. _aspect = camera.aspect;
  21674. _near = camera.near;
  21675. _far = camera.far;
  21676. _fov = camera.fov;
  21677. var projectionMatrix = camera.projectionMatrix.clone(),
  21678. eyeSep = focalLength / 30 * 0.5,
  21679. eyeSepOnProjection = eyeSep * _near / focalLength,
  21680. ymax = _near * Math.tan( _fov * Math.PI / 360 ),
  21681. xmin, xmax;
  21682. // translate xOffset
  21683. eyeRight.elements[12] = eyeSep;
  21684. eyeLeft.elements[12] = -eyeSep;
  21685. // for left eye
  21686. xmin = -ymax * _aspect + eyeSepOnProjection;
  21687. xmax = ymax * _aspect + eyeSepOnProjection;
  21688. projectionMatrix.elements[0] = 2 * _near / ( xmax - xmin );
  21689. projectionMatrix.elements[8] = ( xmax + xmin ) / ( xmax - xmin );
  21690. _cameraL.projectionMatrix.copy( projectionMatrix );
  21691. // for right eye
  21692. xmin = -ymax * _aspect - eyeSepOnProjection;
  21693. xmax = ymax * _aspect - eyeSepOnProjection;
  21694. projectionMatrix.elements[0] = 2 * _near / ( xmax - xmin );
  21695. projectionMatrix.elements[8] = ( xmax + xmin ) / ( xmax - xmin );
  21696. _cameraR.projectionMatrix.copy( projectionMatrix );
  21697. }
  21698. _cameraL.matrixWorld.copy( camera.matrixWorld ).multiplySelf( eyeLeft );
  21699. _cameraL.position.copy( camera.position );
  21700. _cameraL.near = camera.near;
  21701. _cameraL.far = camera.far;
  21702. _render.call( _this, scene, _cameraL, _renderTargetL, true );
  21703. _cameraR.matrixWorld.copy( camera.matrixWorld ).multiplySelf( eyeRight );
  21704. _cameraR.position.copy( camera.position );
  21705. _cameraR.near = camera.near;
  21706. _cameraR.far = camera.far;
  21707. _render.call( _this, scene, _cameraR, _renderTargetR, true );
  21708. _scene.updateMatrixWorld();
  21709. _render.call( _this, _scene, _camera );
  21710. };
  21711. };
  21712. };
  21713. /**
  21714. * @author alteredq / http://alteredqualia.com/
  21715. */
  21716. if ( THREE.WebGLRenderer ) {
  21717. THREE.CrosseyedWebGLRenderer = function ( parameters ) {
  21718. THREE.WebGLRenderer.call( this, parameters );
  21719. this.autoClear = false;
  21720. var _this = this, _setSize = this.setSize, _render = this.render;
  21721. var _width, _height;
  21722. var _cameraL = new THREE.PerspectiveCamera();
  21723. _cameraL.target = new THREE.Vector3( 0, 0, 0 );
  21724. var _cameraR = new THREE.PerspectiveCamera();
  21725. _cameraR.target = new THREE.Vector3( 0, 0, 0 );
  21726. _this.separation = 10;
  21727. if ( parameters && parameters.separation !== undefined ) _this.separation = parameters.separation;
  21728. var SCREEN_WIDTH = window.innerWidth;
  21729. var SCREEN_HEIGHT = window.innerHeight;
  21730. var HALF_WIDTH = SCREEN_WIDTH / 2;
  21731. this.setSize = function ( width, height ) {
  21732. _setSize.call( _this, width, height );
  21733. _width = width/2;
  21734. _height = height;
  21735. };
  21736. this.render = function ( scene, camera, renderTarget, forceClear ) {
  21737. this.clear();
  21738. _cameraL.fov = camera.fov;
  21739. _cameraL.aspect = 0.5 * camera.aspect;
  21740. _cameraL.near = camera.near;
  21741. _cameraL.far = camera.far;
  21742. _cameraL.updateProjectionMatrix();
  21743. _cameraL.position.copy( camera.position );
  21744. _cameraL.target.copy( camera.target );
  21745. _cameraL.translateX( _this.separation );
  21746. _cameraL.lookAt( _cameraL.target );
  21747. _cameraR.projectionMatrix = _cameraL.projectionMatrix;
  21748. _cameraR.position.copy( camera.position );
  21749. _cameraR.target.copy( camera.target );
  21750. _cameraR.translateX( - _this.separation );
  21751. _cameraR.lookAt( _cameraR.target );
  21752. this.setViewport( 0, 0, _width, _height );
  21753. _render.call( _this, scene, _cameraL );
  21754. this.setViewport( _width, 0, _width, _height );
  21755. _render.call( _this, scene, _cameraR, false );
  21756. };
  21757. };
  21758. }
  21759. /**
  21760. * @author mikael emtinger / http://gomo.se/
  21761. *
  21762. */
  21763. THREE.ShaderFlares = {
  21764. 'lensFlareVertexTexture': {
  21765. vertexShader: [
  21766. "uniform vec3 screenPosition;",
  21767. "uniform vec2 scale;",
  21768. "uniform float rotation;",
  21769. "uniform int renderType;",
  21770. "uniform sampler2D occlusionMap;",
  21771. "attribute vec2 position;",
  21772. "attribute vec2 uv;",
  21773. "varying vec2 vUV;",
  21774. "varying float vVisibility;",
  21775. "void main() {",
  21776. "vUV = uv;",
  21777. "vec2 pos = position;",
  21778. "if( renderType == 2 ) {",
  21779. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21780. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21781. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21782. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21783. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21784. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21785. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21786. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21787. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21788. "vVisibility = ( visibility.r / 9.0 ) *",
  21789. "( 1.0 - visibility.g / 9.0 ) *",
  21790. "( visibility.b / 9.0 ) *",
  21791. "( 1.0 - visibility.a / 9.0 );",
  21792. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21793. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21794. "}",
  21795. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21796. "}"
  21797. ].join( "\n" ),
  21798. fragmentShader: [
  21799. "precision mediump float;",
  21800. "uniform sampler2D map;",
  21801. "uniform float opacity;",
  21802. "uniform int renderType;",
  21803. "uniform vec3 color;",
  21804. "varying vec2 vUV;",
  21805. "varying float vVisibility;",
  21806. "void main() {",
  21807. // pink square
  21808. "if( renderType == 0 ) {",
  21809. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21810. // restore
  21811. "} else if( renderType == 1 ) {",
  21812. "gl_FragColor = texture2D( map, vUV );",
  21813. // flare
  21814. "} else {",
  21815. "vec4 texture = texture2D( map, vUV );",
  21816. "texture.a *= opacity * vVisibility;",
  21817. "gl_FragColor = texture;",
  21818. "gl_FragColor.rgb *= color;",
  21819. "}",
  21820. "}"
  21821. ].join( "\n" )
  21822. },
  21823. 'lensFlare': {
  21824. vertexShader: [
  21825. "uniform vec3 screenPosition;",
  21826. "uniform vec2 scale;",
  21827. "uniform float rotation;",
  21828. "uniform int renderType;",
  21829. "attribute vec2 position;",
  21830. "attribute vec2 uv;",
  21831. "varying vec2 vUV;",
  21832. "void main() {",
  21833. "vUV = uv;",
  21834. "vec2 pos = position;",
  21835. "if( renderType == 2 ) {",
  21836. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21837. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21838. "}",
  21839. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21840. "}"
  21841. ].join( "\n" ),
  21842. fragmentShader: [
  21843. "precision mediump float;",
  21844. "uniform sampler2D map;",
  21845. "uniform sampler2D occlusionMap;",
  21846. "uniform float opacity;",
  21847. "uniform int renderType;",
  21848. "uniform vec3 color;",
  21849. "varying vec2 vUV;",
  21850. "void main() {",
  21851. // pink square
  21852. "if( renderType == 0 ) {",
  21853. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21854. // restore
  21855. "} else if( renderType == 1 ) {",
  21856. "gl_FragColor = texture2D( map, vUV );",
  21857. // flare
  21858. "} else {",
  21859. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21860. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21861. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21862. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21863. "visibility = ( 1.0 - visibility / 4.0 );",
  21864. "vec4 texture = texture2D( map, vUV );",
  21865. "texture.a *= opacity * visibility;",
  21866. "gl_FragColor = texture;",
  21867. "gl_FragColor.rgb *= color;",
  21868. "}",
  21869. "}"
  21870. ].join( "\n" )
  21871. }
  21872. };
  21873. /**
  21874. * @author mikael emtinger / http://gomo.se/
  21875. *
  21876. */
  21877. THREE.ShaderSprite = {
  21878. 'sprite': {
  21879. vertexShader: [
  21880. "uniform int useScreenCoordinates;",
  21881. "uniform int affectedByDistance;",
  21882. "uniform vec3 screenPosition;",
  21883. "uniform mat4 modelViewMatrix;",
  21884. "uniform mat4 projectionMatrix;",
  21885. "uniform float rotation;",
  21886. "uniform vec2 scale;",
  21887. "uniform vec2 alignment;",
  21888. "uniform vec2 uvOffset;",
  21889. "uniform vec2 uvScale;",
  21890. "attribute vec2 position;",
  21891. "attribute vec2 uv;",
  21892. "varying vec2 vUV;",
  21893. "void main() {",
  21894. "vUV = uvOffset + uv * uvScale;",
  21895. "vec2 alignedPosition = position + alignment;",
  21896. "vec2 rotatedPosition;",
  21897. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21898. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21899. "vec4 finalPosition;",
  21900. "if( useScreenCoordinates != 0 ) {",
  21901. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21902. "} else {",
  21903. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21904. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  21905. "}",
  21906. "gl_Position = finalPosition;",
  21907. "}"
  21908. ].join( "\n" ),
  21909. fragmentShader: [
  21910. "precision mediump float;",
  21911. "uniform vec3 color;",
  21912. "uniform sampler2D map;",
  21913. "uniform float opacity;",
  21914. "varying vec2 vUV;",
  21915. "void main() {",
  21916. "vec4 texture = texture2D( map, vUV );",
  21917. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21918. "}"
  21919. ].join( "\n" )
  21920. }
  21921. };