Three.js 799 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426
  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' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  19. }
  20. if ( !window.requestAnimationFrame ) {
  21. window.requestAnimationFrame = function ( callback, element ) {
  22. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  23. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  24. lastTime = currTime + timeToCall;
  25. return id;
  26. };
  27. }
  28. if ( !window.cancelAnimationFrame ) {
  29. window.cancelAnimationFrame = function ( id ) { clearTimeout( id ); };
  30. }
  31. }() );
  32. /**
  33. * @author alteredq / http://alteredqualia.com/
  34. */
  35. THREE.Clock = function ( autoStart ) {
  36. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  37. this.startTime = 0;
  38. this.oldTime = 0;
  39. this.elapsedTime = 0;
  40. this.running = false;
  41. };
  42. THREE.Clock.prototype.start = function () {
  43. this.startTime = Date.now();
  44. this.oldTime = this.startTime;
  45. this.running = true;
  46. };
  47. THREE.Clock.prototype.stop = function () {
  48. this.getElapsedTime();
  49. this.running = false;
  50. };
  51. THREE.Clock.prototype.getElapsedTime = function () {
  52. this.elapsedTime += this.getDelta();
  53. return this.elapsedTime;
  54. };
  55. THREE.Clock.prototype.getDelta = function () {
  56. var diff = 0;
  57. if ( this.autoStart && ! this.running ) {
  58. this.start();
  59. }
  60. if ( this.running ) {
  61. var newTime = Date.now();
  62. diff = 0.001 * ( newTime - this.oldTime );
  63. this.oldTime = newTime;
  64. this.elapsedTime += diff;
  65. }
  66. return diff;
  67. };/**
  68. * @author mr.doob / http://mrdoob.com/
  69. */
  70. THREE.Color = function ( hex ) {
  71. if ( hex !== undefined ) this.setHex( hex );
  72. return this;
  73. };
  74. THREE.Color.prototype = {
  75. constructor: THREE.Color,
  76. r: 1, g: 1, b: 1,
  77. copy: function ( color ) {
  78. this.r = color.r;
  79. this.g = color.g;
  80. this.b = color.b;
  81. return this;
  82. },
  83. copyGammaToLinear: function ( color ) {
  84. this.r = color.r * color.r;
  85. this.g = color.g * color.g;
  86. this.b = color.b * color.b;
  87. return this;
  88. },
  89. copyLinearToGamma: function ( color ) {
  90. this.r = Math.sqrt( color.r );
  91. this.g = Math.sqrt( color.g );
  92. this.b = Math.sqrt( color.b );
  93. return this;
  94. },
  95. convertGammaToLinear: function () {
  96. var r = this.r, g = this.g, b = this.b;
  97. this.r = r * r;
  98. this.g = g * g;
  99. this.b = b * b;
  100. return this;
  101. },
  102. convertLinearToGamma: function () {
  103. this.r = Math.sqrt( this.r );
  104. this.g = Math.sqrt( this.g );
  105. this.b = Math.sqrt( this.b );
  106. return this;
  107. },
  108. setRGB: function ( r, g, b ) {
  109. this.r = r;
  110. this.g = g;
  111. this.b = b;
  112. return this;
  113. },
  114. setHSV: function ( h, s, v ) {
  115. // based on MochiKit implementation by Bob Ippolito
  116. // h,s,v ranges are < 0.0 - 1.0 >
  117. var i, f, p, q, t;
  118. if ( v === 0 ) {
  119. this.r = this.g = this.b = 0;
  120. } else {
  121. i = Math.floor( h * 6 );
  122. f = ( h * 6 ) - i;
  123. p = v * ( 1 - s );
  124. q = v * ( 1 - ( s * f ) );
  125. t = v * ( 1 - ( s * ( 1 - f ) ) );
  126. switch ( i ) {
  127. case 1: this.r = q; this.g = v; this.b = p; break;
  128. case 2: this.r = p; this.g = v; this.b = t; break;
  129. case 3: this.r = p; this.g = q; this.b = v; break;
  130. case 4: this.r = t; this.g = p; this.b = v; break;
  131. case 5: this.r = v; this.g = p; this.b = q; break;
  132. case 6: // fall through
  133. case 0: this.r = v; this.g = t; this.b = p; break;
  134. }
  135. }
  136. return this;
  137. },
  138. setHex: function ( hex ) {
  139. hex = Math.floor( hex );
  140. this.r = ( hex >> 16 & 255 ) / 255;
  141. this.g = ( hex >> 8 & 255 ) / 255;
  142. this.b = ( hex & 255 ) / 255;
  143. return this;
  144. },
  145. lerpSelf: function ( color, alpha ) {
  146. this.r += ( color.r - this.r ) * alpha;
  147. this.g += ( color.g - this.g ) * alpha;
  148. this.b += ( color.b - this.b ) * alpha;
  149. return this;
  150. },
  151. getHex: function () {
  152. return Math.floor( this.r * 255 ) << 16 ^ Math.floor( this.g * 255 ) << 8 ^ Math.floor( this.b * 255 );
  153. },
  154. getContextStyle: function () {
  155. return 'rgb(' + Math.floor( this.r * 255 ) + ',' + Math.floor( this.g * 255 ) + ',' + Math.floor( this.b * 255 ) + ')';
  156. },
  157. clone: function () {
  158. return new THREE.Color().setRGB( this.r, this.g, this.b );
  159. }
  160. };
  161. /**
  162. * @author mr.doob / http://mrdoob.com/
  163. * @author philogb / http://blog.thejit.org/
  164. * @author egraether / http://egraether.com/
  165. * @author zz85 / http://www.lab4games.net/zz85/blog
  166. */
  167. THREE.Vector2 = function ( x, y ) {
  168. this.x = x || 0;
  169. this.y = y || 0;
  170. };
  171. THREE.Vector2.prototype = {
  172. constructor: THREE.Vector2,
  173. set: function ( x, y ) {
  174. this.x = x;
  175. this.y = y;
  176. return this;
  177. },
  178. copy: function ( v ) {
  179. this.x = v.x;
  180. this.y = v.y;
  181. return this;
  182. },
  183. add: function ( a, b ) {
  184. this.x = a.x + b.x;
  185. this.y = a.y + b.y;
  186. return this;
  187. },
  188. addSelf: function ( v ) {
  189. this.x += v.x;
  190. this.y += v.y;
  191. return this;
  192. },
  193. sub: function ( a, b ) {
  194. this.x = a.x - b.x;
  195. this.y = a.y - b.y;
  196. return this;
  197. },
  198. subSelf: function ( v ) {
  199. this.x -= v.x;
  200. this.y -= v.y;
  201. return this;
  202. },
  203. multiplyScalar: function ( s ) {
  204. this.x *= s;
  205. this.y *= s;
  206. return this;
  207. },
  208. divideScalar: function ( s ) {
  209. if ( s ) {
  210. this.x /= s;
  211. this.y /= s;
  212. } else {
  213. this.set( 0, 0 );
  214. }
  215. return this;
  216. },
  217. negate: function() {
  218. return this.multiplyScalar( - 1 );
  219. },
  220. dot: function ( v ) {
  221. return this.x * v.x + this.y * v.y;
  222. },
  223. lengthSq: function () {
  224. return this.x * this.x + this.y * this.y;
  225. },
  226. length: function () {
  227. return Math.sqrt( this.lengthSq() );
  228. },
  229. normalize: function () {
  230. return this.divideScalar( this.length() );
  231. },
  232. distanceTo: function ( v ) {
  233. return Math.sqrt( this.distanceToSquared( v ) );
  234. },
  235. distanceToSquared: function ( v ) {
  236. var dx = this.x - v.x, dy = this.y - v.y;
  237. return dx * dx + dy * dy;
  238. },
  239. setLength: function ( l ) {
  240. return this.normalize().multiplyScalar( l );
  241. },
  242. lerpSelf: function ( v, alpha ) {
  243. this.x += ( v.x - this.x ) * alpha;
  244. this.y += ( v.y - this.y ) * alpha;
  245. return this;
  246. },
  247. equals: function( v ) {
  248. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  249. },
  250. isZero: function () {
  251. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  252. },
  253. clone: function () {
  254. return new THREE.Vector2( this.x, this.y );
  255. }
  256. };
  257. /**
  258. * @author mr.doob / http://mrdoob.com/
  259. * @author kile / http://kile.stravaganza.org/
  260. * @author philogb / http://blog.thejit.org/
  261. * @author mikael emtinger / http://gomo.se/
  262. * @author egraether / http://egraether.com/
  263. */
  264. THREE.Vector3 = function ( x, y, z ) {
  265. this.x = x || 0;
  266. this.y = y || 0;
  267. this.z = z || 0;
  268. };
  269. THREE.Vector3.prototype = {
  270. constructor: THREE.Vector3,
  271. set: function ( x, y, z ) {
  272. this.x = x;
  273. this.y = y;
  274. this.z = z;
  275. return this;
  276. },
  277. setX: function ( x ) {
  278. this.x = x;
  279. return this;
  280. },
  281. setY: function ( y ) {
  282. this.y = y;
  283. return this;
  284. },
  285. setZ: function ( z ) {
  286. this.z = z;
  287. return this;
  288. },
  289. copy: function ( v ) {
  290. this.x = v.x;
  291. this.y = v.y;
  292. this.z = v.z;
  293. return this;
  294. },
  295. add: function ( a, b ) {
  296. this.x = a.x + b.x;
  297. this.y = a.y + b.y;
  298. this.z = a.z + b.z;
  299. return this;
  300. },
  301. addSelf: function ( v ) {
  302. this.x += v.x;
  303. this.y += v.y;
  304. this.z += v.z;
  305. return this;
  306. },
  307. addScalar: function ( s ) {
  308. this.x += s;
  309. this.y += s;
  310. this.z += s;
  311. return this;
  312. },
  313. sub: function ( a, b ) {
  314. this.x = a.x - b.x;
  315. this.y = a.y - b.y;
  316. this.z = a.z - b.z;
  317. return this;
  318. },
  319. subSelf: function ( v ) {
  320. this.x -= v.x;
  321. this.y -= v.y;
  322. this.z -= v.z;
  323. return this;
  324. },
  325. multiply: function ( a, b ) {
  326. this.x = a.x * b.x;
  327. this.y = a.y * b.y;
  328. this.z = a.z * b.z;
  329. return this;
  330. },
  331. multiplySelf: function ( v ) {
  332. this.x *= v.x;
  333. this.y *= v.y;
  334. this.z *= v.z;
  335. return this;
  336. },
  337. multiplyScalar: function ( s ) {
  338. this.x *= s;
  339. this.y *= s;
  340. this.z *= s;
  341. return this;
  342. },
  343. divideSelf: function ( v ) {
  344. this.x /= v.x;
  345. this.y /= v.y;
  346. this.z /= v.z;
  347. return this;
  348. },
  349. divideScalar: function ( s ) {
  350. if ( s ) {
  351. this.x /= s;
  352. this.y /= s;
  353. this.z /= s;
  354. } else {
  355. this.x = 0;
  356. this.y = 0;
  357. this.z = 0;
  358. }
  359. return this;
  360. },
  361. negate: function() {
  362. return this.multiplyScalar( - 1 );
  363. },
  364. dot: function ( v ) {
  365. return this.x * v.x + this.y * v.y + this.z * v.z;
  366. },
  367. lengthSq: function () {
  368. return this.x * this.x + this.y * this.y + this.z * this.z;
  369. },
  370. length: function () {
  371. return Math.sqrt( this.lengthSq() );
  372. },
  373. lengthManhattan: function () {
  374. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  375. },
  376. normalize: function () {
  377. return this.divideScalar( this.length() );
  378. },
  379. setLength: function ( l ) {
  380. return this.normalize().multiplyScalar( l );
  381. },
  382. lerpSelf: function ( v, alpha ) {
  383. this.x += ( v.x - this.x ) * alpha;
  384. this.y += ( v.y - this.y ) * alpha;
  385. this.z += ( v.z - this.z ) * alpha;
  386. return this;
  387. },
  388. cross: function ( a, b ) {
  389. this.x = a.y * b.z - a.z * b.y;
  390. this.y = a.z * b.x - a.x * b.z;
  391. this.z = a.x * b.y - a.y * b.x;
  392. return this;
  393. },
  394. crossSelf: function ( v ) {
  395. var x = this.x, y = this.y, z = this.z;
  396. this.x = y * v.z - z * v.y;
  397. this.y = z * v.x - x * v.z;
  398. this.z = x * v.y - y * v.x;
  399. return this;
  400. },
  401. distanceTo: function ( v ) {
  402. return Math.sqrt( this.distanceToSquared( v ) );
  403. },
  404. distanceToSquared: function ( v ) {
  405. return new THREE.Vector3().sub( this, v ).lengthSq();
  406. },
  407. getPositionFromMatrix: function ( m ) {
  408. this.x = m.elements[12];
  409. this.y = m.elements[13];
  410. this.z = m.elements[14];
  411. return this;
  412. },
  413. getRotationFromMatrix: function ( m, scale ) {
  414. var sx = scale ? scale.x : 1;
  415. var sy = scale ? scale.y : 1;
  416. var sz = scale ? scale.z : 1;
  417. var m11 = m.elements[0] / sx, m12 = m.elements[4] / sy, m13 = m.elements[8] / sz;
  418. var m21 = m.elements[1] / sx, m22 = m.elements[5] / sy, m23 = m.elements[9] / sz;
  419. var m33 = m.elements[10] / sz;
  420. this.y = Math.asin( m13 );
  421. var cosY = Math.cos( this.y );
  422. if ( Math.abs( cosY ) > 0.00001 ) {
  423. this.x = Math.atan2( - m23 / cosY, m33 / cosY );
  424. this.z = Math.atan2( - m12 / cosY, m11 / cosY );
  425. } else {
  426. this.x = 0;
  427. this.z = Math.atan2( m21, m22 );
  428. }
  429. return this;
  430. },
  431. /*
  432. // from http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  433. // order XYZ
  434. getEulerXYZFromQuaternion: function ( q ) {
  435. 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 ) );
  436. this.y = Math.asin( 2 * ( q.x * q.z + q.y * q.w ) );
  437. 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 ) );
  438. },
  439. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/index.htm
  440. // order YZX (assuming heading == y, attitude == z, bank == x)
  441. getEulerYZXFromQuaternion: function ( q ) {
  442. var sqw = q.w * q.w;
  443. var sqx = q.x * q.x;
  444. var sqy = q.y * q.y;
  445. var sqz = q.z * q.z;
  446. var unit = sqx + sqy + sqz + sqw; // if normalised is one, otherwise is correction factor
  447. var test = q.x * q.y + q.z * q.w;
  448. if ( test > 0.499 * unit ) { // singularity at north pole
  449. this.y = 2 * Math.atan2( q.x, q.w );
  450. this.z = Math.PI / 2;
  451. this.x = 0;
  452. return;
  453. }
  454. if ( test < -0.499 * unit ) { // singularity at south pole
  455. this.y = -2 * Math.atan2( q.x, q.w );
  456. this.z = -Math.PI / 2;
  457. this.x = 0;
  458. return;
  459. }
  460. this.y = Math.atan2( 2 * q.y * q.w - 2 * q.x * q.z, sqx - sqy - sqz + sqw );
  461. this.z = Math.asin( 2 * test / unit );
  462. this.x = Math.atan2( 2 * q.x * q.w - 2 * q.y * q.z, -sqx + sqy - sqz + sqw );
  463. },
  464. */
  465. getScaleFromMatrix: function ( m ) {
  466. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  467. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  468. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  469. this.x = sx;
  470. this.y = sy;
  471. this.z = sz;
  472. },
  473. equals: function ( v ) {
  474. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  475. },
  476. isZero: function () {
  477. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  478. },
  479. clone: function () {
  480. return new THREE.Vector3( this.x, this.y, this.z );
  481. }
  482. };
  483. /**
  484. * @author supereggbert / http://www.paulbrunt.co.uk/
  485. * @author philogb / http://blog.thejit.org/
  486. * @author mikael emtinger / http://gomo.se/
  487. * @author egraether / http://egraether.com/
  488. */
  489. THREE.Vector4 = function ( x, y, z, w ) {
  490. this.x = x || 0;
  491. this.y = y || 0;
  492. this.z = z || 0;
  493. this.w = ( w !== undefined ) ? w : 1;
  494. };
  495. THREE.Vector4.prototype = {
  496. constructor: THREE.Vector4,
  497. set: function ( x, y, z, w ) {
  498. this.x = x;
  499. this.y = y;
  500. this.z = z;
  501. this.w = w;
  502. return this;
  503. },
  504. copy: function ( v ) {
  505. this.x = v.x;
  506. this.y = v.y;
  507. this.z = v.z;
  508. this.w = ( v.w !== undefined ) ? v.w : 1;
  509. return this;
  510. },
  511. add: function ( a, b ) {
  512. this.x = a.x + b.x;
  513. this.y = a.y + b.y;
  514. this.z = a.z + b.z;
  515. this.w = a.w + b.w;
  516. return this;
  517. },
  518. addSelf: function ( v ) {
  519. this.x += v.x;
  520. this.y += v.y;
  521. this.z += v.z;
  522. this.w += v.w;
  523. return this;
  524. },
  525. sub: function ( a, b ) {
  526. this.x = a.x - b.x;
  527. this.y = a.y - b.y;
  528. this.z = a.z - b.z;
  529. this.w = a.w - b.w;
  530. return this;
  531. },
  532. subSelf: function ( v ) {
  533. this.x -= v.x;
  534. this.y -= v.y;
  535. this.z -= v.z;
  536. this.w -= v.w;
  537. return this;
  538. },
  539. multiplyScalar: function ( s ) {
  540. this.x *= s;
  541. this.y *= s;
  542. this.z *= s;
  543. this.w *= s;
  544. return this;
  545. },
  546. divideScalar: function ( s ) {
  547. if ( s ) {
  548. this.x /= s;
  549. this.y /= s;
  550. this.z /= s;
  551. this.w /= s;
  552. } else {
  553. this.x = 0;
  554. this.y = 0;
  555. this.z = 0;
  556. this.w = 1;
  557. }
  558. return this;
  559. },
  560. negate: function() {
  561. return this.multiplyScalar( -1 );
  562. },
  563. dot: function ( v ) {
  564. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  565. },
  566. lengthSq: function () {
  567. return this.dot( this );
  568. },
  569. length: function () {
  570. return Math.sqrt( this.lengthSq() );
  571. },
  572. normalize: function () {
  573. return this.divideScalar( this.length() );
  574. },
  575. setLength: function ( l ) {
  576. return this.normalize().multiplyScalar( l );
  577. },
  578. lerpSelf: function ( v, alpha ) {
  579. this.x += ( v.x - this.x ) * alpha;
  580. this.y += ( v.y - this.y ) * alpha;
  581. this.z += ( v.z - this.z ) * alpha;
  582. this.w += ( v.w - this.w ) * alpha;
  583. return this;
  584. },
  585. clone: function () {
  586. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  587. }
  588. };
  589. /**
  590. * @author mrdoob / http://mrdoob.com/
  591. * @author alteredq / http://alteredqualia.com/
  592. */
  593. THREE.Frustum = function ( ) {
  594. this.planes = [
  595. new THREE.Vector4(),
  596. new THREE.Vector4(),
  597. new THREE.Vector4(),
  598. new THREE.Vector4(),
  599. new THREE.Vector4(),
  600. new THREE.Vector4()
  601. ];
  602. };
  603. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  604. var i, plane,
  605. planes = this.planes;
  606. var me = m.elements;
  607. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  608. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  609. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  610. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  611. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  612. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  613. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  614. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  615. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  616. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  617. for ( i = 0; i < 6; i ++ ) {
  618. plane = planes[ i ];
  619. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  620. }
  621. };
  622. THREE.Frustum.prototype.contains = function ( object ) {
  623. var distance,
  624. planes = this.planes,
  625. matrix = object.matrixWorld,
  626. me = matrix.elements,
  627. scale = THREE.Frustum.__v1.set( matrix.getColumnX().length(), matrix.getColumnY().length(), matrix.getColumnZ().length() ),
  628. radius = - object.geometry.boundingSphere.radius * Math.max( scale.x, Math.max( scale.y, scale.z ) );
  629. for ( var i = 0; i < 6; i ++ ) {
  630. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  631. if ( distance <= radius ) return false;
  632. }
  633. return true;
  634. };
  635. THREE.Frustum.__v1 = new THREE.Vector3();
  636. /**
  637. * @author mr.doob / http://mrdoob.com/
  638. */
  639. THREE.Ray = function ( origin, direction ) {
  640. this.origin = origin || new THREE.Vector3();
  641. this.direction = direction || new THREE.Vector3();
  642. var precision = 0.0001;
  643. this.setPrecision = function ( value ) {
  644. precision = value;
  645. };
  646. var a = new THREE.Vector3();
  647. var b = new THREE.Vector3();
  648. var c = new THREE.Vector3();
  649. var d = new THREE.Vector3();
  650. var originCopy = new THREE.Vector3();
  651. var directionCopy = new THREE.Vector3();
  652. var vector = new THREE.Vector3();
  653. var normal = new THREE.Vector3();
  654. var intersectPoint = new THREE.Vector3()
  655. this.intersectObject = function ( object ) {
  656. var intersect, intersects = [];
  657. if ( object instanceof THREE.Particle ) {
  658. var distance = distanceFromIntersection( this.origin, this.direction, object.matrixWorld.getPosition() );
  659. if ( distance > object.scale.x ) {
  660. return [];
  661. }
  662. intersect = {
  663. distance: distance,
  664. point: object.position,
  665. face: null,
  666. object: object
  667. };
  668. intersects.push( intersect );
  669. } else if ( object instanceof THREE.Mesh ) {
  670. // Checking boundingSphere
  671. var distance = distanceFromIntersection( this.origin, this.direction, object.matrixWorld.getPosition() );
  672. var scale = THREE.Frustum.__v1.set( object.matrixWorld.getColumnX().length(), object.matrixWorld.getColumnY().length(), object.matrixWorld.getColumnZ().length() );
  673. if ( distance > object.geometry.boundingSphere.radius * Math.max( scale.x, Math.max( scale.y, scale.z ) ) ) {
  674. return intersects;
  675. }
  676. // Checking faces
  677. var f, fl, face, dot, scalar,
  678. geometry = object.geometry,
  679. vertices = geometry.vertices,
  680. objMatrix;
  681. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  682. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  683. face = geometry.faces[ f ];
  684. originCopy.copy( this.origin );
  685. directionCopy.copy( this.direction );
  686. objMatrix = object.matrixWorld;
  687. // determine if ray intersects the plane of the face
  688. // note: this works regardless of the direction of the face normal
  689. vector = objMatrix.multiplyVector3( vector.copy( face.centroid ) ).subSelf( originCopy );
  690. normal = object.matrixRotationWorld.multiplyVector3( normal.copy( face.normal ) );
  691. dot = directionCopy.dot( normal );
  692. // bail if ray and plane are parallel
  693. if ( Math.abs( dot ) < precision ) continue;
  694. // calc distance to plane
  695. scalar = normal.dot( vector ) / dot;
  696. // if negative distance, then plane is behind ray
  697. if ( scalar < 0 ) continue;
  698. if ( object.doubleSided || ( object.flipSided ? dot > 0 : dot < 0 ) ) {
  699. intersectPoint.add( originCopy, directionCopy.multiplyScalar( scalar ) );
  700. if ( face instanceof THREE.Face3 ) {
  701. a = objMatrix.multiplyVector3( a.copy( vertices[ face.a ] ) );
  702. b = objMatrix.multiplyVector3( b.copy( vertices[ face.b ] ) );
  703. c = objMatrix.multiplyVector3( c.copy( vertices[ face.c ] ) );
  704. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  705. intersect = {
  706. distance: originCopy.distanceTo( intersectPoint ),
  707. point: intersectPoint.clone(),
  708. face: face,
  709. object: object
  710. };
  711. intersects.push( intersect );
  712. }
  713. } else if ( face instanceof THREE.Face4 ) {
  714. a = objMatrix.multiplyVector3( a.copy( vertices[ face.a ] ) );
  715. b = objMatrix.multiplyVector3( b.copy( vertices[ face.b ] ) );
  716. c = objMatrix.multiplyVector3( c.copy( vertices[ face.c ] ) );
  717. d = objMatrix.multiplyVector3( d.copy( vertices[ face.d ] ) );
  718. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  719. intersect = {
  720. distance: originCopy.distanceTo( intersectPoint ),
  721. point: intersectPoint.clone(),
  722. face: face,
  723. object: object
  724. };
  725. intersects.push( intersect );
  726. }
  727. }
  728. }
  729. }
  730. }
  731. return intersects;
  732. }
  733. this.intersectObjects = function ( objects ) {
  734. var intersects = [];
  735. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  736. Array.prototype.push.apply( intersects, this.intersectObject( objects[ i ] ) );
  737. }
  738. intersects.sort( function ( a, b ) { return a.distance - b.distance; } );
  739. return intersects;
  740. };
  741. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  742. var dot, intersect, distance;
  743. function distanceFromIntersection( origin, direction, position ) {
  744. v0.sub( position, origin );
  745. dot = v0.dot( direction );
  746. intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  747. distance = position.distanceTo( intersect );
  748. return distance;
  749. }
  750. // http://www.blackpawn.com/texts/pointinpoly/default.html
  751. var dot00, dot01, dot02, dot11, dot12, invDenom, u, v;
  752. function pointInFace3( p, a, b, c ) {
  753. v0.sub( c, a );
  754. v1.sub( b, a );
  755. v2.sub( p, a );
  756. dot00 = v0.dot( v0 );
  757. dot01 = v0.dot( v1 );
  758. dot02 = v0.dot( v2 );
  759. dot11 = v1.dot( v1 );
  760. dot12 = v1.dot( v2 );
  761. invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  762. u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  763. v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  764. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  765. }
  766. };
  767. /**
  768. * @author mr.doob / http://mrdoob.com/
  769. */
  770. THREE.Rectangle = function () {
  771. var _left, _top, _right, _bottom,
  772. _width, _height, _isEmpty = true;
  773. function resize() {
  774. _width = _right - _left;
  775. _height = _bottom - _top;
  776. }
  777. this.getX = function () {
  778. return _left;
  779. };
  780. this.getY = function () {
  781. return _top;
  782. };
  783. this.getWidth = function () {
  784. return _width;
  785. };
  786. this.getHeight = function () {
  787. return _height;
  788. };
  789. this.getLeft = function() {
  790. return _left;
  791. };
  792. this.getTop = function() {
  793. return _top;
  794. };
  795. this.getRight = function() {
  796. return _right;
  797. };
  798. this.getBottom = function() {
  799. return _bottom;
  800. };
  801. this.set = function ( left, top, right, bottom ) {
  802. _isEmpty = false;
  803. _left = left; _top = top;
  804. _right = right; _bottom = bottom;
  805. resize();
  806. };
  807. this.addPoint = function ( x, y ) {
  808. if ( _isEmpty ) {
  809. _isEmpty = false;
  810. _left = x; _top = y;
  811. _right = x; _bottom = y;
  812. resize();
  813. } else {
  814. _left = _left < x ? _left : x; // Math.min( _left, x );
  815. _top = _top < y ? _top : y; // Math.min( _top, y );
  816. _right = _right > x ? _right : x; // Math.max( _right, x );
  817. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  818. resize();
  819. }
  820. };
  821. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  822. if (_isEmpty) {
  823. _isEmpty = false;
  824. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  825. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  826. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  827. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  828. resize();
  829. } else {
  830. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  831. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  832. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  833. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  834. resize();
  835. };
  836. };
  837. this.addRectangle = function ( r ) {
  838. if ( _isEmpty ) {
  839. _isEmpty = false;
  840. _left = r.getLeft(); _top = r.getTop();
  841. _right = r.getRight(); _bottom = r.getBottom();
  842. resize();
  843. } else {
  844. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  845. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  846. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  847. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  848. resize();
  849. }
  850. };
  851. this.inflate = function ( v ) {
  852. _left -= v; _top -= v;
  853. _right += v; _bottom += v;
  854. resize();
  855. };
  856. this.minSelf = function ( r ) {
  857. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  858. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  859. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  860. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  861. resize();
  862. };
  863. this.intersects = function ( r ) {
  864. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  865. if ( _right < r.getLeft() ) return false;
  866. if ( _left > r.getRight() ) return false;
  867. if ( _bottom < r.getTop() ) return false;
  868. if ( _top > r.getBottom() ) return false;
  869. return true;
  870. };
  871. this.empty = function () {
  872. _isEmpty = true;
  873. _left = 0; _top = 0;
  874. _right = 0; _bottom = 0;
  875. resize();
  876. };
  877. this.isEmpty = function () {
  878. return _isEmpty;
  879. };
  880. };
  881. /**
  882. * @author alteredq / http://alteredqualia.com/
  883. */
  884. THREE.Math = {
  885. // Clamp value to range <a, b>
  886. clamp: function ( x, a, b ) {
  887. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  888. },
  889. // Clamp value to range <a, inf)
  890. clampBottom: function ( x, a ) {
  891. return x < a ? a : x;
  892. },
  893. // Linear mapping from range <a1, a2> to range <b1, b2>
  894. mapLinear: function ( x, a1, a2, b1, b2 ) {
  895. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  896. },
  897. // Random float from <0, 1> with 16 bits of randomness
  898. // (standard Math.random() creates repetitive patterns when applied over larger space)
  899. random16: function () {
  900. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  901. },
  902. // Random integer from <low, high> interval
  903. randInt: function ( low, high ) {
  904. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  905. },
  906. // Random float from <low, high> interval
  907. randFloat: function ( low, high ) {
  908. return low + Math.random() * ( high - low );
  909. },
  910. // Random float from <-range/2, range/2> interval
  911. randFloatSpread: function ( range ) {
  912. return range * ( 0.5 - Math.random() );
  913. },
  914. sign: function ( x ) {
  915. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  916. }
  917. };
  918. /**
  919. * @author alteredq / http://alteredqualia.com/
  920. */
  921. THREE.Matrix3 = function () {
  922. this.elements = new Float32Array(9);
  923. };
  924. THREE.Matrix3.prototype = {
  925. constructor: THREE.Matrix3,
  926. getInverse: function ( matrix ) {
  927. // input: THREE.Matrix4
  928. // ( based on http://code.google.com/p/webgl-mjs/ )
  929. var me = matrix.elements;
  930. var a11 = me[10] * me[5] - me[6] * me[9];
  931. var a21 = - me[10] * me[1] + me[2] * me[9];
  932. var a31 = me[6] * me[1] - me[2] * me[5];
  933. var a12 = - me[10] * me[4] + me[6] * me[8];
  934. var a22 = me[10] * me[0] - me[2] * me[8];
  935. var a32 = - me[6] * me[0] + me[2] * me[4];
  936. var a13 = me[9] * me[4] - me[5] * me[8];
  937. var a23 = - me[9] * me[0] + me[1] * me[8];
  938. var a33 = me[5] * me[0] - me[1] * me[4];
  939. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  940. // no inverse
  941. if ( det === 0 ) {
  942. console.warn( "Matrix3.getInverse(): determinant == 0" );
  943. }
  944. var idet = 1.0 / det;
  945. var m = this.elements;
  946. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  947. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  948. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  949. return this;
  950. },
  951. transpose: function () {
  952. var tmp, m = this.elements;
  953. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  954. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  955. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  956. return this;
  957. },
  958. transposeIntoArray: function ( r ) {
  959. var m = this.m;
  960. r[ 0 ] = m[ 0 ];
  961. r[ 1 ] = m[ 3 ];
  962. r[ 2 ] = m[ 6 ];
  963. r[ 3 ] = m[ 1 ];
  964. r[ 4 ] = m[ 4 ];
  965. r[ 5 ] = m[ 7 ];
  966. r[ 6 ] = m[ 2 ];
  967. r[ 7 ] = m[ 5 ];
  968. r[ 8 ] = m[ 8 ];
  969. return this;
  970. }
  971. };
  972. /**
  973. * @author mr.doob / http://mrdoob.com/
  974. * @author supereggbert / http://www.paulbrunt.co.uk/
  975. * @author philogb / http://blog.thejit.org/
  976. * @author jordi_ros / http://plattsoft.com
  977. * @author D1plo1d / http://github.com/D1plo1d
  978. * @author alteredq / http://alteredqualia.com/
  979. * @author mikael emtinger / http://gomo.se/
  980. * @author timknip / http://www.floorplanner.com/
  981. */
  982. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  983. this.elements = new Float32Array(16);
  984. this.set(
  985. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  986. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  987. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  988. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  989. );
  990. };
  991. THREE.Matrix4.prototype = {
  992. constructor: THREE.Matrix4,
  993. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  994. var te = this.elements;
  995. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  996. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  997. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  998. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  999. return this;
  1000. },
  1001. identity: function () {
  1002. this.set(
  1003. 1, 0, 0, 0,
  1004. 0, 1, 0, 0,
  1005. 0, 0, 1, 0,
  1006. 0, 0, 0, 1
  1007. );
  1008. return this;
  1009. },
  1010. copy: function ( m ) {
  1011. var me = m.elements;
  1012. this.set(
  1013. me[0], me[4], me[8], me[12],
  1014. me[1], me[5], me[9], me[13],
  1015. me[2], me[6], me[10], me[14],
  1016. me[3], me[7], me[11], me[15]
  1017. );
  1018. return this;
  1019. },
  1020. lookAt: function ( eye, target, up ) {
  1021. var te = this.elements;
  1022. var x = THREE.Matrix4.__v1;
  1023. var y = THREE.Matrix4.__v2;
  1024. var z = THREE.Matrix4.__v3;
  1025. z.sub( eye, target ).normalize();
  1026. if ( z.length() === 0 ) {
  1027. z.z = 1;
  1028. }
  1029. x.cross( up, z ).normalize();
  1030. if ( x.length() === 0 ) {
  1031. z.x += 0.0001;
  1032. x.cross( up, z ).normalize();
  1033. }
  1034. y.cross( z, x );
  1035. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1036. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1037. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1038. return this;
  1039. },
  1040. multiply: function ( a, b ) {
  1041. var ae = a.elements,
  1042. be = b.elements,
  1043. te = this.elements;
  1044. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1045. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1046. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1047. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1048. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1049. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1050. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1051. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1052. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1053. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1054. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1055. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1056. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1057. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1058. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1059. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1060. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1061. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1062. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1063. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1064. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1065. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1066. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1067. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1068. return this;
  1069. },
  1070. multiplySelf: function ( m ) {
  1071. return this.multiply( this, m );
  1072. },
  1073. multiplyToArray: function ( a, b, r ) {
  1074. var te = this.elements;
  1075. this.multiply( a, b );
  1076. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1077. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1078. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1079. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1080. return this;
  1081. },
  1082. multiplyScalar: function ( s ) {
  1083. var te = this.elements;
  1084. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1085. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1086. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1087. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1088. return this;
  1089. },
  1090. multiplyVector3: function ( v ) {
  1091. var te = this.elements;
  1092. var vx = v.x, vy = v.y, vz = v.z;
  1093. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1094. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1095. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1096. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1097. return v;
  1098. },
  1099. multiplyVector4: function ( v ) {
  1100. var te = this.elements;
  1101. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1102. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1103. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1104. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1105. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1106. return v;
  1107. },
  1108. rotateAxis: function ( v ) {
  1109. var te = this.elements;
  1110. var vx = v.x, vy = v.y, vz = v.z;
  1111. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1112. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1113. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1114. v.normalize();
  1115. return v;
  1116. },
  1117. crossVector: function ( a ) {
  1118. var te = this.elements;
  1119. var v = new THREE.Vector4();
  1120. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1121. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1122. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1123. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1124. return v;
  1125. },
  1126. determinant: function () {
  1127. var te = this.elements;
  1128. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1129. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1130. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1131. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1132. //TODO: make this more efficient
  1133. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1134. return (
  1135. n14 * n23 * n32 * n41-
  1136. n13 * n24 * n32 * n41-
  1137. n14 * n22 * n33 * n41+
  1138. n12 * n24 * n33 * n41+
  1139. n13 * n22 * n34 * n41-
  1140. n12 * n23 * n34 * n41-
  1141. n14 * n23 * n31 * n42+
  1142. n13 * n24 * n31 * n42+
  1143. n14 * n21 * n33 * n42-
  1144. n11 * n24 * n33 * n42-
  1145. n13 * n21 * n34 * n42+
  1146. n11 * n23 * n34 * n42+
  1147. n14 * n22 * n31 * n43-
  1148. n12 * n24 * n31 * n43-
  1149. n14 * n21 * n32 * n43+
  1150. n11 * n24 * n32 * n43+
  1151. n12 * n21 * n34 * n43-
  1152. n11 * n22 * n34 * n43-
  1153. n13 * n22 * n31 * n44+
  1154. n12 * n23 * n31 * n44+
  1155. n13 * n21 * n32 * n44-
  1156. n11 * n23 * n32 * n44-
  1157. n12 * n21 * n33 * n44+
  1158. n11 * n22 * n33 * n44
  1159. );
  1160. },
  1161. transpose: function () {
  1162. var te = this.elements;
  1163. var tmp;
  1164. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1165. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1166. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1167. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1168. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1169. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1170. return this;
  1171. },
  1172. flattenToArray: function ( flat ) {
  1173. var te = this.elements;
  1174. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1175. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1176. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1177. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1178. return flat;
  1179. },
  1180. flattenToArrayOffset: function( flat, offset ) {
  1181. var te = this.elements;
  1182. flat[ offset ] = te[0];
  1183. flat[ offset + 1 ] = te[1];
  1184. flat[ offset + 2 ] = te[2];
  1185. flat[ offset + 3 ] = te[3];
  1186. flat[ offset + 4 ] = te[4];
  1187. flat[ offset + 5 ] = te[5];
  1188. flat[ offset + 6 ] = te[6];
  1189. flat[ offset + 7 ] = te[7];
  1190. flat[ offset + 8 ] = te[8];
  1191. flat[ offset + 9 ] = te[9];
  1192. flat[ offset + 10 ] = te[10];
  1193. flat[ offset + 11 ] = te[11];
  1194. flat[ offset + 12 ] = te[12];
  1195. flat[ offset + 13 ] = te[13];
  1196. flat[ offset + 14 ] = te[14];
  1197. flat[ offset + 15 ] = te[15];
  1198. return flat;
  1199. },
  1200. getPosition: function () {
  1201. var te = this.elements;
  1202. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1203. },
  1204. setPosition: function ( v ) {
  1205. var te = this.elements;
  1206. te[12] = v.x;
  1207. te[13] = v.y;
  1208. te[14] = v.z;
  1209. return this;
  1210. },
  1211. getColumnX: function () {
  1212. var te = this.elements;
  1213. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1214. },
  1215. getColumnY: function () {
  1216. var te = this.elements;
  1217. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1218. },
  1219. getColumnZ: function() {
  1220. var te = this.elements;
  1221. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1222. },
  1223. getInverse: function ( m ) {
  1224. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1225. var te = this.elements;
  1226. var me = m.elements;
  1227. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1228. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1229. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1230. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1231. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1232. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1233. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1234. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1235. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1236. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1237. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1238. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1239. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1240. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1241. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1242. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1243. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1244. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1245. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1246. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1247. this.multiplyScalar( 1 / m.determinant() );
  1248. return this;
  1249. },
  1250. setRotationFromEuler: function( v, order ) {
  1251. var te = this.elements;
  1252. var x = v.x, y = v.y, z = v.z;
  1253. var a = Math.cos( x ), b = Math.sin( x );
  1254. var c = Math.cos( y ), d = Math.sin( y );
  1255. var e = Math.cos( z ), f = Math.sin( z );
  1256. switch ( order ) {
  1257. case 'YXZ':
  1258. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1259. te[0] = ce + df * b;
  1260. te[4] = de * b - cf;
  1261. te[8] = a * d;
  1262. te[1] = a * f;
  1263. te[5] = a * e;
  1264. te[9] = - b;
  1265. te[2] = cf * b - de;
  1266. te[6] = df + ce * b;
  1267. te[10] = a * c;
  1268. break;
  1269. case 'ZXY':
  1270. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1271. te[0] = ce - df * b;
  1272. te[4] = - a * f;
  1273. te[8] = de + cf * b;
  1274. te[1] = cf + de * b;
  1275. te[5] = a * e;
  1276. te[9] = df - ce * b;
  1277. te[2] = - a * d;
  1278. te[6] = b;
  1279. te[10] = a * c;
  1280. break;
  1281. case 'ZYX':
  1282. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1283. te[0] = c * e;
  1284. te[4] = be * d - af;
  1285. te[8] = ae * d + bf;
  1286. te[1] = c * f;
  1287. te[5] = bf * d + ae;
  1288. te[9] = af * d - be;
  1289. te[2] = - d;
  1290. te[6] = b * c;
  1291. te[10] = a * c;
  1292. break;
  1293. case 'YZX':
  1294. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1295. te[0] = c * e;
  1296. te[4] = bd - ac * f;
  1297. te[8] = bc * f + ad;
  1298. te[1] = f;
  1299. te[5] = a * e;
  1300. te[9] = - b * e;
  1301. te[2] = - d * e;
  1302. te[6] = ad * f + bc;
  1303. te[10] = ac - bd * f;
  1304. break;
  1305. case 'XZY':
  1306. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1307. te[0] = c * e;
  1308. te[4] = - f;
  1309. te[8] = d * e;
  1310. te[1] = ac * f + bd;
  1311. te[5] = a * e;
  1312. te[9] = ad * f - bc;
  1313. te[2] = bc * f - ad;
  1314. te[6] = b * e;
  1315. te[10] = bd * f + ac;
  1316. break;
  1317. default: // 'XYZ'
  1318. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1319. te[0] = c * e;
  1320. te[4] = - c * f;
  1321. te[8] = d;
  1322. te[1] = af + be * d;
  1323. te[5] = ae - bf * d;
  1324. te[9] = - b * c;
  1325. te[2] = bf - ae * d;
  1326. te[6] = be + af * d;
  1327. te[10] = a * c;
  1328. break;
  1329. }
  1330. return this;
  1331. },
  1332. setRotationFromQuaternion: function( q ) {
  1333. var te = this.elements;
  1334. var x = q.x, y = q.y, z = q.z, w = q.w;
  1335. var x2 = x + x, y2 = y + y, z2 = z + z;
  1336. var xx = x * x2, xy = x * y2, xz = x * z2;
  1337. var yy = y * y2, yz = y * z2, zz = z * z2;
  1338. var wx = w * x2, wy = w * y2, wz = w * z2;
  1339. te[0] = 1 - ( yy + zz );
  1340. te[4] = xy - wz;
  1341. te[8] = xz + wy;
  1342. te[1] = xy + wz;
  1343. te[5] = 1 - ( xx + zz );
  1344. te[9] = yz - wx;
  1345. te[2] = xz - wy;
  1346. te[6] = yz + wx;
  1347. te[10] = 1 - ( xx + yy );
  1348. return this;
  1349. },
  1350. compose: function ( translation, rotation, scale ) {
  1351. var te = this.elements;
  1352. var mRotation = THREE.Matrix4.__m1;
  1353. var mScale = THREE.Matrix4.__m2;
  1354. mRotation.identity();
  1355. mRotation.setRotationFromQuaternion( rotation );
  1356. mScale.makeScale( scale.x, scale.y, scale.z );
  1357. this.multiply( mRotation, mScale );
  1358. te[12] = translation.x;
  1359. te[13] = translation.y;
  1360. te[14] = translation.z;
  1361. return this;
  1362. },
  1363. decompose: function ( translation, rotation, scale ) {
  1364. // grab the axis vectors
  1365. var te = this.elements;
  1366. var x = THREE.Matrix4.__v1;
  1367. var y = THREE.Matrix4.__v2;
  1368. var z = THREE.Matrix4.__v3;
  1369. x.set( te[0], te[1], te[2] );
  1370. y.set( te[4], te[5], te[6] );
  1371. z.set( te[8], te[9], te[10] );
  1372. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1373. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1374. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1375. scale.x = x.length();
  1376. scale.y = y.length();
  1377. scale.z = z.length();
  1378. translation.x = te[12];
  1379. translation.y = te[13];
  1380. translation.z = te[14];
  1381. // scale the rotation part
  1382. var matrix = THREE.Matrix4.__m1;
  1383. matrix.copy( this );
  1384. matrix.elements[0] /= scale.x;
  1385. matrix.elements[1] /= scale.x;
  1386. matrix.elements[2] /= scale.x;
  1387. matrix.elements[4] /= scale.y;
  1388. matrix.elements[5] /= scale.y;
  1389. matrix.elements[6] /= scale.y;
  1390. matrix.elements[8] /= scale.z;
  1391. matrix.elements[9] /= scale.z;
  1392. matrix.elements[10] /= scale.z;
  1393. rotation.setFromRotationMatrix( matrix );
  1394. return [ translation, rotation, scale ];
  1395. },
  1396. extractPosition: function ( m ) {
  1397. var te = this.elements;
  1398. var me = m.elements;
  1399. te[12] = me[12];
  1400. te[13] = me[13];
  1401. te[14] = me[14];
  1402. return this;
  1403. },
  1404. extractRotation: function ( m ) {
  1405. var te = this.elements;
  1406. var me = m.elements;
  1407. var vector = THREE.Matrix4.__v1;
  1408. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1409. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1410. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1411. te[0] = me[0] * scaleX;
  1412. te[1] = me[1] * scaleX;
  1413. te[2] = me[2] * scaleX;
  1414. te[4] = me[4] * scaleY;
  1415. te[5] = me[5] * scaleY;
  1416. te[6] = me[6] * scaleY;
  1417. te[8] = me[8] * scaleZ;
  1418. te[9] = me[9] * scaleZ;
  1419. te[10] = me[10] * scaleZ;
  1420. return this;
  1421. },
  1422. //
  1423. translate: function ( v ) {
  1424. var te = this.elements;
  1425. var x = v.x, y = v.y, z = v.z;
  1426. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1427. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1428. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1429. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1430. return this;
  1431. },
  1432. rotateX: function ( angle ) {
  1433. var te = this.elements;
  1434. var m12 = te[4];
  1435. var m22 = te[5];
  1436. var m32 = te[6];
  1437. var m42 = te[7];
  1438. var m13 = te[8];
  1439. var m23 = te[9];
  1440. var m33 = te[10];
  1441. var m43 = te[11];
  1442. var c = Math.cos( angle );
  1443. var s = Math.sin( angle );
  1444. te[4] = c * m12 + s * m13;
  1445. te[5] = c * m22 + s * m23;
  1446. te[6] = c * m32 + s * m33;
  1447. te[7] = c * m42 + s * m43;
  1448. te[8] = c * m13 - s * m12;
  1449. te[9] = c * m23 - s * m22;
  1450. te[10] = c * m33 - s * m32;
  1451. te[11] = c * m43 - s * m42;
  1452. return this;
  1453. },
  1454. rotateY: function ( angle ) {
  1455. var te = this.elements;
  1456. var m11 = te[0];
  1457. var m21 = te[1];
  1458. var m31 = te[2];
  1459. var m41 = te[3];
  1460. var m13 = te[8];
  1461. var m23 = te[9];
  1462. var m33 = te[10];
  1463. var m43 = te[11];
  1464. var c = Math.cos( angle );
  1465. var s = Math.sin( angle );
  1466. te[0] = c * m11 - s * m13;
  1467. te[1] = c * m21 - s * m23;
  1468. te[2] = c * m31 - s * m33;
  1469. te[3] = c * m41 - s * m43;
  1470. te[8] = c * m13 + s * m11;
  1471. te[9] = c * m23 + s * m21;
  1472. te[10] = c * m33 + s * m31;
  1473. te[11] = c * m43 + s * m41;
  1474. return this;
  1475. },
  1476. rotateZ: function ( angle ) {
  1477. var te = this.elements;
  1478. var m11 = te[0];
  1479. var m21 = te[1];
  1480. var m31 = te[2];
  1481. var m41 = te[3];
  1482. var m12 = te[4];
  1483. var m22 = te[5];
  1484. var m32 = te[6];
  1485. var m42 = te[7];
  1486. var c = Math.cos( angle );
  1487. var s = Math.sin( angle );
  1488. te[0] = c * m11 + s * m12;
  1489. te[1] = c * m21 + s * m22;
  1490. te[2] = c * m31 + s * m32;
  1491. te[3] = c * m41 + s * m42;
  1492. te[4] = c * m12 - s * m11;
  1493. te[5] = c * m22 - s * m21;
  1494. te[6] = c * m32 - s * m31;
  1495. te[7] = c * m42 - s * m41;
  1496. return this;
  1497. },
  1498. rotateByAxis: function ( axis, angle ) {
  1499. var te = this.elements;
  1500. // optimize by checking axis
  1501. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1502. return this.rotateX( angle );
  1503. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1504. return this.rotateY( angle );
  1505. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1506. return this.rotateZ( angle );
  1507. }
  1508. var x = axis.x, y = axis.y, z = axis.z;
  1509. var n = Math.sqrt(x * x + y * y + z * z);
  1510. x /= n;
  1511. y /= n;
  1512. z /= n;
  1513. var xx = x * x, yy = y * y, zz = z * z;
  1514. var c = Math.cos( angle );
  1515. var s = Math.sin( angle );
  1516. var oneMinusCosine = 1 - c;
  1517. var xy = x * y * oneMinusCosine;
  1518. var xz = x * z * oneMinusCosine;
  1519. var yz = y * z * oneMinusCosine;
  1520. var xs = x * s;
  1521. var ys = y * s;
  1522. var zs = z * s;
  1523. var r11 = xx + (1 - xx) * c;
  1524. var r21 = xy + zs;
  1525. var r31 = xz - ys;
  1526. var r12 = xy - zs;
  1527. var r22 = yy + (1 - yy) * c;
  1528. var r32 = yz + xs;
  1529. var r13 = xz + ys;
  1530. var r23 = yz - xs;
  1531. var r33 = zz + (1 - zz) * c;
  1532. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1533. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1534. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1535. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1536. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1537. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1538. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1539. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1540. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1541. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1542. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1543. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1544. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1545. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1546. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1547. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1548. return this;
  1549. },
  1550. scale: function ( v ) {
  1551. var te = this.elements;
  1552. var x = v.x, y = v.y, z = v.z;
  1553. te[0] *= x; te[4] *= y; te[8] *= z;
  1554. te[1] *= x; te[5] *= y; te[9] *= z;
  1555. te[2] *= x; te[6] *= y; te[10] *= z;
  1556. te[3] *= x; te[7] *= y; te[11] *= z;
  1557. return this;
  1558. },
  1559. //
  1560. makeTranslation: function ( x, y, z ) {
  1561. this.set(
  1562. 1, 0, 0, x,
  1563. 0, 1, 0, y,
  1564. 0, 0, 1, z,
  1565. 0, 0, 0, 1
  1566. );
  1567. return this;
  1568. },
  1569. makeRotationX: function ( theta ) {
  1570. var c = Math.cos( theta ), s = Math.sin( theta );
  1571. this.set(
  1572. 1, 0, 0, 0,
  1573. 0, c, -s, 0,
  1574. 0, s, c, 0,
  1575. 0, 0, 0, 1
  1576. );
  1577. return this;
  1578. },
  1579. makeRotationY: function ( theta ) {
  1580. var c = Math.cos( theta ), s = Math.sin( theta );
  1581. this.set(
  1582. c, 0, s, 0,
  1583. 0, 1, 0, 0,
  1584. -s, 0, c, 0,
  1585. 0, 0, 0, 1
  1586. );
  1587. return this;
  1588. },
  1589. makeRotationZ: function ( theta ) {
  1590. var c = Math.cos( theta ), s = Math.sin( theta );
  1591. this.set(
  1592. c, -s, 0, 0,
  1593. s, c, 0, 0,
  1594. 0, 0, 1, 0,
  1595. 0, 0, 0, 1
  1596. );
  1597. return this;
  1598. },
  1599. makeRotationAxis: function ( axis, angle ) {
  1600. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1601. var c = Math.cos( angle );
  1602. var s = Math.sin( angle );
  1603. var t = 1 - c;
  1604. var x = axis.x, y = axis.y, z = axis.z;
  1605. var tx = t * x, ty = t * y;
  1606. this.set(
  1607. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1608. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1609. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1610. 0, 0, 0, 1
  1611. );
  1612. return this;
  1613. },
  1614. makeScale: function ( x, y, z ) {
  1615. this.set(
  1616. x, 0, 0, 0,
  1617. 0, y, 0, 0,
  1618. 0, 0, z, 0,
  1619. 0, 0, 0, 1
  1620. );
  1621. return this;
  1622. },
  1623. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1624. var te = this.elements;
  1625. var x = 2 * near / ( right - left );
  1626. var y = 2 * near / ( top - bottom );
  1627. var a = ( right + left ) / ( right - left );
  1628. var b = ( top + bottom ) / ( top - bottom );
  1629. var c = - ( far + near ) / ( far - near );
  1630. var d = - 2 * far * near / ( far - near );
  1631. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1632. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1633. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1634. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1635. return this;
  1636. },
  1637. makePerspective: function ( fov, aspect, near, far ) {
  1638. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1639. var ymin = - ymax;
  1640. var xmin = ymin * aspect;
  1641. var xmax = ymax * aspect;
  1642. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1643. },
  1644. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1645. var te = this.elements;
  1646. var w = right - left;
  1647. var h = top - bottom;
  1648. var p = far - near;
  1649. var x = ( right + left ) / w;
  1650. var y = ( top + bottom ) / h;
  1651. var z = ( far + near ) / p;
  1652. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1653. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1654. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1655. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1656. return this;
  1657. },
  1658. clone: function () {
  1659. var te = this.elements;
  1660. return new THREE.Matrix4(
  1661. te[0], te[4], te[8], te[12],
  1662. te[1], te[5], te[9], te[13],
  1663. te[2], te[6], te[10], te[14],
  1664. te[3], te[7], te[11], te[15]
  1665. );
  1666. }
  1667. };
  1668. THREE.Matrix4.__v1 = new THREE.Vector3();
  1669. THREE.Matrix4.__v2 = new THREE.Vector3();
  1670. THREE.Matrix4.__v3 = new THREE.Vector3();
  1671. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1672. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1673. /**
  1674. * @author mr.doob / http://mrdoob.com/
  1675. * @author mikael emtinger / http://gomo.se/
  1676. * @author alteredq / http://alteredqualia.com/
  1677. */
  1678. THREE.Object3D = function () {
  1679. this.id = THREE.Object3DCount ++;
  1680. this.name = '';
  1681. this.parent = undefined;
  1682. this.children = [];
  1683. this.up = new THREE.Vector3( 0, 1, 0 );
  1684. this.position = new THREE.Vector3();
  1685. this.rotation = new THREE.Vector3();
  1686. this.eulerOrder = 'XYZ';
  1687. this.scale = new THREE.Vector3( 1, 1, 1 );
  1688. this.doubleSided = false;
  1689. this.flipSided = false;
  1690. this.renderDepth = null;
  1691. this.rotationAutoUpdate = true;
  1692. this.matrix = new THREE.Matrix4();
  1693. this.matrixWorld = new THREE.Matrix4();
  1694. this.matrixRotationWorld = new THREE.Matrix4();
  1695. this.matrixAutoUpdate = true;
  1696. this.matrixWorldNeedsUpdate = true;
  1697. this.quaternion = new THREE.Quaternion();
  1698. this.useQuaternion = false;
  1699. this.boundRadius = 0.0;
  1700. this.boundRadiusScale = 1.0;
  1701. this.visible = true;
  1702. this.castShadow = false;
  1703. this.receiveShadow = false;
  1704. this.frustumCulled = true;
  1705. this._vector = new THREE.Vector3();
  1706. };
  1707. THREE.Object3D.prototype = {
  1708. constructor: THREE.Object3D,
  1709. applyMatrix: function ( matrix ) {
  1710. this.matrix.multiply( matrix, this.matrix );
  1711. this.scale.getScaleFromMatrix( this.matrix );
  1712. this.rotation.getRotationFromMatrix( this.matrix, this.scale );
  1713. this.position.getPositionFromMatrix( this.matrix );
  1714. },
  1715. translate: function ( distance, axis ) {
  1716. this.matrix.rotateAxis( axis );
  1717. this.position.addSelf( axis.multiplyScalar( distance ) );
  1718. },
  1719. translateX: function ( distance ) {
  1720. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  1721. },
  1722. translateY: function ( distance ) {
  1723. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  1724. },
  1725. translateZ: function ( distance ) {
  1726. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  1727. },
  1728. lookAt: function ( vector ) {
  1729. // TODO: Add hierarchy support.
  1730. this.matrix.lookAt( vector, this.position, this.up );
  1731. if ( this.rotationAutoUpdate ) {
  1732. this.rotation.getRotationFromMatrix( this.matrix );
  1733. }
  1734. },
  1735. add: function ( object ) {
  1736. if ( object === this ) {
  1737. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  1738. return;
  1739. }
  1740. if ( object instanceof THREE.Object3D ) { // && this.children.indexOf( object ) === - 1
  1741. if ( object.parent !== undefined ) {
  1742. object.parent.remove( object );
  1743. }
  1744. object.parent = this;
  1745. this.children.push( object );
  1746. // add to scene
  1747. var scene = this;
  1748. while ( scene.parent !== undefined ) {
  1749. scene = scene.parent;
  1750. }
  1751. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  1752. scene.__addObject( object );
  1753. }
  1754. }
  1755. },
  1756. remove: function ( object ) {
  1757. var index = this.children.indexOf( object );
  1758. if ( index !== - 1 ) {
  1759. object.parent = undefined;
  1760. this.children.splice( index, 1 );
  1761. // remove from scene
  1762. var scene = this;
  1763. while ( scene.parent !== undefined ) {
  1764. scene = scene.parent;
  1765. }
  1766. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  1767. scene.__removeObject( object );
  1768. }
  1769. }
  1770. },
  1771. getChildByName: function ( name, recursive ) {
  1772. var c, cl, child;
  1773. for ( c = 0, cl = this.children.length; c < cl; c ++ ) {
  1774. child = this.children[ c ];
  1775. if ( child.name === name ) {
  1776. return child;
  1777. }
  1778. if ( recursive ) {
  1779. child = child.getChildByName( name, recursive );
  1780. if ( child !== undefined ) {
  1781. return child;
  1782. }
  1783. }
  1784. }
  1785. return undefined;
  1786. },
  1787. updateMatrix: function () {
  1788. this.matrix.setPosition( this.position );
  1789. if ( this.useQuaternion ) {
  1790. this.matrix.setRotationFromQuaternion( this.quaternion );
  1791. } else {
  1792. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  1793. }
  1794. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  1795. this.matrix.scale( this.scale );
  1796. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  1797. }
  1798. this.matrixWorldNeedsUpdate = true;
  1799. },
  1800. updateMatrixWorld: function ( force ) {
  1801. this.matrixAutoUpdate && this.updateMatrix();
  1802. // update matrixWorld
  1803. if ( this.matrixWorldNeedsUpdate || force ) {
  1804. if ( this.parent ) {
  1805. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  1806. } else {
  1807. this.matrixWorld.copy( this.matrix );
  1808. }
  1809. this.matrixWorldNeedsUpdate = false;
  1810. force = true;
  1811. }
  1812. // update children
  1813. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  1814. this.children[ i ].updateMatrixWorld( force );
  1815. }
  1816. }
  1817. };
  1818. THREE.Object3DCount = 0;
  1819. /**
  1820. * @author mr.doob / http://mrdoob.com/
  1821. * @author supereggbert / http://www.paulbrunt.co.uk/
  1822. * @author julianwa / https://github.com/julianwa
  1823. */
  1824. THREE.Projector = function() {
  1825. var _object, _objectCount, _objectPool = [],
  1826. _vertex, _vertexCount, _vertexPool = [],
  1827. _face, _face3Count, _face3Pool = [], _face4Count, _face4Pool = [],
  1828. _line, _lineCount, _linePool = [],
  1829. _particle, _particleCount, _particlePool = [],
  1830. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  1831. _vector3 = new THREE.Vector3(),
  1832. _vector4 = new THREE.Vector4(),
  1833. _projScreenMatrix = new THREE.Matrix4(),
  1834. _projScreenobjectMatrixWorld = new THREE.Matrix4(),
  1835. _frustum = new THREE.Frustum(),
  1836. _clippedVertex1PositionScreen = new THREE.Vector4(),
  1837. _clippedVertex2PositionScreen = new THREE.Vector4(),
  1838. _face3VertexNormals;
  1839. this.projectVector = function ( vector, camera ) {
  1840. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  1841. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  1842. _projScreenMatrix.multiplyVector3( vector );
  1843. return vector;
  1844. };
  1845. this.unprojectVector = function ( vector, camera ) {
  1846. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  1847. _projScreenMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  1848. _projScreenMatrix.multiplyVector3( vector );
  1849. return vector;
  1850. };
  1851. this.pickingRay = function ( vector, camera ) {
  1852. var end, ray, t;
  1853. // set two vectors with opposing z values
  1854. vector.z = -1.0;
  1855. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  1856. this.unprojectVector( vector, camera );
  1857. this.unprojectVector( end, camera );
  1858. // find direction from vector to end
  1859. end.subSelf( vector ).normalize();
  1860. return new THREE.Ray( vector, end );
  1861. };
  1862. this.projectGraph = function ( root, sort ) {
  1863. _objectCount = 0;
  1864. _renderData.objects.length = 0;
  1865. _renderData.sprites.length = 0;
  1866. _renderData.lights.length = 0;
  1867. var projectObject = function ( object ) {
  1868. if ( object.visible === false ) return;
  1869. if ( ( object instanceof THREE.Mesh || object instanceof THREE.Line ) &&
  1870. ( object.frustumCulled === false || _frustum.contains( object ) ) ) {
  1871. _vector3.copy( object.matrixWorld.getPosition() );
  1872. _projScreenMatrix.multiplyVector3( _vector3 );
  1873. _object = getNextObjectInPool();
  1874. _object.object = object;
  1875. _object.z = _vector3.z;
  1876. _renderData.objects.push( _object );
  1877. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  1878. _vector3.copy( object.matrixWorld.getPosition() );
  1879. _projScreenMatrix.multiplyVector3( _vector3 );
  1880. _object = getNextObjectInPool();
  1881. _object.object = object;
  1882. _object.z = _vector3.z;
  1883. _renderData.sprites.push( _object );
  1884. } else if ( object instanceof THREE.Light ) {
  1885. _renderData.lights.push( object );
  1886. }
  1887. for ( var c = 0, cl = object.children.length; c < cl; c ++ ) {
  1888. projectObject( object.children[ c ] );
  1889. }
  1890. };
  1891. projectObject( root );
  1892. sort && _renderData.objects.sort( painterSort );
  1893. return _renderData;
  1894. };
  1895. this.projectScene = function ( scene, camera, sort ) {
  1896. var near = camera.near, far = camera.far, visible = false,
  1897. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  1898. objectMatrixWorld, objectMatrixWorldRotation,
  1899. geometry, geometryMaterials, vertices, vertex, vertexPositionScreen,
  1900. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  1901. v1, v2, v3, v4;
  1902. _face3Count = 0;
  1903. _face4Count = 0;
  1904. _lineCount = 0;
  1905. _particleCount = 0;
  1906. _renderData.elements.length = 0;
  1907. if ( camera.parent === undefined ) {
  1908. console.warn( 'DEPRECATED: Camera hasn\'t been added to a Scene. Adding it...' );
  1909. scene.add( camera );
  1910. }
  1911. scene.updateMatrixWorld();
  1912. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  1913. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  1914. _frustum.setFromMatrix( _projScreenMatrix );
  1915. _renderData = this.projectGraph( scene, false );
  1916. for ( o = 0, ol = _renderData.objects.length; o < ol; o++ ) {
  1917. object = _renderData.objects[ o ].object;
  1918. objectMatrixWorld = object.matrixWorld;
  1919. _vertexCount = 0;
  1920. if ( object instanceof THREE.Mesh ) {
  1921. geometry = object.geometry;
  1922. geometryMaterials = object.geometry.materials;
  1923. vertices = geometry.vertices;
  1924. faces = geometry.faces;
  1925. faceVertexUvs = geometry.faceVertexUvs;
  1926. objectMatrixWorldRotation = object.matrixRotationWorld.extractRotation( objectMatrixWorld );
  1927. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  1928. _vertex = getNextVertexInPool();
  1929. _vertex.positionWorld.copy( vertices[ v ] );
  1930. objectMatrixWorld.multiplyVector3( _vertex.positionWorld );
  1931. _vertex.positionScreen.copy( _vertex.positionWorld );
  1932. _projScreenMatrix.multiplyVector4( _vertex.positionScreen );
  1933. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  1934. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  1935. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  1936. }
  1937. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  1938. face = faces[ f ];
  1939. if ( face instanceof THREE.Face3 ) {
  1940. v1 = _vertexPool[ face.a ];
  1941. v2 = _vertexPool[ face.b ];
  1942. v3 = _vertexPool[ face.c ];
  1943. if ( v1.visible && v2.visible && v3.visible ) {
  1944. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  1945. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  1946. if ( object.doubleSided || visible != object.flipSided ) {
  1947. _face = getNextFace3InPool();
  1948. _face.v1.copy( v1 );
  1949. _face.v2.copy( v2 );
  1950. _face.v3.copy( v3 );
  1951. } else {
  1952. continue;
  1953. }
  1954. } else {
  1955. continue;
  1956. }
  1957. } else if ( face instanceof THREE.Face4 ) {
  1958. v1 = _vertexPool[ face.a ];
  1959. v2 = _vertexPool[ face.b ];
  1960. v3 = _vertexPool[ face.c ];
  1961. v4 = _vertexPool[ face.d ];
  1962. if ( v1.visible && v2.visible && v3.visible && v4.visible ) {
  1963. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  1964. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  1965. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  1966. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  1967. if ( object.doubleSided || visible != object.flipSided ) {
  1968. _face = getNextFace4InPool();
  1969. _face.v1.copy( v1 );
  1970. _face.v2.copy( v2 );
  1971. _face.v3.copy( v3 );
  1972. _face.v4.copy( v4 );
  1973. } else {
  1974. continue;
  1975. }
  1976. } else {
  1977. continue;
  1978. }
  1979. }
  1980. _face.normalWorld.copy( face.normal );
  1981. if ( !visible && ( object.flipSided || object.doubleSided ) ) _face.normalWorld.negate();
  1982. objectMatrixWorldRotation.multiplyVector3( _face.normalWorld );
  1983. _face.centroidWorld.copy( face.centroid );
  1984. objectMatrixWorld.multiplyVector3( _face.centroidWorld );
  1985. _face.centroidScreen.copy( _face.centroidWorld );
  1986. _projScreenMatrix.multiplyVector3( _face.centroidScreen );
  1987. faceVertexNormals = face.vertexNormals;
  1988. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  1989. normal = _face.vertexNormalsWorld[ n ];
  1990. normal.copy( faceVertexNormals[ n ] );
  1991. if ( !visible && ( object.flipSided || object.doubleSided ) ) normal.negate();
  1992. objectMatrixWorldRotation.multiplyVector3( normal );
  1993. }
  1994. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  1995. uvs = faceVertexUvs[ c ][ f ];
  1996. if ( !uvs ) continue;
  1997. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  1998. _face.uvs[ c ][ u ] = uvs[ u ];
  1999. }
  2000. }
  2001. _face.material = object.material;
  2002. _face.faceMaterial = face.materialIndex !== null ? geometryMaterials[ face.materialIndex ] : null;
  2003. _face.z = _face.centroidScreen.z;
  2004. _renderData.elements.push( _face );
  2005. }
  2006. } else if ( object instanceof THREE.Line ) {
  2007. _projScreenobjectMatrixWorld.multiply( _projScreenMatrix, objectMatrixWorld );
  2008. vertices = object.geometry.vertices;
  2009. v1 = getNextVertexInPool();
  2010. v1.positionScreen.copy( vertices[ 0 ] );
  2011. _projScreenobjectMatrixWorld.multiplyVector4( v1.positionScreen );
  2012. // Handle LineStrip and LinePieces
  2013. var step = object.type === THREE.LinePieces ? 2 : 1;
  2014. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2015. v1 = getNextVertexInPool();
  2016. v1.positionScreen.copy( vertices[ v ] );
  2017. _projScreenobjectMatrixWorld.multiplyVector4( v1.positionScreen );
  2018. if ( ( v + 1 ) % step > 0 ) continue;
  2019. v2 = _vertexPool[ _vertexCount - 2 ];
  2020. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2021. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2022. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) ) {
  2023. // Perform the perspective divide
  2024. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2025. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2026. _line = getNextLineInPool();
  2027. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2028. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2029. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2030. _line.material = object.material;
  2031. _renderData.elements.push( _line );
  2032. }
  2033. }
  2034. }
  2035. }
  2036. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2037. object = _renderData.sprites[ o ].object;
  2038. objectMatrixWorld = object.matrixWorld;
  2039. if ( object instanceof THREE.Particle ) {
  2040. _vector4.set( objectMatrixWorld.elements[12], objectMatrixWorld.elements[13], objectMatrixWorld.elements[14], 1 );
  2041. _projScreenMatrix.multiplyVector4( _vector4 );
  2042. _vector4.z /= _vector4.w;
  2043. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2044. _particle = getNextParticleInPool();
  2045. _particle.x = _vector4.x / _vector4.w;
  2046. _particle.y = _vector4.y / _vector4.w;
  2047. _particle.z = _vector4.z;
  2048. _particle.rotation = object.rotation.z;
  2049. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2050. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2051. _particle.material = object.material;
  2052. _renderData.elements.push( _particle );
  2053. }
  2054. }
  2055. }
  2056. sort && _renderData.elements.sort( painterSort );
  2057. return _renderData;
  2058. };
  2059. // Pools
  2060. function getNextObjectInPool() {
  2061. var object = _objectPool[ _objectCount ] = _objectPool[ _objectCount ] || new THREE.RenderableObject();
  2062. _objectCount ++;
  2063. return object;
  2064. }
  2065. function getNextVertexInPool() {
  2066. var vertex = _vertexPool[ _vertexCount ] = _vertexPool[ _vertexCount ] || new THREE.RenderableVertex();
  2067. _vertexCount ++;
  2068. return vertex;
  2069. }
  2070. function getNextFace3InPool() {
  2071. var face = _face3Pool[ _face3Count ] = _face3Pool[ _face3Count ] || new THREE.RenderableFace3();
  2072. _face3Count ++;
  2073. return face;
  2074. }
  2075. function getNextFace4InPool() {
  2076. var face = _face4Pool[ _face4Count ] = _face4Pool[ _face4Count ] || new THREE.RenderableFace4();
  2077. _face4Count ++;
  2078. return face;
  2079. }
  2080. function getNextLineInPool() {
  2081. var line = _linePool[ _lineCount ] = _linePool[ _lineCount ] || new THREE.RenderableLine();
  2082. _lineCount ++;
  2083. return line;
  2084. }
  2085. function getNextParticleInPool() {
  2086. var particle = _particlePool[ _particleCount ] = _particlePool[ _particleCount ] || new THREE.RenderableParticle();
  2087. _particleCount ++;
  2088. return particle;
  2089. }
  2090. //
  2091. function painterSort( a, b ) {
  2092. return b.z - a.z;
  2093. }
  2094. function clipLine( s1, s2 ) {
  2095. var alpha1 = 0, alpha2 = 1,
  2096. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2097. // Z = -1 and Z = +1, respectively.
  2098. bc1near = s1.z + s1.w,
  2099. bc2near = s2.z + s2.w,
  2100. bc1far = - s1.z + s1.w,
  2101. bc2far = - s2.z + s2.w;
  2102. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2103. // Both vertices lie entirely within all clip planes.
  2104. return true;
  2105. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2106. // Both vertices lie entirely outside one of the clip planes.
  2107. return false;
  2108. } else {
  2109. // The line segment spans at least one clip plane.
  2110. if ( bc1near < 0 ) {
  2111. // v1 lies outside the near plane, v2 inside
  2112. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2113. } else if ( bc2near < 0 ) {
  2114. // v2 lies outside the near plane, v1 inside
  2115. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2116. }
  2117. if ( bc1far < 0 ) {
  2118. // v1 lies outside the far plane, v2 inside
  2119. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2120. } else if ( bc2far < 0 ) {
  2121. // v2 lies outside the far plane, v2 inside
  2122. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2123. }
  2124. if ( alpha2 < alpha1 ) {
  2125. // The line segment spans two boundaries, but is outside both of them.
  2126. // (This can't happen when we're only clipping against just near/far but good
  2127. // to leave the check here for future usage if other clip planes are added.)
  2128. return false;
  2129. } else {
  2130. // Update the s1 and s2 vertices to match the clipped line segment.
  2131. s1.lerpSelf( s2, alpha1 );
  2132. s2.lerpSelf( s1, 1 - alpha2 );
  2133. return true;
  2134. }
  2135. }
  2136. }
  2137. };
  2138. /**
  2139. * @author mikael emtinger / http://gomo.se/
  2140. * @author alteredq / http://alteredqualia.com/
  2141. */
  2142. THREE.Quaternion = function( x, y, z, w ) {
  2143. this.x = x || 0;
  2144. this.y = y || 0;
  2145. this.z = z || 0;
  2146. this.w = ( w !== undefined ) ? w : 1;
  2147. };
  2148. THREE.Quaternion.prototype = {
  2149. constructor: THREE.Quaternion,
  2150. set: function ( x, y, z, w ) {
  2151. this.x = x;
  2152. this.y = y;
  2153. this.z = z;
  2154. this.w = w;
  2155. return this;
  2156. },
  2157. copy: function ( q ) {
  2158. this.x = q.x;
  2159. this.y = q.y;
  2160. this.z = q.z;
  2161. this.w = q.w;
  2162. return this;
  2163. },
  2164. setFromEuler: function ( vector ) {
  2165. var c = Math.PI / 360, // 0.5 * Math.PI / 360, // 0.5 is an optimization
  2166. x = vector.x * c,
  2167. y = vector.y * c,
  2168. z = vector.z * c,
  2169. c1 = Math.cos( y ),
  2170. s1 = Math.sin( y ),
  2171. c2 = Math.cos( -z ),
  2172. s2 = Math.sin( -z ),
  2173. c3 = Math.cos( x ),
  2174. s3 = Math.sin( x ),
  2175. c1c2 = c1 * c2,
  2176. s1s2 = s1 * s2;
  2177. this.w = c1c2 * c3 - s1s2 * s3;
  2178. this.x = c1c2 * s3 + s1s2 * c3;
  2179. this.y = s1 * c2 * c3 + c1 * s2 * s3;
  2180. this.z = c1 * s2 * c3 - s1 * c2 * s3;
  2181. return this;
  2182. },
  2183. setFromAxisAngle: function ( axis, angle ) {
  2184. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2185. // axis have to be normalized
  2186. var halfAngle = angle / 2,
  2187. s = Math.sin( halfAngle );
  2188. this.x = axis.x * s;
  2189. this.y = axis.y * s;
  2190. this.z = axis.z * s;
  2191. this.w = Math.cos( halfAngle );
  2192. return this;
  2193. },
  2194. setFromRotationMatrix: function ( m ) {
  2195. // Adapted from: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2196. function copySign( a, b ) {
  2197. return b < 0 ? -Math.abs( a ) : Math.abs( a );
  2198. }
  2199. var absQ = Math.pow( m.determinant(), 1.0 / 3.0 );
  2200. this.w = Math.sqrt( Math.max( 0, absQ + m.elements[0] + m.elements[5] + m.elements[10] ) ) / 2;
  2201. this.x = Math.sqrt( Math.max( 0, absQ + m.elements[0] - m.elements[5] - m.elements[10] ) ) / 2;
  2202. this.y = Math.sqrt( Math.max( 0, absQ - m.elements[0] + m.elements[5] - m.elements[10] ) ) / 2;
  2203. this.z = Math.sqrt( Math.max( 0, absQ - m.elements[0] - m.elements[5] + m.elements[10] ) ) / 2;
  2204. this.x = copySign( this.x, ( m.elements[6] - m.elements[9] ) );
  2205. this.y = copySign( this.y, ( m.elements[8] - m.elements[2] ) );
  2206. this.z = copySign( this.z, ( m.elements[1] - m.elements[4] ) );
  2207. this.normalize();
  2208. return this;
  2209. },
  2210. calculateW : function () {
  2211. this.w = - Math.sqrt( Math.abs( 1.0 - this.x * this.x - this.y * this.y - this.z * this.z ) );
  2212. return this;
  2213. },
  2214. inverse: function () {
  2215. this.x *= -1;
  2216. this.y *= -1;
  2217. this.z *= -1;
  2218. return this;
  2219. },
  2220. length: function () {
  2221. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2222. },
  2223. normalize: function () {
  2224. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2225. if ( l === 0 ) {
  2226. this.x = 0;
  2227. this.y = 0;
  2228. this.z = 0;
  2229. this.w = 0;
  2230. } else {
  2231. l = 1 / l;
  2232. this.x = this.x * l;
  2233. this.y = this.y * l;
  2234. this.z = this.z * l;
  2235. this.w = this.w * l;
  2236. }
  2237. return this;
  2238. },
  2239. multiply: function ( a, b ) {
  2240. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2241. this.x = a.x * b.w + a.y * b.z - a.z * b.y + a.w * b.x;
  2242. this.y = -a.x * b.z + a.y * b.w + a.z * b.x + a.w * b.y;
  2243. this.z = a.x * b.y - a.y * b.x + a.z * b.w + a.w * b.z;
  2244. this.w = -a.x * b.x - a.y * b.y - a.z * b.z + a.w * b.w;
  2245. return this;
  2246. },
  2247. multiplySelf: function ( b ) {
  2248. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2249. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2250. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2251. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2252. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2253. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2254. return this;
  2255. },
  2256. multiplyVector3: function ( vector, dest ) {
  2257. if ( !dest ) { dest = vector; }
  2258. var x = vector.x, y = vector.y, z = vector.z,
  2259. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2260. // calculate quat * vector
  2261. var ix = qw * x + qy * z - qz * y,
  2262. iy = qw * y + qz * x - qx * z,
  2263. iz = qw * z + qx * y - qy * x,
  2264. iw = -qx * x - qy * y - qz * z;
  2265. // calculate result * inverse quat
  2266. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2267. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2268. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2269. return dest;
  2270. },
  2271. clone: function () {
  2272. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2273. }
  2274. }
  2275. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2276. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2277. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2278. if (cosHalfTheta < 0) {
  2279. qm.w = -qb.w; qm.x = -qb.x; qm.y = -qb.y; qm.z = -qb.z;
  2280. cosHalfTheta = -cosHalfTheta;
  2281. } else {
  2282. qm.copy(qb);
  2283. }
  2284. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2285. qm.w = qa.w; qm.x = qa.x; qm.y = qa.y; qm.z = qa.z;
  2286. return qm;
  2287. }
  2288. var halfTheta = Math.acos( cosHalfTheta ),
  2289. sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2290. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2291. qm.w = 0.5 * ( qa.w + qb.w );
  2292. qm.x = 0.5 * ( qa.x + qb.x );
  2293. qm.y = 0.5 * ( qa.y + qb.y );
  2294. qm.z = 0.5 * ( qa.z + qb.z );
  2295. return qm;
  2296. }
  2297. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2298. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2299. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2300. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2301. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2302. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2303. return qm;
  2304. }
  2305. /**
  2306. * @author mr.doob / http://mrdoob.com/
  2307. */
  2308. THREE.Vertex = THREE.Vector3;
  2309. /**
  2310. * @author mr.doob / http://mrdoob.com/
  2311. * @author alteredq / http://alteredqualia.com/
  2312. */
  2313. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2314. this.a = a;
  2315. this.b = b;
  2316. this.c = c;
  2317. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2318. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2319. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2320. this.vertexColors = color instanceof Array ? color : [];
  2321. this.vertexTangents = [];
  2322. this.materialIndex = materialIndex;
  2323. this.centroid = new THREE.Vector3();
  2324. };
  2325. THREE.Face3.prototype = {
  2326. constructor: THREE.Face3,
  2327. clone: function () {
  2328. var face = new THREE.Face3( this.a, this.b, this.c );
  2329. face.normal.copy( this.normal );
  2330. face.color.copy( this.color );
  2331. face.centroid.copy( this.centroid );
  2332. face.materialIndex = this.materialIndex;
  2333. var i, il;
  2334. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2335. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2336. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2337. return face;
  2338. }
  2339. };
  2340. /**
  2341. * @author mr.doob / http://mrdoob.com/
  2342. * @author alteredq / http://alteredqualia.com/
  2343. */
  2344. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2345. this.a = a;
  2346. this.b = b;
  2347. this.c = c;
  2348. this.d = d;
  2349. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2350. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2351. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2352. this.vertexColors = color instanceof Array ? color : [];
  2353. this.vertexTangents = [];
  2354. this.materialIndex = materialIndex;
  2355. this.centroid = new THREE.Vector3();
  2356. };
  2357. THREE.Face4.prototype = {
  2358. constructor: THREE.Face4,
  2359. clone: function () {
  2360. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  2361. face.normal.copy( this.normal );
  2362. face.color.copy( this.color );
  2363. face.centroid.copy( this.centroid );
  2364. face.materialIndex = this.materialIndex;
  2365. var i, il;
  2366. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2367. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2368. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2369. return face;
  2370. }
  2371. };
  2372. /**
  2373. * @author mr.doob / http://mrdoob.com/
  2374. */
  2375. THREE.UV = function ( u, v ) {
  2376. this.u = u || 0;
  2377. this.v = v || 0;
  2378. };
  2379. THREE.UV.prototype = {
  2380. constructor: THREE.UV,
  2381. set: function ( u, v ) {
  2382. this.u = u;
  2383. this.v = v;
  2384. return this;
  2385. },
  2386. copy: function ( uv ) {
  2387. this.u = uv.u;
  2388. this.v = uv.v;
  2389. return this;
  2390. },
  2391. lerpSelf: function ( uv, alpha ) {
  2392. this.u += ( uv.u - this.u ) * alpha;
  2393. this.v += ( uv.v - this.v ) * alpha;
  2394. return this;
  2395. },
  2396. clone: function () {
  2397. return new THREE.UV( this.u, this.v );
  2398. }
  2399. };
  2400. /**
  2401. * @author mr.doob / http://mrdoob.com/
  2402. * @author kile / http://kile.stravaganza.org/
  2403. * @author alteredq / http://alteredqualia.com/
  2404. * @author mikael emtinger / http://gomo.se/
  2405. * @author zz85 / http://www.lab4games.net/zz85/blog
  2406. */
  2407. THREE.Geometry = function () {
  2408. this.id = THREE.GeometryCount ++;
  2409. this.vertices = [];
  2410. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  2411. this.materials = [];
  2412. this.faces = [];
  2413. this.faceUvs = [[]];
  2414. this.faceVertexUvs = [[]];
  2415. this.morphTargets = [];
  2416. this.morphColors = [];
  2417. this.morphNormals = [];
  2418. this.skinWeights = [];
  2419. this.skinIndices = [];
  2420. this.boundingBox = null;
  2421. this.boundingSphere = null;
  2422. this.hasTangents = false;
  2423. this.dynamic = false; // unless set to true the *Arrays will be deleted once sent to a buffer.
  2424. };
  2425. THREE.Geometry.prototype = {
  2426. constructor : THREE.Geometry,
  2427. applyMatrix: function ( matrix ) {
  2428. var matrixRotation = new THREE.Matrix4();
  2429. matrixRotation.extractRotation( matrix );
  2430. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  2431. var vertex = this.vertices[ i ];
  2432. matrix.multiplyVector3( vertex );
  2433. }
  2434. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  2435. var face = this.faces[ i ];
  2436. matrixRotation.multiplyVector3( face.normal );
  2437. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  2438. matrixRotation.multiplyVector3( face.vertexNormals[ j ] );
  2439. }
  2440. matrix.multiplyVector3( face.centroid );
  2441. }
  2442. },
  2443. computeCentroids: function () {
  2444. var f, fl, face;
  2445. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2446. face = this.faces[ f ];
  2447. face.centroid.set( 0, 0, 0 );
  2448. if ( face instanceof THREE.Face3 ) {
  2449. face.centroid.addSelf( this.vertices[ face.a ] );
  2450. face.centroid.addSelf( this.vertices[ face.b ] );
  2451. face.centroid.addSelf( this.vertices[ face.c ] );
  2452. face.centroid.divideScalar( 3 );
  2453. } else if ( face instanceof THREE.Face4 ) {
  2454. face.centroid.addSelf( this.vertices[ face.a ] );
  2455. face.centroid.addSelf( this.vertices[ face.b ] );
  2456. face.centroid.addSelf( this.vertices[ face.c ] );
  2457. face.centroid.addSelf( this.vertices[ face.d ] );
  2458. face.centroid.divideScalar( 4 );
  2459. }
  2460. }
  2461. },
  2462. computeFaceNormals: function () {
  2463. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  2464. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  2465. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2466. face = this.faces[ f ];
  2467. vA = this.vertices[ face.a ];
  2468. vB = this.vertices[ face.b ];
  2469. vC = this.vertices[ face.c ];
  2470. cb.sub( vC, vB );
  2471. ab.sub( vA, vB );
  2472. cb.crossSelf( ab );
  2473. if ( !cb.isZero() ) {
  2474. cb.normalize();
  2475. }
  2476. face.normal.copy( cb );
  2477. }
  2478. },
  2479. computeVertexNormals: function () {
  2480. var v, vl, f, fl, face, vertices;
  2481. // create internal buffers for reuse when calling this method repeatedly
  2482. // (otherwise memory allocation / deallocation every frame is big resource hog)
  2483. if ( this.__tmpVertices === undefined ) {
  2484. this.__tmpVertices = new Array( this.vertices.length );
  2485. vertices = this.__tmpVertices;
  2486. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2487. vertices[ v ] = new THREE.Vector3();
  2488. }
  2489. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2490. face = this.faces[ f ];
  2491. if ( face instanceof THREE.Face3 ) {
  2492. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2493. } else if ( face instanceof THREE.Face4 ) {
  2494. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2495. }
  2496. }
  2497. } else {
  2498. vertices = this.__tmpVertices;
  2499. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2500. vertices[ v ].set( 0, 0, 0 );
  2501. }
  2502. }
  2503. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2504. face = this.faces[ f ];
  2505. if ( face instanceof THREE.Face3 ) {
  2506. vertices[ face.a ].addSelf( face.normal );
  2507. vertices[ face.b ].addSelf( face.normal );
  2508. vertices[ face.c ].addSelf( face.normal );
  2509. } else if ( face instanceof THREE.Face4 ) {
  2510. vertices[ face.a ].addSelf( face.normal );
  2511. vertices[ face.b ].addSelf( face.normal );
  2512. vertices[ face.c ].addSelf( face.normal );
  2513. vertices[ face.d ].addSelf( face.normal );
  2514. }
  2515. }
  2516. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2517. vertices[ v ].normalize();
  2518. }
  2519. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2520. face = this.faces[ f ];
  2521. if ( face instanceof THREE.Face3 ) {
  2522. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  2523. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  2524. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  2525. } else if ( face instanceof THREE.Face4 ) {
  2526. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  2527. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  2528. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  2529. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  2530. }
  2531. }
  2532. },
  2533. computeMorphNormals: function () {
  2534. var i, il, f, fl, face;
  2535. // save original normals
  2536. // - create temp variables on first access
  2537. // otherwise just copy (for faster repeated calls)
  2538. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2539. face = this.faces[ f ];
  2540. if ( ! face.__originalFaceNormal ) {
  2541. face.__originalFaceNormal = face.normal.clone();
  2542. } else {
  2543. face.__originalFaceNormal.copy( face.normal );
  2544. }
  2545. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  2546. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  2547. if ( ! face.__originalVertexNormals[ i ] ) {
  2548. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  2549. } else {
  2550. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  2551. }
  2552. }
  2553. }
  2554. // use temp geometry to compute face and vertex normals for each morph
  2555. var tmpGeo = new THREE.Geometry();
  2556. tmpGeo.faces = this.faces;
  2557. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  2558. // create on first access
  2559. if ( ! this.morphNormals[ i ] ) {
  2560. this.morphNormals[ i ] = {};
  2561. this.morphNormals[ i ].faceNormals = [];
  2562. this.morphNormals[ i ].vertexNormals = [];
  2563. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  2564. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  2565. var faceNormal, vertexNormals;
  2566. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2567. face = this.faces[ f ];
  2568. faceNormal = new THREE.Vector3();
  2569. if ( face instanceof THREE.Face3 ) {
  2570. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  2571. } else {
  2572. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  2573. }
  2574. dstNormalsFace.push( faceNormal );
  2575. dstNormalsVertex.push( vertexNormals );
  2576. }
  2577. }
  2578. var morphNormals = this.morphNormals[ i ];
  2579. // set vertices to morph target
  2580. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  2581. // compute morph normals
  2582. tmpGeo.computeFaceNormals();
  2583. tmpGeo.computeVertexNormals();
  2584. // store morph normals
  2585. var faceNormal, vertexNormals;
  2586. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2587. face = this.faces[ f ];
  2588. faceNormal = morphNormals.faceNormals[ f ];
  2589. vertexNormals = morphNormals.vertexNormals[ f ];
  2590. faceNormal.copy( face.normal );
  2591. if ( face instanceof THREE.Face3 ) {
  2592. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  2593. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  2594. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  2595. } else {
  2596. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  2597. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  2598. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  2599. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  2600. }
  2601. }
  2602. }
  2603. // restore original normals
  2604. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2605. face = this.faces[ f ];
  2606. face.normal = face.__originalFaceNormal;
  2607. face.vertexNormals = face.__originalVertexNormals;
  2608. }
  2609. },
  2610. computeTangents: function () {
  2611. // based on http://www.terathon.com/code/tangent.html
  2612. // tangents go to vertices
  2613. var f, fl, v, vl, i, il, vertexIndex,
  2614. face, uv, vA, vB, vC, uvA, uvB, uvC,
  2615. x1, x2, y1, y2, z1, z2,
  2616. s1, s2, t1, t2, r, t, test,
  2617. tan1 = [], tan2 = [],
  2618. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  2619. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  2620. n = new THREE.Vector3(), w;
  2621. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2622. tan1[ v ] = new THREE.Vector3();
  2623. tan2[ v ] = new THREE.Vector3();
  2624. }
  2625. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  2626. vA = context.vertices[ a ];
  2627. vB = context.vertices[ b ];
  2628. vC = context.vertices[ c ];
  2629. uvA = uv[ ua ];
  2630. uvB = uv[ ub ];
  2631. uvC = uv[ uc ];
  2632. x1 = vB.x - vA.x;
  2633. x2 = vC.x - vA.x;
  2634. y1 = vB.y - vA.y;
  2635. y2 = vC.y - vA.y;
  2636. z1 = vB.z - vA.z;
  2637. z2 = vC.z - vA.z;
  2638. s1 = uvB.u - uvA.u;
  2639. s2 = uvC.u - uvA.u;
  2640. t1 = uvB.v - uvA.v;
  2641. t2 = uvC.v - uvA.v;
  2642. r = 1.0 / ( s1 * t2 - s2 * t1 );
  2643. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  2644. ( t2 * y1 - t1 * y2 ) * r,
  2645. ( t2 * z1 - t1 * z2 ) * r );
  2646. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  2647. ( s1 * y2 - s2 * y1 ) * r,
  2648. ( s1 * z2 - s2 * z1 ) * r );
  2649. tan1[ a ].addSelf( sdir );
  2650. tan1[ b ].addSelf( sdir );
  2651. tan1[ c ].addSelf( sdir );
  2652. tan2[ a ].addSelf( tdir );
  2653. tan2[ b ].addSelf( tdir );
  2654. tan2[ c ].addSelf( tdir );
  2655. }
  2656. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2657. face = this.faces[ f ];
  2658. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  2659. if ( face instanceof THREE.Face3 ) {
  2660. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  2661. } else if ( face instanceof THREE.Face4 ) {
  2662. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  2663. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  2664. }
  2665. }
  2666. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  2667. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2668. face = this.faces[ f ];
  2669. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  2670. n.copy( face.vertexNormals[ i ] );
  2671. vertexIndex = face[ faceIndex[ i ] ];
  2672. t = tan1[ vertexIndex ];
  2673. // Gram-Schmidt orthogonalize
  2674. tmp.copy( t );
  2675. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  2676. // Calculate handedness
  2677. tmp2.cross( face.vertexNormals[ i ], t );
  2678. test = tmp2.dot( tan2[ vertexIndex ] );
  2679. w = (test < 0.0) ? -1.0 : 1.0;
  2680. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  2681. }
  2682. }
  2683. this.hasTangents = true;
  2684. },
  2685. computeBoundingBox: function () {
  2686. if ( ! this.boundingBox ) {
  2687. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  2688. }
  2689. if ( this.vertices.length > 0 ) {
  2690. var position, firstPosition = this.vertices[ 0 ];
  2691. this.boundingBox.min.copy( firstPosition );
  2692. this.boundingBox.max.copy( firstPosition );
  2693. var min = this.boundingBox.min,
  2694. max = this.boundingBox.max;
  2695. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  2696. position = this.vertices[ v ];
  2697. if ( position.x < min.x ) {
  2698. min.x = position.x;
  2699. } else if ( position.x > max.x ) {
  2700. max.x = position.x;
  2701. }
  2702. if ( position.y < min.y ) {
  2703. min.y = position.y;
  2704. } else if ( position.y > max.y ) {
  2705. max.y = position.y;
  2706. }
  2707. if ( position.z < min.z ) {
  2708. min.z = position.z;
  2709. } else if ( position.z > max.z ) {
  2710. max.z = position.z;
  2711. }
  2712. }
  2713. } else {
  2714. this.boundingBox.min.set( 0, 0, 0 );
  2715. this.boundingBox.max.set( 0, 0, 0 );
  2716. }
  2717. },
  2718. computeBoundingSphere: function () {
  2719. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  2720. var radius, maxRadius = 0;
  2721. for ( var v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2722. radius = this.vertices[ v ].length();
  2723. if ( radius > maxRadius ) maxRadius = radius;
  2724. }
  2725. this.boundingSphere.radius = maxRadius;
  2726. },
  2727. /*
  2728. * Checks for duplicate vertices with hashmap.
  2729. * Duplicated vertices are removed
  2730. * and faces' vertices are updated.
  2731. */
  2732. mergeVertices: function() {
  2733. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  2734. var unique = [], changes = [];
  2735. var v, key;
  2736. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  2737. var precision = Math.pow( 10, precisionPoints );
  2738. var i,il, face;
  2739. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  2740. v = this.vertices[ i ];
  2741. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  2742. if ( verticesMap[ key ] === undefined ) {
  2743. verticesMap[ key ] = i;
  2744. unique.push( this.vertices[ i ] );
  2745. changes[ i ] = unique.length - 1;
  2746. } else {
  2747. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  2748. changes[ i ] = changes[ verticesMap[ key ] ];
  2749. }
  2750. };
  2751. // Start to patch face indices
  2752. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  2753. face = this.faces[ i ];
  2754. if ( face instanceof THREE.Face3 ) {
  2755. face.a = changes[ face.a ];
  2756. face.b = changes[ face.b ];
  2757. face.c = changes[ face.c ];
  2758. } else if ( face instanceof THREE.Face4 ) {
  2759. face.a = changes[ face.a ];
  2760. face.b = changes[ face.b ];
  2761. face.c = changes[ face.c ];
  2762. face.d = changes[ face.d ];
  2763. }
  2764. }
  2765. // Use unique set of vertices
  2766. this.vertices = unique;
  2767. }
  2768. };
  2769. THREE.GeometryCount = 0;
  2770. /**
  2771. * Spline from Tween.js, slightly optimized (and trashed)
  2772. * http://sole.github.com/tween.js/examples/05_spline.html
  2773. *
  2774. * @author mrdoob / http://mrdoob.com/
  2775. * @author alteredq / http://alteredqualia.com/
  2776. */
  2777. THREE.Spline = function ( points ) {
  2778. this.points = points;
  2779. var c = [], v3 = { x: 0, y: 0, z: 0 },
  2780. point, intPoint, weight, w2, w3,
  2781. pa, pb, pc, pd;
  2782. this.initFromArray = function( a ) {
  2783. this.points = [];
  2784. for ( var i = 0; i < a.length; i++ ) {
  2785. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  2786. }
  2787. };
  2788. this.getPoint = function ( k ) {
  2789. point = ( this.points.length - 1 ) * k;
  2790. intPoint = Math.floor( point );
  2791. weight = point - intPoint;
  2792. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  2793. c[ 1 ] = intPoint;
  2794. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  2795. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  2796. pa = this.points[ c[ 0 ] ];
  2797. pb = this.points[ c[ 1 ] ];
  2798. pc = this.points[ c[ 2 ] ];
  2799. pd = this.points[ c[ 3 ] ];
  2800. w2 = weight * weight;
  2801. w3 = weight * w2;
  2802. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  2803. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  2804. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  2805. return v3;
  2806. };
  2807. this.getControlPointsArray = function () {
  2808. var i, p, l = this.points.length,
  2809. coords = [];
  2810. for ( i = 0; i < l; i ++ ) {
  2811. p = this.points[ i ];
  2812. coords[ i ] = [ p.x, p.y, p.z ];
  2813. }
  2814. return coords;
  2815. };
  2816. // approximate length by summing linear segments
  2817. this.getLength = function ( nSubDivisions ) {
  2818. var i, index, nSamples, position,
  2819. point = 0, intPoint = 0, oldIntPoint = 0,
  2820. oldPosition = new THREE.Vector3(),
  2821. tmpVec = new THREE.Vector3(),
  2822. chunkLengths = [],
  2823. totalLength = 0;
  2824. // first point has 0 length
  2825. chunkLengths[ 0 ] = 0;
  2826. if ( !nSubDivisions ) nSubDivisions = 100;
  2827. nSamples = this.points.length * nSubDivisions;
  2828. oldPosition.copy( this.points[ 0 ] );
  2829. for ( i = 1; i < nSamples; i ++ ) {
  2830. index = i / nSamples;
  2831. position = this.getPoint( index );
  2832. tmpVec.copy( position );
  2833. totalLength += tmpVec.distanceTo( oldPosition );
  2834. oldPosition.copy( position );
  2835. point = ( this.points.length - 1 ) * index;
  2836. intPoint = Math.floor( point );
  2837. if ( intPoint != oldIntPoint ) {
  2838. chunkLengths[ intPoint ] = totalLength;
  2839. oldIntPoint = intPoint;
  2840. }
  2841. }
  2842. // last point ends with total length
  2843. chunkLengths[ chunkLengths.length ] = totalLength;
  2844. return { chunks: chunkLengths, total: totalLength };
  2845. };
  2846. this.reparametrizeByArcLength = function ( samplingCoef ) {
  2847. var i, j,
  2848. index, indexCurrent, indexNext,
  2849. linearDistance, realDistance,
  2850. sampling, position,
  2851. newpoints = [],
  2852. tmpVec = new THREE.Vector3(),
  2853. sl = this.getLength();
  2854. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  2855. for ( i = 1; i < this.points.length; i++ ) {
  2856. //tmpVec.copy( this.points[ i - 1 ] );
  2857. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  2858. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  2859. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  2860. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  2861. indexNext = i / ( this.points.length - 1 );
  2862. for ( j = 1; j < sampling - 1; j++ ) {
  2863. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  2864. position = this.getPoint( index );
  2865. newpoints.push( tmpVec.copy( position ).clone() );
  2866. }
  2867. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  2868. }
  2869. this.points = newpoints;
  2870. };
  2871. // Catmull-Rom
  2872. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  2873. var v0 = ( p2 - p0 ) * 0.5,
  2874. v1 = ( p3 - p1 ) * 0.5;
  2875. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  2876. };
  2877. };
  2878. /**
  2879. * @author mr.doob / http://mrdoob.com/
  2880. * @author mikael emtinger / http://gomo.se/
  2881. */
  2882. THREE.Camera = function () {
  2883. THREE.Object3D.call( this );
  2884. this.matrixWorldInverse = new THREE.Matrix4();
  2885. this.projectionMatrix = new THREE.Matrix4();
  2886. this.projectionMatrixInverse = new THREE.Matrix4();
  2887. };
  2888. THREE.Camera.prototype = new THREE.Object3D();
  2889. THREE.Camera.prototype.constructor = THREE.Camera;
  2890. THREE.Camera.prototype.lookAt = function ( vector ) {
  2891. // TODO: Add hierarchy support.
  2892. this.matrix.lookAt( this.position, vector, this.up );
  2893. if ( this.rotationAutoUpdate ) {
  2894. this.rotation.getRotationFromMatrix( this.matrix );
  2895. }
  2896. };
  2897. /**
  2898. * @author alteredq / http://alteredqualia.com/
  2899. */
  2900. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  2901. THREE.Camera.call( this );
  2902. this.left = left;
  2903. this.right = right;
  2904. this.top = top;
  2905. this.bottom = bottom;
  2906. this.near = ( near !== undefined ) ? near : 0.1;
  2907. this.far = ( far !== undefined ) ? far : 2000;
  2908. this.updateProjectionMatrix();
  2909. };
  2910. THREE.OrthographicCamera.prototype = new THREE.Camera();
  2911. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  2912. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  2913. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  2914. };
  2915. /**
  2916. * @author mr.doob / http://mrdoob.com/
  2917. * @author greggman / http://games.greggman.com/
  2918. * @author zz85 / http://www.lab4games.net/zz85/blog
  2919. */
  2920. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  2921. THREE.Camera.call( this );
  2922. this.fov = fov !== undefined ? fov : 50;
  2923. this.aspect = aspect !== undefined ? aspect : 1;
  2924. this.near = near !== undefined ? near : 0.1;
  2925. this.far = far !== undefined ? far : 2000;
  2926. this.updateProjectionMatrix();
  2927. };
  2928. THREE.PerspectiveCamera.prototype = new THREE.Camera();
  2929. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  2930. /**
  2931. * Uses Focal Length (in mm) to estimate and set FOV
  2932. * 35mm (fullframe) camera is used if frame size is not specified;
  2933. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  2934. */
  2935. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  2936. frameHeight = frameHeight !== undefined ? frameHeight : 24;
  2937. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  2938. this.updateProjectionMatrix();
  2939. }
  2940. /**
  2941. * Sets an offset in a larger frustum. This is useful for multi-window or
  2942. * multi-monitor/multi-machine setups.
  2943. *
  2944. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  2945. * the monitors are in grid like this
  2946. *
  2947. * +---+---+---+
  2948. * | A | B | C |
  2949. * +---+---+---+
  2950. * | D | E | F |
  2951. * +---+---+---+
  2952. *
  2953. * then for each monitor you would call it like this
  2954. *
  2955. * var w = 1920;
  2956. * var h = 1080;
  2957. * var fullWidth = w * 3;
  2958. * var fullHeight = h * 2;
  2959. *
  2960. * --A--
  2961. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  2962. * --B--
  2963. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  2964. * --C--
  2965. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  2966. * --D--
  2967. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  2968. * --E--
  2969. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  2970. * --F--
  2971. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  2972. *
  2973. * Note there is no reason monitors have to be the same size or in a grid.
  2974. */
  2975. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  2976. this.fullWidth = fullWidth;
  2977. this.fullHeight = fullHeight;
  2978. this.x = x;
  2979. this.y = y;
  2980. this.width = width;
  2981. this.height = height;
  2982. this.updateProjectionMatrix();
  2983. };
  2984. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  2985. if ( this.fullWidth ) {
  2986. var aspect = this.fullWidth / this.fullHeight;
  2987. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  2988. var bottom = -top;
  2989. var left = aspect * bottom;
  2990. var right = aspect * top;
  2991. var width = Math.abs( right - left );
  2992. var height = Math.abs( top - bottom );
  2993. this.projectionMatrix.makeFrustum(
  2994. left + this.x * width / this.fullWidth,
  2995. left + ( this.x + this.width ) * width / this.fullWidth,
  2996. top - ( this.y + this.height ) * height / this.fullHeight,
  2997. top - this.y * height / this.fullHeight,
  2998. this.near,
  2999. this.far
  3000. );
  3001. } else {
  3002. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  3003. }
  3004. };
  3005. /**
  3006. * @author mr.doob / http://mrdoob.com/
  3007. * @author alteredq / http://alteredqualia.com/
  3008. */
  3009. THREE.Light = function ( hex ) {
  3010. THREE.Object3D.call( this );
  3011. this.color = new THREE.Color( hex );
  3012. };
  3013. THREE.Light.prototype = new THREE.Object3D();
  3014. THREE.Light.prototype.constructor = THREE.Light;
  3015. THREE.Light.prototype.supr = THREE.Object3D.prototype;
  3016. /**
  3017. * @author mr.doob / http://mrdoob.com/
  3018. */
  3019. THREE.AmbientLight = function ( hex ) {
  3020. THREE.Light.call( this, hex );
  3021. };
  3022. THREE.AmbientLight.prototype = new THREE.Light();
  3023. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  3024. /**
  3025. * @author mr.doob / http://mrdoob.com/
  3026. * @author alteredq / http://alteredqualia.com/
  3027. */
  3028. THREE.DirectionalLight = function ( hex, intensity, distance ) {
  3029. THREE.Light.call( this, hex );
  3030. this.position = new THREE.Vector3( 0, 1, 0 );
  3031. this.target = new THREE.Object3D();
  3032. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3033. this.distance = ( distance !== undefined ) ? distance : 0;
  3034. this.castShadow = false;
  3035. this.onlyShadow = false;
  3036. //
  3037. this.shadowCameraNear = 50;
  3038. this.shadowCameraFar = 5000;
  3039. this.shadowCameraLeft = -500;
  3040. this.shadowCameraRight = 500;
  3041. this.shadowCameraTop = 500;
  3042. this.shadowCameraBottom = -500;
  3043. this.shadowCameraVisible = false;
  3044. this.shadowBias = 0;
  3045. this.shadowDarkness = 0.5;
  3046. this.shadowMapWidth = 512;
  3047. this.shadowMapHeight = 512;
  3048. //
  3049. this.shadowCascade = false;
  3050. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  3051. this.shadowCascadeCount = 2;
  3052. this.shadowCascadeBias = [ 0, 0, 0 ];
  3053. this.shadowCascadeWidth = [ 512, 512, 512 ];
  3054. this.shadowCascadeHeight = [ 512, 512, 512 ];
  3055. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  3056. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  3057. this.shadowCascadeArray = [];
  3058. //
  3059. this.shadowMap = null;
  3060. this.shadowMapSize = null;
  3061. this.shadowCamera = null;
  3062. this.shadowMatrix = null;
  3063. };
  3064. THREE.DirectionalLight.prototype = new THREE.Light();
  3065. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  3066. /**
  3067. * @author mr.doob / http://mrdoob.com/
  3068. */
  3069. THREE.PointLight = function ( hex, intensity, distance ) {
  3070. THREE.Light.call( this, hex );
  3071. this.position = new THREE.Vector3( 0, 0, 0 );
  3072. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3073. this.distance = ( distance !== undefined ) ? distance : 0;
  3074. };
  3075. THREE.PointLight.prototype = new THREE.Light();
  3076. THREE.PointLight.prototype.constructor = THREE.PointLight;
  3077. /**
  3078. * @author alteredq / http://alteredqualia.com/
  3079. */
  3080. THREE.SpotLight = function ( hex, intensity, distance ) {
  3081. THREE.Light.call( this, hex );
  3082. this.position = new THREE.Vector3( 0, 1, 0 );
  3083. this.target = new THREE.Object3D();
  3084. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3085. this.distance = ( distance !== undefined ) ? distance : 0;
  3086. this.castShadow = false;
  3087. this.onlyShadow = false;
  3088. //
  3089. this.shadowCameraNear = 50;
  3090. this.shadowCameraFar = 5000;
  3091. this.shadowCameraFov = 50;
  3092. this.shadowCameraVisible = false;
  3093. this.shadowBias = 0;
  3094. this.shadowDarkness = 0.5;
  3095. this.shadowMapWidth = 512;
  3096. this.shadowMapHeight = 512;
  3097. //
  3098. this.shadowMap = null;
  3099. this.shadowMapSize = null;
  3100. this.shadowCamera = null;
  3101. this.shadowMatrix = null;
  3102. };
  3103. THREE.SpotLight.prototype = new THREE.Light();
  3104. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  3105. /**
  3106. * @author mr.doob / http://mrdoob.com/
  3107. * @author alteredq / http://alteredqualia.com/
  3108. */
  3109. THREE.Material = function ( parameters ) {
  3110. parameters = parameters || {};
  3111. this.id = THREE.MaterialCount ++;
  3112. this.name = '';
  3113. this.opacity = parameters.opacity !== undefined ? parameters.opacity : 1;
  3114. this.transparent = parameters.transparent !== undefined ? parameters.transparent : false;
  3115. this.blending = parameters.blending !== undefined ? parameters.blending : THREE.NormalBlending;
  3116. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  3117. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  3118. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  3119. this.depthTest = parameters.depthTest !== undefined ? parameters.depthTest : true;
  3120. this.depthWrite = parameters.depthWrite !== undefined ? parameters.depthWrite : true;
  3121. this.polygonOffset = parameters.polygonOffset !== undefined ? parameters.polygonOffset : false;
  3122. this.polygonOffsetFactor = parameters.polygonOffsetFactor !== undefined ? parameters.polygonOffsetFactor : 0;
  3123. this.polygonOffsetUnits = parameters.polygonOffsetUnits !== undefined ? parameters.polygonOffsetUnits : 0;
  3124. this.alphaTest = parameters.alphaTest !== undefined ? parameters.alphaTest : 0;
  3125. this.overdraw = parameters.overdraw !== undefined ? parameters.overdraw : false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  3126. this.needsUpdate = true;
  3127. }
  3128. THREE.MaterialCount = 0;
  3129. // shading
  3130. THREE.NoShading = 0;
  3131. THREE.FlatShading = 1;
  3132. THREE.SmoothShading = 2;
  3133. // colors
  3134. THREE.NoColors = 0;
  3135. THREE.FaceColors = 1;
  3136. THREE.VertexColors = 2;
  3137. // blending modes
  3138. THREE.NoBlending = 0;
  3139. THREE.NormalBlending = 1;
  3140. THREE.AdditiveBlending = 2;
  3141. THREE.SubtractiveBlending = 3;
  3142. THREE.MultiplyBlending = 4;
  3143. THREE.AdditiveAlphaBlending = 5;
  3144. THREE.CustomBlending = 6;
  3145. // custom blending equations
  3146. // (numbers start from 100 not to clash with other
  3147. // mappings to OpenGL constants defined in Texture.js)
  3148. THREE.AddEquation = 100;
  3149. THREE.SubtractEquation = 101;
  3150. THREE.ReverseSubtractEquation = 102;
  3151. // custom blending destination factors
  3152. THREE.ZeroFactor = 200;
  3153. THREE.OneFactor = 201;
  3154. THREE.SrcColorFactor = 202;
  3155. THREE.OneMinusSrcColorFactor = 203;
  3156. THREE.SrcAlphaFactor = 204;
  3157. THREE.OneMinusSrcAlphaFactor = 205;
  3158. THREE.DstAlphaFactor = 206;
  3159. THREE.OneMinusDstAlphaFactor = 207;
  3160. // custom blending source factors
  3161. //THREE.ZeroFactor = 200;
  3162. //THREE.OneFactor = 201;
  3163. //THREE.SrcAlphaFactor = 204;
  3164. //THREE.OneMinusSrcAlphaFactor = 205;
  3165. //THREE.DstAlphaFactor = 206;
  3166. //THREE.OneMinusDstAlphaFactor = 207;
  3167. THREE.DstColorFactor = 208;
  3168. THREE.OneMinusDstColorFactor = 209;
  3169. THREE.SrcAlphaSaturateFactor = 210;
  3170. /**
  3171. * @author mr.doob / http://mrdoob.com/
  3172. * @author alteredq / http://alteredqualia.com/
  3173. *
  3174. * parameters = {
  3175. * color: <hex>,
  3176. * opacity: <float>,
  3177. *
  3178. * blending: THREE.NormalBlending,
  3179. * depthTest: <bool>,
  3180. *
  3181. * linewidth: <float>,
  3182. * linecap: "round",
  3183. * linejoin: "round",
  3184. *
  3185. * vertexColors: <bool>
  3186. *
  3187. * fog: <bool>
  3188. * }
  3189. */
  3190. THREE.LineBasicMaterial = function ( parameters ) {
  3191. THREE.Material.call( this, parameters );
  3192. parameters = parameters || {};
  3193. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3194. this.linewidth = parameters.linewidth !== undefined ? parameters.linewidth : 1;
  3195. this.linecap = parameters.linecap !== undefined ? parameters.linecap : 'round';
  3196. this.linejoin = parameters.linejoin !== undefined ? parameters.linejoin : 'round';
  3197. this.vertexColors = parameters.vertexColors ? parameters.vertexColors : false;
  3198. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3199. };
  3200. THREE.LineBasicMaterial.prototype = new THREE.Material();
  3201. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  3202. /**
  3203. * @author mr.doob / http://mrdoob.com/
  3204. * @author alteredq / http://alteredqualia.com/
  3205. *
  3206. * parameters = {
  3207. * color: <hex>,
  3208. * opacity: <float>,
  3209. * map: new THREE.Texture( <Image> ),
  3210. *
  3211. * lightMap: new THREE.Texture( <Image> ),
  3212. *
  3213. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  3214. * combine: THREE.Multiply,
  3215. * reflectivity: <float>,
  3216. * refractionRatio: <float>,
  3217. *
  3218. * shading: THREE.SmoothShading,
  3219. * blending: THREE.NormalBlending,
  3220. * depthTest: <bool>,
  3221. *
  3222. * wireframe: <boolean>,
  3223. * wireframeLinewidth: <float>,
  3224. *
  3225. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3226. *
  3227. * skinning: <bool>,
  3228. * morphTargets: <bool>,
  3229. *
  3230. * fog: <bool>
  3231. * }
  3232. */
  3233. THREE.MeshBasicMaterial = function ( parameters ) {
  3234. THREE.Material.call( this, parameters );
  3235. parameters = parameters || {};
  3236. // color property represents emissive for MeshBasicMaterial
  3237. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3238. this.map = parameters.map !== undefined ? parameters.map : null;
  3239. this.lightMap = parameters.lightMap !== undefined ? parameters.lightMap : null;
  3240. this.envMap = parameters.envMap !== undefined ? parameters.envMap : null;
  3241. this.combine = parameters.combine !== undefined ? parameters.combine : THREE.MultiplyOperation;
  3242. this.reflectivity = parameters.reflectivity !== undefined ? parameters.reflectivity : 1;
  3243. this.refractionRatio = parameters.refractionRatio !== undefined ? parameters.refractionRatio : 0.98;
  3244. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3245. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3246. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3247. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3248. this.wireframeLinecap = parameters.wireframeLinecap !== undefined ? parameters.wireframeLinecap : 'round';
  3249. this.wireframeLinejoin = parameters.wireframeLinejoin !== undefined ? parameters.wireframeLinejoin : 'round';
  3250. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors;
  3251. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false;
  3252. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false;
  3253. };
  3254. THREE.MeshBasicMaterial.prototype = new THREE.Material();
  3255. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  3256. /**
  3257. * @author mr.doob / http://mrdoob.com/
  3258. * @author alteredq / http://alteredqualia.com/
  3259. *
  3260. * parameters = {
  3261. * color: <hex>,
  3262. * ambient: <hex>,
  3263. * emissive: <hex>,
  3264. * opacity: <float>,
  3265. *
  3266. * map: new THREE.Texture( <Image> ),
  3267. *
  3268. * lightMap: new THREE.Texture( <Image> ),
  3269. *
  3270. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  3271. * combine: THREE.Multiply,
  3272. * reflectivity: <float>,
  3273. * refractionRatio: <float>,
  3274. *
  3275. * shading: THREE.SmoothShading,
  3276. * blending: THREE.NormalBlending,
  3277. * depthTest: <bool>,
  3278. *
  3279. * wireframe: <boolean>,
  3280. * wireframeLinewidth: <float>,
  3281. *
  3282. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3283. *
  3284. * skinning: <bool>,
  3285. * morphTargets: <bool>,
  3286. * morphNormals: <bool>,
  3287. *
  3288. * fog: <bool>
  3289. * }
  3290. */
  3291. THREE.MeshLambertMaterial = function ( parameters ) {
  3292. THREE.Material.call( this, parameters );
  3293. parameters = parameters || {};
  3294. // color property represents diffuse for MeshLambertMaterial
  3295. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3296. this.ambient = parameters.ambient !== undefined ? new THREE.Color( parameters.ambient ) : new THREE.Color( 0xffffff );
  3297. this.emissive = parameters.emissive !== undefined ? new THREE.Color( parameters.emissive ) : new THREE.Color( 0x000000 );
  3298. this.wrapAround = parameters.wrapAround !== undefined ? parameters.wrapAround: false;
  3299. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  3300. this.map = parameters.map !== undefined ? parameters.map : null;
  3301. this.lightMap = parameters.lightMap !== undefined ? parameters.lightMap : null;
  3302. this.envMap = parameters.envMap !== undefined ? parameters.envMap : null;
  3303. this.combine = parameters.combine !== undefined ? parameters.combine : THREE.MultiplyOperation;
  3304. this.reflectivity = parameters.reflectivity !== undefined ? parameters.reflectivity : 1;
  3305. this.refractionRatio = parameters.refractionRatio !== undefined ? parameters.refractionRatio : 0.98;
  3306. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3307. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3308. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3309. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3310. this.wireframeLinecap = parameters.wireframeLinecap !== undefined ? parameters.wireframeLinecap : 'round';
  3311. this.wireframeLinejoin = parameters.wireframeLinejoin !== undefined ? parameters.wireframeLinejoin : 'round';
  3312. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors;
  3313. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false;
  3314. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false;
  3315. this.morphNormals = parameters.morphNormals !== undefined ? parameters.morphNormals : false;
  3316. };
  3317. THREE.MeshLambertMaterial.prototype = new THREE.Material();
  3318. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  3319. /**
  3320. * @author mr.doob / http://mrdoob.com/
  3321. * @author alteredq / http://alteredqualia.com/
  3322. *
  3323. * parameters = {
  3324. * color: <hex>,
  3325. * ambient: <hex>,
  3326. * emissive: <hex>,
  3327. * specular: <hex>,
  3328. * shininess: <float>,
  3329. * opacity: <float>,
  3330. *
  3331. * map: new THREE.Texture( <Image> ),
  3332. *
  3333. * lightMap: new THREE.Texture( <Image> ),
  3334. *
  3335. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  3336. * combine: THREE.Multiply,
  3337. * reflectivity: <float>,
  3338. * refractionRatio: <float>,
  3339. *
  3340. * shading: THREE.SmoothShading,
  3341. * blending: THREE.NormalBlending,
  3342. * depthTest: <bool>,
  3343. *
  3344. * wireframe: <boolean>,
  3345. * wireframeLinewidth: <float>,
  3346. *
  3347. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3348. *
  3349. * skinning: <bool>,
  3350. * morphTargets: <bool>,
  3351. * morphNormals: <bool>,
  3352. *
  3353. * fog: <bool>
  3354. * }
  3355. */
  3356. THREE.MeshPhongMaterial = function ( parameters ) {
  3357. THREE.Material.call( this, parameters );
  3358. parameters = parameters || {};
  3359. // color property represents diffuse for MeshPhongMaterial
  3360. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3361. this.ambient = parameters.ambient !== undefined ? new THREE.Color( parameters.ambient ) : new THREE.Color( 0xffffff );
  3362. this.emissive = parameters.emissive !== undefined ? new THREE.Color( parameters.emissive ) : new THREE.Color( 0x000000 );
  3363. this.specular = parameters.specular !== undefined ? new THREE.Color( parameters.specular ) : new THREE.Color( 0x111111 );
  3364. this.shininess = parameters.shininess !== undefined ? parameters.shininess : 30;
  3365. this.metal = parameters.metal !== undefined ? parameters.metal : false;
  3366. this.perPixel = parameters.perPixel !== undefined ? parameters.perPixel : false;
  3367. this.wrapAround = parameters.wrapAround !== undefined ? parameters.wrapAround: false;
  3368. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  3369. this.map = parameters.map !== undefined ? parameters.map : null;
  3370. this.lightMap = parameters.lightMap !== undefined ? parameters.lightMap : null;
  3371. this.envMap = parameters.envMap !== undefined ? parameters.envMap : null;
  3372. this.combine = parameters.combine !== undefined ? parameters.combine : THREE.MultiplyOperation;
  3373. this.reflectivity = parameters.reflectivity !== undefined ? parameters.reflectivity : 1;
  3374. this.refractionRatio = parameters.refractionRatio !== undefined ? parameters.refractionRatio : 0.98;
  3375. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3376. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3377. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3378. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3379. this.wireframeLinecap = parameters.wireframeLinecap !== undefined ? parameters.wireframeLinecap : 'round';
  3380. this.wireframeLinejoin = parameters.wireframeLinejoin !== undefined ? parameters.wireframeLinejoin : 'round';
  3381. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors;
  3382. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false;
  3383. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false;
  3384. this.morphNormals = parameters.morphNormals !== undefined ? parameters.morphNormals : false;
  3385. };
  3386. THREE.MeshPhongMaterial.prototype = new THREE.Material();
  3387. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  3388. /**
  3389. * @author mr.doob / http://mrdoob.com/
  3390. * @author alteredq / http://alteredqualia.com/
  3391. *
  3392. * parameters = {
  3393. * opacity: <float>,
  3394. * blending: THREE.NormalBlending,
  3395. * depthTest: <bool>,
  3396. * wireframe: <boolean>,
  3397. * wireframeLinewidth: <float>
  3398. * }
  3399. */
  3400. THREE.MeshDepthMaterial = function ( parameters ) {
  3401. THREE.Material.call( this, parameters );
  3402. parameters = parameters || {};
  3403. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading; // doesn't really apply here, normals are not used
  3404. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3405. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3406. };
  3407. THREE.MeshDepthMaterial.prototype = new THREE.Material();
  3408. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  3409. /**
  3410. * @author mr.doob / http://mrdoob.com/
  3411. *
  3412. * parameters = {
  3413. * opacity: <float>,
  3414. * shading: THREE.FlatShading,
  3415. * blending: THREE.NormalBlending,
  3416. * depthTest: <bool>,
  3417. * wireframe: <boolean>,
  3418. * wireframeLinewidth: <float>
  3419. * }
  3420. */
  3421. THREE.MeshNormalMaterial = function ( parameters ) {
  3422. THREE.Material.call( this, parameters );
  3423. parameters = parameters || {};
  3424. this.shading = parameters.shading ? parameters.shading : THREE.FlatShading;
  3425. this.wireframe = parameters.wireframe ? parameters.wireframe : false;
  3426. this.wireframeLinewidth = parameters.wireframeLinewidth ? parameters.wireframeLinewidth : 1;
  3427. };
  3428. THREE.MeshNormalMaterial.prototype = new THREE.Material();
  3429. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  3430. /**
  3431. * @author mr.doob / http://mrdoob.com/
  3432. */
  3433. THREE.MeshFaceMaterial = function () {
  3434. };
  3435. /**
  3436. * @author mr.doob / http://mrdoob.com/
  3437. * @author alteredq / http://alteredqualia.com/
  3438. *
  3439. * parameters = {
  3440. * color: <hex>,
  3441. * opacity: <float>,
  3442. * map: new THREE.Texture( <Image> ),
  3443. *
  3444. * size: <float>,
  3445. *
  3446. * blending: THREE.NormalBlending,
  3447. * depthTest: <bool>,
  3448. *
  3449. * vertexColors: <bool>,
  3450. *
  3451. * fog: <bool>
  3452. * }
  3453. */
  3454. THREE.ParticleBasicMaterial = function ( parameters ) {
  3455. THREE.Material.call( this, parameters );
  3456. parameters = parameters || {};
  3457. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3458. this.map = parameters.map !== undefined ? parameters.map : null;
  3459. this.size = parameters.size !== undefined ? parameters.size : 1;
  3460. this.sizeAttenuation = parameters.sizeAttenuation !== undefined ? parameters.sizeAttenuation : true;
  3461. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : false;
  3462. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3463. };
  3464. THREE.ParticleBasicMaterial.prototype = new THREE.Material();
  3465. THREE.ParticleBasicMaterial.prototype.constructor = THREE.ParticleBasicMaterial;
  3466. /**
  3467. * @author mr.doob / http://mrdoob.com/
  3468. *
  3469. * parameters = {
  3470. * color: <hex>,
  3471. * program: <function>,
  3472. * opacity: <float>,
  3473. * blending: THREE.NormalBlending
  3474. * }
  3475. */
  3476. THREE.ParticleCanvasMaterial = function ( parameters ) {
  3477. THREE.Material.call( this, parameters );
  3478. parameters = parameters || {};
  3479. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3480. this.program = parameters.program !== undefined ? parameters.program : function ( context, color ) {};
  3481. };
  3482. THREE.ParticleCanvasMaterial.prototype = new THREE.Material();
  3483. THREE.ParticleCanvasMaterial.prototype.constructor = THREE.ParticleCanvasMaterial;
  3484. /**
  3485. * @author mr.doob / http://mrdoob.com/
  3486. */
  3487. THREE.ParticleDOMMaterial = function ( domElement ) {
  3488. THREE.Material.call( this );
  3489. this.domElement = domElement;
  3490. };
  3491. /**
  3492. * @author alteredq / http://alteredqualia.com/
  3493. *
  3494. * parameters = {
  3495. * fragmentShader: <string>,
  3496. * vertexShader: <string>,
  3497. *
  3498. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  3499. *
  3500. * shading: THREE.SmoothShading,
  3501. * blending: THREE.NormalBlending,
  3502. * depthTest: <bool>,
  3503. *
  3504. * wireframe: <boolean>,
  3505. * wireframeLinewidth: <float>,
  3506. *
  3507. * lights: <bool>,
  3508. *
  3509. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3510. *
  3511. * skinning: <bool>,
  3512. * morphTargets: <bool>,
  3513. * morphNormals: <bool>,
  3514. *
  3515. * fog: <bool>
  3516. * }
  3517. */
  3518. THREE.ShaderMaterial = function ( parameters ) {
  3519. THREE.Material.call( this, parameters );
  3520. parameters = parameters || {};
  3521. this.fragmentShader = parameters.fragmentShader !== undefined ? parameters.fragmentShader : "void main() {}";
  3522. this.vertexShader = parameters.vertexShader !== undefined ? parameters.vertexShader : "void main() {}";
  3523. this.uniforms = parameters.uniforms !== undefined ? parameters.uniforms : {};
  3524. this.attributes = parameters.attributes;
  3525. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3526. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3527. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3528. this.fog = parameters.fog !== undefined ? parameters.fog : false; // set to use scene fog
  3529. this.lights = parameters.lights !== undefined ? parameters.lights : false; // set to use scene lights
  3530. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors; // set to use "color" attribute stream
  3531. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false; // set to use skinning attribute streams
  3532. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false; // set to use morph targets
  3533. this.morphNormals = parameters.morphNormals !== undefined ? parameters.morphNormals : false; // set to use morph normals
  3534. };
  3535. THREE.ShaderMaterial.prototype = new THREE.Material();
  3536. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  3537. /**
  3538. * @author mr.doob / http://mrdoob.com/
  3539. * @author alteredq / http://alteredqualia.com/
  3540. * @author szimek / https://github.com/szimek/
  3541. */
  3542. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type ) {
  3543. this.id = THREE.TextureCount ++;
  3544. this.image = image;
  3545. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  3546. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  3547. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  3548. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  3549. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  3550. this.format = format !== undefined ? format : THREE.RGBAFormat;
  3551. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  3552. this.offset = new THREE.Vector2( 0, 0 );
  3553. this.repeat = new THREE.Vector2( 1, 1 );
  3554. this.generateMipmaps = true;
  3555. this.premultiplyAlpha = false;
  3556. this.needsUpdate = false;
  3557. this.onUpdate = null;
  3558. };
  3559. THREE.Texture.prototype = {
  3560. constructor: THREE.Texture,
  3561. clone: function () {
  3562. var clonedTexture = new THREE.Texture( this.image, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter, this.format, this.type );
  3563. clonedTexture.offset.copy( this.offset );
  3564. clonedTexture.repeat.copy( this.repeat );
  3565. return clonedTexture;
  3566. }
  3567. };
  3568. THREE.TextureCount = 0;
  3569. THREE.MultiplyOperation = 0;
  3570. THREE.MixOperation = 1;
  3571. // Mapping modes
  3572. THREE.UVMapping = function () {};
  3573. THREE.CubeReflectionMapping = function () {};
  3574. THREE.CubeRefractionMapping = function () {};
  3575. THREE.SphericalReflectionMapping = function () {};
  3576. THREE.SphericalRefractionMapping = function () {};
  3577. // Wrapping modes
  3578. THREE.RepeatWrapping = 0;
  3579. THREE.ClampToEdgeWrapping = 1;
  3580. THREE.MirroredRepeatWrapping = 2;
  3581. // Filters
  3582. THREE.NearestFilter = 3;
  3583. THREE.NearestMipMapNearestFilter = 4;
  3584. THREE.NearestMipMapLinearFilter = 5;
  3585. THREE.LinearFilter = 6;
  3586. THREE.LinearMipMapNearestFilter = 7;
  3587. THREE.LinearMipMapLinearFilter = 8;
  3588. // Types
  3589. THREE.ByteType = 9;
  3590. THREE.UnsignedByteType = 10;
  3591. THREE.ShortType = 11;
  3592. THREE.UnsignedShortType = 12;
  3593. THREE.IntType = 13;
  3594. THREE.UnsignedIntType = 14;
  3595. THREE.FloatType = 15;
  3596. // Formats
  3597. THREE.AlphaFormat = 16;
  3598. THREE.RGBFormat = 17;
  3599. THREE.RGBAFormat = 18;
  3600. THREE.LuminanceFormat = 19;
  3601. THREE.LuminanceAlphaFormat = 20;
  3602. /**
  3603. * @author alteredq / http://alteredqualia.com/
  3604. */
  3605. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  3606. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  3607. this.image = { data: data, width: width, height: height };
  3608. };
  3609. THREE.DataTexture.prototype = new THREE.Texture();
  3610. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  3611. THREE.DataTexture.prototype.clone = function () {
  3612. 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 );
  3613. clonedTexture.offset.copy( this.offset );
  3614. clonedTexture.repeat.copy( this.repeat );
  3615. return clonedTexture;
  3616. };
  3617. /**
  3618. * @author mr.doob / http://mrdoob.com/
  3619. */
  3620. THREE.Particle = function ( material ) {
  3621. THREE.Object3D.call( this );
  3622. this.material = material;
  3623. };
  3624. THREE.Particle.prototype = new THREE.Object3D();
  3625. THREE.Particle.prototype.constructor = THREE.Particle;
  3626. /**
  3627. * @author alteredq / http://alteredqualia.com/
  3628. */
  3629. THREE.ParticleSystem = function ( geometry, material ) {
  3630. THREE.Object3D.call( this );
  3631. this.geometry = geometry;
  3632. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  3633. this.sortParticles = false;
  3634. if ( this.geometry ) {
  3635. // calc bound radius
  3636. if( !this.geometry.boundingSphere ) {
  3637. this.geometry.computeBoundingSphere();
  3638. }
  3639. this.boundRadius = geometry.boundingSphere.radius;
  3640. }
  3641. this.frustumCulled = false;
  3642. };
  3643. THREE.ParticleSystem.prototype = new THREE.Object3D();
  3644. THREE.ParticleSystem.prototype.constructor = THREE.ParticleSystem;
  3645. /**
  3646. * @author mr.doob / http://mrdoob.com/
  3647. */
  3648. THREE.Line = function ( geometry, material, type ) {
  3649. THREE.Object3D.call( this );
  3650. this.geometry = geometry;
  3651. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  3652. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  3653. if ( this.geometry ) {
  3654. if ( ! this.geometry.boundingSphere ) {
  3655. this.geometry.computeBoundingSphere();
  3656. }
  3657. }
  3658. };
  3659. THREE.LineStrip = 0;
  3660. THREE.LinePieces = 1;
  3661. THREE.Line.prototype = new THREE.Object3D();
  3662. THREE.Line.prototype.constructor = THREE.Line;
  3663. /**
  3664. * @author mr.doob / http://mrdoob.com/
  3665. * @author alteredq / http://alteredqualia.com/
  3666. * @author mikael emtinger / http://gomo.se/
  3667. */
  3668. THREE.Mesh = function ( geometry, material ) {
  3669. THREE.Object3D.call( this );
  3670. this.geometry = geometry;
  3671. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  3672. if ( this.geometry ) {
  3673. // calc bound radius
  3674. if( ! this.geometry.boundingSphere ) {
  3675. this.geometry.computeBoundingSphere();
  3676. }
  3677. this.boundRadius = geometry.boundingSphere.radius;
  3678. // setup morph targets
  3679. if( this.geometry.morphTargets.length ) {
  3680. this.morphTargetBase = -1;
  3681. this.morphTargetForcedOrder = [];
  3682. this.morphTargetInfluences = [];
  3683. this.morphTargetDictionary = {};
  3684. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  3685. this.morphTargetInfluences.push( 0 );
  3686. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  3687. }
  3688. }
  3689. }
  3690. }
  3691. THREE.Mesh.prototype = new THREE.Object3D();
  3692. THREE.Mesh.prototype.constructor = THREE.Mesh;
  3693. THREE.Mesh.prototype.supr = THREE.Object3D.prototype;
  3694. /*
  3695. * Get Morph Target Index by Name
  3696. */
  3697. THREE.Mesh.prototype.getMorphTargetIndexByName = function( name ) {
  3698. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  3699. return this.morphTargetDictionary[ name ];
  3700. }
  3701. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  3702. return 0;
  3703. }
  3704. /**
  3705. * @author mikael emtinger / http://gomo.se/
  3706. * @author alteredq / http://alteredqualia.com/
  3707. */
  3708. THREE.Bone = function( belongsToSkin ) {
  3709. THREE.Object3D.call( this );
  3710. this.skin = belongsToSkin;
  3711. this.skinMatrix = new THREE.Matrix4();
  3712. };
  3713. THREE.Bone.prototype = new THREE.Object3D();
  3714. THREE.Bone.prototype.constructor = THREE.Bone;
  3715. THREE.Bone.prototype.supr = THREE.Object3D.prototype;
  3716. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  3717. // update local
  3718. if ( this.matrixAutoUpdate ) {
  3719. forceUpdate |= this.updateMatrix();
  3720. }
  3721. // update skin matrix
  3722. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  3723. if( parentSkinMatrix ) {
  3724. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  3725. } else {
  3726. this.skinMatrix.copy( this.matrix );
  3727. }
  3728. this.matrixWorldNeedsUpdate = false;
  3729. forceUpdate = true;
  3730. }
  3731. // update children
  3732. var child, i, l = this.children.length;
  3733. for ( i = 0; i < l; i ++ ) {
  3734. this.children[ i ].update( this.skinMatrix, forceUpdate );
  3735. }
  3736. };
  3737. /**
  3738. * @author mikael emtinger / http://gomo.se/
  3739. * @author alteredq / http://alteredqualia.com/
  3740. */
  3741. THREE.SkinnedMesh = function ( geometry, material ) {
  3742. THREE.Mesh.call( this, geometry, material );
  3743. // init bones
  3744. this.identityMatrix = new THREE.Matrix4();
  3745. this.bones = [];
  3746. this.boneMatrices = [];
  3747. var b, bone, gbone, p, q, s;
  3748. if ( this.geometry.bones !== undefined ) {
  3749. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  3750. gbone = this.geometry.bones[ b ];
  3751. p = gbone.pos;
  3752. q = gbone.rotq;
  3753. s = gbone.scl;
  3754. bone = this.addBone();
  3755. bone.name = gbone.name;
  3756. bone.position.set( p[0], p[1], p[2] );
  3757. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  3758. bone.useQuaternion = true;
  3759. if ( s !== undefined ) {
  3760. bone.scale.set( s[0], s[1], s[2] );
  3761. } else {
  3762. bone.scale.set( 1, 1, 1 );
  3763. }
  3764. }
  3765. for ( b = 0; b < this.bones.length; b ++ ) {
  3766. gbone = this.geometry.bones[ b ];
  3767. bone = this.bones[ b ];
  3768. if ( gbone.parent === -1 ) {
  3769. this.add( bone );
  3770. } else {
  3771. this.bones[ gbone.parent ].add( bone );
  3772. }
  3773. }
  3774. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  3775. this.pose();
  3776. }
  3777. };
  3778. THREE.SkinnedMesh.prototype = new THREE.Mesh();
  3779. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  3780. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  3781. if ( bone === undefined ) {
  3782. bone = new THREE.Bone( this );
  3783. }
  3784. this.bones.push( bone );
  3785. return bone;
  3786. };
  3787. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  3788. this.matrixAutoUpdate && this.updateMatrix();
  3789. // update matrixWorld
  3790. if ( this.matrixWorldNeedsUpdate || force ) {
  3791. if ( this.parent ) {
  3792. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  3793. } else {
  3794. this.matrixWorld.copy( this.matrix );
  3795. }
  3796. this.matrixWorldNeedsUpdate = false;
  3797. force = true;
  3798. }
  3799. // update children
  3800. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3801. var child = this.children[ i ];
  3802. if ( child instanceof THREE.Bone ) {
  3803. child.update( this.identityMatrix, false );
  3804. } else {
  3805. child.updateMatrixWorld( true );
  3806. }
  3807. }
  3808. // flatten bone matrices to array
  3809. var b, bl = this.bones.length,
  3810. ba = this.bones,
  3811. bm = this.boneMatrices;
  3812. for ( b = 0; b < bl; b ++ ) {
  3813. ba[ b ].skinMatrix.flattenToArrayOffset( bm, b * 16 );
  3814. }
  3815. };
  3816. /*
  3817. * Pose
  3818. */
  3819. THREE.SkinnedMesh.prototype.pose = function() {
  3820. this.updateMatrixWorld( true );
  3821. var bim, bone, boneInverses = [];
  3822. for ( var b = 0; b < this.bones.length; b ++ ) {
  3823. bone = this.bones[ b ];
  3824. var inverseMatrix = new THREE.Matrix4();
  3825. inverseMatrix.getInverse( bone.skinMatrix );
  3826. boneInverses.push( inverseMatrix );
  3827. bone.skinMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  3828. }
  3829. // project vertices to local
  3830. if ( this.geometry.skinVerticesA === undefined ) {
  3831. this.geometry.skinVerticesA = [];
  3832. this.geometry.skinVerticesB = [];
  3833. var orgVertex, vertex;
  3834. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  3835. orgVertex = this.geometry.vertices[ i ];
  3836. var indexA = this.geometry.skinIndices[ i ].x;
  3837. var indexB = this.geometry.skinIndices[ i ].y;
  3838. vertex = new THREE.Vector3( orgVertex.x, orgVertex.y, orgVertex.z );
  3839. this.geometry.skinVerticesA.push( boneInverses[ indexA ].multiplyVector3( vertex ) );
  3840. vertex = new THREE.Vector3( orgVertex.x, orgVertex.y, orgVertex.z );
  3841. this.geometry.skinVerticesB.push( boneInverses[ indexB ].multiplyVector3( vertex ) );
  3842. // todo: add more influences
  3843. // normalize weights
  3844. if ( this.geometry.skinWeights[ i ].x + this.geometry.skinWeights[ i ].y !== 1 ) {
  3845. var len = ( 1.0 - ( this.geometry.skinWeights[ i ].x + this.geometry.skinWeights[ i ].y ) ) * 0.5;
  3846. this.geometry.skinWeights[ i ].x += len;
  3847. this.geometry.skinWeights[ i ].y += len;
  3848. }
  3849. }
  3850. }
  3851. };
  3852. /**
  3853. * @author alteredq / http://alteredqualia.com/
  3854. */
  3855. THREE.MorphAnimMesh = function ( geometry, material ) {
  3856. THREE.Mesh.call( this, geometry, material );
  3857. // API
  3858. this.duration = 1000; // milliseconds
  3859. this.mirroredLoop = false;
  3860. this.time = 0;
  3861. // internals
  3862. this.lastKeyframe = 0;
  3863. this.currentKeyframe = 0;
  3864. this.direction = 1;
  3865. this.directionBackwards = false;
  3866. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  3867. };
  3868. THREE.MorphAnimMesh.prototype = new THREE.Mesh();
  3869. THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh;
  3870. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  3871. this.startKeyframe = start;
  3872. this.endKeyframe = end;
  3873. this.length = this.endKeyframe - this.startKeyframe + 1;
  3874. };
  3875. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  3876. this.direction = 1;
  3877. this.directionBackwards = false;
  3878. };
  3879. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  3880. this.direction = -1;
  3881. this.directionBackwards = true;
  3882. };
  3883. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  3884. var geometry = this.geometry;
  3885. if ( ! geometry.animations ) geometry.animations = {};
  3886. var firstAnimation, animations = geometry.animations;
  3887. var pattern = /([a-z]+)(\d+)/;
  3888. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  3889. var morph = geometry.morphTargets[ i ];
  3890. var parts = morph.name.match( pattern );
  3891. if ( parts && parts.length > 1 ) {
  3892. var label = parts[ 1 ];
  3893. var num = parts[ 2 ];
  3894. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  3895. var animation = animations[ label ];
  3896. if ( i < animation.start ) animation.start = i;
  3897. if ( i > animation.end ) animation.end = i;
  3898. if ( ! firstAnimation ) firstAnimation = label;
  3899. }
  3900. }
  3901. geometry.firstAnimation = firstAnimation;
  3902. };
  3903. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  3904. if ( ! this.geometry.animations ) this.geometry.animations = {};
  3905. this.geometry.animations[ label ] = { start: start, end: end };
  3906. };
  3907. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  3908. var animation = this.geometry.animations[ label ];
  3909. if ( animation ) {
  3910. this.setFrameRange( animation.start, animation.end );
  3911. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  3912. this.time = 0;
  3913. } else {
  3914. console.warn( "animation[" + label + "] undefined" );
  3915. }
  3916. };
  3917. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  3918. var frameTime = this.duration / this.length;
  3919. this.time += this.direction * delta;
  3920. if ( this.mirroredLoop ) {
  3921. if ( this.time > this.duration || this.time < 0 ) {
  3922. this.direction *= -1;
  3923. if ( this.time > this.duration ) {
  3924. this.time = this.duration;
  3925. this.directionBackwards = true;
  3926. }
  3927. if ( this.time < 0 ) {
  3928. this.time = 0;
  3929. this.directionBackwards = false;
  3930. }
  3931. }
  3932. } else {
  3933. this.time = this.time % this.duration;
  3934. if ( this.time < 0 ) this.time += this.duration;
  3935. }
  3936. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  3937. if ( keyframe !== this.currentKeyframe ) {
  3938. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  3939. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  3940. this.morphTargetInfluences[ keyframe ] = 0;
  3941. this.lastKeyframe = this.currentKeyframe;
  3942. this.currentKeyframe = keyframe;
  3943. }
  3944. var mix = ( this.time % frameTime ) / frameTime;
  3945. if ( this.directionBackwards ) {
  3946. mix = 1 - mix;
  3947. }
  3948. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  3949. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  3950. };
  3951. /**
  3952. * @author alteredq / http://alteredqualia.com/
  3953. */
  3954. THREE.Ribbon = function ( geometry, material ) {
  3955. THREE.Object3D.call( this );
  3956. this.geometry = geometry;
  3957. this.material = material;
  3958. };
  3959. THREE.Ribbon.prototype = new THREE.Object3D();
  3960. THREE.Ribbon.prototype.constructor = THREE.Ribbon;
  3961. /**
  3962. * @author mikael emtinger / http://gomo.se/
  3963. * @author alteredq / http://alteredqualia.com/
  3964. * @author mr.doob / http://mrdoob.com/
  3965. */
  3966. THREE.LOD = function () {
  3967. THREE.Object3D.call( this );
  3968. this.LODs = [];
  3969. };
  3970. THREE.LOD.prototype = new THREE.Object3D();
  3971. THREE.LOD.prototype.constructor = THREE.LOD;
  3972. THREE.LOD.prototype.supr = THREE.Object3D.prototype;
  3973. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  3974. if ( visibleAtDistance === undefined ) {
  3975. visibleAtDistance = 0;
  3976. }
  3977. visibleAtDistance = Math.abs( visibleAtDistance );
  3978. for ( var l = 0; l < this.LODs.length; l ++ ) {
  3979. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  3980. break;
  3981. }
  3982. }
  3983. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  3984. this.add( object3D );
  3985. };
  3986. THREE.LOD.prototype.update = function ( camera ) {
  3987. if ( this.LODs.length > 1 ) {
  3988. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3989. var inverse = camera.matrixWorldInverse;
  3990. 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] );
  3991. this.LODs[ 0 ].object3D.visible = true;
  3992. for ( var l = 1; l < this.LODs.length; l ++ ) {
  3993. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  3994. this.LODs[ l - 1 ].object3D.visible = false;
  3995. this.LODs[ l ].object3D.visible = true;
  3996. } else {
  3997. break;
  3998. }
  3999. }
  4000. for( ; l < this.LODs.length; l ++ ) {
  4001. this.LODs[ l ].object3D.visible = false;
  4002. }
  4003. }
  4004. };
  4005. /**
  4006. * @author mikael emtinger / http://gomo.se/
  4007. */
  4008. THREE.Sprite = function ( parameters ) {
  4009. THREE.Object3D.call( this );
  4010. this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  4011. this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();
  4012. this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;
  4013. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  4014. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  4015. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  4016. this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
  4017. this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
  4018. this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
  4019. this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
  4020. this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center;
  4021. this.rotation3d = this.rotation;
  4022. this.rotation = 0;
  4023. this.opacity = 1;
  4024. this.uvOffset = new THREE.Vector2( 0, 0 );
  4025. this.uvScale = new THREE.Vector2( 1, 1 );
  4026. };
  4027. THREE.Sprite.prototype = new THREE.Object3D();
  4028. THREE.Sprite.prototype.constructor = THREE.Sprite;
  4029. /*
  4030. * Custom update matrix
  4031. */
  4032. THREE.Sprite.prototype.updateMatrix = function () {
  4033. this.matrix.setPosition( this.position );
  4034. this.rotation3d.set( 0, 0, this.rotation );
  4035. this.matrix.setRotationFromEuler( this.rotation3d );
  4036. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  4037. this.matrix.scale( this.scale );
  4038. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  4039. }
  4040. this.matrixWorldNeedsUpdate = true;
  4041. };
  4042. /*
  4043. * Alignment
  4044. */
  4045. THREE.SpriteAlignment = {};
  4046. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  4047. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  4048. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  4049. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  4050. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  4051. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  4052. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  4053. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  4054. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  4055. /**
  4056. * @author mr.doob / http://mrdoob.com/
  4057. */
  4058. THREE.Scene = function () {
  4059. THREE.Object3D.call( this );
  4060. this.fog = null;
  4061. this.overrideMaterial = null;
  4062. this.matrixAutoUpdate = false;
  4063. this.__objects = [];
  4064. this.__lights = [];
  4065. this.__objectsAdded = [];
  4066. this.__objectsRemoved = [];
  4067. };
  4068. THREE.Scene.prototype = new THREE.Object3D();
  4069. THREE.Scene.prototype.constructor = THREE.Scene;
  4070. THREE.Scene.prototype.__addObject = function ( object ) {
  4071. if ( object instanceof THREE.Light ) {
  4072. if ( this.__lights.indexOf( object ) === - 1 ) {
  4073. this.__lights.push( object );
  4074. }
  4075. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  4076. if ( this.__objects.indexOf( object ) === - 1 ) {
  4077. this.__objects.push( object );
  4078. this.__objectsAdded.push( object );
  4079. // check if previously removed
  4080. var i = this.__objectsRemoved.indexOf( object );
  4081. if ( i !== -1 ) {
  4082. this.__objectsRemoved.splice( i, 1 );
  4083. }
  4084. }
  4085. }
  4086. for ( var c = 0; c < object.children.length; c ++ ) {
  4087. this.__addObject( object.children[ c ] );
  4088. }
  4089. };
  4090. THREE.Scene.prototype.__removeObject = function ( object ) {
  4091. if ( object instanceof THREE.Light ) {
  4092. var i = this.__lights.indexOf( object );
  4093. if ( i !== -1 ) {
  4094. this.__lights.splice( i, 1 );
  4095. }
  4096. } else if ( !( object instanceof THREE.Camera ) ) {
  4097. var i = this.__objects.indexOf( object );
  4098. if( i !== -1 ) {
  4099. this.__objects.splice( i, 1 );
  4100. this.__objectsRemoved.push( object );
  4101. // check if previously added
  4102. var ai = this.__objectsAdded.indexOf( object );
  4103. if ( ai !== -1 ) {
  4104. this.__objectsAdded.splice( ai, 1 );
  4105. }
  4106. }
  4107. }
  4108. for ( var c = 0; c < object.children.length; c ++ ) {
  4109. this.__removeObject( object.children[ c ] );
  4110. }
  4111. };
  4112. /**
  4113. * @author mr.doob / http://mrdoob.com/
  4114. * @author alteredq / http://alteredqualia.com/
  4115. */
  4116. THREE.Fog = function ( hex, near, far ) {
  4117. this.color = new THREE.Color( hex );
  4118. this.near = ( near !== undefined ) ? near : 1;
  4119. this.far = ( far !== undefined ) ? far : 1000;
  4120. };
  4121. /**
  4122. * @author mr.doob / http://mrdoob.com/
  4123. * @author alteredq / http://alteredqualia.com/
  4124. */
  4125. THREE.FogExp2 = function ( hex, density ) {
  4126. this.color = new THREE.Color( hex );
  4127. this.density = ( density !== undefined ) ? density : 0.00025;
  4128. };
  4129. /**
  4130. * @author mr.doob / http://mrdoob.com/
  4131. */
  4132. THREE.DOMRenderer = function () {
  4133. console.log( 'THREE.DOMRenderer', THREE.REVISION );
  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. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  4182. parameters = parameters || {};
  4183. var _this = this,
  4184. _renderData, _elements, _lights,
  4185. _projector = new THREE.Projector(),
  4186. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  4187. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  4188. _context = _canvas.getContext( '2d' ),
  4189. _clearColor = new THREE.Color( 0x000000 ),
  4190. _clearOpacity = 0,
  4191. _contextGlobalAlpha = 1,
  4192. _contextGlobalCompositeOperation = 0,
  4193. _contextStrokeStyle = null,
  4194. _contextFillStyle = null,
  4195. _contextLineWidth = null,
  4196. _contextLineCap = null,
  4197. _contextLineJoin = null,
  4198. _v1, _v2, _v3, _v4,
  4199. _v5 = new THREE.RenderableVertex(),
  4200. _v6 = new THREE.RenderableVertex(),
  4201. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  4202. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  4203. _color = new THREE.Color(),
  4204. _color1 = new THREE.Color(),
  4205. _color2 = new THREE.Color(),
  4206. _color3 = new THREE.Color(),
  4207. _color4 = new THREE.Color(),
  4208. _patterns = [], _imagedatas = [],
  4209. _near, _far,
  4210. _image, _uvs,
  4211. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  4212. _clipRect = new THREE.Rectangle(),
  4213. _clearRect = new THREE.Rectangle(),
  4214. _bboxRect = new THREE.Rectangle(),
  4215. _enableLighting = false,
  4216. _ambientLight = new THREE.Color(),
  4217. _directionalLights = new THREE.Color(),
  4218. _pointLights = new THREE.Color(),
  4219. _pi2 = Math.PI * 2,
  4220. _vector3 = new THREE.Vector3(), // Needed for PointLight
  4221. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  4222. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  4223. _pixelMap = document.createElement( 'canvas' );
  4224. _pixelMap.width = _pixelMap.height = 2;
  4225. _pixelMapContext = _pixelMap.getContext( '2d' );
  4226. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  4227. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  4228. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  4229. _pixelMapData = _pixelMapImage.data;
  4230. _gradientMap = document.createElement( 'canvas' );
  4231. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  4232. _gradientMapContext = _gradientMap.getContext( '2d' );
  4233. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  4234. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  4235. _gradientMapQuality --; // Fix UVs
  4236. this.domElement = _canvas;
  4237. this.autoClear = true;
  4238. this.sortObjects = true;
  4239. this.sortElements = true;
  4240. this.info = {
  4241. render: {
  4242. vertices: 0,
  4243. faces: 0
  4244. }
  4245. }
  4246. this.setSize = function ( width, height ) {
  4247. _canvasWidth = width;
  4248. _canvasHeight = height;
  4249. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  4250. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  4251. _canvas.width = _canvasWidth;
  4252. _canvas.height = _canvasHeight;
  4253. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4254. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4255. _contextGlobalAlpha = 1;
  4256. _contextGlobalCompositeOperation = 0;
  4257. _contextStrokeStyle = null;
  4258. _contextFillStyle = null;
  4259. _contextLineWidth = null;
  4260. _contextLineCap = null;
  4261. _contextLineJoin = null;
  4262. };
  4263. this.setClearColor = function ( color, opacity ) {
  4264. _clearColor.copy( color );
  4265. _clearOpacity = opacity !== undefined ? opacity : 1;
  4266. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4267. };
  4268. this.setClearColorHex = function ( hex, opacity ) {
  4269. _clearColor.setHex( hex );
  4270. _clearOpacity = opacity !== undefined ? opacity : 1;
  4271. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4272. };
  4273. this.clear = function () {
  4274. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  4275. if ( !_clearRect.isEmpty() ) {
  4276. _clearRect.minSelf( _clipRect );
  4277. _clearRect.inflate( 2 );
  4278. if ( _clearOpacity < 1 ) {
  4279. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  4280. }
  4281. if ( _clearOpacity > 0 ) {
  4282. setBlending( THREE.NormalBlending );
  4283. setOpacity( 1 );
  4284. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  4285. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  4286. }
  4287. _clearRect.empty();
  4288. }
  4289. };
  4290. this.render = function ( scene, camera ) {
  4291. var e, el, element, material;
  4292. this.autoClear ? this.clear() : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  4293. _this.info.render.vertices = 0;
  4294. _this.info.render.faces = 0;
  4295. _renderData = _projector.projectScene( scene, camera, this.sortElements );
  4296. _elements = _renderData.elements;
  4297. _lights = _renderData.lights;
  4298. /* DEBUG
  4299. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  4300. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  4301. */
  4302. _enableLighting = _lights.length > 0;
  4303. if ( _enableLighting ) {
  4304. calculateLights( _lights );
  4305. }
  4306. for ( e = 0, el = _elements.length; e < el; e++ ) {
  4307. element = _elements[ e ];
  4308. material = element.material;
  4309. material = material instanceof THREE.MeshFaceMaterial ? element.faceMaterial : material;
  4310. if ( material == null || material.opacity == 0 ) continue;
  4311. _bboxRect.empty();
  4312. if ( element instanceof THREE.RenderableParticle ) {
  4313. _v1 = element;
  4314. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  4315. renderParticle( _v1, element, material, scene );
  4316. } else if ( element instanceof THREE.RenderableLine ) {
  4317. _v1 = element.v1; _v2 = element.v2;
  4318. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  4319. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  4320. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4321. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4322. if ( _clipRect.intersects( _bboxRect ) ) {
  4323. renderLine( _v1, _v2, element, material, scene );
  4324. }
  4325. } else if ( element instanceof THREE.RenderableFace3 ) {
  4326. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  4327. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  4328. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  4329. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  4330. if ( material.overdraw ) {
  4331. expand( _v1.positionScreen, _v2.positionScreen );
  4332. expand( _v2.positionScreen, _v3.positionScreen );
  4333. expand( _v3.positionScreen, _v1.positionScreen );
  4334. }
  4335. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  4336. _v2.positionScreen.x, _v2.positionScreen.y,
  4337. _v3.positionScreen.x, _v3.positionScreen.y );
  4338. if ( _clipRect.intersects( _bboxRect ) ) {
  4339. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  4340. }
  4341. } else if ( element instanceof THREE.RenderableFace4 ) {
  4342. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  4343. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  4344. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  4345. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  4346. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  4347. _v5.positionScreen.copy( _v2.positionScreen );
  4348. _v6.positionScreen.copy( _v4.positionScreen );
  4349. if ( material.overdraw ) {
  4350. expand( _v1.positionScreen, _v2.positionScreen );
  4351. expand( _v2.positionScreen, _v4.positionScreen );
  4352. expand( _v4.positionScreen, _v1.positionScreen );
  4353. expand( _v3.positionScreen, _v5.positionScreen );
  4354. expand( _v3.positionScreen, _v6.positionScreen );
  4355. }
  4356. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4357. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4358. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  4359. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  4360. if ( _clipRect.intersects( _bboxRect ) ) {
  4361. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  4362. }
  4363. }
  4364. /*
  4365. _context.lineWidth = 1;
  4366. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  4367. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  4368. */
  4369. _clearRect.addRectangle( _bboxRect );
  4370. }
  4371. /* DEBUG
  4372. _context.lineWidth = 1;
  4373. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  4374. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  4375. */
  4376. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  4377. //
  4378. function calculateLights( lights ) {
  4379. var l, ll, light, lightColor;
  4380. _ambientLight.setRGB( 0, 0, 0 );
  4381. _directionalLights.setRGB( 0, 0, 0 );
  4382. _pointLights.setRGB( 0, 0, 0 );
  4383. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  4384. light = lights[ l ];
  4385. lightColor = light.color;
  4386. if ( light instanceof THREE.AmbientLight ) {
  4387. _ambientLight.r += lightColor.r;
  4388. _ambientLight.g += lightColor.g;
  4389. _ambientLight.b += lightColor.b;
  4390. } else if ( light instanceof THREE.DirectionalLight ) {
  4391. // for particles
  4392. _directionalLights.r += lightColor.r;
  4393. _directionalLights.g += lightColor.g;
  4394. _directionalLights.b += lightColor.b;
  4395. } else if ( light instanceof THREE.PointLight ) {
  4396. // for particles
  4397. _pointLights.r += lightColor.r;
  4398. _pointLights.g += lightColor.g;
  4399. _pointLights.b += lightColor.b;
  4400. }
  4401. }
  4402. }
  4403. function calculateLight( lights, position, normal, color ) {
  4404. var l, ll, light, lightColor, lightPosition, amount;
  4405. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  4406. light = lights[ l ];
  4407. lightColor = light.color;
  4408. if ( light instanceof THREE.DirectionalLight ) {
  4409. lightPosition = light.matrixWorld.getPosition();
  4410. amount = normal.dot( lightPosition );
  4411. if ( amount <= 0 ) continue;
  4412. amount *= light.intensity;
  4413. color.r += lightColor.r * amount;
  4414. color.g += lightColor.g * amount;
  4415. color.b += lightColor.b * amount;
  4416. } else if ( light instanceof THREE.PointLight ) {
  4417. lightPosition = light.matrixWorld.getPosition();
  4418. amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  4419. if ( amount <= 0 ) continue;
  4420. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  4421. if ( amount == 0 ) continue;
  4422. amount *= light.intensity;
  4423. color.r += lightColor.r * amount;
  4424. color.g += lightColor.g * amount;
  4425. color.b += lightColor.b * amount;
  4426. }
  4427. }
  4428. }
  4429. function renderParticle ( v1, element, material, scene ) {
  4430. setOpacity( material.opacity );
  4431. setBlending( material.blending );
  4432. var width, height, scaleX, scaleY,
  4433. bitmap, bitmapWidth, bitmapHeight;
  4434. if ( material instanceof THREE.ParticleBasicMaterial ) {
  4435. if ( material.map ) {
  4436. bitmap = material.map.image;
  4437. bitmapWidth = bitmap.width >> 1;
  4438. bitmapHeight = bitmap.height >> 1;
  4439. scaleX = element.scale.x * _canvasWidthHalf;
  4440. scaleY = element.scale.y * _canvasHeightHalf;
  4441. width = scaleX * bitmapWidth;
  4442. height = scaleY * bitmapHeight;
  4443. // TODO: Rotations break this...
  4444. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  4445. if ( !_clipRect.intersects( _bboxRect ) ) {
  4446. return;
  4447. }
  4448. _context.save();
  4449. _context.translate( v1.x, v1.y );
  4450. _context.rotate( - element.rotation );
  4451. _context.scale( scaleX, - scaleY );
  4452. _context.translate( - bitmapWidth, - bitmapHeight );
  4453. _context.drawImage( bitmap, 0, 0 );
  4454. _context.restore();
  4455. }
  4456. /* DEBUG
  4457. _context.beginPath();
  4458. _context.moveTo( v1.x - 10, v1.y );
  4459. _context.lineTo( v1.x + 10, v1.y );
  4460. _context.moveTo( v1.x, v1.y - 10 );
  4461. _context.lineTo( v1.x, v1.y + 10 );
  4462. _context.closePath();
  4463. _context.strokeStyle = 'rgb(255,255,0)';
  4464. _context.stroke();
  4465. */
  4466. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  4467. width = element.scale.x * _canvasWidthHalf;
  4468. height = element.scale.y * _canvasHeightHalf;
  4469. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  4470. if ( !_clipRect.intersects( _bboxRect ) ) {
  4471. return;
  4472. }
  4473. setStrokeStyle( material.color.getContextStyle() );
  4474. setFillStyle( material.color.getContextStyle() );
  4475. _context.save();
  4476. _context.translate( v1.x, v1.y );
  4477. _context.rotate( - element.rotation );
  4478. _context.scale( width, height );
  4479. material.program( _context );
  4480. _context.restore();
  4481. }
  4482. }
  4483. function renderLine( v1, v2, element, material, scene ) {
  4484. setOpacity( material.opacity );
  4485. setBlending( material.blending );
  4486. _context.beginPath();
  4487. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  4488. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  4489. _context.closePath();
  4490. if ( material instanceof THREE.LineBasicMaterial ) {
  4491. setLineWidth( material.linewidth );
  4492. setLineCap( material.linecap );
  4493. setLineJoin( material.linejoin );
  4494. setStrokeStyle( material.color.getContextStyle() );
  4495. _context.stroke();
  4496. _bboxRect.inflate( material.linewidth * 2 );
  4497. }
  4498. }
  4499. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  4500. _this.info.render.vertices += 3;
  4501. _this.info.render.faces ++;
  4502. setOpacity( material.opacity );
  4503. setBlending( material.blending );
  4504. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  4505. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  4506. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  4507. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  4508. if ( material instanceof THREE.MeshBasicMaterial ) {
  4509. if ( material.map/* && !material.wireframe*/ ) {
  4510. if ( material.map.mapping instanceof THREE.UVMapping ) {
  4511. _uvs = element.uvs[ 0 ];
  4512. 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 );
  4513. }
  4514. } else if ( material.envMap ) {
  4515. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  4516. var cameraMatrix = camera.matrixWorldInverse;
  4517. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  4518. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  4519. _uv1y = - ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  4520. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  4521. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  4522. _uv2y = - ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  4523. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  4524. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  4525. _uv3y = - ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  4526. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  4527. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  4528. }*/
  4529. } else {
  4530. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4531. }
  4532. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  4533. if ( material.map && !material.wireframe ) {
  4534. if ( material.map.mapping instanceof THREE.UVMapping ) {
  4535. _uvs = element.uvs[ 0 ];
  4536. 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 );
  4537. }
  4538. setBlending( THREE.SubtractiveBlending );
  4539. }
  4540. if ( _enableLighting ) {
  4541. if ( !material.wireframe && material.shading == THREE.SmoothShading && element.vertexNormalsWorld.length == 3 ) {
  4542. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  4543. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  4544. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  4545. calculateLight( _lights, element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  4546. calculateLight( _lights, element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  4547. calculateLight( _lights, element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  4548. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  4549. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  4550. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  4551. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  4552. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  4553. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  4554. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  4555. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  4556. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  4557. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  4558. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  4559. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  4560. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4561. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  4562. } else {
  4563. _color.r = _ambientLight.r;
  4564. _color.g = _ambientLight.g;
  4565. _color.b = _ambientLight.b;
  4566. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  4567. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  4568. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  4569. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  4570. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4571. }
  4572. } else {
  4573. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4574. }
  4575. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  4576. _near = camera.near;
  4577. _far = camera.far;
  4578. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  4579. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  4580. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  4581. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  4582. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  4583. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  4584. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4585. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  4586. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  4587. _color.r = normalToComponent( element.normalWorld.x );
  4588. _color.g = normalToComponent( element.normalWorld.y );
  4589. _color.b = normalToComponent( element.normalWorld.z );
  4590. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4591. }
  4592. }
  4593. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  4594. _this.info.render.vertices += 4;
  4595. _this.info.render.faces ++;
  4596. setOpacity( material.opacity );
  4597. setBlending( material.blending );
  4598. if ( material.map || material.envMap ) {
  4599. // Let renderFace3() handle this
  4600. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  4601. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  4602. return;
  4603. }
  4604. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  4605. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  4606. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  4607. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  4608. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  4609. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  4610. if ( material instanceof THREE.MeshBasicMaterial ) {
  4611. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4612. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4613. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  4614. if ( _enableLighting ) {
  4615. if ( !material.wireframe && material.shading == THREE.SmoothShading && element.vertexNormalsWorld.length == 4 ) {
  4616. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  4617. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  4618. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  4619. calculateLight( _lights, element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  4620. calculateLight( _lights, element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  4621. calculateLight( _lights, element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  4622. calculateLight( _lights, element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  4623. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  4624. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  4625. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  4626. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  4627. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  4628. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  4629. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  4630. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  4631. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  4632. _color4.r = Math.max( 0, Math.min( material.color.r * _color4.r, 1 ) );
  4633. _color4.g = Math.max( 0, Math.min( material.color.g * _color4.g, 1 ) );
  4634. _color4.b = Math.max( 0, Math.min( material.color.b * _color4.b, 1 ) );
  4635. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4636. // TODO: UVs are incorrect, v4->v3?
  4637. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  4638. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  4639. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  4640. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  4641. } else {
  4642. _color.r = _ambientLight.r;
  4643. _color.g = _ambientLight.g;
  4644. _color.b = _ambientLight.b;
  4645. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  4646. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  4647. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  4648. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  4649. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4650. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4651. }
  4652. } else {
  4653. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4654. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4655. }
  4656. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  4657. _color.r = normalToComponent( element.normalWorld.x );
  4658. _color.g = normalToComponent( element.normalWorld.y );
  4659. _color.b = normalToComponent( element.normalWorld.z );
  4660. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4661. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4662. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  4663. _near = camera.near;
  4664. _far = camera.far;
  4665. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  4666. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  4667. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  4668. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  4669. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4670. // TODO: UVs are incorrect, v4->v3?
  4671. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  4672. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  4673. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  4674. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  4675. }
  4676. }
  4677. //
  4678. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  4679. _context.beginPath();
  4680. _context.moveTo( x0, y0 );
  4681. _context.lineTo( x1, y1 );
  4682. _context.lineTo( x2, y2 );
  4683. _context.lineTo( x0, y0 );
  4684. _context.closePath();
  4685. }
  4686. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  4687. _context.beginPath();
  4688. _context.moveTo( x0, y0 );
  4689. _context.lineTo( x1, y1 );
  4690. _context.lineTo( x2, y2 );
  4691. _context.lineTo( x3, y3 );
  4692. _context.lineTo( x0, y0 );
  4693. _context.closePath();
  4694. }
  4695. function strokePath( color, linewidth, linecap, linejoin ) {
  4696. setLineWidth( linewidth );
  4697. setLineCap( linecap );
  4698. setLineJoin( linejoin );
  4699. setStrokeStyle( color.getContextStyle() );
  4700. _context.stroke();
  4701. _bboxRect.inflate( linewidth * 2 );
  4702. }
  4703. function fillPath( color ) {
  4704. setFillStyle( color.getContextStyle() );
  4705. _context.fill();
  4706. }
  4707. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  4708. if ( texture.image.width == 0 ) return;
  4709. if ( texture.needsUpdate == true || _patterns[ texture.id ] == undefined ) {
  4710. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  4711. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  4712. _patterns[ texture.id ] = _context.createPattern( texture.image, repeatX && repeatY ? 'repeat' : repeatX && !repeatY ? 'repeat-x' : !repeatX && repeatY ? 'repeat-y' : 'no-repeat' );
  4713. texture.needsUpdate = false;
  4714. }
  4715. setFillStyle( _patterns[ texture.id ] );
  4716. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  4717. var a, b, c, d, e, f, det, idet,
  4718. offsetX = texture.offset.x / texture.repeat.x,
  4719. offsetY = texture.offset.y / texture.repeat.y,
  4720. width = texture.image.width * texture.repeat.x,
  4721. height = texture.image.height * texture.repeat.y;
  4722. u0 = ( u0 + offsetX ) * width;
  4723. v0 = ( v0 + offsetY ) * height;
  4724. u1 = ( u1 + offsetX ) * width;
  4725. v1 = ( v1 + offsetY ) * height;
  4726. u2 = ( u2 + offsetX ) * width;
  4727. v2 = ( v2 + offsetY ) * height;
  4728. x1 -= x0; y1 -= y0;
  4729. x2 -= x0; y2 -= y0;
  4730. u1 -= u0; v1 -= v0;
  4731. u2 -= u0; v2 -= v0;
  4732. det = u1 * v2 - u2 * v1;
  4733. if ( det == 0 ) {
  4734. if ( _imagedatas[ texture.id ] === undefined ) {
  4735. var canvas = document.createElement( 'canvas' )
  4736. canvas.width = texture.image.width;
  4737. canvas.height = texture.image.height;
  4738. var context = canvas.getContext( '2d' );
  4739. context.drawImage( texture.image, 0, 0 );
  4740. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  4741. // variables cannot be deleted in ES5 strict mode
  4742. //delete canvas;
  4743. }
  4744. var data = _imagedatas[ texture.id ];
  4745. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  4746. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  4747. fillPath( _color );
  4748. return;
  4749. }
  4750. idet = 1 / det;
  4751. a = ( v2 * x1 - v1 * x2 ) * idet;
  4752. b = ( v2 * y1 - v1 * y2 ) * idet;
  4753. c = ( u1 * x2 - u2 * x1 ) * idet;
  4754. d = ( u1 * y2 - u2 * y1 ) * idet;
  4755. e = x0 - a * u0 - c * v0;
  4756. f = y0 - b * u0 - d * v0;
  4757. _context.save();
  4758. _context.transform( a, b, c, d, e, f );
  4759. _context.fill();
  4760. _context.restore();
  4761. }
  4762. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  4763. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  4764. var a, b, c, d, e, f, det, idet,
  4765. width = image.width - 1,
  4766. height = image.height - 1;
  4767. u0 *= width; v0 *= height;
  4768. u1 *= width; v1 *= height;
  4769. u2 *= width; v2 *= height;
  4770. x1 -= x0; y1 -= y0;
  4771. x2 -= x0; y2 -= y0;
  4772. u1 -= u0; v1 -= v0;
  4773. u2 -= u0; v2 -= v0;
  4774. det = u1 * v2 - u2 * v1;
  4775. idet = 1 / det;
  4776. a = ( v2 * x1 - v1 * x2 ) * idet;
  4777. b = ( v2 * y1 - v1 * y2 ) * idet;
  4778. c = ( u1 * x2 - u2 * x1 ) * idet;
  4779. d = ( u1 * y2 - u2 * y1 ) * idet;
  4780. e = x0 - a * u0 - c * v0;
  4781. f = y0 - b * u0 - d * v0;
  4782. _context.save();
  4783. _context.transform( a, b, c, d, e, f );
  4784. _context.clip();
  4785. _context.drawImage( image, 0, 0 );
  4786. _context.restore();
  4787. }
  4788. function getGradientTexture( color1, color2, color3, color4 ) {
  4789. // http://mrdoob.com/blog/post/710
  4790. var c1r = ~~ ( color1.r * 255 ), c1g = ~~ ( color1.g * 255 ), c1b = ~~ ( color1.b * 255 ),
  4791. c2r = ~~ ( color2.r * 255 ), c2g = ~~ ( color2.g * 255 ), c2b = ~~ ( color2.b * 255 ),
  4792. c3r = ~~ ( color3.r * 255 ), c3g = ~~ ( color3.g * 255 ), c3b = ~~ ( color3.b * 255 ),
  4793. c4r = ~~ ( color4.r * 255 ), c4g = ~~ ( color4.g * 255 ), c4b = ~~ ( color4.b * 255 );
  4794. _pixelMapData[ 0 ] = c1r < 0 ? 0 : c1r > 255 ? 255 : c1r;
  4795. _pixelMapData[ 1 ] = c1g < 0 ? 0 : c1g > 255 ? 255 : c1g;
  4796. _pixelMapData[ 2 ] = c1b < 0 ? 0 : c1b > 255 ? 255 : c1b;
  4797. _pixelMapData[ 4 ] = c2r < 0 ? 0 : c2r > 255 ? 255 : c2r;
  4798. _pixelMapData[ 5 ] = c2g < 0 ? 0 : c2g > 255 ? 255 : c2g;
  4799. _pixelMapData[ 6 ] = c2b < 0 ? 0 : c2b > 255 ? 255 : c2b;
  4800. _pixelMapData[ 8 ] = c3r < 0 ? 0 : c3r > 255 ? 255 : c3r;
  4801. _pixelMapData[ 9 ] = c3g < 0 ? 0 : c3g > 255 ? 255 : c3g;
  4802. _pixelMapData[ 10 ] = c3b < 0 ? 0 : c3b > 255 ? 255 : c3b;
  4803. _pixelMapData[ 12 ] = c4r < 0 ? 0 : c4r > 255 ? 255 : c4r;
  4804. _pixelMapData[ 13 ] = c4g < 0 ? 0 : c4g > 255 ? 255 : c4g;
  4805. _pixelMapData[ 14 ] = c4b < 0 ? 0 : c4b > 255 ? 255 : c4b;
  4806. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  4807. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  4808. return _gradientMap;
  4809. }
  4810. function smoothstep( value, min, max ) {
  4811. var x = ( value - min ) / ( max - min );
  4812. return x * x * ( 3 - 2 * x );
  4813. }
  4814. function normalToComponent( normal ) {
  4815. var component = ( normal + 1 ) * 0.5;
  4816. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  4817. }
  4818. // Hide anti-alias gaps
  4819. function expand( v1, v2 ) {
  4820. var x = v2.x - v1.x, y = v2.y - v1.y,
  4821. det = x * x + y * y, idet;
  4822. if ( det == 0 ) return;
  4823. idet = 1 / Math.sqrt( det );
  4824. x *= idet; y *= idet;
  4825. v2.x += x; v2.y += y;
  4826. v1.x -= x; v1.y -= y;
  4827. }
  4828. };
  4829. // Context cached methods.
  4830. function setOpacity( value ) {
  4831. if ( _contextGlobalAlpha != value ) {
  4832. _context.globalAlpha = _contextGlobalAlpha = value;
  4833. }
  4834. }
  4835. function setBlending( value ) {
  4836. if ( _contextGlobalCompositeOperation != value ) {
  4837. switch ( value ) {
  4838. case THREE.NormalBlending:
  4839. _context.globalCompositeOperation = 'source-over';
  4840. break;
  4841. case THREE.AdditiveBlending:
  4842. _context.globalCompositeOperation = 'lighter';
  4843. break;
  4844. case THREE.SubtractiveBlending:
  4845. _context.globalCompositeOperation = 'darker';
  4846. break;
  4847. }
  4848. _contextGlobalCompositeOperation = value;
  4849. }
  4850. }
  4851. function setLineWidth( value ) {
  4852. if ( _contextLineWidth != value ) {
  4853. _context.lineWidth = _contextLineWidth = value;
  4854. }
  4855. }
  4856. function setLineCap( value ) {
  4857. // "butt", "round", "square"
  4858. if ( _contextLineCap != value ) {
  4859. _context.lineCap = _contextLineCap = value;
  4860. }
  4861. }
  4862. function setLineJoin( value ) {
  4863. // "round", "bevel", "miter"
  4864. if ( _contextLineJoin != value ) {
  4865. _context.lineJoin = _contextLineJoin = value;
  4866. }
  4867. }
  4868. function setStrokeStyle( style ) {
  4869. if ( _contextStrokeStyle != style ) {
  4870. _context.strokeStyle = _contextStrokeStyle = style;
  4871. }
  4872. }
  4873. function setFillStyle( style ) {
  4874. if ( _contextFillStyle != style ) {
  4875. _context.fillStyle = _contextFillStyle = style;
  4876. }
  4877. }
  4878. };
  4879. /**
  4880. * @author mr.doob / http://mrdoob.com/
  4881. */
  4882. THREE.SVGRenderer = function () {
  4883. console.log( 'THREE.SVGRenderer', THREE.REVISION );
  4884. var _this = this,
  4885. _renderData, _elements, _lights,
  4886. _projector = new THREE.Projector(),
  4887. _svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
  4888. _svgWidth, _svgHeight, _svgWidthHalf, _svgHeightHalf,
  4889. _v1, _v2, _v3, _v4,
  4890. _clipRect = new THREE.Rectangle(),
  4891. _bboxRect = new THREE.Rectangle(),
  4892. _enableLighting = false,
  4893. _color = new THREE.Color(),
  4894. _ambientLight = new THREE.Color(),
  4895. _directionalLights = new THREE.Color(),
  4896. _pointLights = new THREE.Color(),
  4897. _w, // z-buffer to w-buffer
  4898. _vector3 = new THREE.Vector3(), // Needed for PointLight
  4899. _svgPathPool = [], _svgCirclePool = [], _svgLinePool = [],
  4900. _svgNode, _pathCount, _circleCount, _lineCount,
  4901. _quality = 1;
  4902. this.domElement = _svg;
  4903. this.autoClear = true;
  4904. this.sortObjects = true;
  4905. this.sortElements = true;
  4906. this.info = {
  4907. render: {
  4908. vertices: 0,
  4909. faces: 0
  4910. }
  4911. }
  4912. this.setQuality = function( quality ) {
  4913. switch(quality) {
  4914. case "high": _quality = 1; break;
  4915. case "low": _quality = 0; break;
  4916. }
  4917. };
  4918. this.setSize = function( width, height ) {
  4919. _svgWidth = width; _svgHeight = height;
  4920. _svgWidthHalf = _svgWidth / 2; _svgHeightHalf = _svgHeight / 2;
  4921. _svg.setAttribute( 'viewBox', ( - _svgWidthHalf ) + ' ' + ( - _svgHeightHalf ) + ' ' + _svgWidth + ' ' + _svgHeight );
  4922. _svg.setAttribute( 'width', _svgWidth );
  4923. _svg.setAttribute( 'height', _svgHeight );
  4924. _clipRect.set( - _svgWidthHalf, - _svgHeightHalf, _svgWidthHalf, _svgHeightHalf );
  4925. };
  4926. this.clear = function () {
  4927. while ( _svg.childNodes.length > 0 ) {
  4928. _svg.removeChild( _svg.childNodes[ 0 ] );
  4929. }
  4930. };
  4931. this.render = function ( scene, camera ) {
  4932. var e, el, element, material;
  4933. this.autoClear && this.clear();
  4934. _this.info.render.vertices = 0;
  4935. _this.info.render.faces = 0;
  4936. _renderData = _projector.projectScene( scene, camera, this.sortElements );
  4937. _elements = _renderData.elements;
  4938. _lights = _renderData.lights;
  4939. _pathCount = 0; _circleCount = 0; _lineCount = 0;
  4940. _enableLighting = _lights.length > 0;
  4941. if ( _enableLighting ) {
  4942. calculateLights( _lights );
  4943. }
  4944. for ( e = 0, el = _elements.length; e < el; e ++ ) {
  4945. element = _elements[ e ];
  4946. material = element.material;
  4947. material = material instanceof THREE.MeshFaceMaterial ? element.faceMaterial : material;
  4948. if ( material == null || material.opacity == 0 ) continue;
  4949. _bboxRect.empty();
  4950. if ( element instanceof THREE.RenderableParticle ) {
  4951. _v1 = element;
  4952. _v1.x *= _svgWidthHalf; _v1.y *= -_svgHeightHalf;
  4953. renderParticle( _v1, element, material, scene );
  4954. } else if ( element instanceof THREE.RenderableLine ) {
  4955. _v1 = element.v1; _v2 = element.v2;
  4956. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf;
  4957. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf;
  4958. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4959. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4960. if ( !_clipRect.intersects( _bboxRect ) ) {
  4961. continue;
  4962. }
  4963. renderLine( _v1, _v2, element, material, scene );
  4964. } else if ( element instanceof THREE.RenderableFace3 ) {
  4965. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  4966. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf;
  4967. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf;
  4968. _v3.positionScreen.x *= _svgWidthHalf; _v3.positionScreen.y *= - _svgHeightHalf;
  4969. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4970. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4971. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  4972. if ( !_clipRect.intersects( _bboxRect ) ) {
  4973. continue;
  4974. }
  4975. renderFace3( _v1, _v2, _v3, element, material, scene );
  4976. } else if ( element instanceof THREE.RenderableFace4 ) {
  4977. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  4978. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= -_svgHeightHalf;
  4979. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= -_svgHeightHalf;
  4980. _v3.positionScreen.x *= _svgWidthHalf; _v3.positionScreen.y *= -_svgHeightHalf;
  4981. _v4.positionScreen.x *= _svgWidthHalf; _v4.positionScreen.y *= -_svgHeightHalf;
  4982. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4983. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4984. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  4985. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  4986. if ( !_clipRect.intersects( _bboxRect) ) {
  4987. continue;
  4988. }
  4989. renderFace4( _v1, _v2, _v3, _v4, element, material, scene );
  4990. }
  4991. }
  4992. };
  4993. function calculateLights( lights ) {
  4994. var l, ll, light, lightColor;
  4995. _ambientLight.setRGB( 0, 0, 0 );
  4996. _directionalLights.setRGB( 0, 0, 0 );
  4997. _pointLights.setRGB( 0, 0, 0 );
  4998. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  4999. light = lights[ l ];
  5000. lightColor = light.color;
  5001. if ( light instanceof THREE.AmbientLight ) {
  5002. _ambientLight.r += lightColor.r;
  5003. _ambientLight.g += lightColor.g;
  5004. _ambientLight.b += lightColor.b;
  5005. } else if ( light instanceof THREE.DirectionalLight ) {
  5006. _directionalLights.r += lightColor.r;
  5007. _directionalLights.g += lightColor.g;
  5008. _directionalLights.b += lightColor.b;
  5009. } else if ( light instanceof THREE.PointLight ) {
  5010. _pointLights.r += lightColor.r;
  5011. _pointLights.g += lightColor.g;
  5012. _pointLights.b += lightColor.b;
  5013. }
  5014. }
  5015. }
  5016. function calculateLight( lights, position, normal, color ) {
  5017. var l, ll, light, lightColor, lightPosition, amount;
  5018. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  5019. light = lights[ l ];
  5020. lightColor = light.color;
  5021. if ( light instanceof THREE.DirectionalLight ) {
  5022. lightPosition = light.matrixWorld.getPosition();
  5023. amount = normal.dot( lightPosition );
  5024. if ( amount <= 0 ) continue;
  5025. amount *= light.intensity;
  5026. color.r += lightColor.r * amount;
  5027. color.g += lightColor.g * amount;
  5028. color.b += lightColor.b * amount;
  5029. } else if ( light instanceof THREE.PointLight ) {
  5030. lightPosition = light.matrixWorld.getPosition();
  5031. amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  5032. if ( amount <= 0 ) continue;
  5033. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  5034. if ( amount == 0 ) continue;
  5035. amount *= light.intensity;
  5036. color.r += lightColor.r * amount;
  5037. color.g += lightColor.g * amount;
  5038. color.b += lightColor.b * amount;
  5039. }
  5040. }
  5041. }
  5042. function renderParticle( v1, element, material, scene ) {
  5043. /*
  5044. _svgNode = getCircleNode( _circleCount++ );
  5045. _svgNode.setAttribute( 'cx', v1.x );
  5046. _svgNode.setAttribute( 'cy', v1.y );
  5047. _svgNode.setAttribute( 'r', element.scale.x * _svgWidthHalf );
  5048. if ( material instanceof THREE.ParticleCircleMaterial ) {
  5049. if ( _enableLighting ) {
  5050. _color.r = _ambientLight.r + _directionalLights.r + _pointLights.r;
  5051. _color.g = _ambientLight.g + _directionalLights.g + _pointLights.g;
  5052. _color.b = _ambientLight.b + _directionalLights.b + _pointLights.b;
  5053. _color.r = material.color.r * _color.r;
  5054. _color.g = material.color.g * _color.g;
  5055. _color.b = material.color.b * _color.b;
  5056. _color.updateStyleString();
  5057. } else {
  5058. _color = material.color;
  5059. }
  5060. _svgNode.setAttribute( 'style', 'fill: ' + _color.__styleString );
  5061. }
  5062. _svg.appendChild( _svgNode );
  5063. */
  5064. }
  5065. function renderLine ( v1, v2, element, material, scene ) {
  5066. _svgNode = getLineNode( _lineCount ++ );
  5067. _svgNode.setAttribute( 'x1', v1.positionScreen.x );
  5068. _svgNode.setAttribute( 'y1', v1.positionScreen.y );
  5069. _svgNode.setAttribute( 'x2', v2.positionScreen.x );
  5070. _svgNode.setAttribute( 'y2', v2.positionScreen.y );
  5071. if ( material instanceof THREE.LineBasicMaterial ) {
  5072. _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 );
  5073. _svg.appendChild( _svgNode );
  5074. }
  5075. }
  5076. function renderFace3( v1, v2, v3, element, material, scene ) {
  5077. _this.info.render.vertices += 3;
  5078. _this.info.render.faces ++;
  5079. _svgNode = getPathNode( _pathCount ++ );
  5080. _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' );
  5081. if ( material instanceof THREE.MeshBasicMaterial ) {
  5082. _color.copy( material.color );
  5083. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  5084. if ( _enableLighting ) {
  5085. _color.r = _ambientLight.r;
  5086. _color.g = _ambientLight.g;
  5087. _color.b = _ambientLight.b;
  5088. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  5089. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  5090. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  5091. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  5092. } else {
  5093. _color.copy( material.color );
  5094. }
  5095. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  5096. _w = 1 - ( material.__2near / (material.__farPlusNear - element.z * material.__farMinusNear) );
  5097. _color.setRGB( _w, _w, _w );
  5098. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  5099. _color.setRGB( normalToComponent( element.normalWorld.x ), normalToComponent( element.normalWorld.y ), normalToComponent( element.normalWorld.z ) );
  5100. }
  5101. if ( material.wireframe ) {
  5102. _svgNode.setAttribute( 'style', 'fill: none; stroke: ' + _color.getContextStyle() + '; stroke-width: ' + material.wireframeLinewidth + '; stroke-opacity: ' + material.opacity + '; stroke-linecap: ' + material.wireframeLinecap + '; stroke-linejoin: ' + material.wireframeLinejoin );
  5103. } else {
  5104. _svgNode.setAttribute( 'style', 'fill: ' + _color.getContextStyle() + '; fill-opacity: ' + material.opacity );
  5105. }
  5106. _svg.appendChild( _svgNode );
  5107. }
  5108. function renderFace4( v1, v2, v3, v4, element, material, scene ) {
  5109. _this.info.render.vertices += 4;
  5110. _this.info.render.faces ++;
  5111. _svgNode = getPathNode( _pathCount ++ );
  5112. _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' );
  5113. if ( material instanceof THREE.MeshBasicMaterial ) {
  5114. _color.copy( material.color );
  5115. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  5116. if ( _enableLighting ) {
  5117. _color.r = _ambientLight.r;
  5118. _color.g = _ambientLight.g;
  5119. _color.b = _ambientLight.b;
  5120. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  5121. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  5122. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  5123. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  5124. } else {
  5125. _color.copy( material.color );
  5126. }
  5127. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  5128. _w = 1 - ( material.__2near / (material.__farPlusNear - element.z * material.__farMinusNear) );
  5129. _color.setRGB( _w, _w, _w );
  5130. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  5131. _color.setRGB( normalToComponent( element.normalWorld.x ), normalToComponent( element.normalWorld.y ), normalToComponent( element.normalWorld.z ) );
  5132. }
  5133. if ( material.wireframe ) {
  5134. _svgNode.setAttribute( 'style', 'fill: none; stroke: ' + _color.getContextStyle() + '; stroke-width: ' + material.wireframeLinewidth + '; stroke-opacity: ' + material.opacity + '; stroke-linecap: ' + material.wireframeLinecap + '; stroke-linejoin: ' + material.wireframeLinejoin );
  5135. } else {
  5136. _svgNode.setAttribute( 'style', 'fill: ' + _color.getContextStyle() + '; fill-opacity: ' + material.opacity );
  5137. }
  5138. _svg.appendChild( _svgNode );
  5139. }
  5140. function getLineNode( id ) {
  5141. if ( _svgLinePool[ id ] == null ) {
  5142. _svgLinePool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'line' );
  5143. if ( _quality == 0 ) {
  5144. _svgLinePool[ id ].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  5145. }
  5146. return _svgLinePool[ id ];
  5147. }
  5148. return _svgLinePool[ id ];
  5149. }
  5150. function getPathNode( id ) {
  5151. if ( _svgPathPool[ id ] == null ) {
  5152. _svgPathPool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
  5153. if ( _quality == 0 ) {
  5154. _svgPathPool[ id ].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  5155. }
  5156. return _svgPathPool[ id ];
  5157. }
  5158. return _svgPathPool[ id ];
  5159. }
  5160. function getCircleNode( id ) {
  5161. if ( _svgCirclePool[id] == null ) {
  5162. _svgCirclePool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'circle' );
  5163. if ( _quality == 0 ) {
  5164. _svgCirclePool[id].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  5165. }
  5166. return _svgCirclePool[ id ];
  5167. }
  5168. return _svgCirclePool[ id ];
  5169. }
  5170. function normalToComponent( normal ) {
  5171. var component = ( normal + 1 ) * 0.5;
  5172. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  5173. }
  5174. function pad( str ) {
  5175. while ( str.length < 6 ) str = '0' + str;
  5176. return str;
  5177. }
  5178. };
  5179. /**
  5180. * @author alteredq / http://alteredqualia.com/
  5181. * @author mrdoob / http://mrdoob.com/
  5182. * @author mikael emtinger / http://gomo.se/
  5183. */
  5184. THREE.ShaderChunk = {
  5185. // FOG
  5186. fog_pars_fragment: [
  5187. "#ifdef USE_FOG",
  5188. "uniform vec3 fogColor;",
  5189. "#ifdef FOG_EXP2",
  5190. "uniform float fogDensity;",
  5191. "#else",
  5192. "uniform float fogNear;",
  5193. "uniform float fogFar;",
  5194. "#endif",
  5195. "#endif"
  5196. ].join("\n"),
  5197. fog_fragment: [
  5198. "#ifdef USE_FOG",
  5199. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  5200. "#ifdef FOG_EXP2",
  5201. "const float LOG2 = 1.442695;",
  5202. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  5203. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  5204. "#else",
  5205. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  5206. "#endif",
  5207. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  5208. "#endif"
  5209. ].join("\n"),
  5210. // ENVIRONMENT MAP
  5211. envmap_pars_fragment: [
  5212. "#ifdef USE_ENVMAP",
  5213. "varying vec3 vReflect;",
  5214. "uniform float reflectivity;",
  5215. "uniform samplerCube envMap;",
  5216. "uniform float flipEnvMap;",
  5217. "uniform int combine;",
  5218. "#endif"
  5219. ].join("\n"),
  5220. envmap_fragment: [
  5221. "#ifdef USE_ENVMAP",
  5222. "#ifdef DOUBLE_SIDED",
  5223. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  5224. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * vReflect.x, vReflect.yz ) );",
  5225. "#else",
  5226. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * vReflect.x, vReflect.yz ) );",
  5227. "#endif",
  5228. "#ifdef GAMMA_INPUT",
  5229. "cubeColor.xyz *= cubeColor.xyz;",
  5230. "#endif",
  5231. "if ( combine == 1 ) {",
  5232. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, reflectivity );",
  5233. "} else {",
  5234. "gl_FragColor.xyz = gl_FragColor.xyz * cubeColor.xyz;",
  5235. "}",
  5236. "#endif"
  5237. ].join("\n"),
  5238. envmap_pars_vertex: [
  5239. "#ifdef USE_ENVMAP",
  5240. "varying vec3 vReflect;",
  5241. "uniform float refractionRatio;",
  5242. "uniform bool useRefract;",
  5243. "#endif"
  5244. ].join("\n"),
  5245. envmap_vertex : [
  5246. "#ifdef USE_ENVMAP",
  5247. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  5248. "vec3 nWorld = mat3( objectMatrix[ 0 ].xyz, objectMatrix[ 1 ].xyz, objectMatrix[ 2 ].xyz ) * normal;",
  5249. "if ( useRefract ) {",
  5250. "vReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refractionRatio );",
  5251. "} else {",
  5252. "vReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );",
  5253. "}",
  5254. "#endif"
  5255. ].join("\n"),
  5256. // COLOR MAP (particles)
  5257. map_particle_pars_fragment: [
  5258. "#ifdef USE_MAP",
  5259. "uniform sampler2D map;",
  5260. "#endif"
  5261. ].join("\n"),
  5262. map_particle_fragment: [
  5263. "#ifdef USE_MAP",
  5264. "gl_FragColor = gl_FragColor * texture2D( map, gl_PointCoord );",
  5265. "#endif"
  5266. ].join("\n"),
  5267. // COLOR MAP (triangles)
  5268. map_pars_vertex: [
  5269. "#ifdef USE_MAP",
  5270. "varying vec2 vUv;",
  5271. "uniform vec4 offsetRepeat;",
  5272. "#endif"
  5273. ].join("\n"),
  5274. map_pars_fragment: [
  5275. "#ifdef USE_MAP",
  5276. "varying vec2 vUv;",
  5277. "uniform sampler2D map;",
  5278. "#endif"
  5279. ].join("\n"),
  5280. map_vertex: [
  5281. "#ifdef USE_MAP",
  5282. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  5283. "#endif"
  5284. ].join("\n"),
  5285. map_fragment: [
  5286. "#ifdef USE_MAP",
  5287. "#ifdef GAMMA_INPUT",
  5288. "vec4 texelColor = texture2D( map, vUv );",
  5289. "texelColor.xyz *= texelColor.xyz;",
  5290. "gl_FragColor = gl_FragColor * texelColor;",
  5291. "#else",
  5292. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  5293. "#endif",
  5294. "#endif"
  5295. ].join("\n"),
  5296. // LIGHT MAP
  5297. lightmap_pars_fragment: [
  5298. "#ifdef USE_LIGHTMAP",
  5299. "varying vec2 vUv2;",
  5300. "uniform sampler2D lightMap;",
  5301. "#endif"
  5302. ].join("\n"),
  5303. lightmap_pars_vertex: [
  5304. "#ifdef USE_LIGHTMAP",
  5305. "varying vec2 vUv2;",
  5306. "#endif"
  5307. ].join("\n"),
  5308. lightmap_fragment: [
  5309. "#ifdef USE_LIGHTMAP",
  5310. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  5311. "#endif"
  5312. ].join("\n"),
  5313. lightmap_vertex: [
  5314. "#ifdef USE_LIGHTMAP",
  5315. "vUv2 = uv2;",
  5316. "#endif"
  5317. ].join("\n"),
  5318. // LIGHTS LAMBERT
  5319. lights_lambert_pars_vertex: [
  5320. "uniform vec3 ambient;",
  5321. "uniform vec3 diffuse;",
  5322. "uniform vec3 emissive;",
  5323. "uniform vec3 ambientLightColor;",
  5324. "#if MAX_DIR_LIGHTS > 0",
  5325. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  5326. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  5327. "#endif",
  5328. "#if MAX_POINT_LIGHTS > 0",
  5329. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  5330. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  5331. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  5332. "#endif",
  5333. "#ifdef WRAP_AROUND",
  5334. "uniform vec3 wrapRGB;",
  5335. "#endif",
  5336. ].join("\n"),
  5337. lights_lambert_vertex: [
  5338. "vLightFront = vec3( 0.0 );",
  5339. "#ifdef DOUBLE_SIDED",
  5340. "vLightBack = vec3( 0.0 );",
  5341. "#endif",
  5342. "transformedNormal = normalize( transformedNormal );",
  5343. "#if MAX_DIR_LIGHTS > 0",
  5344. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  5345. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  5346. "vec3 dirVector = normalize( lDirection.xyz );",
  5347. "float dotProduct = dot( transformedNormal, dirVector );",
  5348. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  5349. "#ifdef DOUBLE_SIDED",
  5350. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  5351. "#ifdef WRAP_AROUND",
  5352. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  5353. "#endif",
  5354. "#endif",
  5355. "#ifdef WRAP_AROUND",
  5356. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  5357. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  5358. "#ifdef DOUBLE_SIDED",
  5359. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  5360. "#endif",
  5361. "#endif",
  5362. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  5363. "#ifdef DOUBLE_SIDED",
  5364. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  5365. "#endif",
  5366. "}",
  5367. "#endif",
  5368. "#if MAX_POINT_LIGHTS > 0",
  5369. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  5370. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  5371. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  5372. "float lDistance = 1.0;",
  5373. "if ( pointLightDistance[ i ] > 0.0 )",
  5374. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  5375. "lVector = normalize( lVector );",
  5376. "float dotProduct = dot( transformedNormal, lVector );",
  5377. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  5378. "#ifdef DOUBLE_SIDED",
  5379. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  5380. "#ifdef WRAP_AROUND",
  5381. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  5382. "#endif",
  5383. "#endif",
  5384. "#ifdef WRAP_AROUND",
  5385. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  5386. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  5387. "#ifdef DOUBLE_SIDED",
  5388. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  5389. "#endif",
  5390. "#endif",
  5391. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  5392. "#ifdef DOUBLE_SIDED",
  5393. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  5394. "#endif",
  5395. "}",
  5396. "#endif",
  5397. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  5398. "#ifdef DOUBLE_SIDED",
  5399. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  5400. "#endif",
  5401. ].join("\n"),
  5402. // LIGHTS PHONG
  5403. lights_phong_pars_vertex: [
  5404. "#if MAX_POINT_LIGHTS > 0",
  5405. "#ifndef PHONG_PER_PIXEL",
  5406. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  5407. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  5408. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  5409. "#endif",
  5410. "#endif"
  5411. ].join("\n"),
  5412. lights_phong_vertex: [
  5413. "#if MAX_POINT_LIGHTS > 0",
  5414. "#ifndef PHONG_PER_PIXEL",
  5415. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  5416. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  5417. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  5418. "float lDistance = 1.0;",
  5419. "if ( pointLightDistance[ i ] > 0.0 )",
  5420. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  5421. "vPointLight[ i ] = vec4( lVector, lDistance );",
  5422. "}",
  5423. "#endif",
  5424. "#endif"
  5425. ].join("\n"),
  5426. lights_phong_pars_fragment: [
  5427. "uniform vec3 ambientLightColor;",
  5428. "#if MAX_DIR_LIGHTS > 0",
  5429. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  5430. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  5431. "#endif",
  5432. "#if MAX_POINT_LIGHTS > 0",
  5433. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  5434. "#ifdef PHONG_PER_PIXEL",
  5435. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  5436. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  5437. "#else",
  5438. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  5439. "#endif",
  5440. "#endif",
  5441. "#ifdef WRAP_AROUND",
  5442. "uniform vec3 wrapRGB;",
  5443. "#endif",
  5444. "varying vec3 vViewPosition;",
  5445. "varying vec3 vNormal;"
  5446. ].join("\n"),
  5447. lights_phong_fragment: [
  5448. "vec3 normal = normalize( vNormal );",
  5449. "vec3 viewPosition = normalize( vViewPosition );",
  5450. "#ifdef DOUBLE_SIDED",
  5451. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  5452. "#endif",
  5453. "#if MAX_POINT_LIGHTS > 0",
  5454. "vec3 pointDiffuse = vec3( 0.0 );",
  5455. "vec3 pointSpecular = vec3( 0.0 );",
  5456. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  5457. "#ifdef PHONG_PER_PIXEL",
  5458. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  5459. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  5460. "float lDistance = 1.0;",
  5461. "if ( pointLightDistance[ i ] > 0.0 )",
  5462. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  5463. "lVector = normalize( lVector );",
  5464. "#else",
  5465. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  5466. "float lDistance = vPointLight[ i ].w;",
  5467. "#endif",
  5468. // diffuse
  5469. "float dotProduct = dot( normal, lVector );",
  5470. "#ifdef WRAP_AROUND",
  5471. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  5472. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  5473. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  5474. "#else",
  5475. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  5476. "#endif",
  5477. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  5478. // specular
  5479. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  5480. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  5481. "float pointSpecularWeight = max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  5482. "#ifdef PHYSICALLY_BASED_SHADING",
  5483. // 2.0 => 2.0001 is hack to work around ANGLE bug
  5484. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  5485. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  5486. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  5487. "#else",
  5488. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  5489. "#endif",
  5490. "}",
  5491. "#endif",
  5492. "#if MAX_DIR_LIGHTS > 0",
  5493. "vec3 dirDiffuse = vec3( 0.0 );",
  5494. "vec3 dirSpecular = vec3( 0.0 );" ,
  5495. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  5496. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  5497. "vec3 dirVector = normalize( lDirection.xyz );",
  5498. // diffuse
  5499. "float dotProduct = dot( normal, dirVector );",
  5500. "#ifdef WRAP_AROUND",
  5501. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  5502. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  5503. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  5504. "#else",
  5505. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  5506. "#endif",
  5507. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  5508. // specular
  5509. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  5510. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  5511. "float dirSpecularWeight = max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  5512. "#ifdef PHYSICALLY_BASED_SHADING",
  5513. /*
  5514. // fresnel term from skin shader
  5515. "const float F0 = 0.128;",
  5516. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  5517. "float exponential = pow( base, 5.0 );",
  5518. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  5519. */
  5520. /*
  5521. // fresnel term from fresnel shader
  5522. "const float mFresnelBias = 0.08;",
  5523. "const float mFresnelScale = 0.3;",
  5524. "const float mFresnelPower = 5.0;",
  5525. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  5526. */
  5527. // 2.0 => 2.0001 is hack to work around ANGLE bug
  5528. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  5529. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  5530. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  5531. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  5532. "#else",
  5533. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  5534. "#endif",
  5535. "}",
  5536. "#endif",
  5537. "vec3 totalDiffuse = vec3( 0.0 );",
  5538. "vec3 totalSpecular = vec3( 0.0 );",
  5539. "#if MAX_DIR_LIGHTS > 0",
  5540. "totalDiffuse += dirDiffuse;",
  5541. "totalSpecular += dirSpecular;",
  5542. "#endif",
  5543. "#if MAX_POINT_LIGHTS > 0",
  5544. "totalDiffuse += pointDiffuse;",
  5545. "totalSpecular += pointSpecular;",
  5546. "#endif",
  5547. "#ifdef METAL",
  5548. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  5549. "#else",
  5550. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  5551. "#endif"
  5552. ].join("\n"),
  5553. // VERTEX COLORS
  5554. color_pars_fragment: [
  5555. "#ifdef USE_COLOR",
  5556. "varying vec3 vColor;",
  5557. "#endif"
  5558. ].join("\n"),
  5559. color_fragment: [
  5560. "#ifdef USE_COLOR",
  5561. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  5562. "#endif"
  5563. ].join("\n"),
  5564. color_pars_vertex: [
  5565. "#ifdef USE_COLOR",
  5566. "varying vec3 vColor;",
  5567. "#endif"
  5568. ].join("\n"),
  5569. color_vertex: [
  5570. "#ifdef USE_COLOR",
  5571. "#ifdef GAMMA_INPUT",
  5572. "vColor = color * color;",
  5573. "#else",
  5574. "vColor = color;",
  5575. "#endif",
  5576. "#endif"
  5577. ].join("\n"),
  5578. // SKINNING
  5579. skinning_pars_vertex: [
  5580. "#ifdef USE_SKINNING",
  5581. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  5582. "#endif"
  5583. ].join("\n"),
  5584. skinning_vertex: [
  5585. "#ifdef USE_SKINNING",
  5586. "gl_Position = ( boneGlobalMatrices[ int( skinIndex.x ) ] * skinVertexA ) * skinWeight.x;",
  5587. "gl_Position += ( boneGlobalMatrices[ int( skinIndex.y ) ] * skinVertexB ) * skinWeight.y;",
  5588. "gl_Position = projectionMatrix * modelViewMatrix * gl_Position;",
  5589. "#endif"
  5590. ].join("\n"),
  5591. // MORPHING
  5592. morphtarget_pars_vertex: [
  5593. "#ifdef USE_MORPHTARGETS",
  5594. "#ifndef USE_MORPHNORMALS",
  5595. "uniform float morphTargetInfluences[ 8 ];",
  5596. "#else",
  5597. "uniform float morphTargetInfluences[ 4 ];",
  5598. "#endif",
  5599. "#endif"
  5600. ].join("\n"),
  5601. morphtarget_vertex: [
  5602. "#ifdef USE_MORPHTARGETS",
  5603. "vec3 morphed = vec3( 0.0 );",
  5604. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  5605. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  5606. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  5607. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  5608. "#ifndef USE_MORPHNORMALS",
  5609. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  5610. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  5611. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  5612. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  5613. "#endif",
  5614. "morphed += position;",
  5615. "gl_Position = projectionMatrix * modelViewMatrix * vec4( morphed, 1.0 );",
  5616. "#endif"
  5617. ].join("\n"),
  5618. default_vertex : [
  5619. "#ifndef USE_MORPHTARGETS",
  5620. "#ifndef USE_SKINNING",
  5621. "gl_Position = projectionMatrix * mvPosition;",
  5622. "#endif",
  5623. "#endif"
  5624. ].join("\n"),
  5625. morphnormal_vertex: [
  5626. "#ifdef USE_MORPHNORMALS",
  5627. "vec3 morphedNormal = vec3( 0.0 );",
  5628. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  5629. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  5630. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  5631. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  5632. "morphedNormal += normal;",
  5633. "vec3 transformedNormal = normalMatrix * morphedNormal;",
  5634. "#else",
  5635. "vec3 transformedNormal = normalMatrix * normal;",
  5636. "#endif"
  5637. ].join("\n"),
  5638. // SHADOW MAP
  5639. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  5640. // http://spidergl.org/example.php?id=6
  5641. // http://fabiensanglard.net/shadowmapping
  5642. shadowmap_pars_fragment: [
  5643. "#ifdef USE_SHADOWMAP",
  5644. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  5645. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  5646. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  5647. "uniform float shadowBias[ MAX_SHADOWS ];",
  5648. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  5649. "float unpackDepth( const in vec4 rgba_depth ) {",
  5650. "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 );",
  5651. "float depth = dot( rgba_depth, bit_shift );",
  5652. "return depth;",
  5653. "}",
  5654. "#endif"
  5655. ].join("\n"),
  5656. shadowmap_fragment: [
  5657. "#ifdef USE_SHADOWMAP",
  5658. "#ifdef SHADOWMAP_DEBUG",
  5659. "vec3 frustumColors[3];",
  5660. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  5661. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  5662. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  5663. "#endif",
  5664. "#ifdef SHADOWMAP_CASCADE",
  5665. "int inFrustumCount = 0;",
  5666. "#endif",
  5667. "float fDepth;",
  5668. "vec3 shadowColor = vec3( 1.0 );",
  5669. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  5670. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  5671. // "if ( something && something )" breaks ATI OpenGL shader compiler
  5672. // "if ( all( something, something ) )" using this instead
  5673. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  5674. "bool inFrustum = all( inFrustumVec );",
  5675. // don't shadow pixels outside of light frustum
  5676. // use just first frustum (for cascades)
  5677. // don't shadow pixels behind far plane of light frustum
  5678. "#ifdef SHADOWMAP_CASCADE",
  5679. "inFrustumCount += int( inFrustum );",
  5680. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  5681. "#else",
  5682. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  5683. "#endif",
  5684. "bool frustumTest = all( frustumTestVec );",
  5685. "if ( frustumTest ) {",
  5686. "shadowCoord.z += shadowBias[ i ];",
  5687. "#ifdef SHADOWMAP_SOFT",
  5688. // Percentage-close filtering
  5689. // (9 pixel kernel)
  5690. // http://fabiensanglard.net/shadowmappingPCF/
  5691. "float shadow = 0.0;",
  5692. /*
  5693. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  5694. // must enroll loop manually
  5695. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  5696. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  5697. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  5698. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  5699. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  5700. "float fDepth = unpackDepth( rgbaDepth );",
  5701. "if ( fDepth < shadowCoord.z )",
  5702. "shadow += 1.0;",
  5703. "}",
  5704. "shadow /= 9.0;",
  5705. */
  5706. "const float shadowDelta = 1.0 / 9.0;",
  5707. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  5708. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  5709. "float dx0 = -1.25 * xPixelOffset;",
  5710. "float dy0 = -1.25 * yPixelOffset;",
  5711. "float dx1 = 1.25 * xPixelOffset;",
  5712. "float dy1 = 1.25 * yPixelOffset;",
  5713. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  5714. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5715. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  5716. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5717. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  5718. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5719. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  5720. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5721. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  5722. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5723. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  5724. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5725. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  5726. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5727. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  5728. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5729. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  5730. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5731. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  5732. "#else",
  5733. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  5734. "float fDepth = unpackDepth( rgbaDepth );",
  5735. "if ( fDepth < shadowCoord.z )",
  5736. // spot with multiple shadows is darker
  5737. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  5738. // spot with multiple shadows has the same color as single shadow spot
  5739. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  5740. "#endif",
  5741. "}",
  5742. "#ifdef SHADOWMAP_DEBUG",
  5743. "#ifdef SHADOWMAP_CASCADE",
  5744. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  5745. "#else",
  5746. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  5747. "#endif",
  5748. "#endif",
  5749. "}",
  5750. "#ifdef GAMMA_OUTPUT",
  5751. "shadowColor *= shadowColor;",
  5752. "#endif",
  5753. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  5754. "#endif"
  5755. ].join("\n"),
  5756. shadowmap_pars_vertex: [
  5757. "#ifdef USE_SHADOWMAP",
  5758. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  5759. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  5760. "#endif"
  5761. ].join("\n"),
  5762. shadowmap_vertex: [
  5763. "#ifdef USE_SHADOWMAP",
  5764. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  5765. "#ifdef USE_MORPHTARGETS",
  5766. "vShadowCoord[ i ] = shadowMatrix[ i ] * objectMatrix * vec4( morphed, 1.0 );",
  5767. "#else",
  5768. "vShadowCoord[ i ] = shadowMatrix[ i ] * objectMatrix * vec4( position, 1.0 );",
  5769. "#endif",
  5770. "}",
  5771. "#endif"
  5772. ].join("\n"),
  5773. // ALPHATEST
  5774. alphatest_fragment: [
  5775. "#ifdef ALPHATEST",
  5776. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  5777. "#endif"
  5778. ].join("\n"),
  5779. // LINEAR SPACE
  5780. linear_to_gamma_fragment: [
  5781. "#ifdef GAMMA_OUTPUT",
  5782. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  5783. "#endif"
  5784. ].join("\n"),
  5785. };
  5786. THREE.UniformsUtils = {
  5787. merge: function ( uniforms ) {
  5788. var u, p, tmp, merged = {};
  5789. for ( u = 0; u < uniforms.length; u++ ) {
  5790. tmp = this.clone( uniforms[ u ] );
  5791. for ( p in tmp ) {
  5792. merged[ p ] = tmp[ p ];
  5793. }
  5794. }
  5795. return merged;
  5796. },
  5797. clone: function ( uniforms_src ) {
  5798. var u, p, parameter, parameter_src, uniforms_dst = {};
  5799. for ( u in uniforms_src ) {
  5800. uniforms_dst[ u ] = {};
  5801. for ( p in uniforms_src[ u ] ) {
  5802. parameter_src = uniforms_src[ u ][ p ];
  5803. if ( parameter_src instanceof THREE.Color ||
  5804. parameter_src instanceof THREE.Vector2 ||
  5805. parameter_src instanceof THREE.Vector3 ||
  5806. parameter_src instanceof THREE.Vector4 ||
  5807. parameter_src instanceof THREE.Matrix4 ||
  5808. parameter_src instanceof THREE.Texture ) {
  5809. uniforms_dst[ u ][ p ] = parameter_src.clone();
  5810. } else if ( parameter_src instanceof Array ) {
  5811. uniforms_dst[ u ][ p ] = parameter_src.slice();
  5812. } else {
  5813. uniforms_dst[ u ][ p ] = parameter_src;
  5814. }
  5815. }
  5816. }
  5817. return uniforms_dst;
  5818. }
  5819. };
  5820. THREE.UniformsLib = {
  5821. common: {
  5822. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  5823. "opacity" : { type: "f", value: 1.0 },
  5824. "map" : { type: "t", value: 0, texture: null },
  5825. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  5826. "lightMap" : { type: "t", value: 2, texture: null },
  5827. "envMap" : { type: "t", value: 1, texture: null },
  5828. "flipEnvMap" : { type: "f", value: -1 },
  5829. "useRefract" : { type: "i", value: 0 },
  5830. "reflectivity" : { type: "f", value: 1.0 },
  5831. "refractionRatio" : { type: "f", value: 0.98 },
  5832. "combine" : { type: "i", value: 0 },
  5833. "morphTargetInfluences" : { type: "f", value: 0 }
  5834. },
  5835. fog : {
  5836. "fogDensity" : { type: "f", value: 0.00025 },
  5837. "fogNear" : { type: "f", value: 1 },
  5838. "fogFar" : { type: "f", value: 2000 },
  5839. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  5840. },
  5841. lights: {
  5842. "ambientLightColor" : { type: "fv", value: [] },
  5843. "directionalLightDirection" : { type: "fv", value: [] },
  5844. "directionalLightColor" : { type: "fv", value: [] },
  5845. "pointLightColor" : { type: "fv", value: [] },
  5846. "pointLightPosition" : { type: "fv", value: [] },
  5847. "pointLightDistance" : { type: "fv1", value: [] }
  5848. },
  5849. particle: {
  5850. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  5851. "opacity" : { type: "f", value: 1.0 },
  5852. "size" : { type: "f", value: 1.0 },
  5853. "scale" : { type: "f", value: 1.0 },
  5854. "map" : { type: "t", value: 0, texture: null },
  5855. "fogDensity" : { type: "f", value: 0.00025 },
  5856. "fogNear" : { type: "f", value: 1 },
  5857. "fogFar" : { type: "f", value: 2000 },
  5858. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  5859. },
  5860. shadowmap: {
  5861. "shadowMap": { type: "tv", value: 6, texture: [] },
  5862. "shadowMapSize": { type: "v2v", value: [] },
  5863. "shadowBias" : { type: "fv1", value: [] },
  5864. "shadowDarkness": { type: "fv1", value: [] },
  5865. "shadowMatrix" : { type: "m4v", value: [] },
  5866. }
  5867. };
  5868. THREE.ShaderLib = {
  5869. 'depth': {
  5870. uniforms: {
  5871. "mNear": { type: "f", value: 1.0 },
  5872. "mFar" : { type: "f", value: 2000.0 },
  5873. "opacity" : { type: "f", value: 1.0 }
  5874. },
  5875. vertexShader: [
  5876. "void main() {",
  5877. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  5878. "}"
  5879. ].join("\n"),
  5880. fragmentShader: [
  5881. "uniform float mNear;",
  5882. "uniform float mFar;",
  5883. "uniform float opacity;",
  5884. "void main() {",
  5885. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  5886. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  5887. "gl_FragColor = vec4( vec3( color ), opacity );",
  5888. "}"
  5889. ].join("\n")
  5890. },
  5891. 'normal': {
  5892. uniforms: {
  5893. "opacity" : { type: "f", value: 1.0 }
  5894. },
  5895. vertexShader: [
  5896. "varying vec3 vNormal;",
  5897. "void main() {",
  5898. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  5899. "vNormal = normalMatrix * normal;",
  5900. "gl_Position = projectionMatrix * mvPosition;",
  5901. "}"
  5902. ].join("\n"),
  5903. fragmentShader: [
  5904. "uniform float opacity;",
  5905. "varying vec3 vNormal;",
  5906. "void main() {",
  5907. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  5908. "}"
  5909. ].join("\n")
  5910. },
  5911. 'basic': {
  5912. uniforms: THREE.UniformsUtils.merge( [
  5913. THREE.UniformsLib[ "common" ],
  5914. THREE.UniformsLib[ "fog" ],
  5915. THREE.UniformsLib[ "shadowmap" ]
  5916. ] ),
  5917. vertexShader: [
  5918. THREE.ShaderChunk[ "map_pars_vertex" ],
  5919. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  5920. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  5921. THREE.ShaderChunk[ "color_pars_vertex" ],
  5922. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  5923. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  5924. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  5925. "void main() {",
  5926. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  5927. THREE.ShaderChunk[ "map_vertex" ],
  5928. THREE.ShaderChunk[ "lightmap_vertex" ],
  5929. THREE.ShaderChunk[ "envmap_vertex" ],
  5930. THREE.ShaderChunk[ "color_vertex" ],
  5931. THREE.ShaderChunk[ "skinning_vertex" ],
  5932. THREE.ShaderChunk[ "morphtarget_vertex" ],
  5933. THREE.ShaderChunk[ "default_vertex" ],
  5934. THREE.ShaderChunk[ "shadowmap_vertex" ],
  5935. "}"
  5936. ].join("\n"),
  5937. fragmentShader: [
  5938. "uniform vec3 diffuse;",
  5939. "uniform float opacity;",
  5940. THREE.ShaderChunk[ "color_pars_fragment" ],
  5941. THREE.ShaderChunk[ "map_pars_fragment" ],
  5942. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  5943. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  5944. THREE.ShaderChunk[ "fog_pars_fragment" ],
  5945. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  5946. "void main() {",
  5947. "gl_FragColor = vec4( diffuse, opacity );",
  5948. THREE.ShaderChunk[ "map_fragment" ],
  5949. THREE.ShaderChunk[ "alphatest_fragment" ],
  5950. THREE.ShaderChunk[ "lightmap_fragment" ],
  5951. THREE.ShaderChunk[ "color_fragment" ],
  5952. THREE.ShaderChunk[ "envmap_fragment" ],
  5953. THREE.ShaderChunk[ "shadowmap_fragment" ],
  5954. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  5955. THREE.ShaderChunk[ "fog_fragment" ],
  5956. "}"
  5957. ].join("\n")
  5958. },
  5959. 'lambert': {
  5960. uniforms: THREE.UniformsUtils.merge( [
  5961. THREE.UniformsLib[ "common" ],
  5962. THREE.UniformsLib[ "fog" ],
  5963. THREE.UniformsLib[ "lights" ],
  5964. THREE.UniformsLib[ "shadowmap" ],
  5965. {
  5966. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  5967. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  5968. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  5969. }
  5970. ] ),
  5971. vertexShader: [
  5972. "varying vec3 vLightFront;",
  5973. "#ifdef DOUBLE_SIDED",
  5974. "varying vec3 vLightBack;",
  5975. "#endif",
  5976. THREE.ShaderChunk[ "map_pars_vertex" ],
  5977. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  5978. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  5979. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  5980. THREE.ShaderChunk[ "color_pars_vertex" ],
  5981. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  5982. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  5983. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  5984. "void main() {",
  5985. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  5986. THREE.ShaderChunk[ "map_vertex" ],
  5987. THREE.ShaderChunk[ "lightmap_vertex" ],
  5988. THREE.ShaderChunk[ "envmap_vertex" ],
  5989. THREE.ShaderChunk[ "color_vertex" ],
  5990. THREE.ShaderChunk[ "morphnormal_vertex" ],
  5991. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  5992. THREE.ShaderChunk[ "skinning_vertex" ],
  5993. THREE.ShaderChunk[ "morphtarget_vertex" ],
  5994. THREE.ShaderChunk[ "default_vertex" ],
  5995. THREE.ShaderChunk[ "shadowmap_vertex" ],
  5996. "}"
  5997. ].join("\n"),
  5998. fragmentShader: [
  5999. "uniform float opacity;",
  6000. "varying vec3 vLightFront;",
  6001. "#ifdef DOUBLE_SIDED",
  6002. "varying vec3 vLightBack;",
  6003. "#endif",
  6004. THREE.ShaderChunk[ "color_pars_fragment" ],
  6005. THREE.ShaderChunk[ "map_pars_fragment" ],
  6006. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  6007. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  6008. THREE.ShaderChunk[ "fog_pars_fragment" ],
  6009. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  6010. "void main() {",
  6011. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  6012. THREE.ShaderChunk[ "map_fragment" ],
  6013. THREE.ShaderChunk[ "alphatest_fragment" ],
  6014. "#ifdef DOUBLE_SIDED",
  6015. //"float isFront = float( gl_FrontFacing );",
  6016. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  6017. "if ( gl_FrontFacing )",
  6018. "gl_FragColor.xyz *= vLightFront;",
  6019. "else",
  6020. "gl_FragColor.xyz *= vLightBack;",
  6021. "#else",
  6022. "gl_FragColor.xyz *= vLightFront;",
  6023. "#endif",
  6024. THREE.ShaderChunk[ "lightmap_fragment" ],
  6025. THREE.ShaderChunk[ "color_fragment" ],
  6026. THREE.ShaderChunk[ "envmap_fragment" ],
  6027. THREE.ShaderChunk[ "shadowmap_fragment" ],
  6028. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  6029. THREE.ShaderChunk[ "fog_fragment" ],
  6030. "}"
  6031. ].join("\n")
  6032. },
  6033. 'phong': {
  6034. uniforms: THREE.UniformsUtils.merge( [
  6035. THREE.UniformsLib[ "common" ],
  6036. THREE.UniformsLib[ "fog" ],
  6037. THREE.UniformsLib[ "lights" ],
  6038. THREE.UniformsLib[ "shadowmap" ],
  6039. {
  6040. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  6041. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  6042. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  6043. "shininess": { type: "f", value: 30 },
  6044. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  6045. }
  6046. ] ),
  6047. vertexShader: [
  6048. "varying vec3 vViewPosition;",
  6049. "varying vec3 vNormal;",
  6050. THREE.ShaderChunk[ "map_pars_vertex" ],
  6051. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  6052. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  6053. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  6054. THREE.ShaderChunk[ "color_pars_vertex" ],
  6055. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  6056. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  6057. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  6058. "void main() {",
  6059. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  6060. THREE.ShaderChunk[ "map_vertex" ],
  6061. THREE.ShaderChunk[ "lightmap_vertex" ],
  6062. THREE.ShaderChunk[ "envmap_vertex" ],
  6063. THREE.ShaderChunk[ "color_vertex" ],
  6064. "#ifndef USE_ENVMAP",
  6065. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  6066. "#endif",
  6067. "vViewPosition = -mvPosition.xyz;",
  6068. THREE.ShaderChunk[ "morphnormal_vertex" ],
  6069. "vNormal = transformedNormal;",
  6070. THREE.ShaderChunk[ "lights_phong_vertex" ],
  6071. THREE.ShaderChunk[ "skinning_vertex" ],
  6072. THREE.ShaderChunk[ "morphtarget_vertex" ],
  6073. THREE.ShaderChunk[ "default_vertex" ],
  6074. THREE.ShaderChunk[ "shadowmap_vertex" ],
  6075. "}"
  6076. ].join("\n"),
  6077. fragmentShader: [
  6078. "uniform vec3 diffuse;",
  6079. "uniform float opacity;",
  6080. "uniform vec3 ambient;",
  6081. "uniform vec3 emissive;",
  6082. "uniform vec3 specular;",
  6083. "uniform float shininess;",
  6084. THREE.ShaderChunk[ "color_pars_fragment" ],
  6085. THREE.ShaderChunk[ "map_pars_fragment" ],
  6086. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  6087. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  6088. THREE.ShaderChunk[ "fog_pars_fragment" ],
  6089. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  6090. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  6091. "void main() {",
  6092. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  6093. THREE.ShaderChunk[ "map_fragment" ],
  6094. THREE.ShaderChunk[ "alphatest_fragment" ],
  6095. THREE.ShaderChunk[ "lights_phong_fragment" ],
  6096. THREE.ShaderChunk[ "lightmap_fragment" ],
  6097. THREE.ShaderChunk[ "color_fragment" ],
  6098. THREE.ShaderChunk[ "envmap_fragment" ],
  6099. THREE.ShaderChunk[ "shadowmap_fragment" ],
  6100. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  6101. THREE.ShaderChunk[ "fog_fragment" ],
  6102. "}"
  6103. ].join("\n")
  6104. },
  6105. 'particle_basic': {
  6106. uniforms: THREE.UniformsUtils.merge( [
  6107. THREE.UniformsLib[ "particle" ],
  6108. THREE.UniformsLib[ "shadowmap" ]
  6109. ] ),
  6110. vertexShader: [
  6111. "uniform float size;",
  6112. "uniform float scale;",
  6113. THREE.ShaderChunk[ "color_pars_vertex" ],
  6114. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  6115. "void main() {",
  6116. THREE.ShaderChunk[ "color_vertex" ],
  6117. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  6118. "#ifdef USE_SIZEATTENUATION",
  6119. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  6120. "#else",
  6121. "gl_PointSize = size;",
  6122. "#endif",
  6123. "gl_Position = projectionMatrix * mvPosition;",
  6124. THREE.ShaderChunk[ "shadowmap_vertex" ],
  6125. "}"
  6126. ].join("\n"),
  6127. fragmentShader: [
  6128. "uniform vec3 psColor;",
  6129. "uniform float opacity;",
  6130. THREE.ShaderChunk[ "color_pars_fragment" ],
  6131. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  6132. THREE.ShaderChunk[ "fog_pars_fragment" ],
  6133. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  6134. "void main() {",
  6135. "gl_FragColor = vec4( psColor, opacity );",
  6136. THREE.ShaderChunk[ "map_particle_fragment" ],
  6137. THREE.ShaderChunk[ "alphatest_fragment" ],
  6138. THREE.ShaderChunk[ "color_fragment" ],
  6139. THREE.ShaderChunk[ "shadowmap_fragment" ],
  6140. THREE.ShaderChunk[ "fog_fragment" ],
  6141. "}"
  6142. ].join("\n")
  6143. },
  6144. // Depth encoding into RGBA texture
  6145. // based on SpiderGL shadow map example
  6146. // http://spidergl.org/example.php?id=6
  6147. // originally from
  6148. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  6149. // see also here:
  6150. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  6151. 'depthRGBA': {
  6152. uniforms: {},
  6153. vertexShader: [
  6154. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  6155. "void main() {",
  6156. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  6157. THREE.ShaderChunk[ "morphtarget_vertex" ],
  6158. THREE.ShaderChunk[ "default_vertex" ],
  6159. "}"
  6160. ].join("\n"),
  6161. fragmentShader: [
  6162. "vec4 pack_depth( const in float depth ) {",
  6163. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  6164. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  6165. "vec4 res = fract( depth * bit_shift );",
  6166. "res -= res.xxyz * bit_mask;",
  6167. "return res;",
  6168. "}",
  6169. "void main() {",
  6170. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  6171. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  6172. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  6173. //"gl_FragData[ 0 ] = pack_depth( z );",
  6174. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  6175. "}"
  6176. ].join("\n")
  6177. }
  6178. };/**
  6179. * @author supereggbert / http://www.paulbrunt.co.uk/
  6180. * @author mrdoob / http://mrdoob.com/
  6181. * @author alteredq / http://alteredqualia.com/
  6182. * @author szimek / https://github.com/szimek/
  6183. */
  6184. THREE.WebGLRenderer = function ( parameters ) {
  6185. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  6186. parameters = parameters || {};
  6187. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  6188. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  6189. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  6190. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  6191. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  6192. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  6193. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  6194. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  6195. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,
  6196. _maxLights = parameters.maxLights !== undefined ? parameters.maxLights : 4;
  6197. // public properties
  6198. this.domElement = _canvas;
  6199. this.context = null;
  6200. // clearing
  6201. this.autoClear = true;
  6202. this.autoClearColor = true;
  6203. this.autoClearDepth = true;
  6204. this.autoClearStencil = true;
  6205. // scene graph
  6206. this.sortObjects = true;
  6207. this.autoUpdateObjects = true;
  6208. this.autoUpdateScene = true;
  6209. // physically based shading
  6210. this.gammaInput = false;
  6211. this.gammaOutput = false;
  6212. this.physicallyBasedShading = false;
  6213. // shadow map
  6214. this.shadowMapEnabled = false;
  6215. this.shadowMapAutoUpdate = true;
  6216. this.shadowMapSoft = true;
  6217. this.shadowMapCullFrontFaces = true;
  6218. this.shadowMapDebug = false;
  6219. this.shadowMapCascade = false;
  6220. // morphs
  6221. this.maxMorphTargets = 8;
  6222. this.maxMorphNormals = 4;
  6223. // flags
  6224. this.autoScaleCubemaps = true;
  6225. // custom render plugins
  6226. this.renderPluginsPre = [];
  6227. this.renderPluginsPost = [];
  6228. // info
  6229. this.info = {
  6230. memory: {
  6231. programs: 0,
  6232. geometries: 0,
  6233. textures: 0
  6234. },
  6235. render: {
  6236. calls: 0,
  6237. vertices: 0,
  6238. faces: 0,
  6239. points: 0
  6240. }
  6241. };
  6242. // internal properties
  6243. var _this = this,
  6244. _gl,
  6245. _programs = [],
  6246. // internal state cache
  6247. _currentProgram = null,
  6248. _currentFramebuffer = null,
  6249. _currentMaterialId = -1,
  6250. _currentGeometryGroupHash = null,
  6251. _currentCamera = null,
  6252. _geometryGroupCounter = 0,
  6253. // GL state cache
  6254. _oldDoubleSided = null,
  6255. _oldFlipSided = null,
  6256. _oldBlending = null,
  6257. _oldBlendEquation = null,
  6258. _oldBlendSrc = null,
  6259. _oldBlendDst = null,
  6260. _oldDepthTest = null,
  6261. _oldDepthWrite = null,
  6262. _oldPolygonOffset = null,
  6263. _oldPolygonOffsetFactor = null,
  6264. _oldPolygonOffsetUnits = null,
  6265. _oldLineWidth = null,
  6266. _viewportX = 0,
  6267. _viewportY = 0,
  6268. _viewportWidth = 0,
  6269. _viewportHeight = 0,
  6270. _currentWidth = 0,
  6271. _currentHeight = 0,
  6272. // frustum
  6273. _frustum = new THREE.Frustum(),
  6274. // camera matrices cache
  6275. _projScreenMatrix = new THREE.Matrix4(),
  6276. _projScreenMatrixPS = new THREE.Matrix4(),
  6277. _vector3 = new THREE.Vector4(),
  6278. // light arrays cache
  6279. _direction = new THREE.Vector3(),
  6280. _lights = {
  6281. ambient: [ 0, 0, 0 ],
  6282. directional: { length: 0, colors: new Array(), positions: new Array() },
  6283. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() }
  6284. };
  6285. // initialize
  6286. _gl = initGL();
  6287. setDefaultGLState();
  6288. this.context = _gl;
  6289. // GPU capabilities
  6290. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ),
  6291. _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ),
  6292. _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  6293. // API
  6294. this.getContext = function () {
  6295. return _gl;
  6296. };
  6297. this.supportsVertexTextures = function () {
  6298. return _maxVertexTextures > 0;
  6299. };
  6300. this.setSize = function ( width, height ) {
  6301. _canvas.width = width;
  6302. _canvas.height = height;
  6303. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  6304. };
  6305. this.setViewport = function ( x, y, width, height ) {
  6306. _viewportX = x;
  6307. _viewportY = y;
  6308. _viewportWidth = width;
  6309. _viewportHeight = height;
  6310. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  6311. };
  6312. this.setScissor = function ( x, y, width, height ) {
  6313. _gl.scissor( x, y, width, height );
  6314. };
  6315. this.enableScissorTest = function ( enable ) {
  6316. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  6317. };
  6318. // Clearing
  6319. this.setClearColorHex = function ( hex, alpha ) {
  6320. _clearColor.setHex( hex );
  6321. _clearAlpha = alpha;
  6322. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  6323. };
  6324. this.setClearColor = function ( color, alpha ) {
  6325. _clearColor.copy( color );
  6326. _clearAlpha = alpha;
  6327. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  6328. };
  6329. this.getClearColor = function () {
  6330. return _clearColor;
  6331. };
  6332. this.getClearAlpha = function () {
  6333. return _clearAlpha;
  6334. };
  6335. this.clear = function ( color, depth, stencil ) {
  6336. var bits = 0;
  6337. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  6338. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  6339. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  6340. _gl.clear( bits );
  6341. };
  6342. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  6343. this.setRenderTarget( renderTarget );
  6344. this.clear( color, depth, stencil );
  6345. };
  6346. // Plugins
  6347. this.addPostPlugin = function ( plugin ) {
  6348. plugin.init( this );
  6349. this.renderPluginsPost.push( plugin );
  6350. };
  6351. this.addPrePlugin = function ( plugin ) {
  6352. plugin.init( this );
  6353. this.renderPluginsPre.push( plugin );
  6354. };
  6355. // Deallocation
  6356. this.deallocateObject = function ( object ) {
  6357. if ( ! object.__webglInit ) return;
  6358. object.__webglInit = false;
  6359. delete object._modelViewMatrix;
  6360. delete object._normalMatrix;
  6361. delete object._normalMatrixArray;
  6362. delete object._modelViewMatrixArray;
  6363. delete object._objectMatrixArray;
  6364. if ( object instanceof THREE.Mesh ) {
  6365. for ( var g in object.geometry.geometryGroups ) {
  6366. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  6367. }
  6368. } else if ( object instanceof THREE.Ribbon ) {
  6369. deleteRibbonBuffers( object.geometry );
  6370. } else if ( object instanceof THREE.Line ) {
  6371. deleteLineBuffers( object.geometry );
  6372. } else if ( object instanceof THREE.ParticleSystem ) {
  6373. deleteParticleBuffers( object.geometry );
  6374. }
  6375. };
  6376. this.deallocateTexture = function ( texture ) {
  6377. if ( ! texture.__webglInit ) return;
  6378. texture.__webglInit = false;
  6379. _gl.deleteTexture( texture.__webglTexture );
  6380. _this.info.memory.textures --;
  6381. };
  6382. this.deallocateRenderTarget = function ( renderTarget ) {
  6383. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  6384. _gl.deleteTexture( renderTarget.__webglTexture );
  6385. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  6386. for ( var i = 0; i < 6; i ++ ) {
  6387. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  6388. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  6389. }
  6390. } else {
  6391. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  6392. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  6393. }
  6394. };
  6395. // Rendering
  6396. this.updateShadowMap = function ( scene, camera ) {
  6397. _currentProgram = null;
  6398. _oldBlending = -1;
  6399. _oldDepthTest = -1;
  6400. _oldDepthWrite = -1;
  6401. _currentGeometryGroupHash = -1;
  6402. _currentMaterialId = -1;
  6403. this.shadowMapPlugin.update( scene, camera );
  6404. };
  6405. // Internal functions
  6406. // Buffer allocation
  6407. function createParticleBuffers ( geometry ) {
  6408. geometry.__webglVertexBuffer = _gl.createBuffer();
  6409. geometry.__webglColorBuffer = _gl.createBuffer();
  6410. _this.info.geometries ++;
  6411. };
  6412. function createLineBuffers ( geometry ) {
  6413. geometry.__webglVertexBuffer = _gl.createBuffer();
  6414. geometry.__webglColorBuffer = _gl.createBuffer();
  6415. _this.info.memory.geometries ++;
  6416. };
  6417. function createRibbonBuffers ( geometry ) {
  6418. geometry.__webglVertexBuffer = _gl.createBuffer();
  6419. geometry.__webglColorBuffer = _gl.createBuffer();
  6420. _this.info.memory.geometries ++;
  6421. };
  6422. function createMeshBuffers ( geometryGroup ) {
  6423. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  6424. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  6425. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  6426. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  6427. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  6428. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  6429. geometryGroup.__webglSkinVertexABuffer = _gl.createBuffer();
  6430. geometryGroup.__webglSkinVertexBBuffer = _gl.createBuffer();
  6431. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  6432. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  6433. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  6434. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  6435. var m, ml;
  6436. if ( geometryGroup.numMorphTargets ) {
  6437. geometryGroup.__webglMorphTargetsBuffers = [];
  6438. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  6439. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  6440. }
  6441. }
  6442. if ( geometryGroup.numMorphNormals ) {
  6443. geometryGroup.__webglMorphNormalsBuffers = [];
  6444. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  6445. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  6446. }
  6447. }
  6448. _this.info.memory.geometries ++;
  6449. };
  6450. // Buffer deallocation
  6451. function deleteParticleBuffers ( geometry ) {
  6452. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  6453. _gl.deleteBuffer( geometry.__webglColorBuffer );
  6454. _this.info.memory.geometries --;
  6455. };
  6456. function deleteLineBuffers ( geometry ) {
  6457. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  6458. _gl.deleteBuffer( geometry.__webglColorBuffer );
  6459. _this.info.memory.geometries --;
  6460. };
  6461. function deleteRibbonBuffers ( geometry ) {
  6462. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  6463. _gl.deleteBuffer( geometry.__webglColorBuffer );
  6464. _this.info.memory.geometries --;
  6465. };
  6466. function deleteMeshBuffers ( geometryGroup ) {
  6467. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  6468. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  6469. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  6470. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  6471. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  6472. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  6473. _gl.deleteBuffer( geometryGroup.__webglSkinVertexABuffer );
  6474. _gl.deleteBuffer( geometryGroup.__webglSkinVertexBBuffer );
  6475. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  6476. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  6477. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  6478. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  6479. var m, ml;
  6480. if ( geometryGroup.numMorphTargets ) {
  6481. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  6482. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  6483. }
  6484. }
  6485. if ( geometryGroup.numMorphNormals ) {
  6486. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  6487. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  6488. }
  6489. }
  6490. if ( geometryGroup.__webglCustomAttributesList ) {
  6491. for ( var id in geometryGroup.__webglCustomAttributesList ) {
  6492. _gl.deleteBuffer( geometryGroup.__webglCustomAttributesList[ id ].buffer );
  6493. }
  6494. }
  6495. _this.info.memory.geometries --;
  6496. };
  6497. // Buffer initialization
  6498. function initCustomAttributes ( geometry, object ) {
  6499. var nvertices = geometry.vertices.length;
  6500. var material = object.material;
  6501. if ( material.attributes ) {
  6502. if ( geometry.__webglCustomAttributesList === undefined ) {
  6503. geometry.__webglCustomAttributesList = [];
  6504. }
  6505. for ( var a in material.attributes ) {
  6506. var attribute = material.attributes[ a ];
  6507. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  6508. attribute.__webglInitialized = true;
  6509. var size = 1; // "f" and "i"
  6510. if ( attribute.type === "v2" ) size = 2;
  6511. else if ( attribute.type === "v3" ) size = 3;
  6512. else if ( attribute.type === "v4" ) size = 4;
  6513. else if ( attribute.type === "c" ) size = 3;
  6514. attribute.size = size;
  6515. attribute.array = new Float32Array( nvertices * size );
  6516. attribute.buffer = _gl.createBuffer();
  6517. attribute.buffer.belongsToAttribute = a;
  6518. attribute.needsUpdate = true;
  6519. }
  6520. geometry.__webglCustomAttributesList.push( attribute );
  6521. }
  6522. }
  6523. };
  6524. function initParticleBuffers ( geometry, object ) {
  6525. var nvertices = geometry.vertices.length;
  6526. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  6527. geometry.__colorArray = new Float32Array( nvertices * 3 );
  6528. geometry.__sortArray = [];
  6529. geometry.__webglParticleCount = nvertices;
  6530. initCustomAttributes ( geometry, object );
  6531. };
  6532. function initLineBuffers ( geometry, object ) {
  6533. var nvertices = geometry.vertices.length;
  6534. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  6535. geometry.__colorArray = new Float32Array( nvertices * 3 );
  6536. geometry.__webglLineCount = nvertices;
  6537. initCustomAttributes ( geometry, object );
  6538. };
  6539. function initRibbonBuffers ( geometry ) {
  6540. var nvertices = geometry.vertices.length;
  6541. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  6542. geometry.__colorArray = new Float32Array( nvertices * 3 );
  6543. geometry.__webglVertexCount = nvertices;
  6544. };
  6545. function initMeshBuffers ( geometryGroup, object ) {
  6546. var geometry = object.geometry,
  6547. faces3 = geometryGroup.faces3,
  6548. faces4 = geometryGroup.faces4,
  6549. nvertices = faces3.length * 3 + faces4.length * 4,
  6550. ntris = faces3.length * 1 + faces4.length * 2,
  6551. nlines = faces3.length * 3 + faces4.length * 4,
  6552. material = getBufferMaterial( object, geometryGroup ),
  6553. uvType = bufferGuessUVType( material ),
  6554. normalType = bufferGuessNormalType( material ),
  6555. vertexColorType = bufferGuessVertexColorType( material );
  6556. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  6557. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  6558. if ( normalType ) {
  6559. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  6560. }
  6561. if ( geometry.hasTangents ) {
  6562. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  6563. }
  6564. if ( vertexColorType ) {
  6565. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  6566. }
  6567. if ( uvType ) {
  6568. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  6569. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  6570. }
  6571. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  6572. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  6573. }
  6574. }
  6575. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  6576. geometryGroup.__skinVertexAArray = new Float32Array( nvertices * 4 );
  6577. geometryGroup.__skinVertexBArray = new Float32Array( nvertices * 4 );
  6578. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  6579. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  6580. }
  6581. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  6582. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  6583. var m, ml;
  6584. if ( geometryGroup.numMorphTargets ) {
  6585. geometryGroup.__morphTargetsArrays = [];
  6586. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  6587. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  6588. }
  6589. }
  6590. if ( geometryGroup.numMorphNormals ) {
  6591. geometryGroup.__morphNormalsArrays = [];
  6592. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  6593. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  6594. }
  6595. }
  6596. geometryGroup.__webglFaceCount = ntris * 3;
  6597. geometryGroup.__webglLineCount = nlines * 2;
  6598. // custom attributes
  6599. if ( material.attributes ) {
  6600. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  6601. geometryGroup.__webglCustomAttributesList = [];
  6602. }
  6603. for ( var a in material.attributes ) {
  6604. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  6605. // attribute buffers which are correctly indexed in the setMeshBuffers function
  6606. var originalAttribute = material.attributes[ a ];
  6607. var attribute = {};
  6608. for ( var property in originalAttribute ) {
  6609. attribute[ property ] = originalAttribute[ property ];
  6610. }
  6611. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  6612. attribute.__webglInitialized = true;
  6613. var size = 1; // "f" and "i"
  6614. if( attribute.type === "v2" ) size = 2;
  6615. else if( attribute.type === "v3" ) size = 3;
  6616. else if( attribute.type === "v4" ) size = 4;
  6617. else if( attribute.type === "c" ) size = 3;
  6618. attribute.size = size;
  6619. attribute.array = new Float32Array( nvertices * size );
  6620. attribute.buffer = _gl.createBuffer();
  6621. attribute.buffer.belongsToAttribute = a;
  6622. originalAttribute.needsUpdate = true;
  6623. attribute.__original = originalAttribute;
  6624. }
  6625. geometryGroup.__webglCustomAttributesList.push( attribute );
  6626. }
  6627. }
  6628. geometryGroup.__inittedArrays = true;
  6629. };
  6630. function getBufferMaterial( object, geometryGroup ) {
  6631. if ( object.material && ! ( object.material instanceof THREE.MeshFaceMaterial ) ) {
  6632. return object.material;
  6633. } else if ( geometryGroup.materialIndex >= 0 ) {
  6634. return object.geometry.materials[ geometryGroup.materialIndex ];
  6635. }
  6636. };
  6637. function materialNeedsSmoothNormals ( material ) {
  6638. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  6639. };
  6640. function bufferGuessNormalType ( material ) {
  6641. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  6642. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  6643. return false;
  6644. }
  6645. if ( materialNeedsSmoothNormals( material ) ) {
  6646. return THREE.SmoothShading;
  6647. } else {
  6648. return THREE.FlatShading;
  6649. }
  6650. };
  6651. function bufferGuessVertexColorType ( material ) {
  6652. if ( material.vertexColors ) {
  6653. return material.vertexColors;
  6654. }
  6655. return false;
  6656. };
  6657. function bufferGuessUVType ( material ) {
  6658. // material must use some texture to require uvs
  6659. if ( material.map || material.lightMap || material instanceof THREE.ShaderMaterial ) {
  6660. return true;
  6661. }
  6662. return false;
  6663. };
  6664. // Buffer setting
  6665. function setParticleBuffers ( geometry, hint, object ) {
  6666. var v, c, vertex, offset, index, color,
  6667. vertices = geometry.vertices,
  6668. vl = vertices.length,
  6669. colors = geometry.colors,
  6670. cl = colors.length,
  6671. vertexArray = geometry.__vertexArray,
  6672. colorArray = geometry.__colorArray,
  6673. sortArray = geometry.__sortArray,
  6674. dirtyVertices = geometry.__dirtyVertices,
  6675. dirtyElements = geometry.__dirtyElements,
  6676. dirtyColors = geometry.__dirtyColors,
  6677. customAttributes = geometry.__webglCustomAttributesList,
  6678. i, il,
  6679. a, ca, cal, value,
  6680. customAttribute;
  6681. if ( object.sortParticles ) {
  6682. _projScreenMatrixPS.copy( _projScreenMatrix );
  6683. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  6684. for ( v = 0; v < vl; v ++ ) {
  6685. vertex = vertices[ v ];
  6686. _vector3.copy( vertex );
  6687. _projScreenMatrixPS.multiplyVector3( _vector3 );
  6688. sortArray[ v ] = [ _vector3.z, v ];
  6689. }
  6690. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  6691. for ( v = 0; v < vl; v ++ ) {
  6692. vertex = vertices[ sortArray[v][1] ];
  6693. offset = v * 3;
  6694. vertexArray[ offset ] = vertex.x;
  6695. vertexArray[ offset + 1 ] = vertex.y;
  6696. vertexArray[ offset + 2 ] = vertex.z;
  6697. }
  6698. for ( c = 0; c < cl; c ++ ) {
  6699. offset = c * 3;
  6700. color = colors[ sortArray[c][1] ];
  6701. colorArray[ offset ] = color.r;
  6702. colorArray[ offset + 1 ] = color.g;
  6703. colorArray[ offset + 2 ] = color.b;
  6704. }
  6705. if ( customAttributes ) {
  6706. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6707. customAttribute = customAttributes[ i ];
  6708. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  6709. offset = 0;
  6710. cal = customAttribute.value.length;
  6711. if ( customAttribute.size === 1 ) {
  6712. for ( ca = 0; ca < cal; ca ++ ) {
  6713. index = sortArray[ ca ][ 1 ];
  6714. customAttribute.array[ ca ] = customAttribute.value[ index ];
  6715. }
  6716. } else if ( customAttribute.size === 2 ) {
  6717. for ( ca = 0; ca < cal; ca ++ ) {
  6718. index = sortArray[ ca ][ 1 ];
  6719. value = customAttribute.value[ index ];
  6720. customAttribute.array[ offset ] = value.x;
  6721. customAttribute.array[ offset + 1 ] = value.y;
  6722. offset += 2;
  6723. }
  6724. } else if ( customAttribute.size === 3 ) {
  6725. if ( customAttribute.type === "c" ) {
  6726. for ( ca = 0; ca < cal; ca ++ ) {
  6727. index = sortArray[ ca ][ 1 ];
  6728. value = customAttribute.value[ index ];
  6729. customAttribute.array[ offset ] = value.r;
  6730. customAttribute.array[ offset + 1 ] = value.g;
  6731. customAttribute.array[ offset + 2 ] = value.b;
  6732. offset += 3;
  6733. }
  6734. } else {
  6735. for ( ca = 0; ca < cal; ca ++ ) {
  6736. index = sortArray[ ca ][ 1 ];
  6737. value = customAttribute.value[ index ];
  6738. customAttribute.array[ offset ] = value.x;
  6739. customAttribute.array[ offset + 1 ] = value.y;
  6740. customAttribute.array[ offset + 2 ] = value.z;
  6741. offset += 3;
  6742. }
  6743. }
  6744. } else if ( customAttribute.size === 4 ) {
  6745. for ( ca = 0; ca < cal; ca ++ ) {
  6746. index = sortArray[ ca ][ 1 ];
  6747. value = customAttribute.value[ index ];
  6748. customAttribute.array[ offset ] = value.x;
  6749. customAttribute.array[ offset + 1 ] = value.y;
  6750. customAttribute.array[ offset + 2 ] = value.z;
  6751. customAttribute.array[ offset + 3 ] = value.w;
  6752. offset += 4;
  6753. }
  6754. }
  6755. }
  6756. }
  6757. } else {
  6758. if ( dirtyVertices ) {
  6759. for ( v = 0; v < vl; v ++ ) {
  6760. vertex = vertices[ v ];
  6761. offset = v * 3;
  6762. vertexArray[ offset ] = vertex.x;
  6763. vertexArray[ offset + 1 ] = vertex.y;
  6764. vertexArray[ offset + 2 ] = vertex.z;
  6765. }
  6766. }
  6767. if ( dirtyColors ) {
  6768. for ( c = 0; c < cl; c ++ ) {
  6769. color = colors[ c ];
  6770. offset = c * 3;
  6771. colorArray[ offset ] = color.r;
  6772. colorArray[ offset + 1 ] = color.g;
  6773. colorArray[ offset + 2 ] = color.b;
  6774. }
  6775. }
  6776. if ( customAttributes ) {
  6777. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6778. customAttribute = customAttributes[ i ];
  6779. if ( customAttribute.needsUpdate &&
  6780. ( customAttribute.boundTo === undefined ||
  6781. customAttribute.boundTo === "vertices") ) {
  6782. cal = customAttribute.value.length;
  6783. offset = 0;
  6784. if ( customAttribute.size === 1 ) {
  6785. for ( ca = 0; ca < cal; ca ++ ) {
  6786. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  6787. }
  6788. } else if ( customAttribute.size === 2 ) {
  6789. for ( ca = 0; ca < cal; ca ++ ) {
  6790. value = customAttribute.value[ ca ];
  6791. customAttribute.array[ offset ] = value.x;
  6792. customAttribute.array[ offset + 1 ] = value.y;
  6793. offset += 2;
  6794. }
  6795. } else if ( customAttribute.size === 3 ) {
  6796. if ( customAttribute.type === "c" ) {
  6797. for ( ca = 0; ca < cal; ca ++ ) {
  6798. value = customAttribute.value[ ca ];
  6799. customAttribute.array[ offset ] = value.r;
  6800. customAttribute.array[ offset + 1 ] = value.g;
  6801. customAttribute.array[ offset + 2 ] = value.b;
  6802. offset += 3;
  6803. }
  6804. } else {
  6805. for ( ca = 0; ca < cal; ca ++ ) {
  6806. value = customAttribute.value[ ca ];
  6807. customAttribute.array[ offset ] = value.x;
  6808. customAttribute.array[ offset + 1 ] = value.y;
  6809. customAttribute.array[ offset + 2 ] = value.z;
  6810. offset += 3;
  6811. }
  6812. }
  6813. } else if ( customAttribute.size === 4 ) {
  6814. for ( ca = 0; ca < cal; ca ++ ) {
  6815. value = customAttribute.value[ ca ];
  6816. customAttribute.array[ offset ] = value.x;
  6817. customAttribute.array[ offset + 1 ] = value.y;
  6818. customAttribute.array[ offset + 2 ] = value.z;
  6819. customAttribute.array[ offset + 3 ] = value.w;
  6820. offset += 4;
  6821. }
  6822. }
  6823. }
  6824. }
  6825. }
  6826. }
  6827. if ( dirtyVertices || object.sortParticles ) {
  6828. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  6829. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  6830. }
  6831. if ( dirtyColors || object.sortParticles ) {
  6832. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  6833. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  6834. }
  6835. if ( customAttributes ) {
  6836. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6837. customAttribute = customAttributes[ i ];
  6838. if ( customAttribute.needsUpdate || object.sortParticles ) {
  6839. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  6840. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  6841. }
  6842. }
  6843. }
  6844. };
  6845. function setLineBuffers ( geometry, hint ) {
  6846. var v, c, vertex, offset, color,
  6847. vertices = geometry.vertices,
  6848. colors = geometry.colors,
  6849. vl = vertices.length,
  6850. cl = colors.length,
  6851. vertexArray = geometry.__vertexArray,
  6852. colorArray = geometry.__colorArray,
  6853. dirtyVertices = geometry.__dirtyVertices,
  6854. dirtyColors = geometry.__dirtyColors,
  6855. customAttributes = geometry.__webglCustomAttributesList,
  6856. i, il,
  6857. a, ca, cal, value,
  6858. customAttribute;
  6859. if ( dirtyVertices ) {
  6860. for ( v = 0; v < vl; v ++ ) {
  6861. vertex = vertices[ v ];
  6862. offset = v * 3;
  6863. vertexArray[ offset ] = vertex.x;
  6864. vertexArray[ offset + 1 ] = vertex.y;
  6865. vertexArray[ offset + 2 ] = vertex.z;
  6866. }
  6867. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  6868. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  6869. }
  6870. if ( dirtyColors ) {
  6871. for ( c = 0; c < cl; c ++ ) {
  6872. color = colors[ c ];
  6873. offset = c * 3;
  6874. colorArray[ offset ] = color.r;
  6875. colorArray[ offset + 1 ] = color.g;
  6876. colorArray[ offset + 2 ] = color.b;
  6877. }
  6878. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  6879. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  6880. }
  6881. if ( customAttributes ) {
  6882. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6883. customAttribute = customAttributes[ i ];
  6884. if ( customAttribute.needsUpdate &&
  6885. ( customAttribute.boundTo === undefined ||
  6886. customAttribute.boundTo === "vertices" ) ) {
  6887. offset = 0;
  6888. cal = customAttribute.value.length;
  6889. if ( customAttribute.size === 1 ) {
  6890. for ( ca = 0; ca < cal; ca ++ ) {
  6891. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  6892. }
  6893. } else if ( customAttribute.size === 2 ) {
  6894. for ( ca = 0; ca < cal; ca ++ ) {
  6895. value = customAttribute.value[ ca ];
  6896. customAttribute.array[ offset ] = value.x;
  6897. customAttribute.array[ offset + 1 ] = value.y;
  6898. offset += 2;
  6899. }
  6900. } else if ( customAttribute.size === 3 ) {
  6901. if ( customAttribute.type === "c" ) {
  6902. for ( ca = 0; ca < cal; ca ++ ) {
  6903. value = customAttribute.value[ ca ];
  6904. customAttribute.array[ offset ] = value.r;
  6905. customAttribute.array[ offset + 1 ] = value.g;
  6906. customAttribute.array[ offset + 2 ] = value.b;
  6907. offset += 3;
  6908. }
  6909. } else {
  6910. for ( ca = 0; ca < cal; ca ++ ) {
  6911. value = customAttribute.value[ ca ];
  6912. customAttribute.array[ offset ] = value.x;
  6913. customAttribute.array[ offset + 1 ] = value.y;
  6914. customAttribute.array[ offset + 2 ] = value.z;
  6915. offset += 3;
  6916. }
  6917. }
  6918. } else if ( customAttribute.size === 4 ) {
  6919. for ( ca = 0; ca < cal; ca ++ ) {
  6920. value = customAttribute.value[ ca ];
  6921. customAttribute.array[ offset ] = value.x;
  6922. customAttribute.array[ offset + 1 ] = value.y;
  6923. customAttribute.array[ offset + 2 ] = value.z;
  6924. customAttribute.array[ offset + 3 ] = value.w;
  6925. offset += 4;
  6926. }
  6927. }
  6928. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  6929. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  6930. }
  6931. }
  6932. }
  6933. };
  6934. function setRibbonBuffers ( geometry, hint ) {
  6935. var v, c, vertex, offset, color,
  6936. vertices = geometry.vertices,
  6937. colors = geometry.colors,
  6938. vl = vertices.length,
  6939. cl = colors.length,
  6940. vertexArray = geometry.__vertexArray,
  6941. colorArray = geometry.__colorArray,
  6942. dirtyVertices = geometry.__dirtyVertices,
  6943. dirtyColors = geometry.__dirtyColors;
  6944. if ( dirtyVertices ) {
  6945. for ( v = 0; v < vl; v ++ ) {
  6946. vertex = vertices[ v ];
  6947. offset = v * 3;
  6948. vertexArray[ offset ] = vertex.x;
  6949. vertexArray[ offset + 1 ] = vertex.y;
  6950. vertexArray[ offset + 2 ] = vertex.z;
  6951. }
  6952. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  6953. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  6954. }
  6955. if ( dirtyColors ) {
  6956. for ( c = 0; c < cl; c ++ ) {
  6957. color = colors[ c ];
  6958. offset = c * 3;
  6959. colorArray[ offset ] = color.r;
  6960. colorArray[ offset + 1 ] = color.g;
  6961. colorArray[ offset + 2 ] = color.b;
  6962. }
  6963. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  6964. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  6965. }
  6966. };
  6967. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  6968. if ( ! geometryGroup.__inittedArrays ) {
  6969. // console.log( object );
  6970. return;
  6971. }
  6972. var normalType = bufferGuessNormalType( material ),
  6973. vertexColorType = bufferGuessVertexColorType( material ),
  6974. uvType = bufferGuessUVType( material ),
  6975. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  6976. var f, fl, fi, face,
  6977. vertexNormals, faceNormal, normal,
  6978. vertexColors, faceColor,
  6979. vertexTangents,
  6980. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  6981. c1, c2, c3, c4,
  6982. sw1, sw2, sw3, sw4,
  6983. si1, si2, si3, si4,
  6984. sa1, sa2, sa3, sa4,
  6985. sb1, sb2, sb3, sb4,
  6986. m, ml, i, il,
  6987. vn, uvi, uv2i,
  6988. vk, vkl, vka,
  6989. nka, chf, faceVertexNormals,
  6990. a,
  6991. vertexIndex = 0,
  6992. offset = 0,
  6993. offset_uv = 0,
  6994. offset_uv2 = 0,
  6995. offset_face = 0,
  6996. offset_normal = 0,
  6997. offset_tangent = 0,
  6998. offset_line = 0,
  6999. offset_color = 0,
  7000. offset_skin = 0,
  7001. offset_morphTarget = 0,
  7002. offset_custom = 0,
  7003. offset_customSrc = 0,
  7004. value,
  7005. vertexArray = geometryGroup.__vertexArray,
  7006. uvArray = geometryGroup.__uvArray,
  7007. uv2Array = geometryGroup.__uv2Array,
  7008. normalArray = geometryGroup.__normalArray,
  7009. tangentArray = geometryGroup.__tangentArray,
  7010. colorArray = geometryGroup.__colorArray,
  7011. skinVertexAArray = geometryGroup.__skinVertexAArray,
  7012. skinVertexBArray = geometryGroup.__skinVertexBArray,
  7013. skinIndexArray = geometryGroup.__skinIndexArray,
  7014. skinWeightArray = geometryGroup.__skinWeightArray,
  7015. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  7016. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  7017. customAttributes = geometryGroup.__webglCustomAttributesList,
  7018. customAttribute,
  7019. faceArray = geometryGroup.__faceArray,
  7020. lineArray = geometryGroup.__lineArray,
  7021. geometry = object.geometry, // this is shared for all chunks
  7022. dirtyVertices = geometry.__dirtyVertices,
  7023. dirtyElements = geometry.__dirtyElements,
  7024. dirtyUvs = geometry.__dirtyUvs,
  7025. dirtyNormals = geometry.__dirtyNormals,
  7026. dirtyTangents = geometry.__dirtyTangents,
  7027. dirtyColors = geometry.__dirtyColors,
  7028. dirtyMorphTargets = geometry.__dirtyMorphTargets,
  7029. vertices = geometry.vertices,
  7030. chunk_faces3 = geometryGroup.faces3,
  7031. chunk_faces4 = geometryGroup.faces4,
  7032. obj_faces = geometry.faces,
  7033. obj_uvs = geometry.faceVertexUvs[ 0 ],
  7034. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  7035. obj_colors = geometry.colors,
  7036. obj_skinVerticesA = geometry.skinVerticesA,
  7037. obj_skinVerticesB = geometry.skinVerticesB,
  7038. obj_skinIndices = geometry.skinIndices,
  7039. obj_skinWeights = geometry.skinWeights,
  7040. morphTargets = geometry.morphTargets,
  7041. morphNormals = geometry.morphNormals;
  7042. if ( dirtyVertices ) {
  7043. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7044. face = obj_faces[ chunk_faces3[ f ] ];
  7045. v1 = vertices[ face.a ];
  7046. v2 = vertices[ face.b ];
  7047. v3 = vertices[ face.c ];
  7048. vertexArray[ offset ] = v1.x;
  7049. vertexArray[ offset + 1 ] = v1.y;
  7050. vertexArray[ offset + 2 ] = v1.z;
  7051. vertexArray[ offset + 3 ] = v2.x;
  7052. vertexArray[ offset + 4 ] = v2.y;
  7053. vertexArray[ offset + 5 ] = v2.z;
  7054. vertexArray[ offset + 6 ] = v3.x;
  7055. vertexArray[ offset + 7 ] = v3.y;
  7056. vertexArray[ offset + 8 ] = v3.z;
  7057. offset += 9;
  7058. }
  7059. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7060. face = obj_faces[ chunk_faces4[ f ] ];
  7061. v1 = vertices[ face.a ];
  7062. v2 = vertices[ face.b ];
  7063. v3 = vertices[ face.c ];
  7064. v4 = vertices[ face.d ];
  7065. vertexArray[ offset ] = v1.x;
  7066. vertexArray[ offset + 1 ] = v1.y;
  7067. vertexArray[ offset + 2 ] = v1.z;
  7068. vertexArray[ offset + 3 ] = v2.x;
  7069. vertexArray[ offset + 4 ] = v2.y;
  7070. vertexArray[ offset + 5 ] = v2.z;
  7071. vertexArray[ offset + 6 ] = v3.x;
  7072. vertexArray[ offset + 7 ] = v3.y;
  7073. vertexArray[ offset + 8 ] = v3.z;
  7074. vertexArray[ offset + 9 ] = v4.x;
  7075. vertexArray[ offset + 10 ] = v4.y;
  7076. vertexArray[ offset + 11 ] = v4.z;
  7077. offset += 12;
  7078. }
  7079. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  7080. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  7081. }
  7082. if ( dirtyMorphTargets ) {
  7083. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  7084. offset_morphTarget = 0;
  7085. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7086. chf = chunk_faces3[ f ];
  7087. face = obj_faces[ chf ];
  7088. // morph positions
  7089. v1 = morphTargets[ vk ].vertices[ face.a ];
  7090. v2 = morphTargets[ vk ].vertices[ face.b ];
  7091. v3 = morphTargets[ vk ].vertices[ face.c ];
  7092. vka = morphTargetsArrays[ vk ];
  7093. vka[ offset_morphTarget ] = v1.x;
  7094. vka[ offset_morphTarget + 1 ] = v1.y;
  7095. vka[ offset_morphTarget + 2 ] = v1.z;
  7096. vka[ offset_morphTarget + 3 ] = v2.x;
  7097. vka[ offset_morphTarget + 4 ] = v2.y;
  7098. vka[ offset_morphTarget + 5 ] = v2.z;
  7099. vka[ offset_morphTarget + 6 ] = v3.x;
  7100. vka[ offset_morphTarget + 7 ] = v3.y;
  7101. vka[ offset_morphTarget + 8 ] = v3.z;
  7102. // morph normals
  7103. if ( material.morphNormals ) {
  7104. if ( needsSmoothNormals ) {
  7105. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  7106. n1 = faceVertexNormals.a;
  7107. n2 = faceVertexNormals.b;
  7108. n3 = faceVertexNormals.c;
  7109. } else {
  7110. n1 = morphNormals[ vk ].faceNormals[ chf ];
  7111. n2 = n1;
  7112. n3 = n1;
  7113. }
  7114. nka = morphNormalsArrays[ vk ];
  7115. nka[ offset_morphTarget ] = n1.x;
  7116. nka[ offset_morphTarget + 1 ] = n1.y;
  7117. nka[ offset_morphTarget + 2 ] = n1.z;
  7118. nka[ offset_morphTarget + 3 ] = n2.x;
  7119. nka[ offset_morphTarget + 4 ] = n2.y;
  7120. nka[ offset_morphTarget + 5 ] = n2.z;
  7121. nka[ offset_morphTarget + 6 ] = n3.x;
  7122. nka[ offset_morphTarget + 7 ] = n3.y;
  7123. nka[ offset_morphTarget + 8 ] = n3.z;
  7124. }
  7125. //
  7126. offset_morphTarget += 9;
  7127. }
  7128. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7129. chf = chunk_faces4[ f ];
  7130. face = obj_faces[ chf ];
  7131. // morph positions
  7132. v1 = morphTargets[ vk ].vertices[ face.a ];
  7133. v2 = morphTargets[ vk ].vertices[ face.b ];
  7134. v3 = morphTargets[ vk ].vertices[ face.c ];
  7135. v4 = morphTargets[ vk ].vertices[ face.d ];
  7136. vka = morphTargetsArrays[ vk ];
  7137. vka[ offset_morphTarget ] = v1.x;
  7138. vka[ offset_morphTarget + 1 ] = v1.y;
  7139. vka[ offset_morphTarget + 2 ] = v1.z;
  7140. vka[ offset_morphTarget + 3 ] = v2.x;
  7141. vka[ offset_morphTarget + 4 ] = v2.y;
  7142. vka[ offset_morphTarget + 5 ] = v2.z;
  7143. vka[ offset_morphTarget + 6 ] = v3.x;
  7144. vka[ offset_morphTarget + 7 ] = v3.y;
  7145. vka[ offset_morphTarget + 8 ] = v3.z;
  7146. vka[ offset_morphTarget + 9 ] = v4.x;
  7147. vka[ offset_morphTarget + 10 ] = v4.y;
  7148. vka[ offset_morphTarget + 11 ] = v4.z;
  7149. // morph normals
  7150. if ( material.morphNormals ) {
  7151. if ( needsSmoothNormals ) {
  7152. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  7153. n1 = faceVertexNormals.a;
  7154. n2 = faceVertexNormals.b;
  7155. n3 = faceVertexNormals.c;
  7156. n4 = faceVertexNormals.d;
  7157. } else {
  7158. n1 = morphNormals[ vk ].faceNormals[ chf ];
  7159. n2 = n1;
  7160. n3 = n1;
  7161. n4 = n1;
  7162. }
  7163. nka = morphNormalsArrays[ vk ];
  7164. nka[ offset_morphTarget ] = n1.x;
  7165. nka[ offset_morphTarget + 1 ] = n1.y;
  7166. nka[ offset_morphTarget + 2 ] = n1.z;
  7167. nka[ offset_morphTarget + 3 ] = n2.x;
  7168. nka[ offset_morphTarget + 4 ] = n2.y;
  7169. nka[ offset_morphTarget + 5 ] = n2.z;
  7170. nka[ offset_morphTarget + 6 ] = n3.x;
  7171. nka[ offset_morphTarget + 7 ] = n3.y;
  7172. nka[ offset_morphTarget + 8 ] = n3.z;
  7173. nka[ offset_morphTarget + 9 ] = n4.x;
  7174. nka[ offset_morphTarget + 10 ] = n4.y;
  7175. nka[ offset_morphTarget + 11 ] = n4.z;
  7176. }
  7177. //
  7178. offset_morphTarget += 12;
  7179. }
  7180. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  7181. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  7182. if ( material.morphNormals ) {
  7183. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  7184. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  7185. }
  7186. }
  7187. }
  7188. if ( obj_skinWeights.length ) {
  7189. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7190. face = obj_faces[ chunk_faces3[ f ] ];
  7191. // weights
  7192. sw1 = obj_skinWeights[ face.a ];
  7193. sw2 = obj_skinWeights[ face.b ];
  7194. sw3 = obj_skinWeights[ face.c ];
  7195. skinWeightArray[ offset_skin ] = sw1.x;
  7196. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  7197. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  7198. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  7199. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  7200. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  7201. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  7202. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  7203. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  7204. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  7205. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  7206. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  7207. // indices
  7208. si1 = obj_skinIndices[ face.a ];
  7209. si2 = obj_skinIndices[ face.b ];
  7210. si3 = obj_skinIndices[ face.c ];
  7211. skinIndexArray[ offset_skin ] = si1.x;
  7212. skinIndexArray[ offset_skin + 1 ] = si1.y;
  7213. skinIndexArray[ offset_skin + 2 ] = si1.z;
  7214. skinIndexArray[ offset_skin + 3 ] = si1.w;
  7215. skinIndexArray[ offset_skin + 4 ] = si2.x;
  7216. skinIndexArray[ offset_skin + 5 ] = si2.y;
  7217. skinIndexArray[ offset_skin + 6 ] = si2.z;
  7218. skinIndexArray[ offset_skin + 7 ] = si2.w;
  7219. skinIndexArray[ offset_skin + 8 ] = si3.x;
  7220. skinIndexArray[ offset_skin + 9 ] = si3.y;
  7221. skinIndexArray[ offset_skin + 10 ] = si3.z;
  7222. skinIndexArray[ offset_skin + 11 ] = si3.w;
  7223. // vertices A
  7224. sa1 = obj_skinVerticesA[ face.a ];
  7225. sa2 = obj_skinVerticesA[ face.b ];
  7226. sa3 = obj_skinVerticesA[ face.c ];
  7227. skinVertexAArray[ offset_skin ] = sa1.x;
  7228. skinVertexAArray[ offset_skin + 1 ] = sa1.y;
  7229. skinVertexAArray[ offset_skin + 2 ] = sa1.z;
  7230. skinVertexAArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7231. skinVertexAArray[ offset_skin + 4 ] = sa2.x;
  7232. skinVertexAArray[ offset_skin + 5 ] = sa2.y;
  7233. skinVertexAArray[ offset_skin + 6 ] = sa2.z;
  7234. skinVertexAArray[ offset_skin + 7 ] = 1;
  7235. skinVertexAArray[ offset_skin + 8 ] = sa3.x;
  7236. skinVertexAArray[ offset_skin + 9 ] = sa3.y;
  7237. skinVertexAArray[ offset_skin + 10 ] = sa3.z;
  7238. skinVertexAArray[ offset_skin + 11 ] = 1;
  7239. // vertices B
  7240. sb1 = obj_skinVerticesB[ face.a ];
  7241. sb2 = obj_skinVerticesB[ face.b ];
  7242. sb3 = obj_skinVerticesB[ face.c ];
  7243. skinVertexBArray[ offset_skin ] = sb1.x;
  7244. skinVertexBArray[ offset_skin + 1 ] = sb1.y;
  7245. skinVertexBArray[ offset_skin + 2 ] = sb1.z;
  7246. skinVertexBArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7247. skinVertexBArray[ offset_skin + 4 ] = sb2.x;
  7248. skinVertexBArray[ offset_skin + 5 ] = sb2.y;
  7249. skinVertexBArray[ offset_skin + 6 ] = sb2.z;
  7250. skinVertexBArray[ offset_skin + 7 ] = 1;
  7251. skinVertexBArray[ offset_skin + 8 ] = sb3.x;
  7252. skinVertexBArray[ offset_skin + 9 ] = sb3.y;
  7253. skinVertexBArray[ offset_skin + 10 ] = sb3.z;
  7254. skinVertexBArray[ offset_skin + 11 ] = 1;
  7255. offset_skin += 12;
  7256. }
  7257. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7258. face = obj_faces[ chunk_faces4[ f ] ];
  7259. // weights
  7260. sw1 = obj_skinWeights[ face.a ];
  7261. sw2 = obj_skinWeights[ face.b ];
  7262. sw3 = obj_skinWeights[ face.c ];
  7263. sw4 = obj_skinWeights[ face.d ];
  7264. skinWeightArray[ offset_skin ] = sw1.x;
  7265. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  7266. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  7267. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  7268. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  7269. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  7270. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  7271. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  7272. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  7273. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  7274. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  7275. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  7276. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  7277. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  7278. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  7279. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  7280. // indices
  7281. si1 = obj_skinIndices[ face.a ];
  7282. si2 = obj_skinIndices[ face.b ];
  7283. si3 = obj_skinIndices[ face.c ];
  7284. si4 = obj_skinIndices[ face.d ];
  7285. skinIndexArray[ offset_skin ] = si1.x;
  7286. skinIndexArray[ offset_skin + 1 ] = si1.y;
  7287. skinIndexArray[ offset_skin + 2 ] = si1.z;
  7288. skinIndexArray[ offset_skin + 3 ] = si1.w;
  7289. skinIndexArray[ offset_skin + 4 ] = si2.x;
  7290. skinIndexArray[ offset_skin + 5 ] = si2.y;
  7291. skinIndexArray[ offset_skin + 6 ] = si2.z;
  7292. skinIndexArray[ offset_skin + 7 ] = si2.w;
  7293. skinIndexArray[ offset_skin + 8 ] = si3.x;
  7294. skinIndexArray[ offset_skin + 9 ] = si3.y;
  7295. skinIndexArray[ offset_skin + 10 ] = si3.z;
  7296. skinIndexArray[ offset_skin + 11 ] = si3.w;
  7297. skinIndexArray[ offset_skin + 12 ] = si4.x;
  7298. skinIndexArray[ offset_skin + 13 ] = si4.y;
  7299. skinIndexArray[ offset_skin + 14 ] = si4.z;
  7300. skinIndexArray[ offset_skin + 15 ] = si4.w;
  7301. // vertices A
  7302. sa1 = obj_skinVerticesA[ face.a ];
  7303. sa2 = obj_skinVerticesA[ face.b ];
  7304. sa3 = obj_skinVerticesA[ face.c ];
  7305. sa4 = obj_skinVerticesA[ face.d ];
  7306. skinVertexAArray[ offset_skin ] = sa1.x;
  7307. skinVertexAArray[ offset_skin + 1 ] = sa1.y;
  7308. skinVertexAArray[ offset_skin + 2 ] = sa1.z;
  7309. skinVertexAArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7310. skinVertexAArray[ offset_skin + 4 ] = sa2.x;
  7311. skinVertexAArray[ offset_skin + 5 ] = sa2.y;
  7312. skinVertexAArray[ offset_skin + 6 ] = sa2.z;
  7313. skinVertexAArray[ offset_skin + 7 ] = 1;
  7314. skinVertexAArray[ offset_skin + 8 ] = sa3.x;
  7315. skinVertexAArray[ offset_skin + 9 ] = sa3.y;
  7316. skinVertexAArray[ offset_skin + 10 ] = sa3.z;
  7317. skinVertexAArray[ offset_skin + 11 ] = 1;
  7318. skinVertexAArray[ offset_skin + 12 ] = sa4.x;
  7319. skinVertexAArray[ offset_skin + 13 ] = sa4.y;
  7320. skinVertexAArray[ offset_skin + 14 ] = sa4.z;
  7321. skinVertexAArray[ offset_skin + 15 ] = 1;
  7322. // vertices B
  7323. sb1 = obj_skinVerticesB[ face.a ];
  7324. sb2 = obj_skinVerticesB[ face.b ];
  7325. sb3 = obj_skinVerticesB[ face.c ];
  7326. sb4 = obj_skinVerticesB[ face.d ];
  7327. skinVertexBArray[ offset_skin ] = sb1.x;
  7328. skinVertexBArray[ offset_skin + 1 ] = sb1.y;
  7329. skinVertexBArray[ offset_skin + 2 ] = sb1.z;
  7330. skinVertexBArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7331. skinVertexBArray[ offset_skin + 4 ] = sb2.x;
  7332. skinVertexBArray[ offset_skin + 5 ] = sb2.y;
  7333. skinVertexBArray[ offset_skin + 6 ] = sb2.z;
  7334. skinVertexBArray[ offset_skin + 7 ] = 1;
  7335. skinVertexBArray[ offset_skin + 8 ] = sb3.x;
  7336. skinVertexBArray[ offset_skin + 9 ] = sb3.y;
  7337. skinVertexBArray[ offset_skin + 10 ] = sb3.z;
  7338. skinVertexBArray[ offset_skin + 11 ] = 1;
  7339. skinVertexBArray[ offset_skin + 12 ] = sb4.x;
  7340. skinVertexBArray[ offset_skin + 13 ] = sb4.y;
  7341. skinVertexBArray[ offset_skin + 14 ] = sb4.z;
  7342. skinVertexBArray[ offset_skin + 15 ] = 1;
  7343. offset_skin += 16;
  7344. }
  7345. if ( offset_skin > 0 ) {
  7346. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexABuffer );
  7347. _gl.bufferData( _gl.ARRAY_BUFFER, skinVertexAArray, hint );
  7348. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexBBuffer );
  7349. _gl.bufferData( _gl.ARRAY_BUFFER, skinVertexBArray, hint );
  7350. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  7351. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  7352. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  7353. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  7354. }
  7355. }
  7356. if ( dirtyColors && vertexColorType ) {
  7357. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7358. face = obj_faces[ chunk_faces3[ f ] ];
  7359. vertexColors = face.vertexColors;
  7360. faceColor = face.color;
  7361. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  7362. c1 = vertexColors[ 0 ];
  7363. c2 = vertexColors[ 1 ];
  7364. c3 = vertexColors[ 2 ];
  7365. } else {
  7366. c1 = faceColor;
  7367. c2 = faceColor;
  7368. c3 = faceColor;
  7369. }
  7370. colorArray[ offset_color ] = c1.r;
  7371. colorArray[ offset_color + 1 ] = c1.g;
  7372. colorArray[ offset_color + 2 ] = c1.b;
  7373. colorArray[ offset_color + 3 ] = c2.r;
  7374. colorArray[ offset_color + 4 ] = c2.g;
  7375. colorArray[ offset_color + 5 ] = c2.b;
  7376. colorArray[ offset_color + 6 ] = c3.r;
  7377. colorArray[ offset_color + 7 ] = c3.g;
  7378. colorArray[ offset_color + 8 ] = c3.b;
  7379. offset_color += 9;
  7380. }
  7381. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7382. face = obj_faces[ chunk_faces4[ f ] ];
  7383. vertexColors = face.vertexColors;
  7384. faceColor = face.color;
  7385. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  7386. c1 = vertexColors[ 0 ];
  7387. c2 = vertexColors[ 1 ];
  7388. c3 = vertexColors[ 2 ];
  7389. c4 = vertexColors[ 3 ];
  7390. } else {
  7391. c1 = faceColor;
  7392. c2 = faceColor;
  7393. c3 = faceColor;
  7394. c4 = faceColor;
  7395. }
  7396. colorArray[ offset_color ] = c1.r;
  7397. colorArray[ offset_color + 1 ] = c1.g;
  7398. colorArray[ offset_color + 2 ] = c1.b;
  7399. colorArray[ offset_color + 3 ] = c2.r;
  7400. colorArray[ offset_color + 4 ] = c2.g;
  7401. colorArray[ offset_color + 5 ] = c2.b;
  7402. colorArray[ offset_color + 6 ] = c3.r;
  7403. colorArray[ offset_color + 7 ] = c3.g;
  7404. colorArray[ offset_color + 8 ] = c3.b;
  7405. colorArray[ offset_color + 9 ] = c4.r;
  7406. colorArray[ offset_color + 10 ] = c4.g;
  7407. colorArray[ offset_color + 11 ] = c4.b;
  7408. offset_color += 12;
  7409. }
  7410. if ( offset_color > 0 ) {
  7411. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  7412. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  7413. }
  7414. }
  7415. if ( dirtyTangents && geometry.hasTangents ) {
  7416. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7417. face = obj_faces[ chunk_faces3[ f ] ];
  7418. vertexTangents = face.vertexTangents;
  7419. t1 = vertexTangents[ 0 ];
  7420. t2 = vertexTangents[ 1 ];
  7421. t3 = vertexTangents[ 2 ];
  7422. tangentArray[ offset_tangent ] = t1.x;
  7423. tangentArray[ offset_tangent + 1 ] = t1.y;
  7424. tangentArray[ offset_tangent + 2 ] = t1.z;
  7425. tangentArray[ offset_tangent + 3 ] = t1.w;
  7426. tangentArray[ offset_tangent + 4 ] = t2.x;
  7427. tangentArray[ offset_tangent + 5 ] = t2.y;
  7428. tangentArray[ offset_tangent + 6 ] = t2.z;
  7429. tangentArray[ offset_tangent + 7 ] = t2.w;
  7430. tangentArray[ offset_tangent + 8 ] = t3.x;
  7431. tangentArray[ offset_tangent + 9 ] = t3.y;
  7432. tangentArray[ offset_tangent + 10 ] = t3.z;
  7433. tangentArray[ offset_tangent + 11 ] = t3.w;
  7434. offset_tangent += 12;
  7435. }
  7436. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7437. face = obj_faces[ chunk_faces4[ f ] ];
  7438. vertexTangents = face.vertexTangents;
  7439. t1 = vertexTangents[ 0 ];
  7440. t2 = vertexTangents[ 1 ];
  7441. t3 = vertexTangents[ 2 ];
  7442. t4 = vertexTangents[ 3 ];
  7443. tangentArray[ offset_tangent ] = t1.x;
  7444. tangentArray[ offset_tangent + 1 ] = t1.y;
  7445. tangentArray[ offset_tangent + 2 ] = t1.z;
  7446. tangentArray[ offset_tangent + 3 ] = t1.w;
  7447. tangentArray[ offset_tangent + 4 ] = t2.x;
  7448. tangentArray[ offset_tangent + 5 ] = t2.y;
  7449. tangentArray[ offset_tangent + 6 ] = t2.z;
  7450. tangentArray[ offset_tangent + 7 ] = t2.w;
  7451. tangentArray[ offset_tangent + 8 ] = t3.x;
  7452. tangentArray[ offset_tangent + 9 ] = t3.y;
  7453. tangentArray[ offset_tangent + 10 ] = t3.z;
  7454. tangentArray[ offset_tangent + 11 ] = t3.w;
  7455. tangentArray[ offset_tangent + 12 ] = t4.x;
  7456. tangentArray[ offset_tangent + 13 ] = t4.y;
  7457. tangentArray[ offset_tangent + 14 ] = t4.z;
  7458. tangentArray[ offset_tangent + 15 ] = t4.w;
  7459. offset_tangent += 16;
  7460. }
  7461. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  7462. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  7463. }
  7464. if ( dirtyNormals && normalType ) {
  7465. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7466. face = obj_faces[ chunk_faces3[ f ] ];
  7467. vertexNormals = face.vertexNormals;
  7468. faceNormal = face.normal;
  7469. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  7470. for ( i = 0; i < 3; i ++ ) {
  7471. vn = vertexNormals[ i ];
  7472. normalArray[ offset_normal ] = vn.x;
  7473. normalArray[ offset_normal + 1 ] = vn.y;
  7474. normalArray[ offset_normal + 2 ] = vn.z;
  7475. offset_normal += 3;
  7476. }
  7477. } else {
  7478. for ( i = 0; i < 3; i ++ ) {
  7479. normalArray[ offset_normal ] = faceNormal.x;
  7480. normalArray[ offset_normal + 1 ] = faceNormal.y;
  7481. normalArray[ offset_normal + 2 ] = faceNormal.z;
  7482. offset_normal += 3;
  7483. }
  7484. }
  7485. }
  7486. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7487. face = obj_faces[ chunk_faces4[ f ] ];
  7488. vertexNormals = face.vertexNormals;
  7489. faceNormal = face.normal;
  7490. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  7491. for ( i = 0; i < 4; i ++ ) {
  7492. vn = vertexNormals[ i ];
  7493. normalArray[ offset_normal ] = vn.x;
  7494. normalArray[ offset_normal + 1 ] = vn.y;
  7495. normalArray[ offset_normal + 2 ] = vn.z;
  7496. offset_normal += 3;
  7497. }
  7498. } else {
  7499. for ( i = 0; i < 4; i ++ ) {
  7500. normalArray[ offset_normal ] = faceNormal.x;
  7501. normalArray[ offset_normal + 1 ] = faceNormal.y;
  7502. normalArray[ offset_normal + 2 ] = faceNormal.z;
  7503. offset_normal += 3;
  7504. }
  7505. }
  7506. }
  7507. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  7508. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  7509. }
  7510. if ( dirtyUvs && obj_uvs && uvType ) {
  7511. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7512. fi = chunk_faces3[ f ];
  7513. face = obj_faces[ fi ];
  7514. uv = obj_uvs[ fi ];
  7515. if ( uv === undefined ) continue;
  7516. for ( i = 0; i < 3; i ++ ) {
  7517. uvi = uv[ i ];
  7518. uvArray[ offset_uv ] = uvi.u;
  7519. uvArray[ offset_uv + 1 ] = uvi.v;
  7520. offset_uv += 2;
  7521. }
  7522. }
  7523. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7524. fi = chunk_faces4[ f ];
  7525. face = obj_faces[ fi ];
  7526. uv = obj_uvs[ fi ];
  7527. if ( uv === undefined ) continue;
  7528. for ( i = 0; i < 4; i ++ ) {
  7529. uvi = uv[ i ];
  7530. uvArray[ offset_uv ] = uvi.u;
  7531. uvArray[ offset_uv + 1 ] = uvi.v;
  7532. offset_uv += 2;
  7533. }
  7534. }
  7535. if ( offset_uv > 0 ) {
  7536. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  7537. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  7538. }
  7539. }
  7540. if ( dirtyUvs && obj_uvs2 && uvType ) {
  7541. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7542. fi = chunk_faces3[ f ];
  7543. face = obj_faces[ fi ];
  7544. uv2 = obj_uvs2[ fi ];
  7545. if ( uv2 === undefined ) continue;
  7546. for ( i = 0; i < 3; i ++ ) {
  7547. uv2i = uv2[ i ];
  7548. uv2Array[ offset_uv2 ] = uv2i.u;
  7549. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  7550. offset_uv2 += 2;
  7551. }
  7552. }
  7553. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7554. fi = chunk_faces4[ f ];
  7555. face = obj_faces[ fi ];
  7556. uv2 = obj_uvs2[ fi ];
  7557. if ( uv2 === undefined ) continue;
  7558. for ( i = 0; i < 4; i ++ ) {
  7559. uv2i = uv2[ i ];
  7560. uv2Array[ offset_uv2 ] = uv2i.u;
  7561. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  7562. offset_uv2 += 2;
  7563. }
  7564. }
  7565. if ( offset_uv2 > 0 ) {
  7566. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  7567. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  7568. }
  7569. }
  7570. if ( dirtyElements ) {
  7571. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7572. face = obj_faces[ chunk_faces3[ f ] ];
  7573. faceArray[ offset_face ] = vertexIndex;
  7574. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  7575. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  7576. offset_face += 3;
  7577. lineArray[ offset_line ] = vertexIndex;
  7578. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  7579. lineArray[ offset_line + 2 ] = vertexIndex;
  7580. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  7581. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  7582. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  7583. offset_line += 6;
  7584. vertexIndex += 3;
  7585. }
  7586. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7587. face = obj_faces[ chunk_faces4[ f ] ];
  7588. faceArray[ offset_face ] = vertexIndex;
  7589. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  7590. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  7591. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  7592. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  7593. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  7594. offset_face += 6;
  7595. lineArray[ offset_line ] = vertexIndex;
  7596. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  7597. lineArray[ offset_line + 2 ] = vertexIndex;
  7598. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  7599. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  7600. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  7601. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  7602. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  7603. offset_line += 8;
  7604. vertexIndex += 4;
  7605. }
  7606. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  7607. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  7608. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  7609. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  7610. }
  7611. if ( customAttributes ) {
  7612. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  7613. customAttribute = customAttributes[ i ];
  7614. if ( ! customAttribute.__original.needsUpdate ) continue;
  7615. offset_custom = 0;
  7616. offset_customSrc = 0;
  7617. if ( customAttribute.size === 1 ) {
  7618. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7619. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7620. face = obj_faces[ chunk_faces3[ f ] ];
  7621. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  7622. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  7623. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  7624. offset_custom += 3;
  7625. }
  7626. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7627. face = obj_faces[ chunk_faces4[ f ] ];
  7628. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  7629. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  7630. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  7631. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  7632. offset_custom += 4;
  7633. }
  7634. } else if ( customAttribute.boundTo === "faces" ) {
  7635. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7636. value = customAttribute.value[ chunk_faces3[ f ] ];
  7637. customAttribute.array[ offset_custom ] = value;
  7638. customAttribute.array[ offset_custom + 1 ] = value;
  7639. customAttribute.array[ offset_custom + 2 ] = value;
  7640. offset_custom += 3;
  7641. }
  7642. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7643. value = customAttribute.value[ chunk_faces4[ f ] ];
  7644. customAttribute.array[ offset_custom ] = value;
  7645. customAttribute.array[ offset_custom + 1 ] = value;
  7646. customAttribute.array[ offset_custom + 2 ] = value;
  7647. customAttribute.array[ offset_custom + 3 ] = value;
  7648. offset_custom += 4;
  7649. }
  7650. }
  7651. } else if ( customAttribute.size === 2 ) {
  7652. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7653. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7654. face = obj_faces[ chunk_faces3[ f ] ];
  7655. v1 = customAttribute.value[ face.a ];
  7656. v2 = customAttribute.value[ face.b ];
  7657. v3 = customAttribute.value[ face.c ];
  7658. customAttribute.array[ offset_custom ] = v1.x;
  7659. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7660. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7661. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7662. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7663. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7664. offset_custom += 6;
  7665. }
  7666. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7667. face = obj_faces[ chunk_faces4[ f ] ];
  7668. v1 = customAttribute.value[ face.a ];
  7669. v2 = customAttribute.value[ face.b ];
  7670. v3 = customAttribute.value[ face.c ];
  7671. v4 = customAttribute.value[ face.d ];
  7672. customAttribute.array[ offset_custom ] = v1.x;
  7673. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7674. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7675. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7676. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7677. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7678. customAttribute.array[ offset_custom + 6 ] = v4.x;
  7679. customAttribute.array[ offset_custom + 7 ] = v4.y;
  7680. offset_custom += 8;
  7681. }
  7682. } else if ( customAttribute.boundTo === "faces" ) {
  7683. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7684. value = customAttribute.value[ chunk_faces3[ f ] ];
  7685. v1 = value;
  7686. v2 = value;
  7687. v3 = value;
  7688. customAttribute.array[ offset_custom ] = v1.x;
  7689. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7690. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7691. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7692. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7693. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7694. offset_custom += 6;
  7695. }
  7696. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7697. value = customAttribute.value[ chunk_faces4[ f ] ];
  7698. v1 = value;
  7699. v2 = value;
  7700. v3 = value;
  7701. v4 = value;
  7702. customAttribute.array[ offset_custom ] = v1.x;
  7703. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7704. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7705. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7706. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7707. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7708. customAttribute.array[ offset_custom + 6 ] = v4.x;
  7709. customAttribute.array[ offset_custom + 7 ] = v4.y;
  7710. offset_custom += 8;
  7711. }
  7712. }
  7713. } else if ( customAttribute.size === 3 ) {
  7714. var pp;
  7715. if ( customAttribute.type === "c" ) {
  7716. pp = [ "r", "g", "b" ];
  7717. } else {
  7718. pp = [ "x", "y", "z" ];
  7719. }
  7720. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7721. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7722. face = obj_faces[ chunk_faces3[ f ] ];
  7723. v1 = customAttribute.value[ face.a ];
  7724. v2 = customAttribute.value[ face.b ];
  7725. v3 = customAttribute.value[ face.c ];
  7726. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7727. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7728. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7729. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7730. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7731. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7732. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7733. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7734. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7735. offset_custom += 9;
  7736. }
  7737. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7738. face = obj_faces[ chunk_faces4[ f ] ];
  7739. v1 = customAttribute.value[ face.a ];
  7740. v2 = customAttribute.value[ face.b ];
  7741. v3 = customAttribute.value[ face.c ];
  7742. v4 = customAttribute.value[ face.d ];
  7743. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7744. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7745. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7746. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7747. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7748. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7749. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7750. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7751. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7752. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  7753. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  7754. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  7755. offset_custom += 12;
  7756. }
  7757. } else if ( customAttribute.boundTo === "faces" ) {
  7758. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7759. value = customAttribute.value[ chunk_faces3[ f ] ];
  7760. v1 = value;
  7761. v2 = value;
  7762. v3 = value;
  7763. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7764. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7765. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7766. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7767. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7768. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7769. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7770. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7771. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7772. offset_custom += 9;
  7773. }
  7774. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7775. value = customAttribute.value[ chunk_faces4[ f ] ];
  7776. v1 = value;
  7777. v2 = value;
  7778. v3 = value;
  7779. v4 = value;
  7780. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7781. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7782. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7783. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7784. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7785. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7786. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7787. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7788. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7789. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  7790. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  7791. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  7792. offset_custom += 12;
  7793. }
  7794. }
  7795. } else if ( customAttribute.size === 4 ) {
  7796. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7797. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7798. face = obj_faces[ chunk_faces3[ f ] ];
  7799. v1 = customAttribute.value[ face.a ];
  7800. v2 = customAttribute.value[ face.b ];
  7801. v3 = customAttribute.value[ face.c ];
  7802. customAttribute.array[ offset_custom ] = v1.x;
  7803. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7804. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7805. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7806. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7807. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7808. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7809. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7810. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7811. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7812. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7813. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7814. offset_custom += 12;
  7815. }
  7816. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7817. face = obj_faces[ chunk_faces4[ f ] ];
  7818. v1 = customAttribute.value[ face.a ];
  7819. v2 = customAttribute.value[ face.b ];
  7820. v3 = customAttribute.value[ face.c ];
  7821. v4 = customAttribute.value[ face.d ];
  7822. customAttribute.array[ offset_custom ] = v1.x;
  7823. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7824. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7825. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7826. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7827. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7828. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7829. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7830. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7831. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7832. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7833. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7834. customAttribute.array[ offset_custom + 12 ] = v4.x;
  7835. customAttribute.array[ offset_custom + 13 ] = v4.y;
  7836. customAttribute.array[ offset_custom + 14 ] = v4.z;
  7837. customAttribute.array[ offset_custom + 15 ] = v4.w;
  7838. offset_custom += 16;
  7839. }
  7840. } else if ( customAttribute.boundTo === "faces" ) {
  7841. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7842. value = customAttribute.value[ chunk_faces3[ f ] ];
  7843. v1 = value;
  7844. v2 = value;
  7845. v3 = value;
  7846. customAttribute.array[ offset_custom ] = v1.x;
  7847. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7848. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7849. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7850. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7851. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7852. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7853. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7854. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7855. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7856. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7857. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7858. offset_custom += 12;
  7859. }
  7860. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7861. value = customAttribute.value[ chunk_faces4[ f ] ];
  7862. v1 = value;
  7863. v2 = value;
  7864. v3 = value;
  7865. v4 = value;
  7866. customAttribute.array[ offset_custom ] = v1.x;
  7867. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7868. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7869. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7870. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7871. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7872. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7873. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7874. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7875. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7876. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7877. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7878. customAttribute.array[ offset_custom + 12 ] = v4.x;
  7879. customAttribute.array[ offset_custom + 13 ] = v4.y;
  7880. customAttribute.array[ offset_custom + 14 ] = v4.z;
  7881. customAttribute.array[ offset_custom + 15 ] = v4.w;
  7882. offset_custom += 16;
  7883. }
  7884. }
  7885. }
  7886. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  7887. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  7888. }
  7889. }
  7890. if ( dispose ) {
  7891. delete geometryGroup.__inittedArrays;
  7892. delete geometryGroup.__colorArray;
  7893. delete geometryGroup.__normalArray;
  7894. delete geometryGroup.__tangentArray;
  7895. delete geometryGroup.__uvArray;
  7896. delete geometryGroup.__uv2Array;
  7897. delete geometryGroup.__faceArray;
  7898. delete geometryGroup.__vertexArray;
  7899. delete geometryGroup.__lineArray;
  7900. delete geometryGroup.__skinVertexAArray;
  7901. delete geometryGroup.__skinVertexBArray;
  7902. delete geometryGroup.__skinIndexArray;
  7903. delete geometryGroup.__skinWeightArray;
  7904. }
  7905. };
  7906. // Buffer rendering
  7907. this.renderBufferImmediate = function ( object, program, shading ) {
  7908. if ( ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  7909. if ( ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  7910. if ( object.hasPos ) {
  7911. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  7912. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  7913. _gl.enableVertexAttribArray( program.attributes.position );
  7914. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  7915. }
  7916. if ( object.hasNormal ) {
  7917. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  7918. if ( shading === THREE.FlatShading ) {
  7919. var nx, ny, nz,
  7920. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  7921. normalArray,
  7922. i, il = object.count * 3;
  7923. for( i = 0; i < il; i += 9 ) {
  7924. normalArray = object.normalArray;
  7925. nax = normalArray[ i ];
  7926. nay = normalArray[ i + 1 ];
  7927. naz = normalArray[ i + 2 ];
  7928. nbx = normalArray[ i + 3 ];
  7929. nby = normalArray[ i + 4 ];
  7930. nbz = normalArray[ i + 5 ];
  7931. ncx = normalArray[ i + 6 ];
  7932. ncy = normalArray[ i + 7 ];
  7933. ncz = normalArray[ i + 8 ];
  7934. nx = ( nax + nbx + ncx ) / 3;
  7935. ny = ( nay + nby + ncy ) / 3;
  7936. nz = ( naz + nbz + ncz ) / 3;
  7937. normalArray[ i ] = nx;
  7938. normalArray[ i + 1 ] = ny;
  7939. normalArray[ i + 2 ] = nz;
  7940. normalArray[ i + 3 ] = nx;
  7941. normalArray[ i + 4 ] = ny;
  7942. normalArray[ i + 5 ] = nz;
  7943. normalArray[ i + 6 ] = nx;
  7944. normalArray[ i + 7 ] = ny;
  7945. normalArray[ i + 8 ] = nz;
  7946. }
  7947. }
  7948. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  7949. _gl.enableVertexAttribArray( program.attributes.normal );
  7950. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  7951. }
  7952. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  7953. object.count = 0;
  7954. };
  7955. this.renderBufferDirect = function ( camera, lights, fog, material, geometryGroup, object ) {
  7956. if ( material.opacity === 0 ) return;
  7957. var program, attributes, linewidth, primitives, a, attribute;
  7958. program = setProgram( camera, lights, fog, material, object );
  7959. attributes = program.attributes;
  7960. var updateBuffers = false,
  7961. wireframeBit = material.wireframe ? 1 : 0,
  7962. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  7963. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  7964. _currentGeometryGroupHash = geometryGroupHash;
  7965. updateBuffers = true;
  7966. }
  7967. // render mesh
  7968. if ( object instanceof THREE.Mesh ) {
  7969. var offsets = geometryGroup.offsets;
  7970. for ( var i = 0, il = offsets.length; i < il; ++ i ) {
  7971. if ( updateBuffers ) {
  7972. // vertices
  7973. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexPositionBuffer );
  7974. _gl.vertexAttribPointer( attributes.position, geometryGroup.vertexPositionBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 3 );
  7975. // normals
  7976. if ( attributes.normal >= 0 && geometryGroup.vertexNormalBuffer ) {
  7977. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexNormalBuffer );
  7978. _gl.vertexAttribPointer( attributes.normal, geometryGroup.vertexNormalBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 3 );
  7979. }
  7980. // uvs
  7981. if ( attributes.uv >= 0 && geometryGroup.vertexUvBuffer ) {
  7982. if ( geometryGroup.vertexUvBuffer ) {
  7983. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexUvBuffer );
  7984. _gl.vertexAttribPointer( attributes.uv, geometryGroup.vertexUvBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 2 );
  7985. _gl.enableVertexAttribArray( attributes.uv );
  7986. } else {
  7987. _gl.disableVertexAttribArray( attributes.uv );
  7988. }
  7989. }
  7990. // colors
  7991. if ( attributes.color >= 0 && geometryGroup.vertexColorBuffer ) {
  7992. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexColorBuffer );
  7993. _gl.vertexAttribPointer( attributes.color, geometryGroup.vertexColorBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 4 );
  7994. }
  7995. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.vertexIndexBuffer );
  7996. }
  7997. // render indexed triangles
  7998. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 = Uint16
  7999. _this.info.render.calls ++;
  8000. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  8001. _this.info.render.faces += offsets[ i ].count / 3;
  8002. }
  8003. }
  8004. };
  8005. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  8006. if ( material.opacity === 0 ) return;
  8007. var program, attributes, linewidth, primitives, a, attribute, i, il;
  8008. program = setProgram( camera, lights, fog, material, object );
  8009. attributes = program.attributes;
  8010. var updateBuffers = false,
  8011. wireframeBit = material.wireframe ? 1 : 0,
  8012. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  8013. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  8014. _currentGeometryGroupHash = geometryGroupHash;
  8015. updateBuffers = true;
  8016. }
  8017. // vertices
  8018. if ( !material.morphTargets && attributes.position >= 0 ) {
  8019. if ( updateBuffers ) {
  8020. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  8021. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  8022. }
  8023. } else {
  8024. if ( object.morphTargetBase ) {
  8025. setupMorphTargets( material, geometryGroup, object );
  8026. }
  8027. }
  8028. if ( updateBuffers ) {
  8029. // custom attributes
  8030. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  8031. if ( geometryGroup.__webglCustomAttributesList ) {
  8032. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  8033. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  8034. if( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  8035. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  8036. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  8037. }
  8038. }
  8039. }
  8040. // colors
  8041. if ( attributes.color >= 0 ) {
  8042. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  8043. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  8044. }
  8045. // normals
  8046. if ( attributes.normal >= 0 ) {
  8047. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  8048. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  8049. }
  8050. // tangents
  8051. if ( attributes.tangent >= 0 ) {
  8052. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  8053. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  8054. }
  8055. // uvs
  8056. if ( attributes.uv >= 0 ) {
  8057. if ( geometryGroup.__webglUVBuffer ) {
  8058. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  8059. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  8060. _gl.enableVertexAttribArray( attributes.uv );
  8061. } else {
  8062. _gl.disableVertexAttribArray( attributes.uv );
  8063. }
  8064. }
  8065. if ( attributes.uv2 >= 0 ) {
  8066. if ( geometryGroup.__webglUV2Buffer ) {
  8067. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  8068. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  8069. _gl.enableVertexAttribArray( attributes.uv2 );
  8070. } else {
  8071. _gl.disableVertexAttribArray( attributes.uv2 );
  8072. }
  8073. }
  8074. if ( material.skinning &&
  8075. attributes.skinVertexA >= 0 && attributes.skinVertexB >= 0 &&
  8076. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  8077. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexABuffer );
  8078. _gl.vertexAttribPointer( attributes.skinVertexA, 4, _gl.FLOAT, false, 0, 0 );
  8079. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexBBuffer );
  8080. _gl.vertexAttribPointer( attributes.skinVertexB, 4, _gl.FLOAT, false, 0, 0 );
  8081. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  8082. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  8083. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  8084. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  8085. }
  8086. }
  8087. // render mesh
  8088. if ( object instanceof THREE.Mesh ) {
  8089. // wireframe
  8090. if ( material.wireframe ) {
  8091. setLineWidth( material.wireframeLinewidth );
  8092. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  8093. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  8094. // triangles
  8095. } else {
  8096. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  8097. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  8098. }
  8099. _this.info.render.calls ++;
  8100. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  8101. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  8102. // render lines
  8103. } else if ( object instanceof THREE.Line ) {
  8104. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  8105. setLineWidth( material.linewidth );
  8106. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  8107. _this.info.render.calls ++;
  8108. // render particles
  8109. } else if ( object instanceof THREE.ParticleSystem ) {
  8110. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  8111. _this.info.render.calls ++;
  8112. _this.info.render.points += geometryGroup.__webglParticleCount;
  8113. // render ribbon
  8114. } else if ( object instanceof THREE.Ribbon ) {
  8115. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  8116. _this.info.render.calls ++;
  8117. }
  8118. };
  8119. function setupMorphTargets ( material, geometryGroup, object ) {
  8120. // set base
  8121. var attributes = material.program.attributes;
  8122. if ( object.morphTargetBase !== - 1 ) {
  8123. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  8124. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  8125. } else if ( attributes.position >= 0 ) {
  8126. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  8127. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  8128. }
  8129. if ( object.morphTargetForcedOrder.length ) {
  8130. // set forced order
  8131. var m = 0;
  8132. var order = object.morphTargetForcedOrder;
  8133. var influences = object.morphTargetInfluences;
  8134. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  8135. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  8136. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8137. if ( material.morphNormals ) {
  8138. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  8139. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8140. }
  8141. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  8142. m ++;
  8143. }
  8144. } else {
  8145. // find most influencing
  8146. var used = [];
  8147. var candidateInfluence = - 1;
  8148. var candidate = 0;
  8149. var influences = object.morphTargetInfluences;
  8150. var i, il = influences.length;
  8151. var m = 0;
  8152. if ( object.morphTargetBase !== - 1 ) {
  8153. used[ object.morphTargetBase ] = true;
  8154. }
  8155. while ( m < material.numSupportedMorphTargets ) {
  8156. for ( i = 0; i < il; i ++ ) {
  8157. if ( !used[ i ] && influences[ i ] > candidateInfluence ) {
  8158. candidate = i;
  8159. candidateInfluence = influences[ candidate ];
  8160. }
  8161. }
  8162. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ candidate ] );
  8163. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8164. if ( material.morphNormals ) {
  8165. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ candidate ] );
  8166. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8167. }
  8168. object.__webglMorphTargetInfluences[ m ] = candidateInfluence;
  8169. used[ candidate ] = 1;
  8170. candidateInfluence = -1;
  8171. m ++;
  8172. }
  8173. }
  8174. // load updated influences uniform
  8175. if( material.program.uniforms.morphTargetInfluences !== null ) {
  8176. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  8177. }
  8178. };
  8179. function painterSort ( a, b ) {
  8180. return b.z - a.z;
  8181. };
  8182. // Rendering
  8183. this.render = function ( scene, camera, renderTarget, forceClear ) {
  8184. var i, il,
  8185. webglObject, object,
  8186. renderList,
  8187. lights = scene.__lights,
  8188. fog = scene.fog;
  8189. _currentMaterialId = -1;
  8190. // update scene graph
  8191. if ( camera.parent === undefined ) {
  8192. console.warn( 'DEPRECATED: Camera hasn\'t been added to a Scene. Adding it...' );
  8193. scene.add( camera );
  8194. }
  8195. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  8196. // update camera matrices and frustum
  8197. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  8198. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  8199. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  8200. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  8201. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  8202. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  8203. _frustum.setFromMatrix( _projScreenMatrix );
  8204. // update WebGL objects
  8205. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  8206. // custom render plugins (pre pass)
  8207. renderPlugins( this.renderPluginsPre, scene, camera );
  8208. //
  8209. _this.info.render.calls = 0;
  8210. _this.info.render.vertices = 0;
  8211. _this.info.render.faces = 0;
  8212. _this.info.render.points = 0;
  8213. this.setRenderTarget( renderTarget );
  8214. if ( this.autoClear || forceClear ) {
  8215. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  8216. }
  8217. // set matrices for regular objects (frustum culled)
  8218. renderList = scene.__webglObjects;
  8219. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  8220. webglObject = renderList[ i ];
  8221. object = webglObject.object;
  8222. webglObject.render = false;
  8223. if ( object.visible ) {
  8224. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  8225. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8226. setupMatrices( object, camera );
  8227. unrollBufferMaterial( webglObject );
  8228. webglObject.render = true;
  8229. if ( this.sortObjects ) {
  8230. if ( object.renderDepth ) {
  8231. webglObject.z = object.renderDepth;
  8232. } else {
  8233. _vector3.copy( object.matrixWorld.getPosition() );
  8234. _projScreenMatrix.multiplyVector3( _vector3 );
  8235. webglObject.z = _vector3.z;
  8236. }
  8237. }
  8238. }
  8239. }
  8240. }
  8241. if ( this.sortObjects ) {
  8242. renderList.sort( painterSort );
  8243. }
  8244. // set matrices for immediate objects
  8245. renderList = scene.__webglObjectsImmediate;
  8246. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  8247. webglObject = renderList[ i ];
  8248. object = webglObject.object;
  8249. if ( object.visible ) {
  8250. if( object.matrixAutoUpdate ) {
  8251. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8252. }
  8253. setupMatrices( object, camera );
  8254. unrollImmediateBufferMaterial( webglObject );
  8255. }
  8256. }
  8257. if ( scene.overrideMaterial ) {
  8258. var material = scene.overrideMaterial;
  8259. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8260. this.setDepthTest( material.depthTest );
  8261. this.setDepthWrite( material.depthWrite );
  8262. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  8263. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  8264. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  8265. } else {
  8266. // opaque pass (front-to-back order)
  8267. this.setBlending( THREE.NormalBlending );
  8268. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  8269. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  8270. // transparent pass (back-to-front order)
  8271. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  8272. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  8273. }
  8274. // custom render plugins (post pass)
  8275. renderPlugins( this.renderPluginsPost, scene, camera );
  8276. // Generate mipmap if we're using any kind of mipmap filtering
  8277. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  8278. updateRenderTargetMipmap( renderTarget );
  8279. }
  8280. // Ensure depth buffer writing is enabled so it can be cleared on next render
  8281. this.setDepthTest( true );
  8282. this.setDepthWrite( true );
  8283. // _gl.finish();
  8284. };
  8285. function renderPlugins( plugins, scene, camera ) {
  8286. if ( ! plugins.length ) return;
  8287. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  8288. _currentProgram = null;
  8289. _currentCamera = null;
  8290. _oldBlending = -1;
  8291. _oldDepthTest = -1;
  8292. _oldDepthWrite = -1;
  8293. _currentGeometryGroupHash = -1;
  8294. _currentMaterialId = -1;
  8295. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  8296. _currentProgram = null;
  8297. _currentCamera = null;
  8298. _oldBlending = -1;
  8299. _oldDepthTest = -1;
  8300. _oldDepthWrite = -1;
  8301. _currentGeometryGroupHash = -1;
  8302. _currentMaterialId = -1;
  8303. }
  8304. };
  8305. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  8306. var webglObject, object, buffer, material, start, end, delta;
  8307. if ( reverse ) {
  8308. start = renderList.length - 1;
  8309. end = -1;
  8310. delta = -1;
  8311. } else {
  8312. start = 0;
  8313. end = renderList.length;
  8314. delta = 1;
  8315. }
  8316. for ( var i = start; i !== end; i += delta ) {
  8317. webglObject = renderList[ i ];
  8318. if ( webglObject.render ) {
  8319. object = webglObject.object;
  8320. buffer = webglObject.buffer;
  8321. if ( overrideMaterial ) {
  8322. material = overrideMaterial;
  8323. } else {
  8324. material = webglObject[ materialType ];
  8325. if ( ! material ) continue;
  8326. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8327. _this.setDepthTest( material.depthTest );
  8328. _this.setDepthWrite( material.depthWrite );
  8329. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  8330. }
  8331. _this.setObjectFaces( object );
  8332. if ( buffer instanceof THREE.BufferGeometry ) {
  8333. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  8334. } else {
  8335. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  8336. }
  8337. }
  8338. }
  8339. };
  8340. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  8341. var webglObject, object, material, program;
  8342. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  8343. webglObject = renderList[ i ];
  8344. object = webglObject.object;
  8345. if ( object.visible ) {
  8346. if ( overrideMaterial ) {
  8347. material = overrideMaterial;
  8348. } else {
  8349. material = webglObject[ materialType ];
  8350. if ( ! material ) continue;
  8351. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8352. _this.setDepthTest( material.depthTest );
  8353. _this.setDepthWrite( material.depthWrite );
  8354. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  8355. }
  8356. _this.renderImmediateObject( camera, lights, fog, material, object );
  8357. }
  8358. }
  8359. };
  8360. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  8361. var program = setProgram( camera, lights, fog, material, object );
  8362. _currentGeometryGroupHash = -1;
  8363. _this.setObjectFaces( object );
  8364. if ( object.immediateRenderCallback ) {
  8365. object.immediateRenderCallback( program, _gl, _frustum );
  8366. } else {
  8367. object.render( function( object ) { _this.renderBufferImmediate( object, program, material.shading ); } );
  8368. }
  8369. };
  8370. function unrollImmediateBufferMaterial ( globject ) {
  8371. var object = globject.object,
  8372. material = object.material;
  8373. if ( material.transparent ) {
  8374. globject.transparent = material;
  8375. globject.opaque = null;
  8376. } else {
  8377. globject.opaque = material;
  8378. globject.transparent = null;
  8379. }
  8380. };
  8381. function unrollBufferMaterial ( globject ) {
  8382. var object = globject.object,
  8383. buffer = globject.buffer,
  8384. material, materialIndex, meshMaterial;
  8385. meshMaterial = object.material;
  8386. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  8387. materialIndex = buffer.materialIndex;
  8388. if ( materialIndex >= 0 ) {
  8389. material = object.geometry.materials[ materialIndex ];
  8390. if ( material.transparent ) {
  8391. globject.transparent = material;
  8392. globject.opaque = null;
  8393. } else {
  8394. globject.opaque = material;
  8395. globject.transparent = null;
  8396. }
  8397. }
  8398. } else {
  8399. material = meshMaterial;
  8400. if ( material ) {
  8401. if ( material.transparent ) {
  8402. globject.transparent = material;
  8403. globject.opaque = null;
  8404. } else {
  8405. globject.opaque = material;
  8406. globject.transparent = null;
  8407. }
  8408. }
  8409. }
  8410. };
  8411. // Geometry splitting
  8412. function sortFacesByMaterial ( geometry ) {
  8413. var f, fl, face, materialIndex, vertices,
  8414. materialHash, groupHash,
  8415. hash_map = {};
  8416. var numMorphTargets = geometry.morphTargets.length;
  8417. var numMorphNormals = geometry.morphNormals.length;
  8418. geometry.geometryGroups = {};
  8419. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  8420. face = geometry.faces[ f ];
  8421. materialIndex = face.materialIndex;
  8422. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  8423. if ( hash_map[ materialHash ] === undefined ) {
  8424. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  8425. }
  8426. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  8427. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  8428. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  8429. }
  8430. vertices = face instanceof THREE.Face3 ? 3 : 4;
  8431. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  8432. hash_map[ materialHash ].counter += 1;
  8433. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  8434. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  8435. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  8436. }
  8437. }
  8438. if ( face instanceof THREE.Face3 ) {
  8439. geometry.geometryGroups[ groupHash ].faces3.push( f );
  8440. } else {
  8441. geometry.geometryGroups[ groupHash ].faces4.push( f );
  8442. }
  8443. geometry.geometryGroups[ groupHash ].vertices += vertices;
  8444. }
  8445. geometry.geometryGroupsList = [];
  8446. for ( var g in geometry.geometryGroups ) {
  8447. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  8448. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  8449. }
  8450. };
  8451. // Objects refresh
  8452. this.initWebGLObjects = function ( scene ) {
  8453. if ( !scene.__webglObjects ) {
  8454. scene.__webglObjects = [];
  8455. scene.__webglObjectsImmediate = [];
  8456. scene.__webglSprites = [];
  8457. scene.__webglFlares = [];
  8458. }
  8459. while ( scene.__objectsAdded.length ) {
  8460. addObject( scene.__objectsAdded[ 0 ], scene );
  8461. scene.__objectsAdded.splice( 0, 1 );
  8462. }
  8463. while ( scene.__objectsRemoved.length ) {
  8464. removeObject( scene.__objectsRemoved[ 0 ], scene );
  8465. scene.__objectsRemoved.splice( 0, 1 );
  8466. }
  8467. // update must be called after objects adding / removal
  8468. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  8469. updateObject( scene.__webglObjects[ o ].object );
  8470. }
  8471. };
  8472. // Objects adding
  8473. function addObject ( object, scene ) {
  8474. var g, geometry, geometryGroup;
  8475. if ( ! object.__webglInit ) {
  8476. object.__webglInit = true;
  8477. object._modelViewMatrix = new THREE.Matrix4();
  8478. object._normalMatrix = new THREE.Matrix3();
  8479. //object._normalMatrixArray = new Float32Array( 9 );
  8480. //object._modelViewMatrixArray = new Float32Array( 16 );
  8481. //object._objectMatrixArray = new Float32Array( 16 );
  8482. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8483. if ( object instanceof THREE.Mesh ) {
  8484. geometry = object.geometry;
  8485. if ( geometry instanceof THREE.Geometry ) {
  8486. if ( geometry.geometryGroups === undefined ) {
  8487. sortFacesByMaterial( geometry );
  8488. }
  8489. // create separate VBOs per geometry chunk
  8490. for ( g in geometry.geometryGroups ) {
  8491. geometryGroup = geometry.geometryGroups[ g ];
  8492. // initialise VBO on the first access
  8493. if ( ! geometryGroup.__webglVertexBuffer ) {
  8494. createMeshBuffers( geometryGroup );
  8495. initMeshBuffers( geometryGroup, object );
  8496. geometry.__dirtyVertices = true;
  8497. geometry.__dirtyMorphTargets = true;
  8498. geometry.__dirtyElements = true;
  8499. geometry.__dirtyUvs = true;
  8500. geometry.__dirtyNormals = true;
  8501. geometry.__dirtyTangents = true;
  8502. geometry.__dirtyColors = true;
  8503. }
  8504. }
  8505. }
  8506. } else if ( object instanceof THREE.Ribbon ) {
  8507. geometry = object.geometry;
  8508. if( ! geometry.__webglVertexBuffer ) {
  8509. createRibbonBuffers( geometry );
  8510. initRibbonBuffers( geometry );
  8511. geometry.__dirtyVertices = true;
  8512. geometry.__dirtyColors = true;
  8513. }
  8514. } else if ( object instanceof THREE.Line ) {
  8515. geometry = object.geometry;
  8516. if( ! geometry.__webglVertexBuffer ) {
  8517. createLineBuffers( geometry );
  8518. initLineBuffers( geometry, object );
  8519. geometry.__dirtyVertices = true;
  8520. geometry.__dirtyColors = true;
  8521. }
  8522. } else if ( object instanceof THREE.ParticleSystem ) {
  8523. geometry = object.geometry;
  8524. if ( ! geometry.__webglVertexBuffer ) {
  8525. createParticleBuffers( geometry );
  8526. initParticleBuffers( geometry, object );
  8527. geometry.__dirtyVertices = true;
  8528. geometry.__dirtyColors = true;
  8529. }
  8530. }
  8531. }
  8532. if ( ! object.__webglActive ) {
  8533. if ( object instanceof THREE.Mesh ) {
  8534. geometry = object.geometry;
  8535. if ( geometry instanceof THREE.BufferGeometry ) {
  8536. addBuffer( scene.__webglObjects, geometry, object );
  8537. } else {
  8538. for ( g in geometry.geometryGroups ) {
  8539. geometryGroup = geometry.geometryGroups[ g ];
  8540. addBuffer( scene.__webglObjects, geometryGroup, object );
  8541. }
  8542. }
  8543. } else if ( object instanceof THREE.Ribbon ||
  8544. object instanceof THREE.Line ||
  8545. object instanceof THREE.ParticleSystem ) {
  8546. geometry = object.geometry;
  8547. addBuffer( scene.__webglObjects, geometry, object );
  8548. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  8549. addBufferImmediate( scene.__webglObjectsImmediate, object );
  8550. } else if ( object instanceof THREE.Sprite ) {
  8551. scene.__webglSprites.push( object );
  8552. } else if ( object instanceof THREE.LensFlare ) {
  8553. scene.__webglFlares.push( object );
  8554. }
  8555. object.__webglActive = true;
  8556. }
  8557. };
  8558. function addBuffer ( objlist, buffer, object ) {
  8559. objlist.push(
  8560. {
  8561. buffer: buffer,
  8562. object: object,
  8563. opaque: null,
  8564. transparent: null
  8565. }
  8566. );
  8567. };
  8568. function addBufferImmediate ( objlist, object ) {
  8569. objlist.push(
  8570. {
  8571. object: object,
  8572. opaque: null,
  8573. transparent: null
  8574. }
  8575. );
  8576. };
  8577. // Objects updates
  8578. function updateObject ( object ) {
  8579. var geometry = object.geometry,
  8580. geometryGroup, customAttributesDirty, material;
  8581. if ( object instanceof THREE.Mesh ) {
  8582. if ( geometry instanceof THREE.BufferGeometry ) {
  8583. /*
  8584. if ( geometry.__dirtyVertices || geometry.__dirtyElements ||
  8585. geometry.__dirtyUvs || geometry.__dirtyNormals ||
  8586. geometry.__dirtyColors ) {
  8587. // TODO
  8588. // set buffers from typed arrays
  8589. }
  8590. */
  8591. geometry.__dirtyVertices = false;
  8592. geometry.__dirtyElements = false;
  8593. geometry.__dirtyUvs = false;
  8594. geometry.__dirtyNormals = false;
  8595. geometry.__dirtyColors = false;
  8596. } else {
  8597. // check all geometry groups
  8598. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  8599. geometryGroup = geometry.geometryGroupsList[ i ];
  8600. material = getBufferMaterial( object, geometryGroup );
  8601. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  8602. if ( geometry.__dirtyVertices || geometry.__dirtyMorphTargets || geometry.__dirtyElements ||
  8603. geometry.__dirtyUvs || geometry.__dirtyNormals ||
  8604. geometry.__dirtyColors || geometry.__dirtyTangents || customAttributesDirty ) {
  8605. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  8606. }
  8607. }
  8608. geometry.__dirtyVertices = false;
  8609. geometry.__dirtyMorphTargets = false;
  8610. geometry.__dirtyElements = false;
  8611. geometry.__dirtyUvs = false;
  8612. geometry.__dirtyNormals = false;
  8613. geometry.__dirtyColors = false;
  8614. geometry.__dirtyTangents = false;
  8615. material.attributes && clearCustomAttributes( material );
  8616. }
  8617. } else if ( object instanceof THREE.Ribbon ) {
  8618. if ( geometry.__dirtyVertices || geometry.__dirtyColors ) {
  8619. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  8620. }
  8621. geometry.__dirtyVertices = false;
  8622. geometry.__dirtyColors = false;
  8623. } else if ( object instanceof THREE.Line ) {
  8624. material = getBufferMaterial( object, geometryGroup );
  8625. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  8626. if ( geometry.__dirtyVertices || geometry.__dirtyColors || customAttributesDirty ) {
  8627. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  8628. }
  8629. geometry.__dirtyVertices = false;
  8630. geometry.__dirtyColors = false;
  8631. material.attributes && clearCustomAttributes( material );
  8632. } else if ( object instanceof THREE.ParticleSystem ) {
  8633. material = getBufferMaterial( object, geometryGroup );
  8634. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  8635. if ( geometry.__dirtyVertices || geometry.__dirtyColors || object.sortParticles || customAttributesDirty ) {
  8636. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  8637. }
  8638. geometry.__dirtyVertices = false;
  8639. geometry.__dirtyColors = false;
  8640. material.attributes && clearCustomAttributes( material );
  8641. }
  8642. };
  8643. // Objects updates - custom attributes check
  8644. function areCustomAttributesDirty ( material ) {
  8645. for ( var a in material.attributes ) {
  8646. if ( material.attributes[ a ].needsUpdate ) return true;
  8647. }
  8648. return false;
  8649. };
  8650. function clearCustomAttributes ( material ) {
  8651. for ( var a in material.attributes ) {
  8652. material.attributes[ a ].needsUpdate = false;
  8653. }
  8654. };
  8655. // Objects removal
  8656. function removeObject ( object, scene ) {
  8657. if ( object instanceof THREE.Mesh ||
  8658. object instanceof THREE.ParticleSystem ||
  8659. object instanceof THREE.Ribbon ||
  8660. object instanceof THREE.Line ) {
  8661. removeInstances( scene.__webglObjects, object );
  8662. } else if ( object instanceof THREE.Sprite ) {
  8663. removeInstancesDirect( scene.__webglSprites, object );
  8664. } else if ( object instanceof THREE.LensFlare ) {
  8665. removeInstancesDirect( scene.__webglFlares, object );
  8666. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  8667. removeInstances( scene.__webglObjectsImmediate, object );
  8668. }
  8669. object.__webglActive = false;
  8670. };
  8671. function removeInstances ( objlist, object ) {
  8672. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  8673. if ( objlist[ o ].object === object ) {
  8674. objlist.splice( o, 1 );
  8675. }
  8676. }
  8677. };
  8678. function removeInstancesDirect ( objlist, object ) {
  8679. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  8680. if ( objlist[ o ] === object ) {
  8681. objlist.splice( o, 1 );
  8682. }
  8683. }
  8684. };
  8685. // Materials
  8686. this.initMaterial = function ( material, lights, fog, object ) {
  8687. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  8688. if ( material instanceof THREE.MeshDepthMaterial ) {
  8689. shaderID = 'depth';
  8690. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8691. shaderID = 'normal';
  8692. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8693. shaderID = 'basic';
  8694. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  8695. shaderID = 'lambert';
  8696. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  8697. shaderID = 'phong';
  8698. } else if ( material instanceof THREE.LineBasicMaterial ) {
  8699. shaderID = 'basic';
  8700. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  8701. shaderID = 'particle_basic';
  8702. }
  8703. if ( shaderID ) {
  8704. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  8705. }
  8706. // heuristics to create shader parameters according to lights in the scene
  8707. // (not to blow over maxLights budget)
  8708. maxLightCount = allocateLights( lights );
  8709. maxShadows = allocateShadows( lights );
  8710. maxBones = allocateBones( object );
  8711. parameters = {
  8712. map: !!material.map, envMap: !!material.envMap, lightMap: !!material.lightMap,
  8713. vertexColors: material.vertexColors,
  8714. fog: fog, useFog: material.fog,
  8715. sizeAttenuation: material.sizeAttenuation,
  8716. skinning: material.skinning,
  8717. morphTargets: material.morphTargets,
  8718. morphNormals: material.morphNormals,
  8719. maxMorphTargets: this.maxMorphTargets,
  8720. maxMorphNormals: this.maxMorphNormals,
  8721. maxDirLights: maxLightCount.directional, maxPointLights: maxLightCount.point,
  8722. maxBones: maxBones,
  8723. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  8724. shadowMapSoft: this.shadowMapSoft,
  8725. shadowMapDebug: this.shadowMapDebug,
  8726. shadowMapCascade: this.shadowMapCascade,
  8727. maxShadows: maxShadows,
  8728. alphaTest: material.alphaTest,
  8729. metal: material.metal,
  8730. perPixel: material.perPixel,
  8731. wrapAround: material.wrapAround,
  8732. doubleSided: object && object.doubleSided
  8733. };
  8734. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, parameters );
  8735. var attributes = material.program.attributes;
  8736. if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
  8737. if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
  8738. if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
  8739. if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );
  8740. if ( material.skinning &&
  8741. attributes.skinVertexA >=0 && attributes.skinVertexB >= 0 &&
  8742. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  8743. _gl.enableVertexAttribArray( attributes.skinVertexA );
  8744. _gl.enableVertexAttribArray( attributes.skinVertexB );
  8745. _gl.enableVertexAttribArray( attributes.skinIndex );
  8746. _gl.enableVertexAttribArray( attributes.skinWeight );
  8747. }
  8748. if ( material.attributes ) {
  8749. for ( a in material.attributes ) {
  8750. if( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );
  8751. }
  8752. }
  8753. if ( material.morphTargets ) {
  8754. material.numSupportedMorphTargets = 0;
  8755. var id, base = "morphTarget";
  8756. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  8757. id = base + i;
  8758. if ( attributes[ id ] >= 0 ) {
  8759. _gl.enableVertexAttribArray( attributes[ id ] );
  8760. material.numSupportedMorphTargets ++;
  8761. }
  8762. }
  8763. }
  8764. if ( material.morphNormals ) {
  8765. material.numSupportedMorphNormals = 0;
  8766. var id, base = "morphNormal";
  8767. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  8768. id = base + i;
  8769. if ( attributes[ id ] >= 0 ) {
  8770. _gl.enableVertexAttribArray( attributes[ id ] );
  8771. material.numSupportedMorphNormals ++;
  8772. }
  8773. }
  8774. }
  8775. material.uniformsList = [];
  8776. for ( u in material.uniforms ) {
  8777. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  8778. }
  8779. };
  8780. function setMaterialShaders( material, shaders ) {
  8781. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  8782. material.vertexShader = shaders.vertexShader;
  8783. material.fragmentShader = shaders.fragmentShader;
  8784. };
  8785. function setProgram( camera, lights, fog, material, object ) {
  8786. if ( ! material.program || material.needsUpdate ) {
  8787. _this.initMaterial( material, lights, fog, object );
  8788. material.needsUpdate = false;
  8789. }
  8790. if ( material.morphTargets ) {
  8791. if ( ! object.__webglMorphTargetInfluences ) {
  8792. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  8793. for ( var i = 0, il = _this.maxMorphTargets; i < il; i ++ ) {
  8794. object.__webglMorphTargetInfluences[ i ] = 0;
  8795. }
  8796. }
  8797. }
  8798. var refreshMaterial = false;
  8799. var program = material.program,
  8800. p_uniforms = program.uniforms,
  8801. m_uniforms = material.uniforms;
  8802. if ( program !== _currentProgram ) {
  8803. _gl.useProgram( program );
  8804. _currentProgram = program;
  8805. refreshMaterial = true;
  8806. }
  8807. if ( material.id !== _currentMaterialId ) {
  8808. _currentMaterialId = material.id;
  8809. refreshMaterial = true;
  8810. }
  8811. if ( refreshMaterial || camera !== _currentCamera ) {
  8812. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  8813. if ( camera !== _currentCamera ) _currentCamera = camera;
  8814. }
  8815. if ( refreshMaterial ) {
  8816. // refresh uniforms common to several materials
  8817. if ( fog && material.fog ) {
  8818. refreshUniformsFog( m_uniforms, fog );
  8819. }
  8820. if ( material instanceof THREE.MeshPhongMaterial ||
  8821. material instanceof THREE.MeshLambertMaterial ||
  8822. material.lights ) {
  8823. setupLights( program, lights );
  8824. refreshUniformsLights( m_uniforms, _lights );
  8825. }
  8826. if ( material instanceof THREE.MeshBasicMaterial ||
  8827. material instanceof THREE.MeshLambertMaterial ||
  8828. material instanceof THREE.MeshPhongMaterial ) {
  8829. refreshUniformsCommon( m_uniforms, material );
  8830. }
  8831. // refresh single material specific uniforms
  8832. if ( material instanceof THREE.LineBasicMaterial ) {
  8833. refreshUniformsLine( m_uniforms, material );
  8834. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  8835. refreshUniformsParticle( m_uniforms, material );
  8836. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  8837. refreshUniformsPhong( m_uniforms, material );
  8838. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  8839. refreshUniformsLambert( m_uniforms, material );
  8840. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8841. m_uniforms.mNear.value = camera.near;
  8842. m_uniforms.mFar.value = camera.far;
  8843. m_uniforms.opacity.value = material.opacity;
  8844. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8845. m_uniforms.opacity.value = material.opacity;
  8846. }
  8847. if ( object.receiveShadow && ! material._shadowPass ) {
  8848. refreshUniformsShadow( m_uniforms, lights );
  8849. }
  8850. // load common uniforms
  8851. loadUniformsGeneric( program, material.uniformsList );
  8852. // load material specific uniforms
  8853. // (shader material also gets them for the sake of genericity)
  8854. if ( material instanceof THREE.ShaderMaterial ||
  8855. material instanceof THREE.MeshPhongMaterial ||
  8856. material.envMap ) {
  8857. if ( p_uniforms.cameraPosition !== null ) {
  8858. var position = camera.matrixWorld.getPosition();
  8859. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  8860. }
  8861. }
  8862. if ( material instanceof THREE.MeshPhongMaterial ||
  8863. material instanceof THREE.MeshLambertMaterial ||
  8864. material instanceof THREE.ShaderMaterial ||
  8865. material.skinning ) {
  8866. if ( p_uniforms.viewMatrix !== null ) {
  8867. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  8868. }
  8869. }
  8870. if ( material.skinning ) {
  8871. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  8872. }
  8873. }
  8874. loadUniformsMatrices( p_uniforms, object );
  8875. if ( material instanceof THREE.ShaderMaterial ||
  8876. material.envMap ||
  8877. material.skinning ||
  8878. object.receiveShadow ) {
  8879. if ( p_uniforms.objectMatrix !== null ) {
  8880. _gl.uniformMatrix4fv( p_uniforms.objectMatrix, false, object.matrixWorld.elements );
  8881. }
  8882. }
  8883. return program;
  8884. };
  8885. // Uniforms (refresh uniforms objects)
  8886. function refreshUniformsCommon ( uniforms, material ) {
  8887. uniforms.opacity.value = material.opacity;
  8888. if ( _this.gammaInput ) {
  8889. uniforms.diffuse.value.copyGammaToLinear( material.color );
  8890. } else {
  8891. uniforms.diffuse.value = material.color;
  8892. }
  8893. uniforms.map.texture = material.map;
  8894. if ( material.map ) {
  8895. uniforms.offsetRepeat.value.set( material.map.offset.x, material.map.offset.y, material.map.repeat.x, material.map.repeat.y );
  8896. }
  8897. uniforms.lightMap.texture = material.lightMap;
  8898. uniforms.envMap.texture = material.envMap;
  8899. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  8900. if ( _this.gammaInput ) {
  8901. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  8902. uniforms.reflectivity.value = material.reflectivity;
  8903. } else {
  8904. uniforms.reflectivity.value = material.reflectivity;
  8905. }
  8906. uniforms.refractionRatio.value = material.refractionRatio;
  8907. uniforms.combine.value = material.combine;
  8908. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  8909. };
  8910. function refreshUniformsLine ( uniforms, material ) {
  8911. uniforms.diffuse.value = material.color;
  8912. uniforms.opacity.value = material.opacity;
  8913. };
  8914. function refreshUniformsParticle ( uniforms, material ) {
  8915. uniforms.psColor.value = material.color;
  8916. uniforms.opacity.value = material.opacity;
  8917. uniforms.size.value = material.size;
  8918. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  8919. uniforms.map.texture = material.map;
  8920. };
  8921. function refreshUniformsFog ( uniforms, fog ) {
  8922. uniforms.fogColor.value = fog.color;
  8923. if ( fog instanceof THREE.Fog ) {
  8924. uniforms.fogNear.value = fog.near;
  8925. uniforms.fogFar.value = fog.far;
  8926. } else if ( fog instanceof THREE.FogExp2 ) {
  8927. uniforms.fogDensity.value = fog.density;
  8928. }
  8929. };
  8930. function refreshUniformsPhong ( uniforms, material ) {
  8931. uniforms.shininess.value = material.shininess;
  8932. if ( _this.gammaInput ) {
  8933. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  8934. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  8935. uniforms.specular.value.copyGammaToLinear( material.specular );
  8936. } else {
  8937. uniforms.ambient.value = material.ambient;
  8938. uniforms.emissive.value = material.emissive;
  8939. uniforms.specular.value = material.specular;
  8940. }
  8941. if ( material.wrapAround ) {
  8942. uniforms.wrapRGB.value.copy( material.wrapRGB );
  8943. }
  8944. };
  8945. function refreshUniformsLambert ( uniforms, material ) {
  8946. if ( _this.gammaInput ) {
  8947. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  8948. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  8949. } else {
  8950. uniforms.ambient.value = material.ambient;
  8951. uniforms.emissive.value = material.emissive;
  8952. }
  8953. if ( material.wrapAround ) {
  8954. uniforms.wrapRGB.value.copy( material.wrapRGB );
  8955. }
  8956. };
  8957. function refreshUniformsLights ( uniforms, lights ) {
  8958. uniforms.ambientLightColor.value = lights.ambient;
  8959. uniforms.directionalLightColor.value = lights.directional.colors;
  8960. uniforms.directionalLightDirection.value = lights.directional.positions;
  8961. uniforms.pointLightColor.value = lights.point.colors;
  8962. uniforms.pointLightPosition.value = lights.point.positions;
  8963. uniforms.pointLightDistance.value = lights.point.distances;
  8964. };
  8965. function refreshUniformsShadow ( uniforms, lights ) {
  8966. if ( uniforms.shadowMatrix ) {
  8967. var j = 0;
  8968. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  8969. var light = lights[ i ];
  8970. if ( ! light.castShadow ) continue;
  8971. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  8972. uniforms.shadowMap.texture[ j ] = light.shadowMap;
  8973. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  8974. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  8975. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  8976. uniforms.shadowBias.value[ j ] = light.shadowBias;
  8977. j ++;
  8978. }
  8979. }
  8980. }
  8981. };
  8982. // Uniforms (load to GPU)
  8983. function loadUniformsMatrices ( uniforms, object ) {
  8984. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  8985. if ( uniforms.normalMatrix ) {
  8986. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  8987. }
  8988. };
  8989. function loadUniformsGeneric ( program, uniforms ) {
  8990. var uniform, value, type, location, texture, i, il, j, jl, offset;
  8991. for( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  8992. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  8993. if ( !location ) continue;
  8994. uniform = uniforms[ j ][ 0 ];
  8995. type = uniform.type;
  8996. value = uniform.value;
  8997. // single integer
  8998. if( type === "i" ) {
  8999. _gl.uniform1i( location, value );
  9000. // single float
  9001. } else if( type === "f" ) {
  9002. _gl.uniform1f( location, value );
  9003. // single THREE.Vector2
  9004. } else if( type === "v2" ) {
  9005. _gl.uniform2f( location, value.x, value.y );
  9006. // single THREE.Vector3
  9007. } else if( type === "v3" ) {
  9008. _gl.uniform3f( location, value.x, value.y, value.z );
  9009. // single THREE.Vector4
  9010. } else if( type === "v4" ) {
  9011. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  9012. // single THREE.Color
  9013. } else if( type === "c" ) {
  9014. _gl.uniform3f( location, value.r, value.g, value.b );
  9015. // flat array of floats (JS or typed array)
  9016. } else if( type === "fv1" ) {
  9017. _gl.uniform1fv( location, value );
  9018. // flat array of floats with 3 x N size (JS or typed array)
  9019. } else if( type === "fv" ) {
  9020. _gl.uniform3fv( location, value );
  9021. // array of THREE.Vector2
  9022. } else if( type === "v2v" ) {
  9023. if ( ! uniform._array ) {
  9024. uniform._array = new Float32Array( 2 * value.length );
  9025. }
  9026. for ( i = 0, il = value.length; i < il; i ++ ) {
  9027. offset = i * 2;
  9028. uniform._array[ offset ] = value[ i ].x;
  9029. uniform._array[ offset + 1 ] = value[ i ].y;
  9030. }
  9031. _gl.uniform2fv( location, uniform._array );
  9032. // array of THREE.Vector3
  9033. } else if( type === "v3v" ) {
  9034. if ( ! uniform._array ) {
  9035. uniform._array = new Float32Array( 3 * value.length );
  9036. }
  9037. for ( i = 0, il = value.length; i < il; i ++ ) {
  9038. offset = i * 3;
  9039. uniform._array[ offset ] = value[ i ].x;
  9040. uniform._array[ offset + 1 ] = value[ i ].y;
  9041. uniform._array[ offset + 2 ] = value[ i ].z;
  9042. }
  9043. _gl.uniform3fv( location, uniform._array );
  9044. // array of THREE.Vector4
  9045. } else if( type == "v4v" ) {
  9046. if ( ! uniform._array ) {
  9047. uniform._array = new Float32Array( 4 * value.length );
  9048. }
  9049. for ( i = 0, il = value.length; i < il; i ++ ) {
  9050. offset = i * 4;
  9051. uniform._array[ offset ] = value[ i ].x;
  9052. uniform._array[ offset + 1 ] = value[ i ].y;
  9053. uniform._array[ offset + 2 ] = value[ i ].z;
  9054. uniform._array[ offset + 3 ] = value[ i ].w;
  9055. }
  9056. _gl.uniform4fv( location, uniform._array );
  9057. // single THREE.Matrix4
  9058. } else if( type === "m4" ) {
  9059. if ( ! uniform._array ) {
  9060. uniform._array = new Float32Array( 16 );
  9061. }
  9062. value.flattenToArray( uniform._array );
  9063. _gl.uniformMatrix4fv( location, false, uniform._array );
  9064. // array of THREE.Matrix4
  9065. } else if( type === "m4v" ) {
  9066. if ( ! uniform._array ) {
  9067. uniform._array = new Float32Array( 16 * value.length );
  9068. }
  9069. for ( i = 0, il = value.length; i < il; i ++ ) {
  9070. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  9071. }
  9072. _gl.uniformMatrix4fv( location, false, uniform._array );
  9073. // single THREE.Texture (2d or cube)
  9074. } else if( type === "t" ) {
  9075. _gl.uniform1i( location, value );
  9076. texture = uniform.texture;
  9077. if ( !texture ) continue;
  9078. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  9079. setCubeTexture( texture, value );
  9080. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  9081. setCubeTextureDynamic( texture, value );
  9082. } else {
  9083. _this.setTexture( texture, value );
  9084. }
  9085. // array of THREE.Texture (2d)
  9086. } else if( type === "tv" ) {
  9087. if ( ! uniform._array ) {
  9088. uniform._array = [];
  9089. for( i = 0, il = uniform.texture.length; i < il; i ++ ) {
  9090. uniform._array[ i ] = value + i;
  9091. }
  9092. }
  9093. _gl.uniform1iv( location, uniform._array );
  9094. for( i = 0, il = uniform.texture.length; i < il; i ++ ) {
  9095. texture = uniform.texture[ i ];
  9096. if ( !texture ) continue;
  9097. _this.setTexture( texture, uniform._array[ i ] );
  9098. }
  9099. }
  9100. }
  9101. };
  9102. function setupMatrices ( object, camera ) {
  9103. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  9104. object._normalMatrix.getInverse( object._modelViewMatrix );
  9105. object._normalMatrix.transpose();
  9106. };
  9107. function setupLights ( program, lights ) {
  9108. var l, ll, light, n,
  9109. r = 0, g = 0, b = 0,
  9110. color, position, intensity, distance,
  9111. zlights = _lights,
  9112. dcolors = zlights.directional.colors,
  9113. dpositions = zlights.directional.positions,
  9114. pcolors = zlights.point.colors,
  9115. ppositions = zlights.point.positions,
  9116. pdistances = zlights.point.distances,
  9117. dlength = 0,
  9118. plength = 0,
  9119. doffset = 0,
  9120. poffset = 0;
  9121. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  9122. light = lights[ l ];
  9123. if ( light.onlyShadow ) continue;
  9124. color = light.color;
  9125. intensity = light.intensity;
  9126. distance = light.distance;
  9127. if ( light instanceof THREE.AmbientLight ) {
  9128. if ( _this.gammaInput ) {
  9129. r += color.r * color.r;
  9130. g += color.g * color.g;
  9131. b += color.b * color.b;
  9132. } else {
  9133. r += color.r;
  9134. g += color.g;
  9135. b += color.b;
  9136. }
  9137. } else if ( light instanceof THREE.DirectionalLight ) {
  9138. doffset = dlength * 3;
  9139. if ( _this.gammaInput ) {
  9140. dcolors[ doffset ] = color.r * color.r * intensity * intensity;
  9141. dcolors[ doffset + 1 ] = color.g * color.g * intensity * intensity;
  9142. dcolors[ doffset + 2 ] = color.b * color.b * intensity * intensity;
  9143. } else {
  9144. dcolors[ doffset ] = color.r * intensity;
  9145. dcolors[ doffset + 1 ] = color.g * intensity;
  9146. dcolors[ doffset + 2 ] = color.b * intensity;
  9147. }
  9148. _direction.copy( light.matrixWorld.getPosition() );
  9149. _direction.subSelf( light.target.matrixWorld.getPosition() );
  9150. _direction.normalize();
  9151. dpositions[ doffset ] = _direction.x;
  9152. dpositions[ doffset + 1 ] = _direction.y;
  9153. dpositions[ doffset + 2 ] = _direction.z;
  9154. dlength += 1;
  9155. } else if( light instanceof THREE.PointLight || light instanceof THREE.SpotLight ) {
  9156. poffset = plength * 3;
  9157. if ( _this.gammaInput ) {
  9158. pcolors[ poffset ] = color.r * color.r * intensity * intensity;
  9159. pcolors[ poffset + 1 ] = color.g * color.g * intensity * intensity;
  9160. pcolors[ poffset + 2 ] = color.b * color.b * intensity * intensity;
  9161. } else {
  9162. pcolors[ poffset ] = color.r * intensity;
  9163. pcolors[ poffset + 1 ] = color.g * intensity;
  9164. pcolors[ poffset + 2 ] = color.b * intensity;
  9165. }
  9166. position = light.matrixWorld.getPosition();
  9167. ppositions[ poffset ] = position.x;
  9168. ppositions[ poffset + 1 ] = position.y;
  9169. ppositions[ poffset + 2 ] = position.z;
  9170. pdistances[ plength ] = distance;
  9171. plength += 1;
  9172. }
  9173. }
  9174. // null eventual remains from removed lights
  9175. // (this is to avoid if in shader)
  9176. for ( l = dlength * 3, ll = dcolors.length; l < ll; l ++ ) dcolors[ l ] = 0.0;
  9177. for ( l = plength * 3, ll = pcolors.length; l < ll; l ++ ) pcolors[ l ] = 0.0;
  9178. zlights.point.length = plength;
  9179. zlights.directional.length = dlength;
  9180. zlights.ambient[ 0 ] = r;
  9181. zlights.ambient[ 1 ] = g;
  9182. zlights.ambient[ 2 ] = b;
  9183. };
  9184. // GL state setting
  9185. this.setFaceCulling = function ( cullFace, frontFace ) {
  9186. if ( cullFace ) {
  9187. if ( !frontFace || frontFace === "ccw" ) {
  9188. _gl.frontFace( _gl.CCW );
  9189. } else {
  9190. _gl.frontFace( _gl.CW );
  9191. }
  9192. if( cullFace === "back" ) {
  9193. _gl.cullFace( _gl.BACK );
  9194. } else if( cullFace === "front" ) {
  9195. _gl.cullFace( _gl.FRONT );
  9196. } else {
  9197. _gl.cullFace( _gl.FRONT_AND_BACK );
  9198. }
  9199. _gl.enable( _gl.CULL_FACE );
  9200. } else {
  9201. _gl.disable( _gl.CULL_FACE );
  9202. }
  9203. };
  9204. this.setObjectFaces = function ( object ) {
  9205. if ( _oldDoubleSided !== object.doubleSided ) {
  9206. if( object.doubleSided ) {
  9207. _gl.disable( _gl.CULL_FACE );
  9208. } else {
  9209. _gl.enable( _gl.CULL_FACE );
  9210. }
  9211. _oldDoubleSided = object.doubleSided;
  9212. }
  9213. if ( _oldFlipSided !== object.flipSided ) {
  9214. if( object.flipSided ) {
  9215. _gl.frontFace( _gl.CW );
  9216. } else {
  9217. _gl.frontFace( _gl.CCW );
  9218. }
  9219. _oldFlipSided = object.flipSided;
  9220. }
  9221. };
  9222. this.setDepthTest = function ( depthTest ) {
  9223. if ( _oldDepthTest !== depthTest ) {
  9224. if ( depthTest ) {
  9225. _gl.enable( _gl.DEPTH_TEST );
  9226. } else {
  9227. _gl.disable( _gl.DEPTH_TEST );
  9228. }
  9229. _oldDepthTest = depthTest;
  9230. }
  9231. };
  9232. this.setDepthWrite = function ( depthWrite ) {
  9233. if ( _oldDepthWrite !== depthWrite ) {
  9234. _gl.depthMask( depthWrite );
  9235. _oldDepthWrite = depthWrite;
  9236. }
  9237. };
  9238. function setLineWidth ( width ) {
  9239. if ( width !== _oldLineWidth ) {
  9240. _gl.lineWidth( width );
  9241. _oldLineWidth = width;
  9242. }
  9243. };
  9244. function setPolygonOffset ( polygonoffset, factor, units ) {
  9245. if ( _oldPolygonOffset !== polygonoffset ) {
  9246. if ( polygonoffset ) {
  9247. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  9248. } else {
  9249. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  9250. }
  9251. _oldPolygonOffset = polygonoffset;
  9252. }
  9253. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  9254. _gl.polygonOffset( factor, units );
  9255. _oldPolygonOffsetFactor = factor;
  9256. _oldPolygonOffsetUnits = units;
  9257. }
  9258. };
  9259. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  9260. if ( blending !== _oldBlending ) {
  9261. switch ( blending ) {
  9262. case THREE.NoBlending:
  9263. _gl.disable( _gl.BLEND );
  9264. break;
  9265. case THREE.AdditiveBlending:
  9266. _gl.enable( _gl.BLEND );
  9267. _gl.blendEquation( _gl.FUNC_ADD );
  9268. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  9269. break;
  9270. case THREE.SubtractiveBlending:
  9271. // TODO: Find blendFuncSeparate() combination
  9272. _gl.enable( _gl.BLEND );
  9273. _gl.blendEquation( _gl.FUNC_ADD );
  9274. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  9275. break;
  9276. case THREE.MultiplyBlending:
  9277. // TODO: Find blendFuncSeparate() combination
  9278. _gl.enable( _gl.BLEND );
  9279. _gl.blendEquation( _gl.FUNC_ADD );
  9280. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  9281. break;
  9282. case THREE.CustomBlending:
  9283. _gl.enable( _gl.BLEND );
  9284. break;
  9285. default:
  9286. _gl.enable( _gl.BLEND );
  9287. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  9288. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  9289. break;
  9290. }
  9291. _oldBlending = blending;
  9292. }
  9293. if ( blending === THREE.CustomBlending ) {
  9294. if ( blendEquation !== _oldBlendEquation ) {
  9295. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  9296. _oldBlendEquation = blendEquation;
  9297. }
  9298. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  9299. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  9300. _oldBlendSrc = blendSrc;
  9301. _oldBlendDst = blendDst;
  9302. }
  9303. } else {
  9304. _oldBlendEquation = null;
  9305. _oldBlendSrc = null;
  9306. _oldBlendDst = null;
  9307. }
  9308. };
  9309. // Shaders
  9310. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, parameters ) {
  9311. var p, pl, program, code;
  9312. var chunks = [];
  9313. // Generate code
  9314. if ( shaderID ) {
  9315. chunks.push( shaderID );
  9316. } else {
  9317. chunks.push( fragmentShader );
  9318. chunks.push( vertexShader );
  9319. }
  9320. for ( p in parameters ) {
  9321. chunks.push( p );
  9322. chunks.push( parameters[ p ] );
  9323. }
  9324. code = chunks.join();
  9325. // Check if code has been already compiled
  9326. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  9327. if ( _programs[ p ].code === code ) {
  9328. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  9329. return _programs[ p ].program;
  9330. }
  9331. }
  9332. //console.log( "building new program " );
  9333. //
  9334. program = _gl.createProgram();
  9335. var prefix_vertex = [
  9336. "precision " + _precision + " float;",
  9337. ( _maxVertexTextures > 0 ) ? "#define VERTEX_TEXTURES" : "",
  9338. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  9339. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  9340. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  9341. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  9342. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  9343. "#define MAX_SHADOWS " + parameters.maxShadows,
  9344. "#define MAX_BONES " + parameters.maxBones,
  9345. parameters.map ? "#define USE_MAP" : "",
  9346. parameters.envMap ? "#define USE_ENVMAP" : "",
  9347. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  9348. parameters.vertexColors ? "#define USE_COLOR" : "",
  9349. parameters.skinning ? "#define USE_SKINNING" : "",
  9350. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  9351. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  9352. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  9353. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  9354. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  9355. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  9356. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  9357. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  9358. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  9359. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  9360. "uniform mat4 objectMatrix;",
  9361. "uniform mat4 modelViewMatrix;",
  9362. "uniform mat4 projectionMatrix;",
  9363. "uniform mat4 viewMatrix;",
  9364. "uniform mat3 normalMatrix;",
  9365. "uniform vec3 cameraPosition;",
  9366. "attribute vec3 position;",
  9367. "attribute vec3 normal;",
  9368. "attribute vec2 uv;",
  9369. "attribute vec2 uv2;",
  9370. "#ifdef USE_COLOR",
  9371. "attribute vec3 color;",
  9372. "#endif",
  9373. "#ifdef USE_MORPHTARGETS",
  9374. "attribute vec3 morphTarget0;",
  9375. "attribute vec3 morphTarget1;",
  9376. "attribute vec3 morphTarget2;",
  9377. "attribute vec3 morphTarget3;",
  9378. "#ifdef USE_MORPHNORMALS",
  9379. "attribute vec3 morphNormal0;",
  9380. "attribute vec3 morphNormal1;",
  9381. "attribute vec3 morphNormal2;",
  9382. "attribute vec3 morphNormal3;",
  9383. "#else",
  9384. "attribute vec3 morphTarget4;",
  9385. "attribute vec3 morphTarget5;",
  9386. "attribute vec3 morphTarget6;",
  9387. "attribute vec3 morphTarget7;",
  9388. "#endif",
  9389. "#endif",
  9390. "#ifdef USE_SKINNING",
  9391. "attribute vec4 skinVertexA;",
  9392. "attribute vec4 skinVertexB;",
  9393. "attribute vec4 skinIndex;",
  9394. "attribute vec4 skinWeight;",
  9395. "#endif",
  9396. ""
  9397. ].join("\n");
  9398. var prefix_fragment = [
  9399. "precision " + _precision + " float;",
  9400. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  9401. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  9402. "#define MAX_SHADOWS " + parameters.maxShadows,
  9403. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  9404. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  9405. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  9406. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  9407. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  9408. ( parameters.useFog && parameters.fog instanceof THREE.FogExp2 ) ? "#define FOG_EXP2" : "",
  9409. parameters.map ? "#define USE_MAP" : "",
  9410. parameters.envMap ? "#define USE_ENVMAP" : "",
  9411. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  9412. parameters.vertexColors ? "#define USE_COLOR" : "",
  9413. parameters.metal ? "#define METAL" : "",
  9414. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  9415. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  9416. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  9417. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  9418. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  9419. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  9420. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  9421. "uniform mat4 viewMatrix;",
  9422. "uniform vec3 cameraPosition;",
  9423. ""
  9424. ].join("\n");
  9425. _gl.attachShader( program, getShader( "fragment", prefix_fragment + fragmentShader ) );
  9426. _gl.attachShader( program, getShader( "vertex", prefix_vertex + vertexShader ) );
  9427. _gl.linkProgram( program );
  9428. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  9429. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  9430. }
  9431. //console.log( prefix_fragment + fragmentShader );
  9432. //console.log( prefix_vertex + vertexShader );
  9433. program.uniforms = {};
  9434. program.attributes = {};
  9435. var identifiers, u, a, i;
  9436. // cache uniform locations
  9437. identifiers = [
  9438. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'objectMatrix', 'cameraPosition',
  9439. 'boneGlobalMatrices', 'morphTargetInfluences'
  9440. ];
  9441. for ( u in uniforms ) {
  9442. identifiers.push( u );
  9443. }
  9444. cacheUniformLocations( program, identifiers );
  9445. // cache attributes locations
  9446. identifiers = [
  9447. "position", "normal", "uv", "uv2", "tangent", "color",
  9448. "skinVertexA", "skinVertexB", "skinIndex", "skinWeight"
  9449. ];
  9450. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  9451. identifiers.push( "morphTarget" + i );
  9452. }
  9453. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  9454. identifiers.push( "morphNormal" + i );
  9455. }
  9456. for ( a in attributes ) {
  9457. identifiers.push( a );
  9458. }
  9459. cacheAttributeLocations( program, identifiers );
  9460. program.id = _programs.length;
  9461. _programs.push( { program: program, code: code } );
  9462. _this.info.memory.programs = _programs.length;
  9463. return program;
  9464. };
  9465. // Shader parameters cache
  9466. function cacheUniformLocations ( program, identifiers ) {
  9467. var i, l, id;
  9468. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  9469. id = identifiers[ i ];
  9470. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  9471. }
  9472. };
  9473. function cacheAttributeLocations ( program, identifiers ) {
  9474. var i, l, id;
  9475. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  9476. id = identifiers[ i ];
  9477. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  9478. }
  9479. };
  9480. function getShader ( type, string ) {
  9481. var shader;
  9482. if ( type === "fragment" ) {
  9483. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  9484. } else if ( type === "vertex" ) {
  9485. shader = _gl.createShader( _gl.VERTEX_SHADER );
  9486. }
  9487. _gl.shaderSource( shader, string );
  9488. _gl.compileShader( shader );
  9489. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  9490. console.error( _gl.getShaderInfoLog( shader ) );
  9491. console.error( string );
  9492. return null;
  9493. }
  9494. return shader;
  9495. };
  9496. // Textures
  9497. function isPowerOfTwo ( value ) {
  9498. return ( value & ( value - 1 ) ) === 0;
  9499. };
  9500. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  9501. if ( isImagePowerOfTwo ) {
  9502. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  9503. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  9504. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  9505. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  9506. } else {
  9507. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  9508. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  9509. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  9510. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  9511. }
  9512. };
  9513. this.setTexture = function ( texture, slot ) {
  9514. if ( texture.needsUpdate ) {
  9515. if ( ! texture.__webglInit ) {
  9516. texture.__webglInit = true;
  9517. texture.__webglTexture = _gl.createTexture();
  9518. _this.info.memory.textures ++;
  9519. }
  9520. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9521. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  9522. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  9523. var image = texture.image,
  9524. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  9525. glFormat = paramThreeToGL( texture.format ),
  9526. glType = paramThreeToGL( texture.type );
  9527. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  9528. if ( texture instanceof THREE.DataTexture ) {
  9529. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  9530. } else {
  9531. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  9532. }
  9533. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  9534. texture.needsUpdate = false;
  9535. if ( texture.onUpdate ) texture.onUpdate();
  9536. } else {
  9537. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9538. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  9539. }
  9540. };
  9541. function clampToMaxSize ( image, maxSize ) {
  9542. if ( image.width <= maxSize && image.height <= maxSize ) {
  9543. return image;
  9544. }
  9545. // Warning: Scaling through the canvas will only work with images that use
  9546. // premultiplied alpha.
  9547. var maxDimension = Math.max( image.width, image.height );
  9548. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  9549. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  9550. var canvas = document.createElement( 'canvas' );
  9551. canvas.width = newWidth;
  9552. canvas.height = newHeight;
  9553. var ctx = canvas.getContext( "2d" );
  9554. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  9555. return canvas;
  9556. }
  9557. function setCubeTexture ( texture, slot ) {
  9558. if ( texture.image.length === 6 ) {
  9559. if ( texture.needsUpdate ) {
  9560. if ( ! texture.image.__webglTextureCube ) {
  9561. texture.image.__webglTextureCube = _gl.createTexture();
  9562. }
  9563. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9564. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  9565. var cubeImage = [];
  9566. for ( var i = 0; i < 6; i ++ ) {
  9567. if ( _this.autoScaleCubemaps ) {
  9568. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  9569. } else {
  9570. cubeImage[ i ] = texture.image[ i ];
  9571. }
  9572. }
  9573. var image = cubeImage[ 0 ],
  9574. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  9575. glFormat = paramThreeToGL( texture.format ),
  9576. glType = paramThreeToGL( texture.type );
  9577. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  9578. for ( var i = 0; i < 6; i ++ ) {
  9579. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  9580. }
  9581. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  9582. texture.needsUpdate = false;
  9583. if ( texture.onUpdate ) texture.onUpdate();
  9584. } else {
  9585. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9586. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  9587. }
  9588. }
  9589. };
  9590. function setCubeTextureDynamic ( texture, slot ) {
  9591. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9592. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  9593. };
  9594. // Render targets
  9595. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  9596. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  9597. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  9598. };
  9599. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  9600. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  9601. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  9602. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  9603. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  9604. /* For some reason this is not working. Defaulting to RGBA4.
  9605. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  9606. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  9607. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  9608. */
  9609. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  9610. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  9611. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  9612. } else {
  9613. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  9614. }
  9615. };
  9616. this.setRenderTarget = function ( renderTarget ) {
  9617. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  9618. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  9619. if( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  9620. if( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  9621. renderTarget.__webglTexture = _gl.createTexture();
  9622. // Setup texture, create render and frame buffers
  9623. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  9624. glFormat = paramThreeToGL( renderTarget.format ),
  9625. glType = paramThreeToGL( renderTarget.type );
  9626. if ( isCube ) {
  9627. renderTarget.__webglFramebuffer = [];
  9628. renderTarget.__webglRenderbuffer = [];
  9629. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  9630. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  9631. for ( var i = 0; i < 6; i ++ ) {
  9632. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  9633. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  9634. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  9635. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  9636. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  9637. }
  9638. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  9639. } else {
  9640. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  9641. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  9642. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  9643. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  9644. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  9645. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  9646. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  9647. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  9648. }
  9649. // Release everything
  9650. if ( isCube ) {
  9651. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  9652. } else {
  9653. _gl.bindTexture( _gl.TEXTURE_2D, null );
  9654. }
  9655. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  9656. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  9657. }
  9658. var framebuffer, width, height, vx, vy;
  9659. if ( renderTarget ) {
  9660. if ( isCube ) {
  9661. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  9662. } else {
  9663. framebuffer = renderTarget.__webglFramebuffer;
  9664. }
  9665. width = renderTarget.width;
  9666. height = renderTarget.height;
  9667. vx = 0;
  9668. vy = 0;
  9669. } else {
  9670. framebuffer = null;
  9671. width = _viewportWidth;
  9672. height = _viewportHeight;
  9673. vx = _viewportX;
  9674. vy = _viewportY;
  9675. }
  9676. if ( framebuffer !== _currentFramebuffer ) {
  9677. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  9678. _gl.viewport( vx, vy, width, height );
  9679. _currentFramebuffer = framebuffer;
  9680. }
  9681. _currentWidth = width;
  9682. _currentHeight = height;
  9683. };
  9684. function updateRenderTargetMipmap ( renderTarget ) {
  9685. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9686. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  9687. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  9688. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  9689. } else {
  9690. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  9691. _gl.generateMipmap( _gl.TEXTURE_2D );
  9692. _gl.bindTexture( _gl.TEXTURE_2D, null );
  9693. }
  9694. };
  9695. // Fallback filters for non-power-of-2 textures
  9696. function filterFallback ( f ) {
  9697. switch ( f ) {
  9698. case THREE.NearestFilter:
  9699. case THREE.NearestMipMapNearestFilter:
  9700. case THREE.NearestMipMapLinearFilter: return _gl.NEAREST; break;
  9701. case THREE.LinearFilter:
  9702. case THREE.LinearMipMapNearestFilter:
  9703. case THREE.LinearMipMapLinearFilter:
  9704. default:
  9705. return _gl.LINEAR; break;
  9706. }
  9707. };
  9708. // Map three.js constants to WebGL constants
  9709. function paramThreeToGL ( p ) {
  9710. switch ( p ) {
  9711. case THREE.RepeatWrapping: return _gl.REPEAT; break;
  9712. case THREE.ClampToEdgeWrapping: return _gl.CLAMP_TO_EDGE; break;
  9713. case THREE.MirroredRepeatWrapping: return _gl.MIRRORED_REPEAT; break;
  9714. case THREE.NearestFilter: return _gl.NEAREST; break;
  9715. case THREE.NearestMipMapNearestFilter: return _gl.NEAREST_MIPMAP_NEAREST; break;
  9716. case THREE.NearestMipMapLinearFilter: return _gl.NEAREST_MIPMAP_LINEAR; break;
  9717. case THREE.LinearFilter: return _gl.LINEAR; break;
  9718. case THREE.LinearMipMapNearestFilter: return _gl.LINEAR_MIPMAP_NEAREST; break;
  9719. case THREE.LinearMipMapLinearFilter: return _gl.LINEAR_MIPMAP_LINEAR; break;
  9720. case THREE.ByteType: return _gl.BYTE; break;
  9721. case THREE.UnsignedByteType: return _gl.UNSIGNED_BYTE; break;
  9722. case THREE.ShortType: return _gl.SHORT; break;
  9723. case THREE.UnsignedShortType: return _gl.UNSIGNED_SHORT; break;
  9724. case THREE.IntType: return _gl.INT; break;
  9725. case THREE.UnsignedIntType: return _gl.UNSIGNED_INT; break;
  9726. case THREE.FloatType: return _gl.FLOAT; break;
  9727. case THREE.AlphaFormat: return _gl.ALPHA; break;
  9728. case THREE.RGBFormat: return _gl.RGB; break;
  9729. case THREE.RGBAFormat: return _gl.RGBA; break;
  9730. case THREE.LuminanceFormat: return _gl.LUMINANCE; break;
  9731. case THREE.LuminanceAlphaFormat: return _gl.LUMINANCE_ALPHA; break;
  9732. case THREE.AddEquation: return _gl.FUNC_ADD; break;
  9733. case THREE.SubtractEquation: return _gl.FUNC_SUBTRACT; break;
  9734. case THREE.ReverseSubtractEquation: return _gl.FUNC_REVERSE_SUBTRACT; break;
  9735. case THREE.ZeroFactor: return _gl.ZERO; break;
  9736. case THREE.OneFactor: return _gl.ONE; break;
  9737. case THREE.SrcColorFactor: return _gl.SRC_COLOR; break;
  9738. case THREE.OneMinusSrcColorFactor: return _gl.ONE_MINUS_SRC_COLOR; break;
  9739. case THREE.SrcAlphaFactor: return _gl.SRC_ALPHA; break;
  9740. case THREE.OneMinusSrcAlphaFactor: return _gl.ONE_MINUS_SRC_ALPHA; break;
  9741. case THREE.DstAlphaFactor: return _gl.DST_ALPHA; break;
  9742. case THREE.OneMinusDstAlphaFactor: return _gl.ONE_MINUS_DST_ALPHA; break;
  9743. case THREE.DstColorFactor: return _gl.DST_COLOR; break;
  9744. case THREE.OneMinusDstColorFactor: return _gl.ONE_MINUS_DST_COLOR; break;
  9745. case THREE.SrcAlphaSaturateFactor: return _gl.SRC_ALPHA_SATURATE; break;
  9746. }
  9747. return 0;
  9748. };
  9749. // Allocations
  9750. function allocateBones ( object ) {
  9751. // default for when object is not specified
  9752. // ( for example when prebuilding shader
  9753. // to be used with multiple objects )
  9754. //
  9755. // - leave some extra space for other uniforms
  9756. // - limit here is ANGLE's 254 max uniform vectors
  9757. // (up to 54 should be safe)
  9758. var maxBones = 50;
  9759. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  9760. maxBones = object.bones.length;
  9761. }
  9762. return maxBones;
  9763. };
  9764. function allocateLights ( lights ) {
  9765. var l, ll, light, dirLights, pointLights, maxDirLights, maxPointLights;
  9766. dirLights = pointLights = maxDirLights = maxPointLights = 0;
  9767. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  9768. light = lights[ l ];
  9769. if ( light.onlyShadow ) continue;
  9770. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  9771. if ( light instanceof THREE.PointLight ) pointLights ++;
  9772. if ( light instanceof THREE.SpotLight ) pointLights ++;
  9773. }
  9774. if ( ( pointLights + dirLights ) <= _maxLights ) {
  9775. maxDirLights = dirLights;
  9776. maxPointLights = pointLights;
  9777. } else {
  9778. maxDirLights = Math.ceil( _maxLights * dirLights / ( pointLights + dirLights ) );
  9779. maxPointLights = _maxLights - maxDirLights;
  9780. }
  9781. return { 'directional' : maxDirLights, 'point' : maxPointLights };
  9782. };
  9783. function allocateShadows ( lights ) {
  9784. var l, ll, light, maxShadows = 0;
  9785. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  9786. light = lights[ l ];
  9787. if ( ! light.castShadow ) continue;
  9788. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  9789. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  9790. }
  9791. return maxShadows;
  9792. };
  9793. // Initialization
  9794. function initGL () {
  9795. var gl;
  9796. try {
  9797. if ( ! ( gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  9798. throw 'Error creating WebGL context.';
  9799. }
  9800. } catch ( error ) {
  9801. console.error( error );
  9802. }
  9803. return gl;
  9804. };
  9805. function setDefaultGLState () {
  9806. _gl.clearColor( 0, 0, 0, 1 );
  9807. _gl.clearDepth( 1 );
  9808. _gl.clearStencil( 0 );
  9809. _gl.enable( _gl.DEPTH_TEST );
  9810. _gl.depthFunc( _gl.LEQUAL );
  9811. _gl.frontFace( _gl.CCW );
  9812. _gl.cullFace( _gl.BACK );
  9813. _gl.enable( _gl.CULL_FACE );
  9814. _gl.enable( _gl.BLEND );
  9815. _gl.blendEquation( _gl.FUNC_ADD );
  9816. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  9817. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9818. };
  9819. // default plugins (order is important)
  9820. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  9821. this.addPrePlugin( this.shadowMapPlugin );
  9822. this.addPostPlugin( new THREE.SpritePlugin() );
  9823. this.addPostPlugin( new THREE.LensFlarePlugin() );
  9824. };
  9825. /**
  9826. * @author szimek / https://github.com/szimek/
  9827. */
  9828. THREE.WebGLRenderTarget = function ( width, height, options ) {
  9829. this.width = width;
  9830. this.height = height;
  9831. options = options || {};
  9832. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  9833. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  9834. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  9835. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  9836. this.offset = new THREE.Vector2( 0, 0 );
  9837. this.repeat = new THREE.Vector2( 1, 1 );
  9838. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  9839. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  9840. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  9841. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  9842. this.generateMipmaps = true;
  9843. };
  9844. THREE.WebGLRenderTarget.prototype.clone = function() {
  9845. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  9846. tmp.wrapS = this.wrapS;
  9847. tmp.wrapT = this.wrapT;
  9848. tmp.magFilter = this.magFilter;
  9849. tmp.minFilter = this.minFilter;
  9850. tmp.offset.copy( this.offset );
  9851. tmp.repeat.copy( this.repeat );
  9852. tmp.format = this.format;
  9853. tmp.type = this.type;
  9854. tmp.depthBuffer = this.depthBuffer;
  9855. tmp.stencilBuffer = this.stencilBuffer;
  9856. return tmp;
  9857. };
  9858. /**
  9859. * @author alteredq / http://alteredqualia.com
  9860. */
  9861. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  9862. THREE.WebGLRenderTarget.call( this, width, height, options );
  9863. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  9864. };
  9865. THREE.WebGLRenderTargetCube.prototype = new THREE.WebGLRenderTarget();
  9866. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  9867. /**
  9868. * @author mr.doob / http://mrdoob.com/
  9869. */
  9870. THREE.RenderableVertex = function () {
  9871. this.positionWorld = new THREE.Vector3();
  9872. this.positionScreen = new THREE.Vector4();
  9873. this.visible = true;
  9874. };
  9875. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  9876. this.positionWorld.copy( vertex.positionWorld );
  9877. this.positionScreen.copy( vertex.positionScreen );
  9878. }
  9879. /**
  9880. * @author mr.doob / http://mrdoob.com/
  9881. */
  9882. THREE.RenderableFace3 = function () {
  9883. this.v1 = new THREE.RenderableVertex();
  9884. this.v2 = new THREE.RenderableVertex();
  9885. this.v3 = new THREE.RenderableVertex();
  9886. this.centroidWorld = new THREE.Vector3();
  9887. this.centroidScreen = new THREE.Vector3();
  9888. this.normalWorld = new THREE.Vector3();
  9889. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  9890. this.material = null;
  9891. this.faceMaterial = null;
  9892. this.uvs = [[]];
  9893. this.z = null;
  9894. };
  9895. /**
  9896. * @author mr.doob / http://mrdoob.com/
  9897. */
  9898. THREE.RenderableFace4 = function () {
  9899. this.v1 = new THREE.RenderableVertex();
  9900. this.v2 = new THREE.RenderableVertex();
  9901. this.v3 = new THREE.RenderableVertex();
  9902. this.v4 = new THREE.RenderableVertex();
  9903. this.centroidWorld = new THREE.Vector3();
  9904. this.centroidScreen = new THREE.Vector3();
  9905. this.normalWorld = new THREE.Vector3();
  9906. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  9907. this.material = null;
  9908. this.faceMaterial = null;
  9909. this.uvs = [[]];
  9910. this.z = null;
  9911. };
  9912. /**
  9913. * @author mr.doob / http://mrdoob.com/
  9914. */
  9915. THREE.RenderableObject = function () {
  9916. this.object = null;
  9917. this.z = null;
  9918. };
  9919. /**
  9920. * @author mr.doob / http://mrdoob.com/
  9921. */
  9922. THREE.RenderableParticle = function () {
  9923. this.x = null;
  9924. this.y = null;
  9925. this.z = null;
  9926. this.rotation = null;
  9927. this.scale = new THREE.Vector2();
  9928. this.material = null;
  9929. };
  9930. /**
  9931. * @author mr.doob / http://mrdoob.com/
  9932. */
  9933. THREE.RenderableLine = function () {
  9934. this.z = null;
  9935. this.v1 = new THREE.RenderableVertex();
  9936. this.v2 = new THREE.RenderableVertex();
  9937. this.material = null;
  9938. };
  9939. /**
  9940. * @author alteredq / http://alteredqualia.com/
  9941. */
  9942. THREE.ColorUtils = {
  9943. adjustHSV : function ( color, h, s, v ) {
  9944. var hsv = THREE.ColorUtils.__hsv;
  9945. THREE.ColorUtils.rgbToHsv( color, hsv );
  9946. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  9947. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  9948. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  9949. color.setHSV( hsv.h, hsv.s, hsv.v );
  9950. },
  9951. // based on MochiKit implementation by Bob Ippolito
  9952. rgbToHsv : function ( color, hsv ) {
  9953. var r = color.r;
  9954. var g = color.g;
  9955. var b = color.b;
  9956. var max = Math.max( Math.max( r, g ), b );
  9957. var min = Math.min( Math.min( r, g ), b );
  9958. var hue;
  9959. var saturation;
  9960. var value = max;
  9961. if ( min === max ) {
  9962. hue = 0;
  9963. saturation = 0;
  9964. } else {
  9965. var delta = ( max - min );
  9966. saturation = delta / max;
  9967. if ( r === max ) {
  9968. hue = ( g - b ) / delta;
  9969. } else if ( g === max ) {
  9970. hue = 2 + ( ( b - r ) / delta );
  9971. } else {
  9972. hue = 4 + ( ( r - g ) / delta );
  9973. }
  9974. hue /= 6;
  9975. if ( hue < 0 ) {
  9976. hue += 1;
  9977. }
  9978. if ( hue > 1 ) {
  9979. hue -= 1;
  9980. }
  9981. }
  9982. if ( hsv === undefined ) {
  9983. hsv = { h: 0, s: 0, v: 0 };
  9984. }
  9985. hsv.h = hue;
  9986. hsv.s = saturation;
  9987. hsv.v = value;
  9988. return hsv;
  9989. }
  9990. };
  9991. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  9992. * @author mrdoob / http://mrdoob.com/
  9993. * @author alteredq / http://alteredqualia.com/
  9994. */
  9995. THREE.GeometryUtils = {
  9996. // Merge two geometries or geometry and geometry from object (using object's transform)
  9997. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  9998. var matrix, matrixRotation,
  9999. vertexOffset = geometry1.vertices.length,
  10000. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  10001. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  10002. vertices1 = geometry1.vertices,
  10003. vertices2 = geometry2.vertices,
  10004. faces1 = geometry1.faces,
  10005. faces2 = geometry2.faces,
  10006. uvs1 = geometry1.faceVertexUvs[ 0 ],
  10007. uvs2 = geometry2.faceVertexUvs[ 0 ];
  10008. var geo1MaterialsMap = {};
  10009. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  10010. var id = geometry1.materials[ i ].id;
  10011. geo1MaterialsMap[ id ] = i;
  10012. }
  10013. if ( object2 instanceof THREE.Mesh ) {
  10014. object2.matrixAutoUpdate && object2.updateMatrix();
  10015. matrix = object2.matrix;
  10016. matrixRotation = new THREE.Matrix4();
  10017. matrixRotation.extractRotation( matrix, object2.scale );
  10018. }
  10019. // vertices
  10020. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  10021. var vertex = vertices2[ i ];
  10022. var vertexCopy = vertex.clone();
  10023. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  10024. vertices1.push( vertexCopy );
  10025. }
  10026. // faces
  10027. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  10028. var face = faces2[ i ], faceCopy, normal, color,
  10029. faceVertexNormals = face.vertexNormals,
  10030. faceVertexColors = face.vertexColors;
  10031. if ( face instanceof THREE.Face3 ) {
  10032. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  10033. } else if ( face instanceof THREE.Face4 ) {
  10034. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  10035. }
  10036. faceCopy.normal.copy( face.normal );
  10037. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  10038. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  10039. normal = faceVertexNormals[ j ].clone();
  10040. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  10041. faceCopy.vertexNormals.push( normal );
  10042. }
  10043. faceCopy.color.copy( face.color );
  10044. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  10045. color = faceVertexColors[ j ];
  10046. faceCopy.vertexColors.push( color.clone() );
  10047. }
  10048. if ( face.materialIndex !== undefined ) {
  10049. var material2 = geometry2.materials[ face.materialIndex ];
  10050. var materialId2 = material2.id;
  10051. var materialIndex = geo1MaterialsMap[ materialId2 ];
  10052. if ( materialIndex === undefined ) {
  10053. materialIndex = geometry1.materials.length;
  10054. geo1MaterialsMap[ materialId2 ] = materialIndex;
  10055. geometry1.materials.push( material2 );
  10056. }
  10057. faceCopy.materialIndex = materialIndex;
  10058. }
  10059. faceCopy.centroid.copy( face.centroid );
  10060. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  10061. faces1.push( faceCopy );
  10062. }
  10063. // uvs
  10064. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  10065. var uv = uvs2[ i ], uvCopy = [];
  10066. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  10067. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  10068. }
  10069. uvs1.push( uvCopy );
  10070. }
  10071. },
  10072. clone: function ( geometry ) {
  10073. var cloneGeo = new THREE.Geometry();
  10074. var i, il;
  10075. var vertices = geometry.vertices,
  10076. faces = geometry.faces,
  10077. uvs = geometry.faceVertexUvs[ 0 ];
  10078. // materials
  10079. if ( geometry.materials ) {
  10080. cloneGeo.materials = geometry.materials.slice();
  10081. }
  10082. // vertices
  10083. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  10084. var vertex = vertices[ i ];
  10085. cloneGeo.vertices.push( vertex.clone() );
  10086. }
  10087. // faces
  10088. for ( i = 0, il = faces.length; i < il; i ++ ) {
  10089. var face = faces[ i ];
  10090. cloneGeo.faces.push( face.clone() );
  10091. }
  10092. // uvs
  10093. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  10094. var uv = uvs[ i ], uvCopy = [];
  10095. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  10096. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  10097. }
  10098. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  10099. }
  10100. return cloneGeo;
  10101. },
  10102. // Get random point in triangle (via barycentric coordinates)
  10103. // (uniform distribution)
  10104. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  10105. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  10106. var a, b, c,
  10107. point = new THREE.Vector3(),
  10108. tmp = THREE.GeometryUtils.__v1;
  10109. a = THREE.GeometryUtils.random();
  10110. b = THREE.GeometryUtils.random();
  10111. if ( ( a + b ) > 1 ) {
  10112. a = 1 - a;
  10113. b = 1 - b;
  10114. }
  10115. c = 1 - a - b;
  10116. point.copy( vectorA );
  10117. point.multiplyScalar( a );
  10118. tmp.copy( vectorB );
  10119. tmp.multiplyScalar( b );
  10120. point.addSelf( tmp );
  10121. tmp.copy( vectorC );
  10122. tmp.multiplyScalar( c );
  10123. point.addSelf( tmp );
  10124. return point;
  10125. },
  10126. // Get random point in face (triangle / quad)
  10127. // (uniform distribution)
  10128. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  10129. var vA, vB, vC, vD;
  10130. if ( face instanceof THREE.Face3 ) {
  10131. vA = geometry.vertices[ face.a ];
  10132. vB = geometry.vertices[ face.b ];
  10133. vC = geometry.vertices[ face.c ];
  10134. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  10135. } else if ( face instanceof THREE.Face4 ) {
  10136. vA = geometry.vertices[ face.a ];
  10137. vB = geometry.vertices[ face.b ];
  10138. vC = geometry.vertices[ face.c ];
  10139. vD = geometry.vertices[ face.d ];
  10140. var area1, area2;
  10141. if ( useCachedAreas ) {
  10142. if ( face._area1 && face._area2 ) {
  10143. area1 = face._area1;
  10144. area2 = face._area2;
  10145. } else {
  10146. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  10147. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  10148. face._area1 = area1;
  10149. face._area2 = area2;
  10150. }
  10151. } else {
  10152. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  10153. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  10154. }
  10155. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  10156. if ( r < area1 ) {
  10157. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  10158. } else {
  10159. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  10160. }
  10161. }
  10162. },
  10163. // Get uniformly distributed random points in mesh
  10164. // - create array with cumulative sums of face areas
  10165. // - pick random number from 0 to total area
  10166. // - find corresponding place in area array by binary search
  10167. // - get random point in face
  10168. randomPointsInGeometry: function ( geometry, n ) {
  10169. var face, i,
  10170. faces = geometry.faces,
  10171. vertices = geometry.vertices,
  10172. il = faces.length,
  10173. totalArea = 0,
  10174. cumulativeAreas = [],
  10175. vA, vB, vC, vD;
  10176. // precompute face areas
  10177. for ( i = 0; i < il; i ++ ) {
  10178. face = faces[ i ];
  10179. if ( face instanceof THREE.Face3 ) {
  10180. vA = vertices[ face.a ];
  10181. vB = vertices[ face.b ];
  10182. vC = vertices[ face.c ];
  10183. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  10184. } else if ( face instanceof THREE.Face4 ) {
  10185. vA = vertices[ face.a ];
  10186. vB = vertices[ face.b ];
  10187. vC = vertices[ face.c ];
  10188. vD = vertices[ face.d ];
  10189. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  10190. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  10191. face._area = face._area1 + face._area2;
  10192. }
  10193. totalArea += face._area;
  10194. cumulativeAreas[ i ] = totalArea;
  10195. }
  10196. // binary search cumulative areas array
  10197. function binarySearchIndices( value ) {
  10198. function binarySearch( start, end ) {
  10199. // return closest larger index
  10200. // if exact number is not found
  10201. if ( end < start )
  10202. return start;
  10203. var mid = start + Math.floor( ( end - start ) / 2 );
  10204. if ( cumulativeAreas[ mid ] > value ) {
  10205. return binarySearch( start, mid - 1 );
  10206. } else if ( cumulativeAreas[ mid ] < value ) {
  10207. return binarySearch( mid + 1, end );
  10208. } else {
  10209. return mid;
  10210. }
  10211. }
  10212. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  10213. return result;
  10214. }
  10215. // pick random face weighted by face area
  10216. var r, index,
  10217. result = [];
  10218. var stats = {};
  10219. for ( i = 0; i < n; i ++ ) {
  10220. r = THREE.GeometryUtils.random() * totalArea;
  10221. index = binarySearchIndices( r );
  10222. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  10223. if ( ! stats[ index ] ) {
  10224. stats[ index ] = 1;
  10225. } else {
  10226. stats[ index ] += 1;
  10227. }
  10228. }
  10229. return result;
  10230. },
  10231. // Get triangle area (by Heron's formula)
  10232. // http://en.wikipedia.org/wiki/Heron%27s_formula
  10233. triangleArea: function ( vectorA, vectorB, vectorC ) {
  10234. var s, a, b, c,
  10235. tmp = THREE.GeometryUtils.__v1;
  10236. tmp.sub( vectorA, vectorB );
  10237. a = tmp.length();
  10238. tmp.sub( vectorA, vectorC );
  10239. b = tmp.length();
  10240. tmp.sub( vectorB, vectorC );
  10241. c = tmp.length();
  10242. s = 0.5 * ( a + b + c );
  10243. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  10244. },
  10245. // Center geometry so that 0,0,0 is in center of bounding box
  10246. center: function ( geometry ) {
  10247. geometry.computeBoundingBox();
  10248. var bb = geometry.boundingBox;
  10249. var offset = new THREE.Vector3();
  10250. offset.add( bb.min, bb.max );
  10251. offset.multiplyScalar( -0.5 );
  10252. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  10253. geometry.computeBoundingBox();
  10254. return offset;
  10255. },
  10256. // Normalize UVs to be from <0,1>
  10257. // (for now just the first set of UVs)
  10258. normalizeUVs: function ( geometry ) {
  10259. var uvSet = geometry.faceVertexUvs[ 0 ];
  10260. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  10261. var uvs = uvSet[ i ];
  10262. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  10263. // texture repeat
  10264. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  10265. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  10266. }
  10267. }
  10268. },
  10269. triangulateQuads: function ( geometry ) {
  10270. var i, il, j, jl;
  10271. var faces = [];
  10272. var faceUvs = [];
  10273. var faceVertexUvs = [];
  10274. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  10275. faceUvs[ i ] = [];
  10276. }
  10277. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  10278. faceVertexUvs[ i ] = [];
  10279. }
  10280. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  10281. var face = geometry.faces[ i ];
  10282. if ( face instanceof THREE.Face4 ) {
  10283. var a = face.a;
  10284. var b = face.b;
  10285. var c = face.c;
  10286. var d = face.d;
  10287. var triA = new THREE.Face3();
  10288. var triB = new THREE.Face3();
  10289. triA.color.copy( face.color );
  10290. triB.color.copy( face.color );
  10291. triA.materialIndex = face.materialIndex;
  10292. triB.materialIndex = face.materialIndex;
  10293. triA.a = a;
  10294. triA.b = b;
  10295. triA.c = d;
  10296. triB.a = b;
  10297. triB.b = c;
  10298. triB.c = d;
  10299. if ( face.vertexColors.length === 4 ) {
  10300. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  10301. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  10302. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  10303. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  10304. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  10305. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  10306. }
  10307. faces.push( triA, triB );
  10308. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10309. if ( geometry.faceVertexUvs[ j ].length ) {
  10310. var uvs = geometry.faceVertexUvs[ j ][ i ];
  10311. var uvA = uvs[ 0 ];
  10312. var uvB = uvs[ 1 ];
  10313. var uvC = uvs[ 2 ];
  10314. var uvD = uvs[ 3 ];
  10315. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  10316. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  10317. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  10318. }
  10319. }
  10320. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  10321. if ( geometry.faceUvs[ j ].length ) {
  10322. var faceUv = geometry.faceUvs[ j ][ i ];
  10323. faceUvs[ j ].push( faceUv, faceUv );
  10324. }
  10325. }
  10326. } else {
  10327. faces.push( face );
  10328. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  10329. faceUvs[ j ].push( geometry.faceUvs[ j ] );
  10330. }
  10331. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10332. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  10333. }
  10334. }
  10335. }
  10336. geometry.faces = faces;
  10337. geometry.faceUvs = faceUvs;
  10338. geometry.faceVertexUvs = faceVertexUvs;
  10339. geometry.computeCentroids();
  10340. geometry.computeFaceNormals();
  10341. geometry.computeVertexNormals();
  10342. if ( geometry.hasTangents ) geometry.computeTangents();
  10343. },
  10344. // Make all faces use unique vertices
  10345. // so that each face can be separated from others
  10346. explode: function( geometry ) {
  10347. var vertices = [];
  10348. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  10349. var n = vertices.length;
  10350. var face = geometry.faces[ i ];
  10351. if ( face instanceof THREE.Face4 ) {
  10352. var a = face.a;
  10353. var b = face.b;
  10354. var c = face.c;
  10355. var d = face.d;
  10356. var va = geometry.vertices[ a ];
  10357. var vb = geometry.vertices[ b ];
  10358. var vc = geometry.vertices[ c ];
  10359. var vd = geometry.vertices[ d ];
  10360. vertices.push( va.clone() );
  10361. vertices.push( vb.clone() );
  10362. vertices.push( vc.clone() );
  10363. vertices.push( vd.clone() );
  10364. face.a = n;
  10365. face.b = n + 1;
  10366. face.c = n + 2;
  10367. face.d = n + 3;
  10368. } else {
  10369. var a = face.a;
  10370. var b = face.b;
  10371. var c = face.c;
  10372. var va = geometry.vertices[ a ];
  10373. var vb = geometry.vertices[ b ];
  10374. var vc = geometry.vertices[ c ];
  10375. vertices.push( va.clone() );
  10376. vertices.push( vb.clone() );
  10377. vertices.push( vc.clone() );
  10378. face.a = n;
  10379. face.b = n + 1;
  10380. face.c = n + 2;
  10381. }
  10382. }
  10383. geometry.vertices = vertices;
  10384. delete geometry.__tmpVertices;
  10385. },
  10386. // Break faces with edges longer than maxEdgeLength
  10387. // - not recursive
  10388. tessellate: function ( geometry, maxEdgeLength ) {
  10389. var i, il, face,
  10390. a, b, c, d,
  10391. va, vb, vc, vd,
  10392. dab, dbc, dac, dcd, dad,
  10393. m, m1, m2,
  10394. vm, vm1, vm2,
  10395. vnm, vnm1, vnm2,
  10396. vcm, vcm1, vcm2,
  10397. triA, triB,
  10398. quadA, quadB,
  10399. edge;
  10400. var faces = [];
  10401. var faceVertexUvs = [];
  10402. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  10403. faceVertexUvs[ i ] = [];
  10404. }
  10405. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  10406. face = geometry.faces[ i ];
  10407. if ( face instanceof THREE.Face3 ) {
  10408. a = face.a;
  10409. b = face.b;
  10410. c = face.c;
  10411. va = geometry.vertices[ a ];
  10412. vb = geometry.vertices[ b ];
  10413. vc = geometry.vertices[ c ];
  10414. dab = va.distanceTo( vb );
  10415. dbc = vb.distanceTo( vc );
  10416. dac = va.distanceTo( vc );
  10417. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  10418. m = geometry.vertices.length;
  10419. triA = face.clone();
  10420. triB = face.clone();
  10421. if ( dab >= dbc && dab >= dac ) {
  10422. vm = va.clone();
  10423. vm.lerpSelf( vb, 0.5 );
  10424. triA.a = a;
  10425. triA.b = m;
  10426. triA.c = c;
  10427. triB.a = m;
  10428. triB.b = b;
  10429. triB.c = c;
  10430. if ( face.vertexNormals.length === 3 ) {
  10431. vnm = face.vertexNormals[ 0 ].clone();
  10432. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  10433. triA.vertexNormals[ 1 ].copy( vnm );
  10434. triB.vertexNormals[ 0 ].copy( vnm );
  10435. }
  10436. if ( face.vertexColors.length === 3 ) {
  10437. vcm = face.vertexColors[ 0 ].clone();
  10438. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  10439. triA.vertexColors[ 1 ].copy( vcm );
  10440. triB.vertexColors[ 0 ].copy( vcm );
  10441. }
  10442. edge = 0;
  10443. } else if ( dbc >= dab && dbc >= dac ) {
  10444. vm = vb.clone();
  10445. vm.lerpSelf( vc, 0.5 );
  10446. triA.a = a;
  10447. triA.b = b;
  10448. triA.c = m;
  10449. triB.a = m;
  10450. triB.b = c;
  10451. triB.c = a;
  10452. if ( face.vertexNormals.length === 3 ) {
  10453. vnm = face.vertexNormals[ 1 ].clone();
  10454. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  10455. triA.vertexNormals[ 2 ].copy( vnm );
  10456. triB.vertexNormals[ 0 ].copy( vnm );
  10457. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  10458. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  10459. }
  10460. if ( face.vertexColors.length === 3 ) {
  10461. vcm = face.vertexColors[ 1 ].clone();
  10462. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  10463. triA.vertexColors[ 2 ].copy( vcm );
  10464. triB.vertexColors[ 0 ].copy( vcm );
  10465. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  10466. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  10467. }
  10468. edge = 1;
  10469. } else {
  10470. vm = va.clone();
  10471. vm.lerpSelf( vc, 0.5 );
  10472. triA.a = a;
  10473. triA.b = b;
  10474. triA.c = m;
  10475. triB.a = m;
  10476. triB.b = b;
  10477. triB.c = c;
  10478. if ( face.vertexNormals.length === 3 ) {
  10479. vnm = face.vertexNormals[ 0 ].clone();
  10480. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  10481. triA.vertexNormals[ 2 ].copy( vnm );
  10482. triB.vertexNormals[ 0 ].copy( vnm );
  10483. }
  10484. if ( face.vertexColors.length === 3 ) {
  10485. vcm = face.vertexColors[ 0 ].clone();
  10486. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  10487. triA.vertexColors[ 2 ].copy( vcm );
  10488. triB.vertexColors[ 0 ].copy( vcm );
  10489. }
  10490. edge = 2;
  10491. }
  10492. faces.push( triA, triB );
  10493. geometry.vertices.push( vm );
  10494. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  10495. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10496. if ( geometry.faceVertexUvs[ j ].length ) {
  10497. uvs = geometry.faceVertexUvs[ j ][ i ];
  10498. uvA = uvs[ 0 ];
  10499. uvB = uvs[ 1 ];
  10500. uvC = uvs[ 2 ];
  10501. // AB
  10502. if ( edge === 0 ) {
  10503. uvM = uvA.clone();
  10504. uvM.lerpSelf( uvB, 0.5 );
  10505. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  10506. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  10507. // BC
  10508. } else if ( edge === 1 ) {
  10509. uvM = uvB.clone();
  10510. uvM.lerpSelf( uvC, 0.5 );
  10511. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  10512. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  10513. // AC
  10514. } else {
  10515. uvM = uvA.clone();
  10516. uvM.lerpSelf( uvC, 0.5 );
  10517. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  10518. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  10519. }
  10520. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  10521. }
  10522. }
  10523. } else {
  10524. faces.push( face );
  10525. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10526. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  10527. }
  10528. }
  10529. } else {
  10530. a = face.a;
  10531. b = face.b;
  10532. c = face.c;
  10533. d = face.d;
  10534. va = geometry.vertices[ a ];
  10535. vb = geometry.vertices[ b ];
  10536. vc = geometry.vertices[ c ];
  10537. vd = geometry.vertices[ d ];
  10538. dab = va.distanceTo( vb );
  10539. dbc = vb.distanceTo( vc );
  10540. dcd = vc.distanceTo( vd );
  10541. dad = va.distanceTo( vd );
  10542. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  10543. m1 = geometry.vertices.length;
  10544. m2 = geometry.vertices.length + 1;
  10545. quadA = face.clone();
  10546. quadB = face.clone();
  10547. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  10548. vm1 = va.clone();
  10549. vm1.lerpSelf( vb, 0.5 );
  10550. vm2 = vc.clone();
  10551. vm2.lerpSelf( vd, 0.5 );
  10552. quadA.a = a;
  10553. quadA.b = m1;
  10554. quadA.c = m2;
  10555. quadA.d = d;
  10556. quadB.a = m1;
  10557. quadB.b = b;
  10558. quadB.c = c;
  10559. quadB.d = m2;
  10560. if ( face.vertexNormals.length === 4 ) {
  10561. vnm1 = face.vertexNormals[ 0 ].clone();
  10562. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  10563. vnm2 = face.vertexNormals[ 2 ].clone();
  10564. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  10565. quadA.vertexNormals[ 1 ].copy( vnm1 );
  10566. quadA.vertexNormals[ 2 ].copy( vnm2 );
  10567. quadB.vertexNormals[ 0 ].copy( vnm1 );
  10568. quadB.vertexNormals[ 3 ].copy( vnm2 );
  10569. }
  10570. if ( face.vertexColors.length === 4 ) {
  10571. vcm1 = face.vertexColors[ 0 ].clone();
  10572. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  10573. vcm2 = face.vertexColors[ 2 ].clone();
  10574. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  10575. quadA.vertexColors[ 1 ].copy( vcm1 );
  10576. quadA.vertexColors[ 2 ].copy( vcm2 );
  10577. quadB.vertexColors[ 0 ].copy( vcm1 );
  10578. quadB.vertexColors[ 3 ].copy( vcm2 );
  10579. }
  10580. edge = 0;
  10581. } else {
  10582. vm1 = vb.clone();
  10583. vm1.lerpSelf( vc, 0.5 );
  10584. vm2 = vd.clone();
  10585. vm2.lerpSelf( va, 0.5 );
  10586. quadA.a = a;
  10587. quadA.b = b;
  10588. quadA.c = m1;
  10589. quadA.d = m2;
  10590. quadB.a = m2;
  10591. quadB.b = m1;
  10592. quadB.c = c;
  10593. quadB.d = d;
  10594. if ( face.vertexNormals.length === 4 ) {
  10595. vnm1 = face.vertexNormals[ 1 ].clone();
  10596. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  10597. vnm2 = face.vertexNormals[ 3 ].clone();
  10598. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  10599. quadA.vertexNormals[ 2 ].copy( vnm1 );
  10600. quadA.vertexNormals[ 3 ].copy( vnm2 );
  10601. quadB.vertexNormals[ 0 ].copy( vnm2 );
  10602. quadB.vertexNormals[ 1 ].copy( vnm1 );
  10603. }
  10604. if ( face.vertexColors.length === 4 ) {
  10605. vcm1 = face.vertexColors[ 1 ].clone();
  10606. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  10607. vcm2 = face.vertexColors[ 3 ].clone();
  10608. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  10609. quadA.vertexColors[ 2 ].copy( vcm1 );
  10610. quadA.vertexColors[ 3 ].copy( vcm2 );
  10611. quadB.vertexColors[ 0 ].copy( vcm2 );
  10612. quadB.vertexColors[ 1 ].copy( vcm1 );
  10613. }
  10614. edge = 1;
  10615. }
  10616. faces.push( quadA, quadB );
  10617. geometry.vertices.push( vm1, vm2 );
  10618. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  10619. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10620. if ( geometry.faceVertexUvs[ j ].length ) {
  10621. uvs = geometry.faceVertexUvs[ j ][ i ];
  10622. uvA = uvs[ 0 ];
  10623. uvB = uvs[ 1 ];
  10624. uvC = uvs[ 2 ];
  10625. uvD = uvs[ 3 ];
  10626. // AB + CD
  10627. if ( edge === 0 ) {
  10628. uvM1 = uvA.clone();
  10629. uvM1.lerpSelf( uvB, 0.5 );
  10630. uvM2 = uvC.clone();
  10631. uvM2.lerpSelf( uvD, 0.5 );
  10632. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  10633. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  10634. // BC + AD
  10635. } else {
  10636. uvM1 = uvB.clone();
  10637. uvM1.lerpSelf( uvC, 0.5 );
  10638. uvM2 = uvD.clone();
  10639. uvM2.lerpSelf( uvA, 0.5 );
  10640. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  10641. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  10642. }
  10643. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  10644. }
  10645. }
  10646. } else {
  10647. faces.push( face );
  10648. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10649. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  10650. }
  10651. }
  10652. }
  10653. }
  10654. geometry.faces = faces;
  10655. geometry.faceVertexUvs = faceVertexUvs;
  10656. }
  10657. };
  10658. THREE.GeometryUtils.random = THREE.Math.random16;
  10659. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  10660. /**
  10661. * @author alteredq / http://alteredqualia.com/
  10662. * @author mrdoob / http://mrdoob.com/
  10663. */
  10664. THREE.ImageUtils = {
  10665. crossOrigin: 'anonymous',
  10666. loadTexture: function ( path, mapping, callback ) {
  10667. var image = new Image(), texture = new THREE.Texture( image, mapping );
  10668. image.onload = function () { texture.needsUpdate = true; if ( callback ) callback( this ); };
  10669. image.crossOrigin = this.crossOrigin;
  10670. image.src = path;
  10671. return texture;
  10672. },
  10673. loadTextureCube: function ( array, mapping, callback ) {
  10674. var i, l, images = [], texture = new THREE.Texture( images, mapping );
  10675. images.loadCount = 0;
  10676. for ( i = 0, l = array.length; i < l; ++ i ) {
  10677. images[ i ] = new Image();
  10678. images[ i ].onload = function () {
  10679. images.loadCount += 1;
  10680. if ( images.loadCount === 6 ) texture.needsUpdate = true;
  10681. if ( callback ) callback( this );
  10682. };
  10683. images[ i ].crossOrigin = this.crossOrigin;
  10684. images[ i ].src = array[ i ];
  10685. }
  10686. return texture;
  10687. },
  10688. getNormalMap: function ( image, depth ) {
  10689. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  10690. var cross = function ( a, b ) {
  10691. 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 ] ];
  10692. }
  10693. var subtract = function ( a, b ) {
  10694. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  10695. }
  10696. var normalize = function ( a ) {
  10697. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  10698. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  10699. }
  10700. depth = depth | 1;
  10701. var width = image.width;
  10702. var height = image.height;
  10703. var canvas = document.createElement( 'canvas' );
  10704. canvas.width = width;
  10705. canvas.height = height;
  10706. var context = canvas.getContext( '2d' );
  10707. context.drawImage( image, 0, 0 );
  10708. var data = context.getImageData( 0, 0, width, height ).data;
  10709. var imageData = context.createImageData( width, height );
  10710. var output = imageData.data;
  10711. for ( var x = 0; x < width; x ++ ) {
  10712. for ( var y = 1; y < height; y ++ ) {
  10713. var ly = y - 1 < 0 ? height - 1 : y - 1;
  10714. var uy = ( y + 1 ) % height;
  10715. var lx = x - 1 < 0 ? width - 1 : x - 1;
  10716. var ux = ( x + 1 ) % width;
  10717. var points = [];
  10718. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  10719. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  10720. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  10721. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  10722. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  10723. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  10724. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  10725. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  10726. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  10727. var normals = [];
  10728. var num_points = points.length;
  10729. for ( var i = 0; i < num_points; i ++ ) {
  10730. var v1 = points[ i ];
  10731. var v2 = points[ ( i + 1 ) % num_points ];
  10732. v1 = subtract( v1, origin );
  10733. v2 = subtract( v2, origin );
  10734. normals.push( normalize( cross( v1, v2 ) ) );
  10735. }
  10736. var normal = [ 0, 0, 0 ];
  10737. for ( var i = 0; i < normals.length; i ++ ) {
  10738. normal[ 0 ] += normals[ i ][ 0 ];
  10739. normal[ 1 ] += normals[ i ][ 1 ];
  10740. normal[ 2 ] += normals[ i ][ 2 ];
  10741. }
  10742. normal[ 0 ] /= normals.length;
  10743. normal[ 1 ] /= normals.length;
  10744. normal[ 2 ] /= normals.length;
  10745. var idx = ( y * width + x ) * 4;
  10746. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  10747. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 / 2.0 ) * 255 ) | 0;
  10748. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  10749. output[ idx + 3 ] = 255;
  10750. }
  10751. }
  10752. context.putImageData( imageData, 0, 0 );
  10753. return canvas;
  10754. },
  10755. generateDataTexture: function ( width, height, color ) {
  10756. var size = width * height;
  10757. var data = new Uint8Array( 3 * size );
  10758. var r = Math.floor( color.r * 255 );
  10759. var g = Math.floor( color.g * 255 );
  10760. var b = Math.floor( color.b * 255 );
  10761. for ( var i = 0; i < size; i ++ ) {
  10762. data[ i * 3 ] = r;
  10763. data[ i * 3 + 1 ] = g;
  10764. data[ i * 3 + 2 ] = b;
  10765. }
  10766. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  10767. texture.needsUpdate = true;
  10768. return texture;
  10769. }
  10770. };
  10771. /**
  10772. * @author alteredq / http://alteredqualia.com/
  10773. */
  10774. THREE.SceneUtils = {
  10775. showHierarchy : function ( root, visible ) {
  10776. THREE.SceneUtils.traverseHierarchy( root, function( node ) { node.visible = visible; } );
  10777. },
  10778. traverseHierarchy : function ( root, callback ) {
  10779. var n, i, l = root.children.length;
  10780. for ( i = 0; i < l; i ++ ) {
  10781. n = root.children[ i ];
  10782. callback( n );
  10783. THREE.SceneUtils.traverseHierarchy( n, callback );
  10784. }
  10785. },
  10786. createMultiMaterialObject : function ( geometry, materials ) {
  10787. var i, il = materials.length,
  10788. group = new THREE.Object3D();
  10789. for ( i = 0; i < il; i ++ ) {
  10790. var object = new THREE.Mesh( geometry, materials[ i ] );
  10791. group.add( object );
  10792. }
  10793. return group;
  10794. },
  10795. cloneObject: function ( source ) {
  10796. var object;
  10797. // subclass specific properties
  10798. // (must process in order from more specific subclasses to more abstract classes)
  10799. if ( source instanceof THREE.MorphAnimMesh ) {
  10800. object = new THREE.MorphAnimMesh( source.geometry, source.material );
  10801. object.duration = source.duration;
  10802. object.mirroredLoop = source.mirroredLoop;
  10803. object.time = source.time;
  10804. object.lastKeyframe = source.lastKeyframe;
  10805. object.currentKeyframe = source.currentKeyframe;
  10806. object.direction = source.direction;
  10807. object.directionBackwards = source.directionBackwards;
  10808. } else if ( source instanceof THREE.SkinnedMesh ) {
  10809. object = new THREE.SkinnedMesh( source.geometry, source.material );
  10810. } else if ( source instanceof THREE.Mesh ) {
  10811. object = new THREE.Mesh( source.geometry, source.material );
  10812. } else if ( source instanceof THREE.Line ) {
  10813. object = new THREE.Line( source.geometry, source.material, source.type );
  10814. } else if ( source instanceof THREE.Ribbon ) {
  10815. object = new THREE.Ribbon( source.geometry, source.material );
  10816. } else if ( source instanceof THREE.ParticleSystem ) {
  10817. object = new THREE.ParticleSystem( source.geometry, source.material );
  10818. object.sortParticles = source.sortParticles;
  10819. } else if ( source instanceof THREE.Particle ) {
  10820. object = new THREE.Particle( source.material );
  10821. } else if ( source instanceof THREE.Sprite ) {
  10822. object = new THREE.Sprite( {} );
  10823. object.color.copy( source.color );
  10824. object.map = source.map;
  10825. object.blending = source.blending;
  10826. object.useScreenCoordinates = source.useScreenCoordinates;
  10827. object.mergeWith3D = source.mergeWith3D;
  10828. object.affectedByDistance = source.affectedByDistance;
  10829. object.scaleByViewport = source.scaleByViewport;
  10830. object.alignment = source.alignment;
  10831. object.rotation3d.copy( source.rotation3d );
  10832. object.rotation = source.rotation;
  10833. object.opacity = source.opacity;
  10834. object.uvOffset.copy( source.uvOffset );
  10835. object.uvScale.copy( source.uvScale);
  10836. } else if ( source instanceof THREE.LOD ) {
  10837. object = new THREE.LOD();
  10838. } else if ( source instanceof THREE.MarchingCubes ) {
  10839. object = new THREE.MarchingCubes( source.resolution, source.material );
  10840. object.field.set( source.field );
  10841. object.isolation = source.isolation;
  10842. } else if ( source instanceof THREE.Object3D ) {
  10843. object = new THREE.Object3D();
  10844. }
  10845. // base class properties
  10846. object.name = source.name;
  10847. object.parent = source.parent;
  10848. object.up.copy( source.up );
  10849. object.position.copy( source.position );
  10850. // because of Sprite madness
  10851. if ( object.rotation instanceof THREE.Vector3 )
  10852. object.rotation.copy( source.rotation );
  10853. object.eulerOrder = source.eulerOrder;
  10854. object.scale.copy( source.scale );
  10855. object.dynamic = source.dynamic;
  10856. object.doubleSided = source.doubleSided;
  10857. object.flipSided = source.flipSided;
  10858. object.renderDepth = source.renderDepth;
  10859. object.rotationAutoUpdate = source.rotationAutoUpdate;
  10860. object.matrix.copy( source.matrix );
  10861. object.matrixWorld.copy( source.matrixWorld );
  10862. object.matrixRotationWorld.copy( source.matrixRotationWorld );
  10863. object.matrixAutoUpdate = source.matrixAutoUpdate;
  10864. object.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10865. object.quaternion.copy( source.quaternion );
  10866. object.useQuaternion = source.useQuaternion;
  10867. object.boundRadius = source.boundRadius;
  10868. object.boundRadiusScale = source.boundRadiusScale;
  10869. object.visible = source.visible;
  10870. object.castShadow = source.castShadow;
  10871. object.receiveShadow = source.receiveShadow;
  10872. object.frustumCulled = source.frustumCulled;
  10873. // children
  10874. for ( var i = 0; i < source.children.length; i ++ ) {
  10875. var child = THREE.SceneUtils.cloneObject( source.children[ i ] );
  10876. object.children[ i ] = child;
  10877. child.parent = object;
  10878. }
  10879. // LODs need to be patched separately to use cloned children
  10880. if ( source instanceof THREE.LOD ) {
  10881. for ( var i = 0; i < source.LODs.length; i ++ ) {
  10882. var lod = source.LODs[ i ];
  10883. object.LODs[ i ] = { visibleAtDistance: lod.visibleAtDistance, object3D: object.children[ i ] };
  10884. }
  10885. }
  10886. return object;
  10887. },
  10888. detach : function ( child, parent, scene ) {
  10889. child.applyMatrix( parent.matrixWorld );
  10890. parent.remove( child );
  10891. scene.add( child );
  10892. },
  10893. attach: function ( child, scene, parent ) {
  10894. var matrixWorldInverse = new THREE.Matrix4();
  10895. matrixWorldInverse.getInverse( parent.matrixWorld );
  10896. child.applyMatrix( matrixWorldInverse );
  10897. scene.remove( child );
  10898. parent.add( child );
  10899. }
  10900. };
  10901. /**
  10902. * @author alteredq / http://alteredqualia.com/
  10903. * @author mr.doob / http://mrdoob.com/
  10904. *
  10905. * ShaderUtils currently contains:
  10906. *
  10907. * fresnel
  10908. * normal
  10909. * cube
  10910. *
  10911. */
  10912. if ( THREE.WebGLRenderer ) {
  10913. THREE.ShaderUtils = {
  10914. lib: {
  10915. /* -------------------------------------------------------------------------
  10916. // Fresnel shader
  10917. // - based on Nvidia Cg tutorial
  10918. ------------------------------------------------------------------------- */
  10919. 'fresnel': {
  10920. uniforms: {
  10921. "mRefractionRatio": { type: "f", value: 1.02 },
  10922. "mFresnelBias": { type: "f", value: 0.1 },
  10923. "mFresnelPower": { type: "f", value: 2.0 },
  10924. "mFresnelScale": { type: "f", value: 1.0 },
  10925. "tCube": { type: "t", value: 1, texture: null }
  10926. },
  10927. fragmentShader: [
  10928. "uniform samplerCube tCube;",
  10929. "varying vec3 vReflect;",
  10930. "varying vec3 vRefract[3];",
  10931. "varying float vReflectionFactor;",
  10932. "void main() {",
  10933. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  10934. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  10935. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  10936. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  10937. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  10938. "refractedColor.a = 1.0;",
  10939. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  10940. "}"
  10941. ].join("\n"),
  10942. vertexShader: [
  10943. "uniform float mRefractionRatio;",
  10944. "uniform float mFresnelBias;",
  10945. "uniform float mFresnelScale;",
  10946. "uniform float mFresnelPower;",
  10947. "varying vec3 vReflect;",
  10948. "varying vec3 vRefract[3];",
  10949. "varying float vReflectionFactor;",
  10950. "void main() {",
  10951. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10952. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  10953. "vec3 nWorld = normalize ( mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal );",
  10954. "vec3 I = mPosition.xyz - cameraPosition;",
  10955. "vReflect = reflect( I, nWorld );",
  10956. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  10957. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  10958. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  10959. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  10960. "gl_Position = projectionMatrix * mvPosition;",
  10961. "}"
  10962. ].join("\n")
  10963. },
  10964. /* -------------------------------------------------------------------------
  10965. // Normal map shader
  10966. // - Blinn-Phong
  10967. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10968. // - point and directional lights (use with "lights: true" material option)
  10969. ------------------------------------------------------------------------- */
  10970. 'normal' : {
  10971. uniforms: THREE.UniformsUtils.merge( [
  10972. THREE.UniformsLib[ "fog" ],
  10973. THREE.UniformsLib[ "lights" ],
  10974. THREE.UniformsLib[ "shadowmap" ],
  10975. {
  10976. "enableAO" : { type: "i", value: 0 },
  10977. "enableDiffuse" : { type: "i", value: 0 },
  10978. "enableSpecular" : { type: "i", value: 0 },
  10979. "enableReflection": { type: "i", value: 0 },
  10980. "tDiffuse" : { type: "t", value: 0, texture: null },
  10981. "tCube" : { type: "t", value: 1, texture: null },
  10982. "tNormal" : { type: "t", value: 2, texture: null },
  10983. "tSpecular" : { type: "t", value: 3, texture: null },
  10984. "tAO" : { type: "t", value: 4, texture: null },
  10985. "tDisplacement": { type: "t", value: 5, texture: null },
  10986. "uNormalScale": { type: "f", value: 1.0 },
  10987. "uDisplacementBias": { type: "f", value: 0.0 },
  10988. "uDisplacementScale": { type: "f", value: 1.0 },
  10989. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10990. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  10991. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10992. "uShininess": { type: "f", value: 30 },
  10993. "uOpacity": { type: "f", value: 1 },
  10994. "uReflectivity": { type: "f", value: 0.5 },
  10995. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  10996. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10997. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10998. }
  10999. ] ),
  11000. fragmentShader: [
  11001. "uniform vec3 uAmbientColor;",
  11002. "uniform vec3 uDiffuseColor;",
  11003. "uniform vec3 uSpecularColor;",
  11004. "uniform float uShininess;",
  11005. "uniform float uOpacity;",
  11006. "uniform bool enableDiffuse;",
  11007. "uniform bool enableSpecular;",
  11008. "uniform bool enableAO;",
  11009. "uniform bool enableReflection;",
  11010. "uniform sampler2D tDiffuse;",
  11011. "uniform sampler2D tNormal;",
  11012. "uniform sampler2D tSpecular;",
  11013. "uniform sampler2D tAO;",
  11014. "uniform samplerCube tCube;",
  11015. "uniform float uNormalScale;",
  11016. "uniform float uReflectivity;",
  11017. "varying vec3 vTangent;",
  11018. "varying vec3 vBinormal;",
  11019. "varying vec3 vNormal;",
  11020. "varying vec2 vUv;",
  11021. "uniform vec3 ambientLightColor;",
  11022. "#if MAX_DIR_LIGHTS > 0",
  11023. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11024. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11025. "#endif",
  11026. "#if MAX_POINT_LIGHTS > 0",
  11027. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11028. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  11029. "#endif",
  11030. "#ifdef WRAP_AROUND",
  11031. "uniform vec3 wrapRGB;",
  11032. "#endif",
  11033. "varying vec3 vViewPosition;",
  11034. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11035. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11036. "void main() {",
  11037. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11038. "vec3 specularTex = vec3( 1.0 );",
  11039. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11040. "normalTex.xy *= uNormalScale;",
  11041. "normalTex = normalize( normalTex );",
  11042. "if( enableDiffuse ) {",
  11043. "#ifdef GAMMA_INPUT",
  11044. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11045. "texelColor.xyz *= texelColor.xyz;",
  11046. "gl_FragColor = gl_FragColor * texelColor;",
  11047. "#else",
  11048. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11049. "#endif",
  11050. "}",
  11051. "if( enableAO ) {",
  11052. "#ifdef GAMMA_INPUT",
  11053. "vec4 aoColor = texture2D( tAO, vUv );",
  11054. "aoColor.xyz *= aoColor.xyz;",
  11055. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11056. "#else",
  11057. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11058. "#endif",
  11059. "}",
  11060. "if( enableSpecular )",
  11061. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11062. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11063. "vec3 finalNormal = tsb * normalTex;",
  11064. "vec3 normal = normalize( finalNormal );",
  11065. "vec3 viewPosition = normalize( vViewPosition );",
  11066. // point lights
  11067. "#if MAX_POINT_LIGHTS > 0",
  11068. "vec3 pointDiffuse = vec3( 0.0 );",
  11069. "vec3 pointSpecular = vec3( 0.0 );",
  11070. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11071. "vec3 pointVector = normalize( vPointLight[ i ].xyz );",
  11072. "float pointDistance = vPointLight[ i ].w;",
  11073. // diffuse
  11074. "#ifdef WRAP_AROUND",
  11075. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11076. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11077. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11078. "#else",
  11079. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11080. "#endif",
  11081. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11082. // specular
  11083. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11084. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11085. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11086. "#ifdef PHYSICALLY_BASED_SHADING",
  11087. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11088. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11089. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11090. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11091. "#else",
  11092. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11093. "#endif",
  11094. "}",
  11095. "#endif",
  11096. // directional lights
  11097. "#if MAX_DIR_LIGHTS > 0",
  11098. "vec3 dirDiffuse = vec3( 0.0 );",
  11099. "vec3 dirSpecular = vec3( 0.0 );",
  11100. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11101. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11102. "vec3 dirVector = normalize( lDirection.xyz );",
  11103. // diffuse
  11104. "#ifdef WRAP_AROUND",
  11105. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11106. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11107. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11108. "#else",
  11109. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11110. "#endif",
  11111. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11112. // specular
  11113. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11114. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11115. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11116. "#ifdef PHYSICALLY_BASED_SHADING",
  11117. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11118. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11119. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11120. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11121. "#else",
  11122. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11123. "#endif",
  11124. "}",
  11125. "#endif",
  11126. // all lights contribution summation
  11127. "vec3 totalDiffuse = vec3( 0.0 );",
  11128. "vec3 totalSpecular = vec3( 0.0 );",
  11129. "#if MAX_DIR_LIGHTS > 0",
  11130. "totalDiffuse += dirDiffuse;",
  11131. "totalSpecular += dirSpecular;",
  11132. "#endif",
  11133. "#if MAX_POINT_LIGHTS > 0",
  11134. "totalDiffuse += pointDiffuse;",
  11135. "totalSpecular += pointSpecular;",
  11136. "#endif",
  11137. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor) + totalSpecular;",
  11138. "if ( enableReflection ) {",
  11139. "vec3 wPos = cameraPosition - vViewPosition;",
  11140. "vec3 vReflect = reflect( normalize( wPos ), normal );",
  11141. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11142. "#ifdef GAMMA_INPUT",
  11143. "cubeColor.xyz *= cubeColor.xyz;",
  11144. "#endif",
  11145. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11146. "}",
  11147. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11148. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11149. THREE.ShaderChunk[ "fog_fragment" ],
  11150. "}"
  11151. ].join("\n"),
  11152. vertexShader: [
  11153. "attribute vec4 tangent;",
  11154. "uniform vec2 uOffset;",
  11155. "uniform vec2 uRepeat;",
  11156. "#ifdef VERTEX_TEXTURES",
  11157. "uniform sampler2D tDisplacement;",
  11158. "uniform float uDisplacementScale;",
  11159. "uniform float uDisplacementBias;",
  11160. "#endif",
  11161. "varying vec3 vTangent;",
  11162. "varying vec3 vBinormal;",
  11163. "varying vec3 vNormal;",
  11164. "varying vec2 vUv;",
  11165. "#if MAX_POINT_LIGHTS > 0",
  11166. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11167. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11168. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  11169. "#endif",
  11170. "varying vec3 vViewPosition;",
  11171. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11172. "void main() {",
  11173. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11174. "vViewPosition = -mvPosition.xyz;",
  11175. // normal, tangent and binormal vectors
  11176. "vNormal = normalMatrix * normal;",
  11177. "vTangent = normalMatrix * tangent.xyz;",
  11178. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  11179. "vUv = uv * uRepeat + uOffset;",
  11180. // point lights
  11181. "#if MAX_POINT_LIGHTS > 0",
  11182. "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {",
  11183. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11184. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  11185. "float lDistance = 1.0;",
  11186. "if ( pointLightDistance[ i ] > 0.0 )",
  11187. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  11188. "lVector = normalize( lVector );",
  11189. "vPointLight[ i ] = vec4( lVector, lDistance );",
  11190. "}",
  11191. "#endif",
  11192. // displacement mapping
  11193. "#ifdef VERTEX_TEXTURES",
  11194. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11195. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11196. "vec4 displacedPosition = vec4( normalize( vNormal.xyz ) * df, 0.0 ) + mvPosition;",
  11197. "gl_Position = projectionMatrix * displacedPosition;",
  11198. "#else",
  11199. "gl_Position = projectionMatrix * mvPosition;",
  11200. "#endif",
  11201. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11202. "}"
  11203. ].join("\n")
  11204. },
  11205. /* -------------------------------------------------------------------------
  11206. // Cube map shader
  11207. ------------------------------------------------------------------------- */
  11208. 'cube': {
  11209. uniforms: { "tCube": { type: "t", value: 1, texture: null },
  11210. "tFlip": { type: "f", value: -1 } },
  11211. vertexShader: [
  11212. "varying vec3 vViewPosition;",
  11213. "void main() {",
  11214. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  11215. "vViewPosition = cameraPosition - mPosition.xyz;",
  11216. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11217. "}"
  11218. ].join("\n"),
  11219. fragmentShader: [
  11220. "uniform samplerCube tCube;",
  11221. "uniform float tFlip;",
  11222. "varying vec3 vViewPosition;",
  11223. "void main() {",
  11224. "vec3 wPos = cameraPosition - vViewPosition;",
  11225. "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
  11226. "}"
  11227. ].join("\n")
  11228. }
  11229. }
  11230. };
  11231. };/**
  11232. * @author alteredq / http://alteredqualia.com/
  11233. */
  11234. THREE.BufferGeometry = function () {
  11235. this.id = THREE.GeometryCount ++;
  11236. // GL buffers
  11237. this.vertexIndexBuffer = null;
  11238. this.vertexPositionBuffer = null;
  11239. this.vertexNormalBuffer = null;
  11240. this.vertexUvBuffer = null;
  11241. this.vertexColorBuffer = null;
  11242. // typed arrays (kept only if dynamic flag is set)
  11243. this.vertexIndexArray = null;
  11244. this.vertexPositionArray = null;
  11245. this.vertexNormalArray = null;
  11246. this.vertexUvArray = null;
  11247. this.vertexColorArray = null;
  11248. this.dynamic = false;
  11249. // boundings
  11250. this.boundingBox = null;
  11251. this.boundingSphere = null;
  11252. // for compatibility
  11253. this.morphTargets = [];
  11254. };
  11255. THREE.BufferGeometry.prototype = {
  11256. constructor : THREE.BufferGeometry,
  11257. // for compatibility
  11258. computeBoundingBox: function () {
  11259. },
  11260. // for compatibility
  11261. computeBoundingSphere: function () {
  11262. }
  11263. };
  11264. /**
  11265. * @author zz85 / http://www.lab4games.net/zz85/blog
  11266. * Extensible curve object
  11267. *
  11268. * Some common of Curve methods
  11269. * .getPoint(t), getTangent(t)
  11270. * .getPointAt(u), getTagentAt(u)
  11271. * .getPoints(), .getSpacedPoints()
  11272. * .getLength()
  11273. * .updateArcLengths()
  11274. *
  11275. * This file contains following classes:
  11276. *
  11277. * -- 2d classes --
  11278. * THREE.Curve
  11279. * THREE.LineCurve
  11280. * THREE.QuadraticBezierCurve
  11281. * THREE.CubicBezierCurve
  11282. * THREE.SplineCurve
  11283. * THREE.ArcCurve
  11284. *
  11285. * -- 3d classes --
  11286. * THREE.LineCurve3
  11287. * THREE.QuadraticBezierCurve3
  11288. * THREE.CubicBezierCurve3
  11289. * THREE.SplineCurve3
  11290. * THREE.ClosedSplineCurve3
  11291. *
  11292. * A series of curves can be represented as a THREE.CurvePath
  11293. *
  11294. **/
  11295. /**************************************************************
  11296. * Abstract Curve base class
  11297. **************************************************************/
  11298. THREE.Curve = function () {
  11299. };
  11300. // Virtual base class method to overwrite and implement in subclasses
  11301. // - t [0 .. 1]
  11302. THREE.Curve.prototype.getPoint = function ( t ) {
  11303. console.log( "Warning, getPoint() not implemented!" );
  11304. return null;
  11305. };
  11306. // Get point at relative position in curve according to arc length
  11307. // - u [0 .. 1]
  11308. THREE.Curve.prototype.getPointAt = function ( u ) {
  11309. var t = this.getUtoTmapping( u );
  11310. return this.getPoint( t );
  11311. };
  11312. // Get sequence of points using getPoint( t )
  11313. THREE.Curve.prototype.getPoints = function ( divisions ) {
  11314. if ( !divisions ) divisions = 5;
  11315. var d, pts = [];
  11316. for ( d = 0; d <= divisions; d ++ ) {
  11317. pts.push( this.getPoint( d / divisions ) );
  11318. }
  11319. return pts;
  11320. };
  11321. // Get sequence of points using getPointAt( u )
  11322. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  11323. if ( !divisions ) divisions = 5;
  11324. var d, pts = [];
  11325. for ( d = 0; d <= divisions; d ++ ) {
  11326. pts.push( this.getPointAt( d / divisions ) );
  11327. }
  11328. return pts;
  11329. };
  11330. // Get total curve arc length
  11331. THREE.Curve.prototype.getLength = function () {
  11332. var lengths = this.getLengths();
  11333. return lengths[ lengths.length - 1 ];
  11334. };
  11335. // Get list of cumulative segment lengths
  11336. THREE.Curve.prototype.getLengths = function ( divisions ) {
  11337. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  11338. if ( this.cacheArcLengths
  11339. && ( this.cacheArcLengths.length == divisions + 1 )
  11340. && !this.needsUpdate) {
  11341. //console.log( "cached", this.cacheArcLengths );
  11342. return this.cacheArcLengths;
  11343. }
  11344. this.needsUpdate = false;
  11345. var cache = [];
  11346. var current, last = this.getPoint( 0 );
  11347. var p, sum = 0;
  11348. cache.push( 0 );
  11349. for ( p = 1; p <= divisions; p ++ ) {
  11350. current = this.getPoint ( p / divisions );
  11351. sum += current.distanceTo( last );
  11352. cache.push( sum );
  11353. last = current;
  11354. }
  11355. this.cacheArcLengths = cache;
  11356. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  11357. };
  11358. THREE.Curve.prototype.updateArcLengths = function() {
  11359. this.needsUpdate = true;
  11360. this.getLengths();
  11361. };
  11362. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  11363. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  11364. var arcLengths = this.getLengths();
  11365. var i = 0, il = arcLengths.length;
  11366. var targetArcLength; // The targeted u distance value to get
  11367. if ( distance ) {
  11368. targetArcLength = distance;
  11369. } else {
  11370. targetArcLength = u * arcLengths[ il - 1 ];
  11371. }
  11372. //var time = Date.now();
  11373. // binary search for the index with largest value smaller than target u distance
  11374. var low = 0, high = il - 1, comparison;
  11375. while ( low <= high ) {
  11376. 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
  11377. comparison = arcLengths[ i ] - targetArcLength;
  11378. if ( comparison < 0 ) {
  11379. low = i + 1;
  11380. continue;
  11381. } else if ( comparison > 0 ) {
  11382. high = i - 1;
  11383. continue;
  11384. } else {
  11385. high = i;
  11386. break;
  11387. // DONE
  11388. }
  11389. }
  11390. i = high;
  11391. //console.log('b' , i, low, high, Date.now()- time);
  11392. if ( arcLengths[ i ] == targetArcLength ) {
  11393. var t = i / ( il - 1 );
  11394. return t;
  11395. }
  11396. // we could get finer grain at lengths, or use simple interpolatation between two points
  11397. var lengthBefore = arcLengths[ i ];
  11398. var lengthAfter = arcLengths[ i + 1 ];
  11399. var segmentLength = lengthAfter - lengthBefore;
  11400. // determine where we are between the 'before' and 'after' points
  11401. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  11402. // add that fractional amount to t
  11403. var t = ( i + segmentFraction ) / ( il -1 );
  11404. return t;
  11405. };
  11406. // In 2D space, there are actually 2 normal vectors,
  11407. // and in 3D space, infinte
  11408. // TODO this should be depreciated.
  11409. THREE.Curve.prototype.getNormalVector = function( t ) {
  11410. var vec = this.getTangent( t );
  11411. return new THREE.Vector2( -vec.y , vec.x );
  11412. };
  11413. // Returns a unit vector tangent at t
  11414. // In case any sub curve does not implement its tangent / normal finding,
  11415. // we get 2 points with a small delta and find a gradient of the 2 points
  11416. // which seems to make a reasonable approximation
  11417. THREE.Curve.prototype.getTangent = function( t ) {
  11418. var delta = 0.0001;
  11419. var t1 = t - delta;
  11420. var t2 = t + delta;
  11421. // Capping in case of danger
  11422. if ( t1 < 0 ) t1 = 0;
  11423. if ( t2 > 1 ) t2 = 1;
  11424. var pt1 = this.getPoint( t1 );
  11425. var pt2 = this.getPoint( t2 );
  11426. var vec = pt2.clone().subSelf(pt1);
  11427. return vec.normalize();
  11428. };
  11429. THREE.Curve.prototype.getTangentAt = function ( u ) {
  11430. var t = this.getUtoTmapping( u );
  11431. return this.getTangent( t );
  11432. };
  11433. /**************************************************************
  11434. * Line
  11435. **************************************************************/
  11436. THREE.LineCurve = function ( v1, v2 ) {
  11437. this.v1 = v1;
  11438. this.v2 = v2;
  11439. };
  11440. THREE.LineCurve.prototype = new THREE.Curve();
  11441. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  11442. THREE.LineCurve.prototype.getPoint = function ( t ) {
  11443. var point = this.v2.clone().subSelf(this.v1);
  11444. point.multiplyScalar( t ).addSelf( this.v1 );
  11445. return point;
  11446. };
  11447. // Line curve is linear, so we can overwrite default getPointAt
  11448. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  11449. return this.getPoint( u );
  11450. };
  11451. THREE.LineCurve.prototype.getTangent = function( t ) {
  11452. var tangent = this.v2.clone().subSelf(this.v1);
  11453. return tangent.normalize();
  11454. };
  11455. /**************************************************************
  11456. * Quadratic Bezier curve
  11457. **************************************************************/
  11458. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  11459. this.v0 = v0;
  11460. this.v1 = v1;
  11461. this.v2 = v2;
  11462. };
  11463. THREE.QuadraticBezierCurve.prototype = new THREE.Curve();
  11464. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  11465. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  11466. var tx, ty;
  11467. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  11468. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  11469. return new THREE.Vector2( tx, ty );
  11470. };
  11471. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  11472. var tx, ty;
  11473. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  11474. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  11475. // returns unit vector
  11476. var tangent = new THREE.Vector2( tx, ty );
  11477. tangent.normalize();
  11478. return tangent;
  11479. };
  11480. /**************************************************************
  11481. * Cubic Bezier curve
  11482. **************************************************************/
  11483. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  11484. this.v0 = v0;
  11485. this.v1 = v1;
  11486. this.v2 = v2;
  11487. this.v3 = v3;
  11488. };
  11489. THREE.CubicBezierCurve.prototype = new THREE.Curve();
  11490. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  11491. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  11492. var tx, ty;
  11493. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  11494. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  11495. return new THREE.Vector2( tx, ty );
  11496. };
  11497. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  11498. var tx, ty;
  11499. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  11500. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  11501. var tangent = new THREE.Vector2( tx, ty );
  11502. tangent.normalize();
  11503. return tangent;
  11504. };
  11505. /**************************************************************
  11506. * Spline curve
  11507. **************************************************************/
  11508. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  11509. this.points = (points == undefined) ? [] : points;
  11510. };
  11511. THREE.SplineCurve.prototype = new THREE.Curve();
  11512. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  11513. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  11514. var v = new THREE.Vector2();
  11515. var c = [];
  11516. var points = this.points, point, intPoint, weight;
  11517. point = ( points.length - 1 ) * t;
  11518. intPoint = Math.floor( point );
  11519. weight = point - intPoint;
  11520. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  11521. c[ 1 ] = intPoint;
  11522. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  11523. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  11524. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  11525. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  11526. return v;
  11527. };
  11528. /**************************************************************
  11529. * Arc curve
  11530. **************************************************************/
  11531. THREE.ArcCurve = function ( aX, aY, aRadius,
  11532. aStartAngle, aEndAngle,
  11533. aClockwise ) {
  11534. this.aX = aX;
  11535. this.aY = aY;
  11536. this.aRadius = aRadius;
  11537. this.aStartAngle = aStartAngle;
  11538. this.aEndAngle = aEndAngle;
  11539. this.aClockwise = aClockwise;
  11540. };
  11541. THREE.ArcCurve.prototype = new THREE.Curve();
  11542. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  11543. THREE.ArcCurve.prototype.getPoint = function ( t ) {
  11544. var deltaAngle = this.aEndAngle - this.aStartAngle;
  11545. if ( !this.aClockwise ) {
  11546. t = 1 - t;
  11547. }
  11548. var angle = this.aStartAngle + t * deltaAngle;
  11549. var tx = this.aX + this.aRadius * Math.cos( angle );
  11550. var ty = this.aY + this.aRadius * Math.sin( angle );
  11551. return new THREE.Vector2( tx, ty );
  11552. };
  11553. /**************************************************************
  11554. * Utils
  11555. **************************************************************/
  11556. THREE.Curve.Utils = {
  11557. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  11558. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  11559. },
  11560. // Puay Bing, thanks for helping with this derivative!
  11561. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  11562. return -3 * p0 * (1 - t) * (1 - t) +
  11563. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  11564. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  11565. 3 * t * t * p3;
  11566. },
  11567. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  11568. // To check if my formulas are correct
  11569. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  11570. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  11571. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  11572. var h11 = 3 * t * t - 2 * t; // t3 − t2
  11573. return h00 + h10 + h01 + h11;
  11574. },
  11575. // Catmull-Rom
  11576. interpolate: function( p0, p1, p2, p3, t ) {
  11577. var v0 = ( p2 - p0 ) * 0.5;
  11578. var v1 = ( p3 - p1 ) * 0.5;
  11579. var t2 = t * t;
  11580. var t3 = t * t2;
  11581. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  11582. }
  11583. };
  11584. // TODO: Transformation for Curves?
  11585. /**************************************************************
  11586. * 3D Curves
  11587. **************************************************************/
  11588. // A Factory method for creating new curve subclasses
  11589. THREE.Curve.create = function( constructor, getPointFunc ) {
  11590. var subClass = constructor;
  11591. subClass.prototype = new THREE.Curve();
  11592. subClass.prototype.constructor = constructor;
  11593. subClass.prototype.getPoint = getPointFunc;
  11594. return subClass;
  11595. };
  11596. /**************************************************************
  11597. * Line3D
  11598. **************************************************************/
  11599. THREE.LineCurve3 = THREE.Curve.create(
  11600. function ( v1, v2 ) {
  11601. this.v1 = v1;
  11602. this.v2 = v2;
  11603. },
  11604. function ( t ) {
  11605. var r = new THREE.Vector3();
  11606. r.sub( this.v2, this.v1 ); // diff
  11607. r.multiplyScalar( t );
  11608. r.addSelf( this.v1 );
  11609. return r;
  11610. }
  11611. );
  11612. /**************************************************************
  11613. * Quadratic Bezier 3D curve
  11614. **************************************************************/
  11615. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  11616. function ( v0, v1, v2 ) {
  11617. this.v0 = v0;
  11618. this.v1 = v1;
  11619. this.v2 = v2;
  11620. },
  11621. function ( t ) {
  11622. var tx, ty, tz;
  11623. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  11624. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  11625. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  11626. return new THREE.Vector3( tx, ty, tz );
  11627. }
  11628. );
  11629. /**************************************************************
  11630. * Cubic Bezier 3D curve
  11631. **************************************************************/
  11632. THREE.CubicBezierCurve3 = THREE.Curve.create(
  11633. function ( v0, v1, v2, v3 ) {
  11634. this.v0 = v0;
  11635. this.v1 = v1;
  11636. this.v2 = v2;
  11637. this.v3 = v3;
  11638. },
  11639. function ( t ) {
  11640. var tx, ty, tz;
  11641. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  11642. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  11643. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  11644. return new THREE.Vector3( tx, ty, tz );
  11645. }
  11646. );
  11647. /**************************************************************
  11648. * Spline 3D curve
  11649. **************************************************************/
  11650. THREE.SplineCurve3 = THREE.Curve.create(
  11651. function ( points /* array of Vector3 */) {
  11652. this.points = (points == undefined) ? [] : points;
  11653. },
  11654. function ( t ) {
  11655. var v = new THREE.Vector3();
  11656. var c = [];
  11657. var points = this.points, point, intPoint, weight;
  11658. point = ( points.length - 1 ) * t;
  11659. intPoint = Math.floor( point );
  11660. weight = point - intPoint;
  11661. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  11662. c[ 1 ] = intPoint;
  11663. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  11664. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  11665. var pt0 = points[ c[0] ],
  11666. pt1 = points[ c[1] ],
  11667. pt2 = points[ c[2] ],
  11668. pt3 = points[ c[3] ];
  11669. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  11670. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  11671. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  11672. return v;
  11673. }
  11674. );
  11675. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  11676. // var v = new THREE.Vector3();
  11677. // var c = [];
  11678. // var points = this.points, point, intPoint, weight;
  11679. // point = ( points.length - 1 ) * t;
  11680. // intPoint = Math.floor( point );
  11681. // weight = point - intPoint;
  11682. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  11683. // c[ 1 ] = intPoint;
  11684. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  11685. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  11686. // var pt0 = points[ c[0] ],
  11687. // pt1 = points[ c[1] ],
  11688. // pt2 = points[ c[2] ],
  11689. // pt3 = points[ c[3] ];
  11690. // // t = weight;
  11691. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  11692. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  11693. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  11694. // return v;
  11695. // }
  11696. /**************************************************************
  11697. * Closed Spline 3D curve
  11698. **************************************************************/
  11699. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  11700. function ( points /* array of Vector3 */) {
  11701. this.points = (points == undefined) ? [] : points;
  11702. },
  11703. function ( t ) {
  11704. var v = new THREE.Vector3();
  11705. var c = [];
  11706. var points = this.points, point, intPoint, weight;
  11707. point = ( points.length - 0 ) * t;
  11708. // This needs to be from 0-length +1
  11709. intPoint = Math.floor( point );
  11710. weight = point - intPoint;
  11711. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  11712. c[ 0 ] = ( intPoint - 1 ) % points.length;
  11713. c[ 1 ] = ( intPoint ) % points.length;
  11714. c[ 2 ] = ( intPoint + 1 ) % points.length;
  11715. c[ 3 ] = ( intPoint + 2 ) % points.length;
  11716. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  11717. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  11718. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  11719. return v;
  11720. }
  11721. );/**
  11722. * @author zz85 / http://www.lab4games.net/zz85/blog
  11723. *
  11724. **/
  11725. /**************************************************************
  11726. * Curved Path - a curve path is simply a array of connected
  11727. * curves, but retains the api of a curve
  11728. **************************************************************/
  11729. THREE.CurvePath = function () {
  11730. this.curves = [];
  11731. this.bends = [];
  11732. this.autoClose = false; // Automatically closes the path
  11733. };
  11734. THREE.CurvePath.prototype = new THREE.Curve();
  11735. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  11736. THREE.CurvePath.prototype.add = function ( curve ) {
  11737. this.curves.push( curve );
  11738. };
  11739. THREE.CurvePath.prototype.checkConnection = function() {
  11740. // TODO
  11741. // If the ending of curve is not connected to the starting
  11742. // or the next curve, then, this is not a real path
  11743. };
  11744. THREE.CurvePath.prototype.closePath = function() {
  11745. // TODO Test
  11746. // and verify for vector3 (needs to implement equals)
  11747. // Add a line curve if start and end of lines are not connected
  11748. var startPoint = this.curves[0].getPoint(0);
  11749. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  11750. if (!startPoint.equals(endPoint)) {
  11751. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  11752. }
  11753. };
  11754. // To get accurate point with reference to
  11755. // entire path distance at time t,
  11756. // following has to be done:
  11757. // 1. Length of each sub path have to be known
  11758. // 2. Locate and identify type of curve
  11759. // 3. Get t for the curve
  11760. // 4. Return curve.getPointAt(t')
  11761. THREE.CurvePath.prototype.getPoint = function( t ) {
  11762. var d = t * this.getLength();
  11763. var curveLengths = this.getCurveLengths();
  11764. var i = 0, diff, curve;
  11765. // To think about boundaries points.
  11766. while ( i < curveLengths.length ) {
  11767. if ( curveLengths[ i ] >= d ) {
  11768. diff = curveLengths[ i ] - d;
  11769. curve = this.curves[ i ];
  11770. var u = 1 - diff / curve.getLength();
  11771. return curve.getPointAt( u );
  11772. break;
  11773. }
  11774. i ++;
  11775. }
  11776. return null;
  11777. // loop where sum != 0, sum > d , sum+1 <d
  11778. };
  11779. /*
  11780. THREE.CurvePath.prototype.getTangent = function( t ) {
  11781. };*/
  11782. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11783. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11784. // getPoint() depends on getLength
  11785. THREE.CurvePath.prototype.getLength = function() {
  11786. var lens = this.getCurveLengths();
  11787. return lens[ lens.length - 1 ];
  11788. };
  11789. // Compute lengths and cache them
  11790. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11791. THREE.CurvePath.prototype.getCurveLengths = function() {
  11792. // We use cache values if curves and cache array are same length
  11793. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  11794. return this.cacheLengths;
  11795. };
  11796. // Get length of subsurve
  11797. // Push sums into cached array
  11798. var lengths = [], sums = 0;
  11799. var i, il = this.curves.length;
  11800. for ( i = 0; i < il; i ++ ) {
  11801. sums += this.curves[ i ].getLength();
  11802. lengths.push( sums );
  11803. }
  11804. this.cacheLengths = lengths;
  11805. return lengths;
  11806. };
  11807. // Returns min and max coordinates, as well as centroid
  11808. THREE.CurvePath.prototype.getBoundingBox = function () {
  11809. var points = this.getPoints();
  11810. var maxX, maxY;
  11811. var minX, minY;
  11812. maxX = maxY = Number.NEGATIVE_INFINITY;
  11813. minX = minY = Number.POSITIVE_INFINITY;
  11814. var p, i, il, sum;
  11815. sum = new THREE.Vector2();
  11816. for ( i = 0, il = points.length; i < il; i ++ ) {
  11817. p = points[ i ];
  11818. if ( p.x > maxX ) maxX = p.x;
  11819. else if ( p.x < minX ) minX = p.x;
  11820. if ( p.y > maxY ) maxY = p.y;
  11821. else if ( p.y < maxY ) minY = p.y;
  11822. sum.addSelf( p.x, p.y );
  11823. }
  11824. return {
  11825. minX: minX,
  11826. minY: minY,
  11827. maxX: maxX,
  11828. maxY: maxY,
  11829. centroid: sum.divideScalar( il )
  11830. };
  11831. };
  11832. /**************************************************************
  11833. * Create Geometries Helpers
  11834. **************************************************************/
  11835. /// Generate geometry from path points (for Line or ParticleSystem objects)
  11836. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  11837. var pts = this.getPoints( divisions, true );
  11838. return this.createGeometry( pts );
  11839. };
  11840. // Generate geometry from equidistance sampling along the path
  11841. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  11842. var pts = this.getSpacedPoints( divisions, true );
  11843. return this.createGeometry( pts );
  11844. };
  11845. THREE.CurvePath.prototype.createGeometry = function( points ) {
  11846. var geometry = new THREE.Geometry();
  11847. for( var i = 0; i < points.length; i ++ ) {
  11848. geometry.vertices.push( new THREE.Vertex( points[ i ].x, points[ i ].y, 0 ) );
  11849. }
  11850. return geometry;
  11851. };
  11852. /**************************************************************
  11853. * Bend / Wrap Helper Methods
  11854. **************************************************************/
  11855. // Wrap path / Bend modifiers?
  11856. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  11857. this.bends.push( bendpath );
  11858. };
  11859. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  11860. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  11861. var i, il;
  11862. if ( !bends ) {
  11863. bends = this.bends;
  11864. }
  11865. for ( i = 0, il = bends.length; i < il; i ++ ) {
  11866. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  11867. }
  11868. return oldPts;
  11869. };
  11870. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  11871. var oldPts = this.getSpacedPoints( segments );
  11872. var i, il;
  11873. if ( !bends ) {
  11874. bends = this.bends;
  11875. }
  11876. for ( i = 0, il = bends.length; i < il; i ++ ) {
  11877. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  11878. }
  11879. return oldPts;
  11880. };
  11881. // This returns getPoints() bend/wrapped around the contour of a path.
  11882. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  11883. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  11884. var bounds = this.getBoundingBox();
  11885. var i, il, p, oldX, oldY, xNorm;
  11886. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  11887. p = oldPts[ i ];
  11888. oldX = p.x;
  11889. oldY = p.y;
  11890. xNorm = oldX / bounds.maxX;
  11891. // If using actual distance, for length > path, requires line extrusions
  11892. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  11893. xNorm = path.getUtoTmapping( xNorm, oldX );
  11894. // check for out of bounds?
  11895. var pathPt = path.getPoint( xNorm );
  11896. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  11897. p.x = pathPt.x + normal.x;
  11898. p.y = pathPt.y + normal.y;
  11899. }
  11900. return oldPts;
  11901. };
  11902. /**
  11903. * https://github.com/mrdoob/eventtarget.js/
  11904. */
  11905. THREE.EventTarget = function () {
  11906. var listeners = {};
  11907. this.addEventListener = function ( type, listener ) {
  11908. if ( listeners[ type ] == undefined ) {
  11909. listeners[ type ] = [];
  11910. }
  11911. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  11912. listeners[ type ].push( listener );
  11913. }
  11914. };
  11915. this.dispatchEvent = function ( event ) {
  11916. for ( var listener in listeners[ event.type ] ) {
  11917. listeners[ event.type ][ listener ]( event );
  11918. }
  11919. };
  11920. this.removeEventListener = function ( type, listener ) {
  11921. var index = listeners[ type ].indexOf( listener );
  11922. if ( index !== - 1 ) {
  11923. listeners[ type ].splice( index, 1 );
  11924. }
  11925. };
  11926. };
  11927. /**
  11928. * @author alteredq / http://alteredqualia.com/
  11929. */
  11930. THREE.Gyroscope = function () {
  11931. THREE.Object3D.call( this );
  11932. };
  11933. THREE.Gyroscope.prototype = new THREE.Object3D();
  11934. THREE.Gyroscope.prototype.constructor = THREE.Gyroscope;
  11935. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  11936. this.matrixAutoUpdate && this.updateMatrix();
  11937. // update matrixWorld
  11938. if ( this.matrixWorldNeedsUpdate || force ) {
  11939. if ( this.parent ) {
  11940. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  11941. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  11942. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  11943. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  11944. } else {
  11945. this.matrixWorld.copy( this.matrix );
  11946. }
  11947. this.matrixWorldNeedsUpdate = false;
  11948. force = true;
  11949. }
  11950. // update children
  11951. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  11952. this.children[ i ].updateMatrixWorld( force );
  11953. }
  11954. };
  11955. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  11956. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  11957. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  11958. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  11959. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  11960. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  11961. /**
  11962. * @author zz85 / http://www.lab4games.net/zz85/blog
  11963. * Creates free form 2d path using series of points, lines or curves.
  11964. *
  11965. **/
  11966. THREE.Path = function ( points ) {
  11967. THREE.CurvePath.call(this);
  11968. this.actions = [];
  11969. if ( points ) {
  11970. this.fromPoints( points );
  11971. }
  11972. };
  11973. THREE.Path.prototype = new THREE.CurvePath();
  11974. THREE.Path.prototype.constructor = THREE.Path;
  11975. THREE.PathActions = {
  11976. MOVE_TO: 'moveTo',
  11977. LINE_TO: 'lineTo',
  11978. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  11979. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  11980. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  11981. ARC: 'arc' // Circle
  11982. };
  11983. // TODO Clean up PATH API
  11984. // Create path using straight lines to connect all points
  11985. // - vectors: array of Vector2
  11986. THREE.Path.prototype.fromPoints = function ( vectors ) {
  11987. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  11988. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  11989. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  11990. };
  11991. };
  11992. // startPath() endPath()?
  11993. THREE.Path.prototype.moveTo = function ( x, y ) {
  11994. var args = Array.prototype.slice.call( arguments );
  11995. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  11996. };
  11997. THREE.Path.prototype.lineTo = function ( x, y ) {
  11998. var args = Array.prototype.slice.call( arguments );
  11999. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12000. var x0 = lastargs[ lastargs.length - 2 ];
  12001. var y0 = lastargs[ lastargs.length - 1 ];
  12002. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  12003. this.curves.push( curve );
  12004. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  12005. };
  12006. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  12007. var args = Array.prototype.slice.call( arguments );
  12008. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12009. var x0 = lastargs[ lastargs.length - 2 ];
  12010. var y0 = lastargs[ lastargs.length - 1 ];
  12011. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  12012. new THREE.Vector2( aCPx, aCPy ),
  12013. new THREE.Vector2( aX, aY ) );
  12014. this.curves.push( curve );
  12015. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  12016. };
  12017. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  12018. aCP2x, aCP2y,
  12019. aX, aY ) {
  12020. var args = Array.prototype.slice.call( arguments );
  12021. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12022. var x0 = lastargs[ lastargs.length - 2 ];
  12023. var y0 = lastargs[ lastargs.length - 1 ];
  12024. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  12025. new THREE.Vector2( aCP1x, aCP1y ),
  12026. new THREE.Vector2( aCP2x, aCP2y ),
  12027. new THREE.Vector2( aX, aY ) );
  12028. this.curves.push( curve );
  12029. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  12030. };
  12031. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  12032. var args = Array.prototype.slice.call( arguments );
  12033. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12034. var x0 = lastargs[ lastargs.length - 2 ];
  12035. var y0 = lastargs[ lastargs.length - 1 ];
  12036. //---
  12037. var npts = [ new THREE.Vector2( x0, y0 ) ];
  12038. Array.prototype.push.apply( npts, pts );
  12039. var curve = new THREE.SplineCurve( npts );
  12040. this.curves.push( curve );
  12041. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  12042. };
  12043. // FUTURE: Change the API or follow canvas API?
  12044. // TODO ARC ( x, y, x - radius, y - radius, startAngle, endAngle )
  12045. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  12046. aStartAngle, aEndAngle, aClockwise ) {
  12047. var args = Array.prototype.slice.call( arguments );
  12048. var laste = this.actions[ this.actions.length - 1];
  12049. var curve = new THREE.ArcCurve( laste.x + aX, laste.y + aY, aRadius,
  12050. aStartAngle, aEndAngle, aClockwise );
  12051. this.curves.push( curve );
  12052. // All of the other actions look to the last two elements in the list to
  12053. // find the ending point, so we need to append them.
  12054. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  12055. args.push(lastPoint.x);
  12056. args.push(lastPoint.y);
  12057. this.actions.push( { action: THREE.PathActions.ARC, args: args } );
  12058. };
  12059. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  12060. aStartAngle, aEndAngle, aClockwise ) {
  12061. var args = Array.prototype.slice.call( arguments );
  12062. var curve = new THREE.ArcCurve( aX, aY, aRadius,
  12063. aStartAngle, aEndAngle, aClockwise );
  12064. this.curves.push( curve );
  12065. // console.log( 'arc', args );
  12066. // All of the other actions look to the last two elements in the list to
  12067. // find the ending point, so we need to append them.
  12068. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  12069. args.push(lastPoint.x);
  12070. args.push(lastPoint.y);
  12071. this.actions.push( { action: THREE.PathActions.ARC, args: args } );
  12072. };
  12073. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  12074. if ( ! divisions ) divisions = 40;
  12075. var points = [];
  12076. for ( var i = 0; i < divisions; i ++ ) {
  12077. points.push( this.getPoint( i / divisions ) );
  12078. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  12079. }
  12080. // if ( closedPath ) {
  12081. //
  12082. // points.push( points[ 0 ] );
  12083. //
  12084. // }
  12085. return points;
  12086. };
  12087. /* Return an array of vectors based on contour of the path */
  12088. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  12089. if (this.useSpacedPoints) {
  12090. console.log('tata');
  12091. return this.getSpacedPoints( divisions, closedPath );
  12092. }
  12093. divisions = divisions || 12;
  12094. var points = [];
  12095. var i, il, item, action, args;
  12096. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  12097. laste, j,
  12098. t, tx, ty;
  12099. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  12100. item = this.actions[ i ];
  12101. action = item.action;
  12102. args = item.args;
  12103. switch( action ) {
  12104. case THREE.PathActions.MOVE_TO:
  12105. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  12106. break;
  12107. case THREE.PathActions.LINE_TO:
  12108. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  12109. break;
  12110. case THREE.PathActions.QUADRATIC_CURVE_TO:
  12111. cpx = args[ 2 ];
  12112. cpy = args[ 3 ];
  12113. cpx1 = args[ 0 ];
  12114. cpy1 = args[ 1 ];
  12115. if ( points.length > 0 ) {
  12116. laste = points[ points.length - 1 ];
  12117. cpx0 = laste.x;
  12118. cpy0 = laste.y;
  12119. } else {
  12120. laste = this.actions[ i - 1 ].args;
  12121. cpx0 = laste[ laste.length - 2 ];
  12122. cpy0 = laste[ laste.length - 1 ];
  12123. }
  12124. for ( j = 1; j <= divisions; j ++ ) {
  12125. t = j / divisions;
  12126. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  12127. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  12128. points.push( new THREE.Vector2( tx, ty ) );
  12129. }
  12130. break;
  12131. case THREE.PathActions.BEZIER_CURVE_TO:
  12132. cpx = args[ 4 ];
  12133. cpy = args[ 5 ];
  12134. cpx1 = args[ 0 ];
  12135. cpy1 = args[ 1 ];
  12136. cpx2 = args[ 2 ];
  12137. cpy2 = args[ 3 ];
  12138. if ( points.length > 0 ) {
  12139. laste = points[ points.length - 1 ];
  12140. cpx0 = laste.x;
  12141. cpy0 = laste.y;
  12142. } else {
  12143. laste = this.actions[ i - 1 ].args;
  12144. cpx0 = laste[ laste.length - 2 ];
  12145. cpy0 = laste[ laste.length - 1 ];
  12146. }
  12147. for ( j = 1; j <= divisions; j ++ ) {
  12148. t = j / divisions;
  12149. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  12150. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  12151. points.push( new THREE.Vector2( tx, ty ) );
  12152. }
  12153. break;
  12154. case THREE.PathActions.CSPLINE_THRU:
  12155. laste = this.actions[ i - 1 ].args;
  12156. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  12157. var spts = [ last ];
  12158. var n = divisions * args[ 0 ].length;
  12159. spts = spts.concat( args[ 0 ] );
  12160. var spline = new THREE.SplineCurve( spts );
  12161. for ( j = 1; j <= n; j ++ ) {
  12162. points.push( spline.getPointAt( j / n ) ) ;
  12163. }
  12164. break;
  12165. case THREE.PathActions.ARC:
  12166. laste = this.actions[ i - 1 ].args;
  12167. var aX = args[ 0 ], aY = args[ 1 ],
  12168. aRadius = args[ 2 ],
  12169. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  12170. aClockwise = !!args[ 5 ];
  12171. var deltaAngle = aEndAngle - aStartAngle;
  12172. var angle;
  12173. var tdivisions = divisions * 2;
  12174. for ( j = 1; j <= tdivisions; j ++ ) {
  12175. t = j / tdivisions;
  12176. if ( ! aClockwise ) {
  12177. t = 1 - t;
  12178. }
  12179. angle = aStartAngle + t * deltaAngle;
  12180. tx = aX + aRadius * Math.cos( angle );
  12181. ty = aY + aRadius * Math.sin( angle );
  12182. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  12183. points.push( new THREE.Vector2( tx, ty ) );
  12184. }
  12185. //console.log(points);
  12186. break;
  12187. } // end switch
  12188. }
  12189. // Normalize to remove the closing point by default.
  12190. var lastPoint = points[ points.length - 1];
  12191. var EPSILON = 0.0000000001;
  12192. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  12193. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  12194. points.splice( points.length - 1, 1);
  12195. if ( closedPath ) {
  12196. points.push( points[ 0 ] );
  12197. }
  12198. return points;
  12199. };
  12200. // This was used for testing purposes. Should be removed soon.
  12201. THREE.Path.prototype.transform = function( path, segments ) {
  12202. var bounds = this.getBoundingBox();
  12203. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  12204. //console.log( path.cacheArcLengths() );
  12205. //path.getLengths(400);
  12206. //segments = 40;
  12207. return this.getWrapPoints( oldPts, path );
  12208. };
  12209. // Read http://www.tinaja.com/glib/nonlingr.pdf
  12210. // nonlinear transforms
  12211. THREE.Path.prototype.nltransform = function( a, b, c, d, e, f ) {
  12212. // a - horizontal size
  12213. // b - lean
  12214. // c - x offset
  12215. // d - vertical size
  12216. // e - climb
  12217. // f - y offset
  12218. var oldPts = this.getPoints();
  12219. var i, il, p, oldX, oldY;
  12220. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  12221. p = oldPts[i];
  12222. oldX = p.x;
  12223. oldY = p.y;
  12224. p.x = a * oldX + b * oldY + c;
  12225. p.y = d * oldY + e * oldX + f;
  12226. }
  12227. return oldPts;
  12228. };
  12229. // FUTURE Export JSON Format
  12230. /* Draws this path onto a 2d canvas easily */
  12231. THREE.Path.prototype.debug = function( canvas ) {
  12232. var bounds = this.getBoundingBox();
  12233. if ( !canvas ) {
  12234. canvas = document.createElement( "canvas" );
  12235. canvas.setAttribute( 'width', bounds.maxX + 100 );
  12236. canvas.setAttribute( 'height', bounds.maxY + 100 );
  12237. document.body.appendChild( canvas );
  12238. }
  12239. var ctx = canvas.getContext( "2d" );
  12240. ctx.fillStyle = "white";
  12241. ctx.fillRect( 0, 0, canvas.width, canvas.height );
  12242. ctx.strokeStyle = "black";
  12243. ctx.beginPath();
  12244. var i, il, item, action, args;
  12245. // Debug Path
  12246. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  12247. item = this.actions[ i ];
  12248. args = item.args;
  12249. action = item.action;
  12250. // Short hand for now
  12251. if ( action != THREE.PathActions.CSPLINE_THRU ) {
  12252. ctx[ action ].apply( ctx, args );
  12253. }
  12254. /*
  12255. switch ( action ) {
  12256. case THREE.PathActions.MOVE_TO:
  12257. ctx[ action ]( args[ 0 ], args[ 1 ] );
  12258. break;
  12259. case THREE.PathActions.LINE_TO:
  12260. ctx[ action ]( args[ 0 ], args[ 1 ] );
  12261. break;
  12262. case THREE.PathActions.QUADRATIC_CURVE_TO:
  12263. ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ] );
  12264. break;
  12265. case THREE.PathActions.CUBIC_CURVE_TO:
  12266. ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ], args[ 4 ], args[ 5 ] );
  12267. break;
  12268. }
  12269. */
  12270. }
  12271. ctx.stroke();
  12272. ctx.closePath();
  12273. // Debug Points
  12274. ctx.strokeStyle = "red";
  12275. /* TO CLEAN UP */
  12276. var p, points = this.getPoints();
  12277. for ( i = 0, il = points.length; i < il; i ++ ) {
  12278. p = points[ i ];
  12279. ctx.beginPath();
  12280. ctx.arc( p.x, p.y, 1.5, 0, Math.PI * 2, false );
  12281. ctx.stroke();
  12282. ctx.closePath();
  12283. }
  12284. };
  12285. // Breaks path into shapes
  12286. THREE.Path.prototype.toShapes = function() {
  12287. var i, il, item, action, args;
  12288. var subPaths = [], lastPath = new THREE.Path();
  12289. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  12290. item = this.actions[ i ];
  12291. args = item.args;
  12292. action = item.action;
  12293. if ( action == THREE.PathActions.MOVE_TO ) {
  12294. if ( lastPath.actions.length != 0 ) {
  12295. subPaths.push( lastPath );
  12296. lastPath = new THREE.Path();
  12297. }
  12298. }
  12299. lastPath[ action ].apply( lastPath, args );
  12300. }
  12301. if ( lastPath.actions.length != 0 ) {
  12302. subPaths.push( lastPath );
  12303. }
  12304. // console.log(subPaths);
  12305. if ( subPaths.length == 0 ) return [];
  12306. var tmpPath, tmpShape, shapes = [];
  12307. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  12308. // console.log("Holes first", holesFirst);
  12309. if ( subPaths.length == 1) {
  12310. tmpPath = subPaths[0];
  12311. tmpShape = new THREE.Shape();
  12312. tmpShape.actions = tmpPath.actions;
  12313. tmpShape.curves = tmpPath.curves;
  12314. shapes.push( tmpShape );
  12315. return shapes;
  12316. };
  12317. if ( holesFirst ) {
  12318. tmpShape = new THREE.Shape();
  12319. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  12320. tmpPath = subPaths[ i ];
  12321. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  12322. tmpShape.actions = tmpPath.actions;
  12323. tmpShape.curves = tmpPath.curves;
  12324. shapes.push( tmpShape );
  12325. tmpShape = new THREE.Shape();
  12326. //console.log('cw', i);
  12327. } else {
  12328. tmpShape.holes.push( tmpPath );
  12329. //console.log('ccw', i);
  12330. }
  12331. }
  12332. } else {
  12333. // Shapes first
  12334. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  12335. tmpPath = subPaths[ i ];
  12336. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  12337. if ( tmpShape ) shapes.push( tmpShape );
  12338. tmpShape = new THREE.Shape();
  12339. tmpShape.actions = tmpPath.actions;
  12340. tmpShape.curves = tmpPath.curves;
  12341. } else {
  12342. tmpShape.holes.push( tmpPath );
  12343. }
  12344. }
  12345. shapes.push( tmpShape );
  12346. }
  12347. //console.log("shape", shapes);
  12348. return shapes;
  12349. };
  12350. /**
  12351. * @author zz85 / http://www.lab4games.net/zz85/blog
  12352. * Defines a 2d shape plane using paths.
  12353. **/
  12354. // STEP 1 Create a path.
  12355. // STEP 2 Turn path into shape.
  12356. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  12357. // STEP 3a - Extract points from each shape, turn to vertices
  12358. // STEP 3b - Triangulate each shape, add faces.
  12359. THREE.Shape = function ( ) {
  12360. THREE.Path.apply( this, arguments );
  12361. this.holes = [];
  12362. };
  12363. THREE.Shape.prototype = new THREE.Path();
  12364. THREE.Shape.prototype.constructor = THREE.Path;
  12365. // Convenience method to return ExtrudeGeometry
  12366. THREE.Shape.prototype.extrude = function ( options ) {
  12367. var extruded = new THREE.ExtrudeGeometry( this, options );
  12368. return extruded;
  12369. };
  12370. // Get points of holes
  12371. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  12372. var i, il = this.holes.length, holesPts = [];
  12373. for ( i = 0; i < il; i ++ ) {
  12374. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  12375. }
  12376. return holesPts;
  12377. };
  12378. // Get points of holes (spaced by regular distance)
  12379. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  12380. var i, il = this.holes.length, holesPts = [];
  12381. for ( i = 0; i < il; i ++ ) {
  12382. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  12383. }
  12384. return holesPts;
  12385. };
  12386. // Get points of shape and holes (keypoints based on segments parameter)
  12387. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  12388. return {
  12389. shape: this.getTransformedPoints( divisions ),
  12390. holes: this.getPointsHoles( divisions )
  12391. };
  12392. };
  12393. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  12394. if (this.useSpacedPoints) {
  12395. return this.extractAllSpacedPoints(divisions);
  12396. }
  12397. return this.extractAllPoints(divisions);
  12398. };
  12399. //
  12400. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  12401. //
  12402. // return {
  12403. //
  12404. // shape: this.transform( bend, divisions ),
  12405. // holes: this.getPointsHoles( divisions, bend )
  12406. //
  12407. // };
  12408. //
  12409. // };
  12410. // Get points of shape and holes (spaced by regular distance)
  12411. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  12412. return {
  12413. shape: this.getTransformedSpacedPoints( divisions ),
  12414. holes: this.getSpacedPointsHoles( divisions )
  12415. };
  12416. };
  12417. /**************************************************************
  12418. * Utils
  12419. **************************************************************/
  12420. THREE.Shape.Utils = {
  12421. /*
  12422. contour - array of vector2 for contour
  12423. holes - array of array of vector2
  12424. */
  12425. removeHoles: function ( contour, holes ) {
  12426. var shape = contour.concat(); // work on this shape
  12427. var allpoints = shape.concat();
  12428. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  12429. var prevShapeVert, nextShapeVert,
  12430. prevHoleVert, nextHoleVert,
  12431. holeIndex, shapeIndex,
  12432. shapeId, shapeGroup,
  12433. h, h2,
  12434. hole, shortest, d,
  12435. p, pts1, pts2,
  12436. tmpShape1, tmpShape2,
  12437. tmpHole1, tmpHole2,
  12438. verts = [];
  12439. for ( h = 0; h < holes.length; h ++ ) {
  12440. hole = holes[ h ];
  12441. /*
  12442. shapeholes[ h ].concat(); // preserves original
  12443. holes.push( hole );
  12444. */
  12445. Array.prototype.push.apply( allpoints, hole );
  12446. shortest = Number.POSITIVE_INFINITY;
  12447. // Find the shortest pair of pts between shape and hole
  12448. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  12449. // Using distanceToSquared() intead of distanceTo() should speed a little
  12450. // since running square roots operations are reduced.
  12451. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  12452. pts1 = hole[ h2 ];
  12453. var dist = [];
  12454. for ( p = 0; p < shape.length; p++ ) {
  12455. pts2 = shape[ p ];
  12456. d = pts1.distanceToSquared( pts2 );
  12457. dist.push( d );
  12458. if ( d < shortest ) {
  12459. shortest = d;
  12460. holeIndex = h2;
  12461. shapeIndex = p;
  12462. }
  12463. }
  12464. }
  12465. //console.log("shortest", shortest, dist);
  12466. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  12467. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  12468. var areaapts = [
  12469. hole[ holeIndex ],
  12470. shape[ shapeIndex ],
  12471. shape[ prevShapeVert ]
  12472. ];
  12473. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  12474. var areabpts = [
  12475. hole[ holeIndex ],
  12476. hole[ prevHoleVert ],
  12477. shape[ shapeIndex ]
  12478. ];
  12479. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  12480. var shapeOffset = 1;
  12481. var holeOffset = -1;
  12482. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  12483. shapeIndex += shapeOffset;
  12484. holeIndex += holeOffset;
  12485. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  12486. shapeIndex %= shape.length;
  12487. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  12488. holeIndex %= hole.length;
  12489. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  12490. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  12491. areaapts = [
  12492. hole[ holeIndex ],
  12493. shape[ shapeIndex ],
  12494. shape[ prevShapeVert ]
  12495. ];
  12496. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  12497. areabpts = [
  12498. hole[ holeIndex ],
  12499. hole[ prevHoleVert ],
  12500. shape[ shapeIndex ]
  12501. ];
  12502. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  12503. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  12504. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  12505. // In case areas are not correct.
  12506. //console.log("USE THIS");
  12507. shapeIndex = oldShapeIndex;
  12508. holeIndex = oldHoleIndex ;
  12509. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  12510. shapeIndex %= shape.length;
  12511. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  12512. holeIndex %= hole.length;
  12513. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  12514. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  12515. } else {
  12516. //console.log("USE THAT ")
  12517. }
  12518. tmpShape1 = shape.slice( 0, shapeIndex );
  12519. tmpShape2 = shape.slice( shapeIndex );
  12520. tmpHole1 = hole.slice( holeIndex );
  12521. tmpHole2 = hole.slice( 0, holeIndex );
  12522. // Should check orders here again?
  12523. var trianglea = [
  12524. hole[ holeIndex ],
  12525. shape[ shapeIndex ],
  12526. shape[ prevShapeVert ]
  12527. ];
  12528. var triangleb = [
  12529. hole[ holeIndex ] ,
  12530. hole[ prevHoleVert ],
  12531. shape[ shapeIndex ]
  12532. ];
  12533. verts.push( trianglea );
  12534. verts.push( triangleb );
  12535. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  12536. }
  12537. return {
  12538. shape:shape, /* shape with no holes */
  12539. isolatedPts: verts, /* isolated faces */
  12540. allpoints: allpoints
  12541. }
  12542. },
  12543. triangulateShape: function ( contour, holes ) {
  12544. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  12545. var shape = shapeWithoutHoles.shape,
  12546. allpoints = shapeWithoutHoles.allpoints,
  12547. isolatedPts = shapeWithoutHoles.isolatedPts;
  12548. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  12549. // 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.
  12550. //console.log( "triangles",triangles, triangles.length );
  12551. //console.log( "allpoints",allpoints, allpoints.length );
  12552. var i, il, f, face,
  12553. key, index,
  12554. allPointsMap = {},
  12555. isolatedPointsMap = {};
  12556. // prepare all points map
  12557. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  12558. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  12559. if ( allPointsMap[ key ] !== undefined ) {
  12560. console.log( "Duplicate point", key );
  12561. }
  12562. allPointsMap[ key ] = i;
  12563. }
  12564. // check all face vertices against all points map
  12565. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  12566. face = triangles[ i ];
  12567. for ( f = 0; f < 3; f ++ ) {
  12568. key = face[ f ].x + ":" + face[ f ].y;
  12569. index = allPointsMap[ key ];
  12570. if ( index !== undefined ) {
  12571. face[ f ] = index;
  12572. }
  12573. }
  12574. }
  12575. // check isolated points vertices against all points map
  12576. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  12577. face = isolatedPts[ i ];
  12578. for ( f = 0; f < 3; f ++ ) {
  12579. key = face[ f ].x + ":" + face[ f ].y;
  12580. index = allPointsMap[ key ];
  12581. if ( index !== undefined ) {
  12582. face[ f ] = index;
  12583. }
  12584. }
  12585. }
  12586. return triangles.concat( isolatedPts );
  12587. }, // end triangulate shapes
  12588. /*
  12589. triangulate2 : function( pts, holes ) {
  12590. // For use with Poly2Tri.js
  12591. var allpts = pts.concat();
  12592. var shape = [];
  12593. for (var p in pts) {
  12594. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  12595. }
  12596. var swctx = new js.poly2tri.SweepContext(shape);
  12597. for (var h in holes) {
  12598. var aHole = holes[h];
  12599. var newHole = []
  12600. for (i in aHole) {
  12601. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  12602. allpts.push(aHole[i]);
  12603. }
  12604. swctx.AddHole(newHole);
  12605. }
  12606. var find;
  12607. var findIndexForPt = function (pt) {
  12608. find = new THREE.Vector2(pt.x, pt.y);
  12609. var p;
  12610. for (p=0, pl = allpts.length; p<pl; p++) {
  12611. if (allpts[p].equals(find)) return p;
  12612. }
  12613. return -1;
  12614. };
  12615. // triangulate
  12616. js.poly2tri.sweep.Triangulate(swctx);
  12617. var triangles = swctx.GetTriangles();
  12618. var tr ;
  12619. var facesPts = [];
  12620. for (var t in triangles) {
  12621. tr = triangles[t];
  12622. facesPts.push([
  12623. findIndexForPt(tr.GetPoint(0)),
  12624. findIndexForPt(tr.GetPoint(1)),
  12625. findIndexForPt(tr.GetPoint(2))
  12626. ]);
  12627. }
  12628. // console.log(facesPts);
  12629. // console.log("triangles", triangles.length, triangles);
  12630. // Returns array of faces with 3 element each
  12631. return facesPts;
  12632. },
  12633. */
  12634. isClockWise: function ( pts ) {
  12635. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  12636. },
  12637. // Bezier Curves formulas obtained from
  12638. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  12639. // Quad Bezier Functions
  12640. b2p0: function ( t, p ) {
  12641. var k = 1 - t;
  12642. return k * k * p;
  12643. },
  12644. b2p1: function ( t, p ) {
  12645. return 2 * ( 1 - t ) * t * p;
  12646. },
  12647. b2p2: function ( t, p ) {
  12648. return t * t * p;
  12649. },
  12650. b2: function ( t, p0, p1, p2 ) {
  12651. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  12652. },
  12653. // Cubic Bezier Functions
  12654. b3p0: function ( t, p ) {
  12655. var k = 1 - t;
  12656. return k * k * k * p;
  12657. },
  12658. b3p1: function ( t, p ) {
  12659. var k = 1 - t;
  12660. return 3 * k * k * t * p;
  12661. },
  12662. b3p2: function ( t, p ) {
  12663. var k = 1 - t;
  12664. return 3 * k * t * t * p;
  12665. },
  12666. b3p3: function ( t, p ) {
  12667. return t * t * t * p;
  12668. },
  12669. b3: function ( t, p0, p1, p2, p3 ) {
  12670. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  12671. }
  12672. };
  12673. /**
  12674. * @author zz85 / http://www.lab4games.net/zz85/blog
  12675. *
  12676. * TextPath
  12677. *
  12678. **/
  12679. THREE.TextPath = function ( text, parameters ) {
  12680. THREE.Path.call( this );
  12681. this.parameters = parameters || {};
  12682. this.set( text );
  12683. };
  12684. THREE.TextPath.prototype.set = function ( text, parameters ) {
  12685. parameters = parameters || this.parameters;
  12686. this.text = text;
  12687. var size = parameters.size !== undefined ? parameters.size : 100;
  12688. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  12689. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  12690. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  12691. var style = parameters.style !== undefined ? parameters.style : "normal";
  12692. THREE.FontUtils.size = size;
  12693. THREE.FontUtils.divisions = curveSegments;
  12694. THREE.FontUtils.face = font;
  12695. THREE.FontUtils.weight = weight;
  12696. THREE.FontUtils.style = style;
  12697. };
  12698. THREE.TextPath.prototype.toShapes = function () {
  12699. // Get a Font data json object
  12700. var data = THREE.FontUtils.drawText( this.text );
  12701. var paths = data.paths;
  12702. var shapes = [];
  12703. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  12704. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  12705. }
  12706. return shapes;
  12707. //console.log(path);
  12708. //console.log(fontShapes);
  12709. // Either find actions or curves.
  12710. //var text3d = new THREE.ExtrudeGeometry( shapes , { amount: 20, bevelEnabled:true, bevelThickness:3 } );
  12711. //return text3d;
  12712. };
  12713. /**
  12714. * @author mikael emtinger / http://gomo.se/
  12715. */
  12716. THREE.AnimationHandler = (function() {
  12717. var playing = [];
  12718. var library = {};
  12719. var that = {};
  12720. //--- update ---
  12721. that.update = function( deltaTimeMS ) {
  12722. for( var i = 0; i < playing.length; i++ )
  12723. playing[ i ].update( deltaTimeMS );
  12724. };
  12725. //--- add ---
  12726. that.addToUpdate = function( animation ) {
  12727. if( playing.indexOf( animation ) === -1 )
  12728. playing.push( animation );
  12729. };
  12730. //--- remove ---
  12731. that.removeFromUpdate = function( animation ) {
  12732. var index = playing.indexOf( animation );
  12733. if( index !== -1 )
  12734. playing.splice( index, 1 );
  12735. };
  12736. //--- add ---
  12737. that.add = function( data ) {
  12738. if( library[ data.name ] !== undefined )
  12739. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  12740. library[ data.name ] = data;
  12741. initData( data );
  12742. };
  12743. //--- get ---
  12744. that.get = function( name ) {
  12745. if( typeof name === "string" ) {
  12746. if( library[ name ] ) {
  12747. return library[ name ];
  12748. } else {
  12749. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  12750. return null;
  12751. }
  12752. } else {
  12753. // todo: add simple tween library
  12754. }
  12755. };
  12756. //--- parse ---
  12757. that.parse = function( root ) {
  12758. // setup hierarchy
  12759. var hierarchy = [];
  12760. if ( root instanceof THREE.SkinnedMesh ) {
  12761. for( var b = 0; b < root.bones.length; b++ ) {
  12762. hierarchy.push( root.bones[ b ] );
  12763. }
  12764. } else {
  12765. parseRecurseHierarchy( root, hierarchy );
  12766. }
  12767. return hierarchy;
  12768. };
  12769. var parseRecurseHierarchy = function( root, hierarchy ) {
  12770. hierarchy.push( root );
  12771. for( var c = 0; c < root.children.length; c++ )
  12772. parseRecurseHierarchy( root.children[ c ], hierarchy );
  12773. }
  12774. //--- init data ---
  12775. var initData = function( data ) {
  12776. if( data.initialized === true )
  12777. return;
  12778. // loop through all keys
  12779. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  12780. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12781. // remove minus times
  12782. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  12783. data.hierarchy[ h ].keys[ k ].time = 0;
  12784. // create quaternions
  12785. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  12786. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  12787. var quat = data.hierarchy[ h ].keys[ k ].rot;
  12788. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  12789. }
  12790. }
  12791. // prepare morph target keys
  12792. if( data.hierarchy[h].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  12793. // get all used
  12794. var usedMorphTargets = {};
  12795. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12796. for( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  12797. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  12798. usedMorphTargets[ morphTargetName ] = -1;
  12799. }
  12800. }
  12801. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  12802. // set all used on all frames
  12803. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12804. var influences = {};
  12805. for( var morphTargetName in usedMorphTargets ) {
  12806. for( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  12807. if( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  12808. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  12809. break;
  12810. }
  12811. }
  12812. if( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  12813. influences[ morphTargetName ] = 0;
  12814. }
  12815. }
  12816. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  12817. }
  12818. }
  12819. // remove all keys that are on the same time
  12820. for( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12821. if( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  12822. data.hierarchy[ h ].keys.splice( k, 1 );
  12823. k --;
  12824. }
  12825. }
  12826. // set index
  12827. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12828. data.hierarchy[ h ].keys[ k ].index = k;
  12829. }
  12830. }
  12831. // JIT
  12832. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  12833. data.JIT = {};
  12834. data.JIT.hierarchy = [];
  12835. for( var h = 0; h < data.hierarchy.length; h ++ )
  12836. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  12837. // done
  12838. data.initialized = true;
  12839. };
  12840. // interpolation types
  12841. that.LINEAR = 0;
  12842. that.CATMULLROM = 1;
  12843. that.CATMULLROM_FORWARD = 2;
  12844. return that;
  12845. }());
  12846. /**
  12847. * @author mikael emtinger / http://gomo.se/
  12848. * @author mrdoob / http://mrdoob.com/
  12849. * @author alteredq / http://alteredqualia.com/
  12850. */
  12851. THREE.Animation = function( root, data, interpolationType, JITCompile ) {
  12852. this.root = root;
  12853. this.data = THREE.AnimationHandler.get( data );
  12854. this.hierarchy = THREE.AnimationHandler.parse( root );
  12855. this.currentTime = 0;
  12856. this.timeScale = 1;
  12857. this.isPlaying = false;
  12858. this.isPaused = true;
  12859. this.loop = true;
  12860. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  12861. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  12862. this.points = [];
  12863. this.target = new THREE.Vector3();
  12864. };
  12865. // Play
  12866. THREE.Animation.prototype.play = function( loop, startTimeMS ) {
  12867. if( !this.isPlaying ) {
  12868. this.isPlaying = true;
  12869. this.loop = loop !== undefined ? loop : true;
  12870. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  12871. // reset key cache
  12872. var h, hl = this.hierarchy.length,
  12873. object;
  12874. for ( h = 0; h < hl; h++ ) {
  12875. object = this.hierarchy[ h ];
  12876. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  12877. object.useQuaternion = true;
  12878. }
  12879. object.matrixAutoUpdate = true;
  12880. if ( object.animationCache === undefined ) {
  12881. object.animationCache = {};
  12882. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  12883. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  12884. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  12885. }
  12886. var prevKey = object.animationCache.prevKey;
  12887. var nextKey = object.animationCache.nextKey;
  12888. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  12889. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  12890. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  12891. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  12892. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  12893. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  12894. }
  12895. this.update( 0 );
  12896. }
  12897. this.isPaused = false;
  12898. THREE.AnimationHandler.addToUpdate( this );
  12899. };
  12900. // Pause
  12901. THREE.Animation.prototype.pause = function() {
  12902. if( this.isPaused ) {
  12903. THREE.AnimationHandler.addToUpdate( this );
  12904. } else {
  12905. THREE.AnimationHandler.removeFromUpdate( this );
  12906. }
  12907. this.isPaused = !this.isPaused;
  12908. };
  12909. // Stop
  12910. THREE.Animation.prototype.stop = function() {
  12911. this.isPlaying = false;
  12912. this.isPaused = false;
  12913. THREE.AnimationHandler.removeFromUpdate( this );
  12914. // reset JIT matrix and remove cache
  12915. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  12916. if ( this.hierarchy[ h ].animationCache !== undefined ) {
  12917. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  12918. this.hierarchy[ h ].skinMatrix = this.hierarchy[ h ].animationCache.originalMatrix;
  12919. } else {
  12920. this.hierarchy[ h ].matrix = this.hierarchy[ h ].animationCache.originalMatrix;
  12921. }
  12922. delete this.hierarchy[ h ].animationCache;
  12923. }
  12924. }
  12925. };
  12926. // Update
  12927. THREE.Animation.prototype.update = function( deltaTimeMS ) {
  12928. // early out
  12929. if( !this.isPlaying ) return;
  12930. // vars
  12931. var types = [ "pos", "rot", "scl" ];
  12932. var type;
  12933. var scale;
  12934. var vector;
  12935. var prevXYZ, nextXYZ;
  12936. var prevKey, nextKey;
  12937. var object;
  12938. var animationCache;
  12939. var frame;
  12940. var JIThierarchy = this.data.JIT.hierarchy;
  12941. var currentTime, unloopedCurrentTime;
  12942. var currentPoint, forwardPoint, angle;
  12943. // update
  12944. this.currentTime += deltaTimeMS * this.timeScale;
  12945. unloopedCurrentTime = this.currentTime;
  12946. currentTime = this.currentTime = this.currentTime % this.data.length;
  12947. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  12948. // update
  12949. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  12950. object = this.hierarchy[ h ];
  12951. animationCache = object.animationCache;
  12952. // use JIT?
  12953. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  12954. if( object instanceof THREE.Bone ) {
  12955. object.skinMatrix = JIThierarchy[ h ][ frame ];
  12956. object.matrixAutoUpdate = false;
  12957. object.matrixWorldNeedsUpdate = false;
  12958. } else {
  12959. object.matrix = JIThierarchy[ h ][ frame ];
  12960. object.matrixAutoUpdate = false;
  12961. object.matrixWorldNeedsUpdate = true;
  12962. }
  12963. // use interpolation
  12964. } else {
  12965. // make sure so original matrix and not JIT matrix is set
  12966. if ( this.JITCompile ) {
  12967. if( object instanceof THREE.Bone ) {
  12968. object.skinMatrix = object.animationCache.originalMatrix;
  12969. } else {
  12970. object.matrix = object.animationCache.originalMatrix;
  12971. }
  12972. }
  12973. // loop through pos/rot/scl
  12974. for ( var t = 0; t < 3; t++ ) {
  12975. // get keys
  12976. type = types[ t ];
  12977. prevKey = animationCache.prevKey[ type ];
  12978. nextKey = animationCache.nextKey[ type ];
  12979. // switch keys?
  12980. if ( nextKey.time <= unloopedCurrentTime ) {
  12981. // did we loop?
  12982. if ( currentTime < unloopedCurrentTime ) {
  12983. if ( this.loop ) {
  12984. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  12985. nextKey = this.getNextKeyWith( type, h, 1 );
  12986. while( nextKey.time < currentTime ) {
  12987. prevKey = nextKey;
  12988. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  12989. }
  12990. } else {
  12991. this.stop();
  12992. return;
  12993. }
  12994. } else {
  12995. do {
  12996. prevKey = nextKey;
  12997. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  12998. } while( nextKey.time < currentTime )
  12999. }
  13000. animationCache.prevKey[ type ] = prevKey;
  13001. animationCache.nextKey[ type ] = nextKey;
  13002. }
  13003. object.matrixAutoUpdate = true;
  13004. object.matrixWorldNeedsUpdate = true;
  13005. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  13006. prevXYZ = prevKey[ type ];
  13007. nextXYZ = nextKey[ type ];
  13008. // check scale error
  13009. if ( scale < 0 || scale > 1 ) {
  13010. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  13011. scale = scale < 0 ? 0 : 1;
  13012. }
  13013. // interpolate
  13014. if ( type === "pos" ) {
  13015. vector = object.position;
  13016. if( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  13017. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  13018. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  13019. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  13020. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  13021. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13022. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  13023. this.points[ 1 ] = prevXYZ;
  13024. this.points[ 2 ] = nextXYZ;
  13025. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  13026. scale = scale * 0.33 + 0.33;
  13027. currentPoint = this.interpolateCatmullRom( this.points, scale );
  13028. vector.x = currentPoint[ 0 ];
  13029. vector.y = currentPoint[ 1 ];
  13030. vector.z = currentPoint[ 2 ];
  13031. if( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13032. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  13033. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  13034. this.target.subSelf( vector );
  13035. this.target.y = 0;
  13036. this.target.normalize();
  13037. angle = Math.atan2( this.target.x, this.target.z );
  13038. object.rotation.set( 0, angle, 0 );
  13039. }
  13040. }
  13041. } else if ( type === "rot" ) {
  13042. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  13043. } else if( type === "scl" ) {
  13044. vector = object.scale;
  13045. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  13046. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  13047. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  13048. }
  13049. }
  13050. }
  13051. }
  13052. // update JIT?
  13053. if ( this.JITCompile ) {
  13054. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  13055. this.hierarchy[ 0 ].updateMatrixWorld( true );
  13056. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  13057. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  13058. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  13059. } else {
  13060. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  13061. }
  13062. }
  13063. }
  13064. }
  13065. };
  13066. // Catmull-Rom spline
  13067. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  13068. var c = [], v3 = [],
  13069. point, intPoint, weight, w2, w3,
  13070. pa, pb, pc, pd;
  13071. point = ( points.length - 1 ) * scale;
  13072. intPoint = Math.floor( point );
  13073. weight = point - intPoint;
  13074. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  13075. c[ 1 ] = intPoint;
  13076. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  13077. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  13078. pa = points[ c[ 0 ] ];
  13079. pb = points[ c[ 1 ] ];
  13080. pc = points[ c[ 2 ] ];
  13081. pd = points[ c[ 3 ] ];
  13082. w2 = weight * weight;
  13083. w3 = weight * w2;
  13084. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  13085. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  13086. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  13087. return v3;
  13088. };
  13089. THREE.Animation.prototype.interpolate = function( p0, p1, p2, p3, t, t2, t3 ) {
  13090. var v0 = ( p2 - p0 ) * 0.5,
  13091. v1 = ( p3 - p1 ) * 0.5;
  13092. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  13093. };
  13094. // Get next key with
  13095. THREE.Animation.prototype.getNextKeyWith = function( type, h, key ) {
  13096. var keys = this.data.hierarchy[ h ].keys;
  13097. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  13098. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13099. key = key < keys.length - 1 ? key : keys.length - 1;
  13100. } else {
  13101. key = key % keys.length;
  13102. }
  13103. for ( ; key < keys.length; key++ ) {
  13104. if ( keys[ key ][ type ] !== undefined ) {
  13105. return keys[ key ];
  13106. }
  13107. }
  13108. return this.data.hierarchy[ h ].keys[ 0 ];
  13109. };
  13110. // Get previous key with
  13111. THREE.Animation.prototype.getPrevKeyWith = function( type, h, key ) {
  13112. var keys = this.data.hierarchy[ h ].keys;
  13113. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  13114. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13115. key = key > 0 ? key : 0;
  13116. } else {
  13117. key = key >= 0 ? key : key + keys.length;
  13118. }
  13119. for ( ; key >= 0; key-- ) {
  13120. if ( keys[ key ][ type ] !== undefined ) {
  13121. return keys[ key ];
  13122. }
  13123. }
  13124. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  13125. };/**
  13126. * @author mikael emtinger / http://gomo.se/
  13127. * @author mrdoob / http://mrdoob.com/
  13128. * @author alteredq / http://alteredqualia.com/
  13129. * @author khang duong
  13130. * @author erik kitson
  13131. */
  13132. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  13133. this.root = root;
  13134. this.data = THREE.AnimationHandler.get( data );
  13135. this.hierarchy = THREE.AnimationHandler.parse( root );
  13136. this.currentTime = 0;
  13137. this.timeScale = 0.001;
  13138. this.isPlaying = false;
  13139. this.isPaused = true;
  13140. this.loop = true;
  13141. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  13142. // initialize to first keyframes
  13143. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  13144. var keys = this.data.hierarchy[h].keys,
  13145. sids = this.data.hierarchy[h].sids,
  13146. obj = this.hierarchy[h];
  13147. if ( keys.length && sids ) {
  13148. for ( var s = 0; s < sids.length; s++ ) {
  13149. var sid = sids[ s ],
  13150. next = this.getNextKeyWith( sid, h, 0 );
  13151. if ( next ) {
  13152. next.apply( sid );
  13153. }
  13154. }
  13155. obj.matrixAutoUpdate = false;
  13156. this.data.hierarchy[h].node.updateMatrix();
  13157. obj.matrixWorldNeedsUpdate = true;
  13158. }
  13159. }
  13160. };
  13161. // Play
  13162. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  13163. if( !this.isPlaying ) {
  13164. this.isPlaying = true;
  13165. this.loop = loop !== undefined ? loop : true;
  13166. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  13167. this.startTimeMs = startTimeMS;
  13168. this.startTime = 10000000;
  13169. this.endTime = -this.startTime;
  13170. // reset key cache
  13171. var h, hl = this.hierarchy.length,
  13172. object,
  13173. node;
  13174. for ( h = 0; h < hl; h++ ) {
  13175. object = this.hierarchy[ h ];
  13176. node = this.data.hierarchy[ h ];
  13177. object.useQuaternion = true;
  13178. if ( node.animationCache === undefined ) {
  13179. node.animationCache = {};
  13180. node.animationCache.prevKey = null;
  13181. node.animationCache.nextKey = null;
  13182. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  13183. }
  13184. var keys = this.data.hierarchy[h].keys;
  13185. if (keys.length) {
  13186. node.animationCache.prevKey = keys[ 0 ];
  13187. node.animationCache.nextKey = keys[ 1 ];
  13188. this.startTime = Math.min( keys[0].time, this.startTime );
  13189. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  13190. }
  13191. }
  13192. this.update( 0 );
  13193. }
  13194. this.isPaused = false;
  13195. THREE.AnimationHandler.addToUpdate( this );
  13196. };
  13197. // Pause
  13198. THREE.KeyFrameAnimation.prototype.pause = function() {
  13199. if( this.isPaused ) {
  13200. THREE.AnimationHandler.addToUpdate( this );
  13201. } else {
  13202. THREE.AnimationHandler.removeFromUpdate( this );
  13203. }
  13204. this.isPaused = !this.isPaused;
  13205. };
  13206. // Stop
  13207. THREE.KeyFrameAnimation.prototype.stop = function() {
  13208. this.isPlaying = false;
  13209. this.isPaused = false;
  13210. THREE.AnimationHandler.removeFromUpdate( this );
  13211. // reset JIT matrix and remove cache
  13212. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  13213. var obj = this.hierarchy[ h ];
  13214. var node = this.data.hierarchy[ h ];
  13215. if ( node.animationCache !== undefined ) {
  13216. var original = node.animationCache.originalMatrix;
  13217. if( obj instanceof THREE.Bone ) {
  13218. original.copy( obj.skinMatrix );
  13219. obj.skinMatrix = original;
  13220. } else {
  13221. original.copy( obj.matrix );
  13222. obj.matrix = original;
  13223. }
  13224. delete node.animationCache;
  13225. }
  13226. }
  13227. };
  13228. // Update
  13229. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  13230. // early out
  13231. if( !this.isPlaying ) return;
  13232. // vars
  13233. var prevKey, nextKey;
  13234. var object;
  13235. var node;
  13236. var frame;
  13237. var JIThierarchy = this.data.JIT.hierarchy;
  13238. var currentTime, unloopedCurrentTime;
  13239. var looped;
  13240. // update
  13241. this.currentTime += deltaTimeMS * this.timeScale;
  13242. unloopedCurrentTime = this.currentTime;
  13243. currentTime = this.currentTime = this.currentTime % this.data.length;
  13244. // if looped around, the current time should be based on the startTime
  13245. if ( currentTime < this.startTimeMs ) {
  13246. currentTime = this.currentTime = this.startTimeMs + currentTime;
  13247. }
  13248. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  13249. looped = currentTime < unloopedCurrentTime;
  13250. if ( looped && !this.loop ) {
  13251. // Set the animation to the last keyframes and stop
  13252. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  13253. var keys = this.data.hierarchy[h].keys,
  13254. sids = this.data.hierarchy[h].sids,
  13255. end = keys.length-1,
  13256. obj = this.hierarchy[h];
  13257. if ( keys.length ) {
  13258. for ( var s = 0; s < sids.length; s++ ) {
  13259. var sid = sids[ s ],
  13260. prev = this.getPrevKeyWith( sid, h, end );
  13261. if ( prev ) {
  13262. prev.apply( sid );
  13263. }
  13264. }
  13265. this.data.hierarchy[h].node.updateMatrix();
  13266. obj.matrixWorldNeedsUpdate = true;
  13267. }
  13268. }
  13269. this.stop();
  13270. return;
  13271. }
  13272. // check pre-infinity
  13273. if ( currentTime < this.startTime ) {
  13274. return;
  13275. }
  13276. // update
  13277. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  13278. object = this.hierarchy[ h ];
  13279. node = this.data.hierarchy[ h ];
  13280. var keys = node.keys,
  13281. animationCache = node.animationCache;
  13282. // use JIT?
  13283. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  13284. if( object instanceof THREE.Bone ) {
  13285. object.skinMatrix = JIThierarchy[ h ][ frame ];
  13286. object.matrixWorldNeedsUpdate = false;
  13287. } else {
  13288. object.matrix = JIThierarchy[ h ][ frame ];
  13289. object.matrixWorldNeedsUpdate = true;
  13290. }
  13291. // use interpolation
  13292. } else if ( keys.length ) {
  13293. // make sure so original matrix and not JIT matrix is set
  13294. if ( this.JITCompile && animationCache ) {
  13295. if( object instanceof THREE.Bone ) {
  13296. object.skinMatrix = animationCache.originalMatrix;
  13297. } else {
  13298. object.matrix = animationCache.originalMatrix;
  13299. }
  13300. }
  13301. prevKey = animationCache.prevKey;
  13302. nextKey = animationCache.nextKey;
  13303. if ( prevKey && nextKey ) {
  13304. // switch keys?
  13305. if ( nextKey.time <= unloopedCurrentTime ) {
  13306. // did we loop?
  13307. if ( looped && this.loop ) {
  13308. prevKey = keys[ 0 ];
  13309. nextKey = keys[ 1 ];
  13310. while ( nextKey.time < currentTime ) {
  13311. prevKey = nextKey;
  13312. nextKey = keys[ prevKey.index + 1 ];
  13313. }
  13314. } else if ( !looped ) {
  13315. var lastIndex = keys.length - 1;
  13316. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  13317. prevKey = nextKey;
  13318. nextKey = keys[ prevKey.index + 1 ];
  13319. }
  13320. }
  13321. animationCache.prevKey = prevKey;
  13322. animationCache.nextKey = nextKey;
  13323. }
  13324. if(nextKey.time >= currentTime)
  13325. prevKey.interpolate( nextKey, currentTime );
  13326. else
  13327. prevKey.interpolate( nextKey, nextKey.time);
  13328. }
  13329. this.data.hierarchy[h].node.updateMatrix();
  13330. object.matrixWorldNeedsUpdate = true;
  13331. }
  13332. }
  13333. // update JIT?
  13334. if ( this.JITCompile ) {
  13335. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  13336. this.hierarchy[ 0 ].updateMatrixWorld( true );
  13337. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  13338. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  13339. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  13340. } else {
  13341. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  13342. }
  13343. }
  13344. }
  13345. }
  13346. };
  13347. // Get next key with
  13348. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  13349. var keys = this.data.hierarchy[ h ].keys;
  13350. key = key % keys.length;
  13351. for ( ; key < keys.length; key++ ) {
  13352. if ( keys[ key ].hasTarget( sid ) ) {
  13353. return keys[ key ];
  13354. }
  13355. }
  13356. return keys[ 0 ];
  13357. };
  13358. // Get previous key with
  13359. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  13360. var keys = this.data.hierarchy[ h ].keys;
  13361. key = key >= 0 ? key : key + keys.length;
  13362. for ( ; key >= 0; key-- ) {
  13363. if ( keys[ key ].hasTarget( sid ) ) {
  13364. return keys[ key ];
  13365. }
  13366. }
  13367. return keys[ keys.length - 1 ];
  13368. };
  13369. /**
  13370. * Camera for rendering cube maps
  13371. * - renders scene into axis-aligned cube
  13372. *
  13373. * @author alteredq / http://alteredqualia.com/
  13374. */
  13375. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  13376. THREE.Object3D.call( this );
  13377. var fov = 90, aspect = 1;
  13378. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13379. cameraPX.up.set( 0, -1, 0 );
  13380. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  13381. this.add( cameraPX );
  13382. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13383. cameraNX.up.set( 0, -1, 0 );
  13384. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  13385. this.add( cameraNX );
  13386. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13387. cameraPY.up.set( 0, 0, 1 );
  13388. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  13389. this.add( cameraPY );
  13390. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13391. cameraNY.up.set( 0, 0, -1 );
  13392. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  13393. this.add( cameraNY );
  13394. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13395. cameraPZ.up.set( 0, -1, 0 );
  13396. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  13397. this.add( cameraPZ );
  13398. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13399. cameraNZ.up.set( 0, -1, 0 );
  13400. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  13401. this.add( cameraNZ );
  13402. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  13403. this.updateCubeMap = function ( renderer, scene ) {
  13404. var renderTarget = this.renderTarget;
  13405. var generateMipmaps = renderTarget.generateMipmaps;
  13406. renderTarget.generateMipmaps = false;
  13407. renderTarget.activeCubeFace = 0;
  13408. renderer.render( scene, cameraPX, renderTarget );
  13409. renderTarget.activeCubeFace = 1;
  13410. renderer.render( scene, cameraNX, renderTarget );
  13411. renderTarget.activeCubeFace = 2;
  13412. renderer.render( scene, cameraPY, renderTarget );
  13413. renderTarget.activeCubeFace = 3;
  13414. renderer.render( scene, cameraNY, renderTarget );
  13415. renderTarget.activeCubeFace = 4;
  13416. renderer.render( scene, cameraPZ, renderTarget );
  13417. renderTarget.generateMipmaps = generateMipmaps;
  13418. renderTarget.activeCubeFace = 5;
  13419. renderer.render( scene, cameraNZ, renderTarget );
  13420. };
  13421. };
  13422. THREE.CubeCamera.prototype = new THREE.Object3D();
  13423. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  13424. /*
  13425. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  13426. *
  13427. * A general perpose camera, for setting FOV, Lens Focal Length,
  13428. * and switching between perspective and orthographic views easily.
  13429. * Use this only if you do not wish to manage
  13430. * both a Orthographic and Perspective Camera
  13431. *
  13432. */
  13433. THREE.CombinedCamera = function ( width, height, fov, near, far, orthonear, orthofar ) {
  13434. THREE.Camera.call( this );
  13435. this.fov = fov;
  13436. this.left = -width / 2;
  13437. this.right = width / 2
  13438. this.top = height / 2;
  13439. this.bottom = -height / 2;
  13440. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  13441. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthonear, orthofar );
  13442. this.cameraP = new THREE.PerspectiveCamera( fov, width/height, near, far );
  13443. this.zoom = 1;
  13444. this.toPerspective();
  13445. var aspect = width/height;
  13446. };
  13447. THREE.CombinedCamera.prototype = new THREE.Camera();
  13448. THREE.CombinedCamera.prototype.constructor = THREE.CombinedCamera;
  13449. THREE.CombinedCamera.prototype.toPerspective = function () {
  13450. // Switches to the Perspective Camera
  13451. this.near = this.cameraP.near;
  13452. this.far = this.cameraP.far;
  13453. this.cameraP.fov = this.fov / this.zoom ;
  13454. this.cameraP.updateProjectionMatrix();
  13455. this.projectionMatrix = this.cameraP.projectionMatrix;
  13456. this.inPersepectiveMode = true;
  13457. this.inOrthographicMode = false;
  13458. };
  13459. THREE.CombinedCamera.prototype.toOrthographic = function () {
  13460. // Switches to the Orthographic camera estimating viewport from Perspective
  13461. var fov = this.fov;
  13462. var aspect = this.cameraP.aspect;
  13463. var near = this.cameraP.near;
  13464. var far = this.cameraP.far;
  13465. // The size that we set is the mid plane of the viewing frustum
  13466. var hyperfocus = ( near + far ) / 2;
  13467. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  13468. var planeHeight = 2 * halfHeight;
  13469. var planeWidth = planeHeight * aspect;
  13470. var halfWidth = planeWidth / 2;
  13471. halfHeight /= this.zoom;
  13472. halfWidth /= this.zoom;
  13473. this.cameraO.left = -halfWidth;
  13474. this.cameraO.right = halfWidth;
  13475. this.cameraO.top = halfHeight;
  13476. this.cameraO.bottom = -halfHeight;
  13477. // this.cameraO.left = -farHalfWidth;
  13478. // this.cameraO.right = farHalfWidth;
  13479. // this.cameraO.top = farHalfHeight;
  13480. // this.cameraO.bottom = -farHalfHeight;
  13481. // this.cameraO.left = this.left / this.zoom;
  13482. // this.cameraO.right = this.right / this.zoom;
  13483. // this.cameraO.top = this.top / this.zoom;
  13484. // this.cameraO.bottom = this.bottom / this.zoom;
  13485. this.cameraO.updateProjectionMatrix();
  13486. this.near = this.cameraO.near;
  13487. this.far = this.cameraO.far;
  13488. this.projectionMatrix = this.cameraO.projectionMatrix;
  13489. this.inPersepectiveMode = false;
  13490. this.inOrthographicMode = true;
  13491. };
  13492. THREE.CombinedCamera.prototype.setSize = function(width, height) {
  13493. this.cameraP.aspect = width / height;
  13494. this.left = -width / 2;
  13495. this.right = width / 2
  13496. this.top = height / 2;
  13497. this.bottom = -height / 2;
  13498. }
  13499. THREE.CombinedCamera.prototype.setFov = function(fov) {
  13500. this.fov = fov;
  13501. if (this.inPersepectiveMode) {
  13502. this.toPerspective();
  13503. } else {
  13504. this.toOrthographic();
  13505. }
  13506. };
  13507. // For mantaining similar API with PerspectiveCamera
  13508. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  13509. if (this.inPersepectiveMode) {
  13510. this.toPerspective();
  13511. } else {
  13512. this.toPerspective();
  13513. this.toOrthographic();
  13514. }
  13515. };
  13516. /*
  13517. * Uses Focal Length (in mm) to estimate and set FOV
  13518. * 35mm (fullframe) camera is used if frame size is not specified;
  13519. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  13520. */
  13521. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  13522. frameHeight = frameHeight !== undefined ? frameHeight : 24;
  13523. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  13524. this.setFov( fov );
  13525. return fov;
  13526. };
  13527. THREE.CombinedCamera.prototype.setZoom = function(zoom) {
  13528. this.zoom = zoom;
  13529. if (this.inPersepectiveMode) {
  13530. this.toPerspective();
  13531. } else {
  13532. this.toOrthographic();
  13533. }
  13534. };
  13535. THREE.CombinedCamera.prototype.toFrontView = function() {
  13536. this.rotation.x = 0;
  13537. this.rotation.y = 0;
  13538. this.rotation.z = 0;
  13539. // should we be modifing the matrix instead?
  13540. this.rotationAutoUpdate = false;
  13541. };
  13542. THREE.CombinedCamera.prototype.toBackView = function() {
  13543. this.rotation.x = 0;
  13544. this.rotation.y = Math.PI;
  13545. this.rotation.z = 0;
  13546. this.rotationAutoUpdate = false;
  13547. };
  13548. THREE.CombinedCamera.prototype.toLeftView = function() {
  13549. this.rotation.x = 0;
  13550. this.rotation.y = - Math.PI / 2;
  13551. this.rotation.z = 0;
  13552. this.rotationAutoUpdate = false;
  13553. };
  13554. THREE.CombinedCamera.prototype.toRightView = function() {
  13555. this.rotation.x = 0;
  13556. this.rotation.y = Math.PI / 2;
  13557. this.rotation.z = 0;
  13558. this.rotationAutoUpdate = false;
  13559. };
  13560. THREE.CombinedCamera.prototype.toTopView = function() {
  13561. this.rotation.x = - Math.PI / 2;
  13562. this.rotation.y = 0;
  13563. this.rotation.z = 0;
  13564. this.rotationAutoUpdate = false;
  13565. };
  13566. THREE.CombinedCamera.prototype.toBottomView = function() {
  13567. this.rotation.x = Math.PI / 2;
  13568. this.rotation.y = 0;
  13569. this.rotation.z = 0;
  13570. this.rotationAutoUpdate = false;
  13571. };
  13572. /**
  13573. * @author mrdoob / http://mrdoob.com/
  13574. * @author alteredq / http://alteredqualia.com/
  13575. * @author paulirish / http://paulirish.com/
  13576. */
  13577. THREE.FirstPersonControls = function ( object, domElement ) {
  13578. this.object = object;
  13579. this.target = new THREE.Vector3( 0, 0, 0 );
  13580. this.domElement = ( domElement !== undefined ) ? domElement : document;
  13581. this.movementSpeed = 1.0;
  13582. this.lookSpeed = 0.005;
  13583. this.noFly = false;
  13584. this.lookVertical = true;
  13585. this.autoForward = false;
  13586. this.activeLook = true;
  13587. this.heightSpeed = false;
  13588. this.heightCoef = 1.0;
  13589. this.heightMin = 0.0;
  13590. this.constrainVertical = false;
  13591. this.verticalMin = 0;
  13592. this.verticalMax = Math.PI;
  13593. this.autoSpeedFactor = 0.0;
  13594. this.mouseX = 0;
  13595. this.mouseY = 0;
  13596. this.lat = 0;
  13597. this.lon = 0;
  13598. this.phi = 0;
  13599. this.theta = 0;
  13600. this.moveForward = false;
  13601. this.moveBackward = false;
  13602. this.moveLeft = false;
  13603. this.moveRight = false;
  13604. this.freeze = false;
  13605. this.mouseDragOn = false;
  13606. if ( this.domElement === document ) {
  13607. this.viewHalfX = window.innerWidth / 2;
  13608. this.viewHalfY = window.innerHeight / 2;
  13609. } else {
  13610. this.viewHalfX = this.domElement.offsetWidth / 2;
  13611. this.viewHalfY = this.domElement.offsetHeight / 2;
  13612. this.domElement.setAttribute( 'tabindex', -1 );
  13613. }
  13614. this.onMouseDown = function ( event ) {
  13615. if ( this.domElement !== document ) {
  13616. this.domElement.focus();
  13617. }
  13618. event.preventDefault();
  13619. event.stopPropagation();
  13620. if ( this.activeLook ) {
  13621. switch ( event.button ) {
  13622. case 0: this.moveForward = true; break;
  13623. case 2: this.moveBackward = true; break;
  13624. }
  13625. }
  13626. this.mouseDragOn = true;
  13627. };
  13628. this.onMouseUp = function ( event ) {
  13629. event.preventDefault();
  13630. event.stopPropagation();
  13631. if ( this.activeLook ) {
  13632. switch ( event.button ) {
  13633. case 0: this.moveForward = false; break;
  13634. case 2: this.moveBackward = false; break;
  13635. }
  13636. }
  13637. this.mouseDragOn = false;
  13638. };
  13639. this.onMouseMove = function ( event ) {
  13640. if ( this.domElement === document ) {
  13641. this.mouseX = event.pageX - this.viewHalfX;
  13642. this.mouseY = event.pageY - this.viewHalfY;
  13643. } else {
  13644. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  13645. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  13646. }
  13647. };
  13648. this.onKeyDown = function ( event ) {
  13649. switch( event.keyCode ) {
  13650. case 38: /*up*/
  13651. case 87: /*W*/ this.moveForward = true; break;
  13652. case 37: /*left*/
  13653. case 65: /*A*/ this.moveLeft = true; break;
  13654. case 40: /*down*/
  13655. case 83: /*S*/ this.moveBackward = true; break;
  13656. case 39: /*right*/
  13657. case 68: /*D*/ this.moveRight = true; break;
  13658. case 82: /*R*/ this.moveUp = true; break;
  13659. case 70: /*F*/ this.moveDown = true; break;
  13660. case 81: /*Q*/ this.freeze = !this.freeze; break;
  13661. }
  13662. };
  13663. this.onKeyUp = function ( event ) {
  13664. switch( event.keyCode ) {
  13665. case 38: /*up*/
  13666. case 87: /*W*/ this.moveForward = false; break;
  13667. case 37: /*left*/
  13668. case 65: /*A*/ this.moveLeft = false; break;
  13669. case 40: /*down*/
  13670. case 83: /*S*/ this.moveBackward = false; break;
  13671. case 39: /*right*/
  13672. case 68: /*D*/ this.moveRight = false; break;
  13673. case 82: /*R*/ this.moveUp = false; break;
  13674. case 70: /*F*/ this.moveDown = false; break;
  13675. }
  13676. };
  13677. this.update = function( delta ) {
  13678. var actualMoveSpeed = 0;
  13679. if ( this.freeze ) {
  13680. return;
  13681. } else {
  13682. if ( this.heightSpeed ) {
  13683. var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
  13684. var heightDelta = y - this.heightMin;
  13685. this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );
  13686. } else {
  13687. this.autoSpeedFactor = 0.0;
  13688. }
  13689. actualMoveSpeed = delta * this.movementSpeed;
  13690. if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
  13691. if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed );
  13692. if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed );
  13693. if ( this.moveRight ) this.object.translateX( actualMoveSpeed );
  13694. if ( this.moveUp ) this.object.translateY( actualMoveSpeed );
  13695. if ( this.moveDown ) this.object.translateY( - actualMoveSpeed );
  13696. var actualLookSpeed = delta * this.lookSpeed;
  13697. if ( !this.activeLook ) {
  13698. actualLookSpeed = 0;
  13699. }
  13700. this.lon += this.mouseX * actualLookSpeed;
  13701. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed;
  13702. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  13703. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  13704. this.theta = this.lon * Math.PI / 180;
  13705. var targetPosition = this.target,
  13706. position = this.object.position;
  13707. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  13708. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  13709. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  13710. }
  13711. var verticalLookRatio = 1;
  13712. if ( this.constrainVertical ) {
  13713. verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );
  13714. }
  13715. this.lon += this.mouseX * actualLookSpeed;
  13716. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;
  13717. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  13718. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  13719. this.theta = this.lon * Math.PI / 180;
  13720. if ( this.constrainVertical ) {
  13721. this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );
  13722. }
  13723. var targetPosition = this.target,
  13724. position = this.object.position;
  13725. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  13726. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  13727. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  13728. this.object.lookAt( targetPosition );
  13729. };
  13730. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  13731. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  13732. this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
  13733. this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
  13734. this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
  13735. this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
  13736. function bind( scope, fn ) {
  13737. return function () {
  13738. fn.apply( scope, arguments );
  13739. };
  13740. };
  13741. };
  13742. /**
  13743. * @author alteredq / http://alteredqualia.com/
  13744. */
  13745. THREE.PathControls = function ( object, domElement ) {
  13746. this.object = object;
  13747. this.domElement = ( domElement !== undefined ) ? domElement : document;
  13748. this.id = "PathControls" + THREE.PathControlsIdCounter ++;
  13749. // API
  13750. this.duration = 10 * 1000; // milliseconds
  13751. this.waypoints = [];
  13752. this.useConstantSpeed = true;
  13753. this.resamplingCoef = 50;
  13754. this.debugPath = new THREE.Object3D();
  13755. this.debugDummy = new THREE.Object3D();
  13756. this.animationParent = new THREE.Object3D();
  13757. this.lookSpeed = 0.005;
  13758. this.lookVertical = true;
  13759. this.lookHorizontal = true;
  13760. this.verticalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  13761. this.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  13762. // internals
  13763. this.target = new THREE.Object3D();
  13764. this.mouseX = 0;
  13765. this.mouseY = 0;
  13766. this.lat = 0;
  13767. this.lon = 0;
  13768. this.phi = 0;
  13769. this.theta = 0;
  13770. if ( this.domElement === document ) {
  13771. this.viewHalfX = window.innerWidth / 2;
  13772. this.viewHalfY = window.innerHeight / 2;
  13773. } else {
  13774. this.viewHalfX = this.domElement.offsetWidth / 2;
  13775. this.viewHalfY = this.domElement.offsetHeight / 2;
  13776. this.domElement.setAttribute( 'tabindex', -1 );
  13777. }
  13778. var PI2 = Math.PI * 2,
  13779. PI180 = Math.PI / 180;
  13780. // methods
  13781. this.update = function ( delta ) {
  13782. var srcRange, dstRange;
  13783. if( this.lookHorizontal ) this.lon += this.mouseX * this.lookSpeed * delta;
  13784. if( this.lookVertical ) this.lat -= this.mouseY * this.lookSpeed * delta;
  13785. this.lon = Math.max( 0, Math.min( 360, this.lon ) );
  13786. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  13787. this.phi = ( 90 - this.lat ) * PI180;
  13788. this.theta = this.lon * PI180;
  13789. this.phi = normalize_angle_rad( this.phi );
  13790. // constrain vertical look angle
  13791. srcRange = this.verticalAngleMap.srcRange;
  13792. dstRange = this.verticalAngleMap.dstRange;
  13793. var tmpPhi = THREE.Math.mapLinear( this.phi, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  13794. var tmpPhiFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  13795. var tmpPhiNormalized = ( tmpPhi - dstRange[ 0 ] ) / tmpPhiFullRange;
  13796. this.phi = QuadraticEaseInOut( tmpPhiNormalized ) * tmpPhiFullRange + dstRange[ 0 ];
  13797. // constrain horizontal look angle
  13798. srcRange = this.horizontalAngleMap.srcRange;
  13799. dstRange = this.horizontalAngleMap.dstRange;
  13800. var tmpTheta = THREE.Math.mapLinear( this.theta, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  13801. var tmpThetaFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  13802. var tmpThetaNormalized = ( tmpTheta - dstRange[ 0 ] ) / tmpThetaFullRange;
  13803. this.theta = QuadraticEaseInOut( tmpThetaNormalized ) * tmpThetaFullRange + dstRange[ 0 ];
  13804. var targetPosition = this.target.position,
  13805. position = this.object.position;
  13806. targetPosition.x = 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  13807. targetPosition.y = 100 * Math.cos( this.phi );
  13808. targetPosition.z = 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  13809. this.object.lookAt( this.target.position );
  13810. };
  13811. this.onMouseMove = function ( event ) {
  13812. if ( this.domElement === document ) {
  13813. this.mouseX = event.pageX - this.viewHalfX;
  13814. this.mouseY = event.pageY - this.viewHalfY;
  13815. } else {
  13816. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  13817. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  13818. }
  13819. };
  13820. // utils
  13821. function normalize_angle_rad( a ) {
  13822. var b = a % PI2;
  13823. return b >= 0 ? b : b + PI2;
  13824. };
  13825. function distance( a, b ) {
  13826. var dx = a[ 0 ] - b[ 0 ],
  13827. dy = a[ 1 ] - b[ 1 ],
  13828. dz = a[ 2 ] - b[ 2 ];
  13829. return Math.sqrt( dx * dx + dy * dy + dz * dz );
  13830. };
  13831. function QuadraticEaseInOut ( k ) {
  13832. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  13833. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  13834. };
  13835. function bind( scope, fn ) {
  13836. return function () {
  13837. fn.apply( scope, arguments );
  13838. };
  13839. };
  13840. function initAnimationPath( parent, spline, name, duration ) {
  13841. var animationData = {
  13842. name: name,
  13843. fps: 0.6,
  13844. length: duration,
  13845. hierarchy: []
  13846. };
  13847. var i,
  13848. parentAnimation, childAnimation,
  13849. path = spline.getControlPointsArray(),
  13850. sl = spline.getLength(),
  13851. pl = path.length,
  13852. t = 0,
  13853. first = 0,
  13854. last = pl - 1;
  13855. parentAnimation = { parent: -1, keys: [] };
  13856. parentAnimation.keys[ first ] = { time: 0, pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  13857. parentAnimation.keys[ last ] = { time: duration, pos: path[ last ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  13858. for ( i = 1; i < pl - 1; i++ ) {
  13859. // real distance (approximation via linear segments)
  13860. t = duration * sl.chunks[ i ] / sl.total;
  13861. // equal distance
  13862. //t = duration * ( i / pl );
  13863. // linear distance
  13864. //t += duration * distance( path[ i ], path[ i - 1 ] ) / sl.total;
  13865. parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };
  13866. }
  13867. animationData.hierarchy[ 0 ] = parentAnimation;
  13868. THREE.AnimationHandler.add( animationData );
  13869. return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );
  13870. };
  13871. function createSplineGeometry( spline, n_sub ) {
  13872. var i, index, position,
  13873. geometry = new THREE.Geometry();
  13874. for ( i = 0; i < spline.points.length * n_sub; i ++ ) {
  13875. index = i / ( spline.points.length * n_sub );
  13876. position = spline.getPoint( index );
  13877. geometry.vertices[ i ] = new THREE.Vertex( position.x, position.y, position.z );
  13878. }
  13879. return geometry;
  13880. };
  13881. function createPath( parent, spline ) {
  13882. var lineGeo = createSplineGeometry( spline, 10 ),
  13883. particleGeo = createSplineGeometry( spline, 10 ),
  13884. lineMat = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 3 } ),
  13885. lineObj = new THREE.Line( lineGeo, lineMat ),
  13886. particleObj = new THREE.ParticleSystem( particleGeo, new THREE.ParticleBasicMaterial( { color: 0xffaa00, size: 3 } ) );
  13887. lineObj.scale.set( 1, 1, 1 );
  13888. parent.add( lineObj );
  13889. particleObj.scale.set( 1, 1, 1 );
  13890. parent.add( particleObj );
  13891. var waypoint,
  13892. geo = new THREE.SphereGeometry( 1, 16, 8 ),
  13893. mat = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  13894. for ( var i = 0; i < spline.points.length; i ++ ) {
  13895. waypoint = new THREE.Mesh( geo, mat );
  13896. waypoint.position.copy( spline.points[ i ] );
  13897. parent.add( waypoint );
  13898. }
  13899. };
  13900. this.init = function ( ) {
  13901. // constructor
  13902. this.spline = new THREE.Spline();
  13903. this.spline.initFromArray( this.waypoints );
  13904. if ( this.useConstantSpeed ) {
  13905. this.spline.reparametrizeByArcLength( this.resamplingCoef );
  13906. }
  13907. if ( this.createDebugDummy ) {
  13908. var dummyParentMaterial = new THREE.MeshLambertMaterial( { color: 0x0077ff } ),
  13909. dummyChildMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ),
  13910. dummyParentGeo = new THREE.CubeGeometry( 10, 10, 20 ),
  13911. dummyChildGeo = new THREE.CubeGeometry( 2, 2, 10 );
  13912. this.animationParent = new THREE.Mesh( dummyParentGeo, dummyParentMaterial );
  13913. var dummyChild = new THREE.Mesh( dummyChildGeo, dummyChildMaterial );
  13914. dummyChild.position.set( 0, 10, 0 );
  13915. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  13916. this.animationParent.add( this.object );
  13917. this.animationParent.add( this.target );
  13918. this.animationParent.add( dummyChild );
  13919. } else {
  13920. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  13921. this.animationParent.add( this.target );
  13922. this.animationParent.add( this.object );
  13923. }
  13924. if ( this.createDebugPath ) {
  13925. createPath( this.debugPath, this.spline );
  13926. }
  13927. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  13928. };
  13929. };
  13930. THREE.PathControlsIdCounter = 0;
  13931. /**
  13932. * @author James Baicoianu / http://www.baicoianu.com/
  13933. */
  13934. THREE.FlyControls = function ( object, domElement ) {
  13935. this.object = object;
  13936. this.domElement = ( domElement !== undefined ) ? domElement : document;
  13937. if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );
  13938. // API
  13939. this.movementSpeed = 1.0;
  13940. this.rollSpeed = 0.005;
  13941. this.dragToLook = false;
  13942. this.autoForward = false;
  13943. // disable default target object behavior
  13944. this.object.useQuaternion = true;
  13945. // internals
  13946. this.tmpQuaternion = new THREE.Quaternion();
  13947. this.mouseStatus = 0;
  13948. 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 };
  13949. this.moveVector = new THREE.Vector3( 0, 0, 0 );
  13950. this.rotationVector = new THREE.Vector3( 0, 0, 0 );
  13951. this.handleEvent = function ( event ) {
  13952. if ( typeof this[ event.type ] == 'function' ) {
  13953. this[ event.type ]( event );
  13954. }
  13955. };
  13956. this.keydown = function( event ) {
  13957. if ( event.altKey ) {
  13958. return;
  13959. }
  13960. switch( event.keyCode ) {
  13961. case 16: /* shift */ this.movementSpeedMultiplier = .1; break;
  13962. case 87: /*W*/ this.moveState.forward = 1; break;
  13963. case 83: /*S*/ this.moveState.back = 1; break;
  13964. case 65: /*A*/ this.moveState.left = 1; break;
  13965. case 68: /*D*/ this.moveState.right = 1; break;
  13966. case 82: /*R*/ this.moveState.up = 1; break;
  13967. case 70: /*F*/ this.moveState.down = 1; break;
  13968. case 38: /*up*/ this.moveState.pitchUp = 1; break;
  13969. case 40: /*down*/ this.moveState.pitchDown = 1; break;
  13970. case 37: /*left*/ this.moveState.yawLeft = 1; break;
  13971. case 39: /*right*/ this.moveState.yawRight = 1; break;
  13972. case 81: /*Q*/ this.moveState.rollLeft = 1; break;
  13973. case 69: /*E*/ this.moveState.rollRight = 1; break;
  13974. }
  13975. this.updateMovementVector();
  13976. this.updateRotationVector();
  13977. };
  13978. this.keyup = function( event ) {
  13979. switch( event.keyCode ) {
  13980. case 16: /* shift */ this.movementSpeedMultiplier = 1; break;
  13981. case 87: /*W*/ this.moveState.forward = 0; break;
  13982. case 83: /*S*/ this.moveState.back = 0; break;
  13983. case 65: /*A*/ this.moveState.left = 0; break;
  13984. case 68: /*D*/ this.moveState.right = 0; break;
  13985. case 82: /*R*/ this.moveState.up = 0; break;
  13986. case 70: /*F*/ this.moveState.down = 0; break;
  13987. case 38: /*up*/ this.moveState.pitchUp = 0; break;
  13988. case 40: /*down*/ this.moveState.pitchDown = 0; break;
  13989. case 37: /*left*/ this.moveState.yawLeft = 0; break;
  13990. case 39: /*right*/ this.moveState.yawRight = 0; break;
  13991. case 81: /*Q*/ this.moveState.rollLeft = 0; break;
  13992. case 69: /*E*/ this.moveState.rollRight = 0; break;
  13993. }
  13994. this.updateMovementVector();
  13995. this.updateRotationVector();
  13996. };
  13997. this.mousedown = function( event ) {
  13998. if ( this.domElement !== document ) {
  13999. this.domElement.focus();
  14000. }
  14001. event.preventDefault();
  14002. event.stopPropagation();
  14003. if ( this.dragToLook ) {
  14004. this.mouseStatus ++;
  14005. } else {
  14006. switch ( event.button ) {
  14007. case 0: this.object.moveForward = true; break;
  14008. case 2: this.object.moveBackward = true; break;
  14009. }
  14010. }
  14011. };
  14012. this.mousemove = function( event ) {
  14013. if ( !this.dragToLook || this.mouseStatus > 0 ) {
  14014. var container = this.getContainerDimensions();
  14015. var halfWidth = container.size[ 0 ] / 2;
  14016. var halfHeight = container.size[ 1 ] / 2;
  14017. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  14018. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  14019. this.updateRotationVector();
  14020. }
  14021. };
  14022. this.mouseup = function( event ) {
  14023. event.preventDefault();
  14024. event.stopPropagation();
  14025. if ( this.dragToLook ) {
  14026. this.mouseStatus --;
  14027. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  14028. } else {
  14029. switch ( event.button ) {
  14030. case 0: this.moveForward = false; break;
  14031. case 2: this.moveBackward = false; break;
  14032. }
  14033. }
  14034. this.updateRotationVector();
  14035. };
  14036. this.update = function( delta ) {
  14037. var moveMult = delta * this.movementSpeed;
  14038. var rotMult = delta * this.rollSpeed;
  14039. this.object.translateX( this.moveVector.x * moveMult );
  14040. this.object.translateY( this.moveVector.y * moveMult );
  14041. this.object.translateZ( this.moveVector.z * moveMult );
  14042. this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
  14043. this.object.quaternion.multiplySelf( this.tmpQuaternion );
  14044. this.object.matrix.setPosition( this.object.position );
  14045. this.object.matrix.setRotationFromQuaternion( this.object.quaternion );
  14046. this.object.matrixWorldNeedsUpdate = true;
  14047. };
  14048. this.updateMovementVector = function() {
  14049. var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;
  14050. this.moveVector.x = ( -this.moveState.left + this.moveState.right );
  14051. this.moveVector.y = ( -this.moveState.down + this.moveState.up );
  14052. this.moveVector.z = ( -forward + this.moveState.back );
  14053. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  14054. };
  14055. this.updateRotationVector = function() {
  14056. this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
  14057. this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
  14058. this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
  14059. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  14060. };
  14061. this.getContainerDimensions = function() {
  14062. if ( this.domElement != document ) {
  14063. return {
  14064. size : [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  14065. offset : [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  14066. };
  14067. } else {
  14068. return {
  14069. size : [ window.innerWidth, window.innerHeight ],
  14070. offset : [ 0, 0 ]
  14071. };
  14072. }
  14073. };
  14074. function bind( scope, fn ) {
  14075. return function () {
  14076. fn.apply( scope, arguments );
  14077. };
  14078. };
  14079. this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
  14080. this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
  14081. this.domElement.addEventListener( 'mouseup', bind( this, this.mouseup ), false );
  14082. this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
  14083. this.domElement.addEventListener( 'keyup', bind( this, this.keyup ), false );
  14084. this.updateMovementVector();
  14085. this.updateRotationVector();
  14086. };
  14087. /**
  14088. * @author mikael emtinger / http://gomo.se/
  14089. * @author alteredq / http://alteredqualia.com/
  14090. */
  14091. THREE.RollControls = function ( object, domElement ) {
  14092. this.object = object;
  14093. this.domElement = ( domElement !== undefined ) ? domElement : document;
  14094. // API
  14095. this.mouseLook = true;
  14096. this.autoForward = false;
  14097. this.lookSpeed = 1;
  14098. this.movementSpeed = 1;
  14099. this.rollSpeed = 1;
  14100. this.constrainVertical = [ -0.9, 0.9 ];
  14101. // disable default target object behavior
  14102. this.object.matrixAutoUpdate = false;
  14103. // internals
  14104. this.forward = new THREE.Vector3( 0, 0, 1 );
  14105. this.roll = 0;
  14106. var xTemp = new THREE.Vector3();
  14107. var yTemp = new THREE.Vector3();
  14108. var zTemp = new THREE.Vector3();
  14109. var rollMatrix = new THREE.Matrix4();
  14110. var doRoll = false, rollDirection = 1, forwardSpeed = 0, sideSpeed = 0, upSpeed = 0;
  14111. var mouseX = 0, mouseY = 0;
  14112. var windowHalfX = window.innerWidth / 2;
  14113. var windowHalfY = window.innerHeight / 2;
  14114. // custom update
  14115. this.update = function ( delta ) {
  14116. if ( this.mouseLook ) {
  14117. var actualLookSpeed = delta * this.lookSpeed;
  14118. this.rotateHorizontally( actualLookSpeed * mouseX );
  14119. this.rotateVertically( actualLookSpeed * mouseY );
  14120. }
  14121. var actualSpeed = delta * this.movementSpeed;
  14122. var forwardOrAuto = ( forwardSpeed > 0 || ( this.autoForward && ! ( forwardSpeed < 0 ) ) ) ? 1 : forwardSpeed;
  14123. this.object.translateZ( -actualSpeed * forwardOrAuto );
  14124. this.object.translateX( actualSpeed * sideSpeed );
  14125. this.object.translateY( actualSpeed * upSpeed );
  14126. if( doRoll ) {
  14127. this.roll += this.rollSpeed * delta * rollDirection;
  14128. }
  14129. // cap forward up / down
  14130. if( this.forward.y > this.constrainVertical[ 1 ] ) {
  14131. this.forward.y = this.constrainVertical[ 1 ];
  14132. this.forward.normalize();
  14133. } else if( this.forward.y < this.constrainVertical[ 0 ] ) {
  14134. this.forward.y = this.constrainVertical[ 0 ];
  14135. this.forward.normalize();
  14136. }
  14137. // construct unrolled camera matrix
  14138. zTemp.copy( this.forward );
  14139. yTemp.set( 0, 1, 0 );
  14140. xTemp.cross( yTemp, zTemp ).normalize();
  14141. yTemp.cross( zTemp, xTemp ).normalize();
  14142. this.object.matrix.elements[0] = xTemp.x; this.object.matrix.elements[4] = yTemp.x; this.object.matrix.elements[8] = zTemp.x;
  14143. this.object.matrix.elements[1] = xTemp.y; this.object.matrix.elements[5] = yTemp.y; this.object.matrix.elements[9] = zTemp.y;
  14144. this.object.matrix.elements[2] = xTemp.z; this.object.matrix.elements[6] = yTemp.z; this.object.matrix.elements[10] = zTemp.z;
  14145. // calculate roll matrix
  14146. rollMatrix.identity();
  14147. rollMatrix.elements[0] = Math.cos( this.roll ); rollMatrix.elements[4] = -Math.sin( this.roll );
  14148. rollMatrix.elements[1] = Math.sin( this.roll ); rollMatrix.elements[5] = Math.cos( this.roll );
  14149. // multiply camera with roll
  14150. this.object.matrix.multiplySelf( rollMatrix );
  14151. this.object.matrixWorldNeedsUpdate = true;
  14152. // set position
  14153. this.object.matrix.elements[12] = this.object.position.x;
  14154. this.object.matrix.elements[13] = this.object.position.y;
  14155. this.object.matrix.elements[14] = this.object.position.z;
  14156. };
  14157. this.translateX = function ( distance ) {
  14158. this.object.position.x += this.object.matrix.elements[0] * distance;
  14159. this.object.position.y += this.object.matrix.elements[1] * distance;
  14160. this.object.position.z += this.object.matrix.elements[2] * distance;
  14161. };
  14162. this.translateY = function ( distance ) {
  14163. this.object.position.x += this.object.matrix.elements[4] * distance;
  14164. this.object.position.y += this.object.matrix.elements[5] * distance;
  14165. this.object.position.z += this.object.matrix.elements[6] * distance;
  14166. };
  14167. this.translateZ = function ( distance ) {
  14168. this.object.position.x -= this.object.matrix.elements[8] * distance;
  14169. this.object.position.y -= this.object.matrix.elements[9] * distance;
  14170. this.object.position.z -= this.object.matrix.elements[10] * distance;
  14171. };
  14172. this.rotateHorizontally = function ( amount ) {
  14173. // please note that the amount is NOT degrees, but a scale value
  14174. xTemp.set( this.object.matrix.elements[0], this.object.matrix.elements[1], this.object.matrix.elements[2] );
  14175. xTemp.multiplyScalar( amount );
  14176. this.forward.subSelf( xTemp );
  14177. this.forward.normalize();
  14178. };
  14179. this.rotateVertically = function ( amount ) {
  14180. // please note that the amount is NOT degrees, but a scale value
  14181. yTemp.set( this.object.matrix.elements[4], this.object.matrix.elements[5], this.object.matrix.elements[6] );
  14182. yTemp.multiplyScalar( amount );
  14183. this.forward.addSelf( yTemp );
  14184. this.forward.normalize();
  14185. };
  14186. function onKeyDown( event ) {
  14187. switch( event.keyCode ) {
  14188. case 38: /*up*/
  14189. case 87: /*W*/ forwardSpeed = 1; break;
  14190. case 37: /*left*/
  14191. case 65: /*A*/ sideSpeed = -1; break;
  14192. case 40: /*down*/
  14193. case 83: /*S*/ forwardSpeed = -1; break;
  14194. case 39: /*right*/
  14195. case 68: /*D*/ sideSpeed = 1; break;
  14196. case 81: /*Q*/ doRoll = true; rollDirection = 1; break;
  14197. case 69: /*E*/ doRoll = true; rollDirection = -1; break;
  14198. case 82: /*R*/ upSpeed = 1; break;
  14199. case 70: /*F*/ upSpeed = -1; break;
  14200. }
  14201. };
  14202. function onKeyUp( event ) {
  14203. switch( event.keyCode ) {
  14204. case 38: /*up*/
  14205. case 87: /*W*/ forwardSpeed = 0; break;
  14206. case 37: /*left*/
  14207. case 65: /*A*/ sideSpeed = 0; break;
  14208. case 40: /*down*/
  14209. case 83: /*S*/ forwardSpeed = 0; break;
  14210. case 39: /*right*/
  14211. case 68: /*D*/ sideSpeed = 0; break;
  14212. case 81: /*Q*/ doRoll = false; break;
  14213. case 69: /*E*/ doRoll = false; break;
  14214. case 82: /*R*/ upSpeed = 0; break;
  14215. case 70: /*F*/ upSpeed = 0; break;
  14216. }
  14217. };
  14218. function onMouseMove( event ) {
  14219. mouseX = ( event.clientX - windowHalfX ) / window.innerWidth;
  14220. mouseY = ( event.clientY - windowHalfY ) / window.innerHeight;
  14221. };
  14222. function onMouseDown ( event ) {
  14223. event.preventDefault();
  14224. event.stopPropagation();
  14225. switch ( event.button ) {
  14226. case 0: forwardSpeed = 1; break;
  14227. case 2: forwardSpeed = -1; break;
  14228. }
  14229. };
  14230. function onMouseUp ( event ) {
  14231. event.preventDefault();
  14232. event.stopPropagation();
  14233. switch ( event.button ) {
  14234. case 0: forwardSpeed = 0; break;
  14235. case 2: forwardSpeed = 0; break;
  14236. }
  14237. };
  14238. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  14239. this.domElement.addEventListener( 'mousemove', onMouseMove, false );
  14240. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  14241. this.domElement.addEventListener( 'mouseup', onMouseUp, false );
  14242. this.domElement.addEventListener( 'keydown', onKeyDown, false );
  14243. this.domElement.addEventListener( 'keyup', onKeyUp, false );
  14244. };
  14245. /**
  14246. * @author Eberhard Graether / http://egraether.com/
  14247. */
  14248. THREE.TrackballControls = function ( object, domElement ) {
  14249. THREE.EventTarget.call( this );
  14250. var _this = this,
  14251. STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };
  14252. this.object = object;
  14253. this.domElement = ( domElement !== undefined ) ? domElement : document;
  14254. // API
  14255. this.enabled = true;
  14256. this.screen = { width: window.innerWidth, height: window.innerHeight, offsetLeft: 0, offsetTop: 0 };
  14257. this.radius = ( this.screen.width + this.screen.height ) / 4;
  14258. this.rotateSpeed = 1.0;
  14259. this.zoomSpeed = 1.2;
  14260. this.panSpeed = 0.3;
  14261. this.noRotate = false;
  14262. this.noZoom = false;
  14263. this.noPan = false;
  14264. this.staticMoving = false;
  14265. this.dynamicDampingFactor = 0.2;
  14266. this.minDistance = 0;
  14267. this.maxDistance = Infinity;
  14268. this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
  14269. // internals
  14270. this.target = new THREE.Vector3();
  14271. var lastPosition = new THREE.Vector3();
  14272. var _keyPressed = false,
  14273. _state = STATE.NONE,
  14274. _eye = new THREE.Vector3(),
  14275. _rotateStart = new THREE.Vector3(),
  14276. _rotateEnd = new THREE.Vector3(),
  14277. _zoomStart = new THREE.Vector2(),
  14278. _zoomEnd = new THREE.Vector2(),
  14279. _panStart = new THREE.Vector2(),
  14280. _panEnd = new THREE.Vector2();
  14281. // events
  14282. var changeEvent = { type: 'change' };
  14283. // methods
  14284. this.handleEvent = function ( event ) {
  14285. if ( typeof this[ event.type ] == 'function' ) {
  14286. this[ event.type ]( event );
  14287. }
  14288. };
  14289. this.getMouseOnScreen = function ( clientX, clientY ) {
  14290. return new THREE.Vector2(
  14291. ( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
  14292. ( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
  14293. );
  14294. };
  14295. this.getMouseProjectionOnBall = function ( clientX, clientY ) {
  14296. var mouseOnBall = new THREE.Vector3(
  14297. ( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
  14298. ( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
  14299. 0.0
  14300. );
  14301. var length = mouseOnBall.length();
  14302. if ( length > 1.0 ) {
  14303. mouseOnBall.normalize();
  14304. } else {
  14305. mouseOnBall.z = Math.sqrt( 1.0 - length * length );
  14306. }
  14307. _eye.copy( _this.object.position ).subSelf( _this.target );
  14308. var projection = _this.object.up.clone().setLength( mouseOnBall.y );
  14309. projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
  14310. projection.addSelf( _eye.setLength( mouseOnBall.z ) );
  14311. return projection;
  14312. };
  14313. this.rotateCamera = function () {
  14314. var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
  14315. if ( angle ) {
  14316. var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
  14317. quaternion = new THREE.Quaternion();
  14318. angle *= _this.rotateSpeed;
  14319. quaternion.setFromAxisAngle( axis, -angle );
  14320. quaternion.multiplyVector3( _eye );
  14321. quaternion.multiplyVector3( _this.object.up );
  14322. quaternion.multiplyVector3( _rotateEnd );
  14323. if ( _this.staticMoving ) {
  14324. _rotateStart = _rotateEnd;
  14325. } else {
  14326. quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
  14327. quaternion.multiplyVector3( _rotateStart );
  14328. }
  14329. }
  14330. };
  14331. this.zoomCamera = function () {
  14332. var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
  14333. if ( factor !== 1.0 && factor > 0.0 ) {
  14334. _eye.multiplyScalar( factor );
  14335. if ( _this.staticMoving ) {
  14336. _zoomStart = _zoomEnd;
  14337. } else {
  14338. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  14339. }
  14340. }
  14341. };
  14342. this.panCamera = function () {
  14343. var mouseChange = _panEnd.clone().subSelf( _panStart );
  14344. if ( mouseChange.lengthSq() ) {
  14345. mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
  14346. var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
  14347. pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );
  14348. _this.object.position.addSelf( pan );
  14349. _this.target.addSelf( pan );
  14350. if ( _this.staticMoving ) {
  14351. _panStart = _panEnd;
  14352. } else {
  14353. _panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
  14354. }
  14355. }
  14356. };
  14357. this.checkDistances = function () {
  14358. if ( !_this.noZoom || !_this.noPan ) {
  14359. if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {
  14360. _this.object.position.setLength( _this.maxDistance );
  14361. }
  14362. if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
  14363. _this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );
  14364. }
  14365. }
  14366. };
  14367. this.update = function () {
  14368. _eye.copy( _this.object.position ).subSelf( _this.target );
  14369. if ( !_this.noRotate ) {
  14370. _this.rotateCamera();
  14371. }
  14372. if ( !_this.noZoom ) {
  14373. _this.zoomCamera();
  14374. }
  14375. if ( !_this.noPan ) {
  14376. _this.panCamera();
  14377. }
  14378. _this.object.position.add( _this.target, _eye );
  14379. _this.checkDistances();
  14380. _this.object.lookAt( _this.target );
  14381. if ( lastPosition.distanceTo( _this.object.position ) > 0 ) {
  14382. _this.dispatchEvent( changeEvent );
  14383. lastPosition.copy( _this.object.position );
  14384. }
  14385. };
  14386. // listeners
  14387. function keydown( event ) {
  14388. if ( ! _this.enabled ) return;
  14389. if ( _state !== STATE.NONE ) {
  14390. return;
  14391. } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
  14392. _state = STATE.ROTATE;
  14393. } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
  14394. _state = STATE.ZOOM;
  14395. } else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
  14396. _state = STATE.PAN;
  14397. }
  14398. if ( _state !== STATE.NONE ) {
  14399. _keyPressed = true;
  14400. }
  14401. };
  14402. function keyup( event ) {
  14403. if ( ! _this.enabled ) return;
  14404. if ( _state !== STATE.NONE ) {
  14405. _state = STATE.NONE;
  14406. }
  14407. };
  14408. function mousedown( event ) {
  14409. if ( ! _this.enabled ) return;
  14410. event.preventDefault();
  14411. event.stopPropagation();
  14412. if ( _state === STATE.NONE ) {
  14413. _state = event.button;
  14414. if ( _state === STATE.ROTATE && !_this.noRotate ) {
  14415. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  14416. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  14417. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14418. } else if ( !this.noPan ) {
  14419. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14420. }
  14421. }
  14422. };
  14423. function mousemove( event ) {
  14424. if ( ! _this.enabled ) return;
  14425. if ( _keyPressed ) {
  14426. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  14427. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14428. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14429. _keyPressed = false;
  14430. }
  14431. if ( _state === STATE.NONE ) {
  14432. return;
  14433. } else if ( _state === STATE.ROTATE && !_this.noRotate ) {
  14434. _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  14435. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  14436. _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14437. } else if ( _state === STATE.PAN && !_this.noPan ) {
  14438. _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14439. }
  14440. };
  14441. function mouseup( event ) {
  14442. if ( ! _this.enabled ) return;
  14443. event.preventDefault();
  14444. event.stopPropagation();
  14445. _state = STATE.NONE;
  14446. };
  14447. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  14448. this.domElement.addEventListener( 'mousemove', mousemove, false );
  14449. this.domElement.addEventListener( 'mousedown', mousedown, false );
  14450. this.domElement.addEventListener( 'mouseup', mouseup, false );
  14451. window.addEventListener( 'keydown', keydown, false );
  14452. window.addEventListener( 'keyup', keyup, false );
  14453. };
  14454. /**
  14455. * @author mr.doob / http://mrdoob.com/
  14456. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  14457. */
  14458. THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
  14459. THREE.Geometry.call( this );
  14460. var scope = this,
  14461. width_half = width / 2,
  14462. height_half = height / 2,
  14463. depth_half = depth / 2;
  14464. var mpx, mpy, mpz, mnx, mny, mnz;
  14465. if ( materials !== undefined ) {
  14466. if ( materials instanceof Array ) {
  14467. this.materials = materials;
  14468. } else {
  14469. this.materials = [];
  14470. for ( var i = 0; i < 6; i ++ ) {
  14471. this.materials.push( materials );
  14472. }
  14473. }
  14474. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  14475. } else {
  14476. this.materials = [];
  14477. }
  14478. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  14479. if ( sides != undefined ) {
  14480. for ( var s in sides ) {
  14481. if ( this.sides[ s ] !== undefined ) {
  14482. this.sides[ s ] = sides[ s ];
  14483. }
  14484. }
  14485. }
  14486. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
  14487. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, mnx ); // nx
  14488. this.sides.py && buildPlane( 'x', 'z', 1, 1, width, depth, height_half, mpy ); // py
  14489. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, mny ); // ny
  14490. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, mpz ); // pz
  14491. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz
  14492. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  14493. var w, ix, iy,
  14494. gridX = segmentsWidth || 1,
  14495. gridY = segmentsHeight || 1,
  14496. width_half = width / 2,
  14497. height_half = height / 2,
  14498. offset = scope.vertices.length;
  14499. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  14500. w = 'z';
  14501. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  14502. w = 'y';
  14503. gridY = segmentsDepth || 1;
  14504. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  14505. w = 'x';
  14506. gridX = segmentsDepth || 1;
  14507. }
  14508. var gridX1 = gridX + 1,
  14509. gridY1 = gridY + 1,
  14510. segment_width = width / gridX,
  14511. segment_height = height / gridY,
  14512. normal = new THREE.Vector3();
  14513. normal[ w ] = depth > 0 ? 1 : - 1;
  14514. for ( iy = 0; iy < gridY1; iy ++ ) {
  14515. for ( ix = 0; ix < gridX1; ix ++ ) {
  14516. var vector = new THREE.Vertex();
  14517. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  14518. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  14519. vector[ w ] = depth;
  14520. scope.vertices.push( vector );
  14521. }
  14522. }
  14523. for ( iy = 0; iy < gridY; iy++ ) {
  14524. for ( ix = 0; ix < gridX; ix++ ) {
  14525. var a = ix + gridX1 * iy;
  14526. var b = ix + gridX1 * ( iy + 1 );
  14527. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  14528. var d = ( ix + 1 ) + gridX1 * iy;
  14529. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  14530. face.normal.copy( normal );
  14531. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  14532. face.materialIndex = material;
  14533. scope.faces.push( face );
  14534. scope.faceVertexUvs[ 0 ].push( [
  14535. new THREE.UV( ix / gridX, iy / gridY ),
  14536. new THREE.UV( ix / gridX, ( iy + 1 ) / gridY ),
  14537. new THREE.UV( ( ix + 1 ) / gridX, ( iy + 1 ) / gridY ),
  14538. new THREE.UV( ( ix + 1 ) / gridX, iy / gridY )
  14539. ] );
  14540. }
  14541. }
  14542. }
  14543. this.computeCentroids();
  14544. this.mergeVertices();
  14545. };
  14546. THREE.CubeGeometry.prototype = new THREE.Geometry();
  14547. THREE.CubeGeometry.prototype.constructor = THREE.CubeGeometry;
  14548. /**
  14549. * @author mr.doob / http://mrdoob.com/
  14550. */
  14551. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded ) {
  14552. THREE.Geometry.call( this );
  14553. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  14554. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  14555. height = height !== undefined ? height : 100;
  14556. var heightHalf = height / 2;
  14557. var segmentsX = segmentsRadius || 8;
  14558. var segmentsY = segmentsHeight || 1;
  14559. var x, y, vertices = [], uvs = [];
  14560. for ( y = 0; y <= segmentsY; y ++ ) {
  14561. var verticesRow = [];
  14562. var uvsRow = [];
  14563. var v = y / segmentsY;
  14564. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  14565. for ( x = 0; x <= segmentsX; x ++ ) {
  14566. var u = x / segmentsX;
  14567. var xpos = radius * Math.sin( u * Math.PI * 2 );
  14568. var ypos = - v * height + heightHalf;
  14569. var zpos = radius * Math.cos( u * Math.PI * 2 );
  14570. this.vertices.push( new THREE.Vertex( xpos, ypos, zpos ) );
  14571. verticesRow.push( this.vertices.length - 1 );
  14572. uvsRow.push( new THREE.UV( u, v ) );
  14573. }
  14574. vertices.push( verticesRow );
  14575. uvs.push( uvsRow );
  14576. }
  14577. for ( y = 0; y < segmentsY; y ++ ) {
  14578. for ( x = 0; x < segmentsX; x ++ ) {
  14579. var v1 = vertices[ y ][ x ];
  14580. var v2 = vertices[ y + 1 ][ x ];
  14581. var v3 = vertices[ y + 1 ][ x + 1 ];
  14582. var v4 = vertices[ y ][ x + 1 ];
  14583. // FIXME: These normals aren't right for cones.
  14584. var n1 = this.vertices[ v1 ].clone().setY( 0 ).normalize();
  14585. var n2 = this.vertices[ v2 ].clone().setY( 0 ).normalize();
  14586. var n3 = this.vertices[ v3 ].clone().setY( 0 ).normalize();
  14587. var n4 = this.vertices[ v4 ].clone().setY( 0 ).normalize();
  14588. var uv1 = uvs[ y ][ x ].clone();
  14589. var uv2 = uvs[ y + 1 ][ x ].clone();
  14590. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  14591. var uv4 = uvs[ y ][ x + 1 ].clone();
  14592. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  14593. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  14594. }
  14595. }
  14596. // top cap
  14597. if ( !openEnded && radiusTop > 0 ) {
  14598. this.vertices.push( new THREE.Vertex( 0, heightHalf, 0 ) );
  14599. for ( x = 0; x < segmentsX; x ++ ) {
  14600. var v1 = vertices[ 0 ][ x ];
  14601. var v2 = vertices[ 0 ][ x + 1 ];
  14602. var v3 = this.vertices.length - 1;
  14603. var n1 = new THREE.Vector3( 0, 1, 0 );
  14604. var n2 = new THREE.Vector3( 0, 1, 0 );
  14605. var n3 = new THREE.Vector3( 0, 1, 0 );
  14606. var uv1 = uvs[ 0 ][ x ].clone();
  14607. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  14608. var uv3 = new THREE.UV( uv2.u, 0 );
  14609. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  14610. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  14611. }
  14612. }
  14613. // bottom cap
  14614. if ( !openEnded && radiusBottom > 0 ) {
  14615. this.vertices.push( new THREE.Vertex( 0, - heightHalf, 0 ) );
  14616. for ( x = 0; x < segmentsX; x ++ ) {
  14617. var v1 = vertices[ y ][ x + 1 ];
  14618. var v2 = vertices[ y ][ x ];
  14619. var v3 = this.vertices.length - 1;
  14620. var n1 = new THREE.Vector3( 0, - 1, 0 );
  14621. var n2 = new THREE.Vector3( 0, - 1, 0 );
  14622. var n3 = new THREE.Vector3( 0, - 1, 0 );
  14623. var uv1 = uvs[ y ][ x + 1 ].clone();
  14624. var uv2 = uvs[ y ][ x ].clone();
  14625. var uv3 = new THREE.UV( uv2.u, 1 );
  14626. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  14627. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  14628. }
  14629. }
  14630. this.computeCentroids();
  14631. this.computeFaceNormals();
  14632. }
  14633. THREE.CylinderGeometry.prototype = new THREE.Geometry();
  14634. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  14635. /**
  14636. * @author zz85 / http://www.lab4games.net/zz85/blog
  14637. *
  14638. * Creates extruded geometry from a path shape.
  14639. *
  14640. * parameters = {
  14641. *
  14642. * size: <float>, // size of the text
  14643. * height: <float>, // thickness to extrude text
  14644. * curveSegments: <int>, // number of points on the curves
  14645. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  14646. amount: <int>, // Amount
  14647. *
  14648. * bevelEnabled: <bool>, // turn on bevel
  14649. * bevelThickness: <float>, // how deep into text bevel goes
  14650. * bevelSize: <float>, // how far from text outline is bevel
  14651. * bevelSegments: <int>, // number of bevel layers
  14652. *
  14653. * extrudePath: <THREE.CurvePath> // 2d/3d spline path to extrude shape orthogonality to
  14654. * bendPath: <THREE.CurvePath> // 2d path for bend the shape around x/y plane
  14655. *
  14656. * material: <int> // material index for front and back faces
  14657. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  14658. *
  14659. * }
  14660. **/
  14661. THREE.ExtrudeGeometry = function( shapes, options ) {
  14662. if ( typeof( shapes ) === "undefined" ) {
  14663. shapes = [];
  14664. return;
  14665. }
  14666. THREE.Geometry.call( this );
  14667. shapes = shapes instanceof Array ? shapes : [ shapes ];
  14668. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  14669. this.addShapeList( shapes, options );
  14670. this.computeCentroids();
  14671. this.computeFaceNormals();
  14672. // can't really use automatic vertex normals
  14673. // as then front and back sides get smoothed too
  14674. // should do separate smoothing just for sides
  14675. //this.computeVertexNormals();
  14676. //console.log( "took", ( Date.now() - startTime ) );
  14677. };
  14678. THREE.ExtrudeGeometry.prototype = new THREE.Geometry();
  14679. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  14680. THREE.ExtrudeGeometry.prototype.addShapeList = function(shapes, options) {
  14681. var sl = shapes.length;
  14682. for ( var s = 0; s < sl; s ++ ) {
  14683. var shape = shapes[ s ];
  14684. this.addShape( shape, options );
  14685. }
  14686. };
  14687. THREE.ExtrudeGeometry.prototype.addShape = function( shape, options ) {
  14688. var amount = options.amount !== undefined ? options.amount : 100;
  14689. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  14690. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  14691. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  14692. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  14693. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  14694. var steps = options.steps !== undefined ? options.steps : 1;
  14695. var bendPath = options.bendPath;
  14696. var extrudePath = options.extrudePath;
  14697. var extrudePts, extrudeByPath = false;
  14698. var material = options.material;
  14699. var extrudeMaterial = options.extrudeMaterial;
  14700. var shapebb = this.shapebb;
  14701. //shapebb = shape.getBoundingBox();
  14702. var splineTube, binormal, normal, position2;
  14703. if ( extrudePath ) {
  14704. extrudePts = extrudePath.getSpacedPoints( steps );
  14705. extrudeByPath = true;
  14706. bevelEnabled = false; // bevels not supported for path extrusion
  14707. // SETUP TNB variables
  14708. // Reuse TNB from TubeGeomtry for now.
  14709. // TODO1 - have a .isClosed in spline?
  14710. splineTube = new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  14711. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  14712. binormal = new THREE.Vector3();
  14713. normal = new THREE.Vector3();
  14714. position2 = new THREE.Vector3();
  14715. }
  14716. // Safeguards if bevels are not enabled
  14717. if ( ! bevelEnabled ) {
  14718. bevelSegments = 0;
  14719. bevelThickness = 0;
  14720. bevelSize = 0;
  14721. }
  14722. // Variables initalization
  14723. var ahole, h, hl; // looping of holes
  14724. var scope = this;
  14725. var bevelPoints = [];
  14726. var shapesOffset = this.vertices.length;
  14727. if ( bendPath ) {
  14728. shape.addWrapPath( bendPath );
  14729. }
  14730. var shapePoints = shape.extractPoints();
  14731. var vertices = shapePoints.shape;
  14732. var holes = shapePoints.holes;
  14733. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  14734. if ( reverse ) {
  14735. vertices = vertices.reverse();
  14736. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  14737. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14738. ahole = holes[ h ];
  14739. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  14740. holes[ h ] = ahole.reverse();
  14741. }
  14742. }
  14743. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  14744. }
  14745. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  14746. //var faces = THREE.Shape.Utils.triangulate2( vertices, holes );
  14747. // Would it be better to move points after triangulation?
  14748. // shapePoints = shape.extractAllPointsWithBend( curveSegments, bendPath );
  14749. // vertices = shapePoints.shape;
  14750. // holes = shapePoints.holes;
  14751. //console.log(faces);
  14752. ////
  14753. /// Handle Vertices
  14754. ////
  14755. var contour = vertices; // vertices has all points but contour has only points of circumference
  14756. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14757. ahole = holes[ h ];
  14758. vertices = vertices.concat( ahole );
  14759. }
  14760. function scalePt2 ( pt, vec, size ) {
  14761. if ( !vec ) console.log( "die" );
  14762. return vec.clone().multiplyScalar( size ).addSelf( pt );
  14763. }
  14764. var b, bs, t, z,
  14765. vert, vlen = vertices.length,
  14766. face, flen = faces.length,
  14767. cont, clen = contour.length;
  14768. //------
  14769. // Find directions for point movement
  14770. //
  14771. var RAD_TO_DEGREES = 180 / Math.PI;
  14772. function getBevelVec( pt_i, pt_j, pt_k ) {
  14773. // Algorithm 2
  14774. return getBevelVec2( pt_i, pt_j, pt_k );
  14775. }
  14776. function getBevelVec1( pt_i, pt_j, pt_k ) {
  14777. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  14778. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  14779. if ( anglea > angleb ) {
  14780. angleb += Math.PI * 2;
  14781. }
  14782. var anglec = ( anglea + angleb ) / 2;
  14783. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  14784. var x = - Math.cos( anglec );
  14785. var y = - Math.sin( anglec );
  14786. var vec = new THREE.Vector2( x, y ); //.normalize();
  14787. return vec;
  14788. }
  14789. function getBevelVec2( pt_i, pt_j, pt_k ) {
  14790. var a = THREE.ExtrudeGeometry.__v1,
  14791. b = THREE.ExtrudeGeometry.__v2,
  14792. v_hat = THREE.ExtrudeGeometry.__v3,
  14793. w_hat = THREE.ExtrudeGeometry.__v4,
  14794. p = THREE.ExtrudeGeometry.__v5,
  14795. q = THREE.ExtrudeGeometry.__v6,
  14796. v, w,
  14797. v_dot_w_hat, q_sub_p_dot_w_hat,
  14798. s, intersection;
  14799. // good reading for line-line intersection
  14800. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  14801. // define a as vector j->i
  14802. // define b as vectot k->i
  14803. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  14804. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  14805. // get unit vectors
  14806. v = a.normalize();
  14807. w = b.normalize();
  14808. // normals from pt i
  14809. v_hat.set( -v.y, v.x );
  14810. w_hat.set( w.y, -w.x );
  14811. // pts from i
  14812. p.copy( pt_i ).addSelf( v_hat );
  14813. q.copy( pt_i ).addSelf( w_hat );
  14814. if ( p.equals( q ) ) {
  14815. //console.log("Warning: lines are straight");
  14816. return w_hat.clone();
  14817. }
  14818. // Points from j, k. helps prevents points cross overover most of the time
  14819. p.copy( pt_j ).addSelf( v_hat );
  14820. q.copy( pt_k ).addSelf( w_hat );
  14821. v_dot_w_hat = v.dot( w_hat );
  14822. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  14823. // We should not reach these conditions
  14824. if ( v_dot_w_hat === 0 ) {
  14825. console.log( "Either infinite or no solutions!" );
  14826. if ( q_sub_p_dot_w_hat === 0 ) {
  14827. console.log( "Its finite solutions." );
  14828. } else {
  14829. console.log( "Too bad, no solutions." );
  14830. }
  14831. }
  14832. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  14833. if ( s < 0 ) {
  14834. // in case of emergecy, revert to algorithm 1.
  14835. return getBevelVec1( pt_i, pt_j, pt_k );
  14836. }
  14837. intersection = v.multiplyScalar( s ).addSelf( p );
  14838. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  14839. }
  14840. var contourMovements = [];
  14841. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  14842. if ( j === il ) j = 0;
  14843. if ( k === il ) k = 0;
  14844. // (j)---(i)---(k)
  14845. // console.log('i,j,k', i, j , k)
  14846. var pt_i = contour[ i ];
  14847. var pt_j = contour[ j ];
  14848. var pt_k = contour[ k ];
  14849. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  14850. }
  14851. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  14852. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14853. ahole = holes[ h ];
  14854. oneHoleMovements = [];
  14855. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  14856. if ( j === il ) j = 0;
  14857. if ( k === il ) k = 0;
  14858. // (j)---(i)---(k)
  14859. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  14860. }
  14861. holesMovements.push( oneHoleMovements );
  14862. verticesMovements = verticesMovements.concat( oneHoleMovements );
  14863. }
  14864. // Loop bevelSegments, 1 for the front, 1 for the back
  14865. for ( b = 0; b < bevelSegments; b ++ ) {
  14866. //for ( b = bevelSegments; b > 0; b -- ) {
  14867. t = b / bevelSegments;
  14868. z = bevelThickness * ( 1 - t );
  14869. //z = bevelThickness * t;
  14870. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  14871. //bs = bevelSize * t ; // linear
  14872. // contract shape
  14873. for ( i = 0, il = contour.length; i < il; i ++ ) {
  14874. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  14875. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  14876. v( vert.x, vert.y, - z );
  14877. }
  14878. // expand holes
  14879. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  14880. ahole = holes[ h ];
  14881. oneHoleMovements = holesMovements[ h ];
  14882. for ( i = 0, il = ahole.length; i < il; i++ ) {
  14883. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  14884. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  14885. v( vert.x, vert.y, -z );
  14886. }
  14887. }
  14888. }
  14889. bs = bevelSize;
  14890. // Back facing vertices
  14891. for ( i = 0; i < vlen; i ++ ) {
  14892. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  14893. if ( !extrudeByPath ) {
  14894. v( vert.x, vert.y, 0 );
  14895. } else {
  14896. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  14897. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  14898. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  14899. position2.copy(extrudePts[0]).addSelf(normal).addSelf(binormal);
  14900. v(position2.x, position2.y, position2.z);
  14901. }
  14902. }
  14903. // Add stepped vertices...
  14904. // Including front facing vertices
  14905. var s;
  14906. for ( s = 1; s <= steps; s ++ ) {
  14907. for ( i = 0; i < vlen; i ++ ) {
  14908. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  14909. if ( !extrudeByPath ) {
  14910. v( vert.x, vert.y, amount / steps * s );
  14911. } else {
  14912. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  14913. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  14914. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  14915. position2.copy(extrudePts[s]).addSelf(normal).addSelf(binormal);
  14916. v(position2.x, position2.y, position2.z );
  14917. }
  14918. }
  14919. }
  14920. // Add bevel segments planes
  14921. //for ( b = 1; b <= bevelSegments; b ++ ) {
  14922. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  14923. t = b / bevelSegments;
  14924. z = bevelThickness * ( 1 - t );
  14925. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  14926. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  14927. // contract shape
  14928. for ( i = 0, il = contour.length; i < il; i ++ ) {
  14929. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  14930. v( vert.x, vert.y, amount + z );
  14931. }
  14932. // expand holes
  14933. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14934. ahole = holes[ h ];
  14935. oneHoleMovements = holesMovements[ h ];
  14936. for ( i = 0, il = ahole.length; i < il; i++ ) {
  14937. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  14938. if ( !extrudeByPath ) {
  14939. v( vert.x, vert.y, amount + z );
  14940. } else {
  14941. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  14942. }
  14943. }
  14944. }
  14945. }
  14946. // set UV generator
  14947. var uvgen = THREE.ExtrudeGeometry.WorldUVGenerator;
  14948. ////
  14949. /// Handle Faces
  14950. ////
  14951. // Top and bottom faces
  14952. buildLidFaces();
  14953. // Sides faces
  14954. buildSideFaces();
  14955. ///// Internal functions
  14956. function buildLidFaces() {
  14957. if ( bevelEnabled ) {
  14958. var layer = 0 ; // steps + 1
  14959. var offset = vlen * layer;
  14960. // Bottom faces
  14961. for ( i = 0; i < flen; i ++ ) {
  14962. face = faces[ i ];
  14963. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  14964. }
  14965. layer = steps + bevelSegments * 2;
  14966. offset = vlen * layer;
  14967. // Top faces
  14968. for ( i = 0; i < flen; i ++ ) {
  14969. face = faces[ i ];
  14970. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  14971. }
  14972. } else {
  14973. // Bottom faces
  14974. for ( i = 0; i < flen; i++ ) {
  14975. face = faces[ i ];
  14976. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  14977. }
  14978. // Top faces
  14979. for ( i = 0; i < flen; i ++ ) {
  14980. face = faces[ i ];
  14981. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  14982. }
  14983. }
  14984. }
  14985. // Create faces for the z-sides of the shape
  14986. function buildSideFaces() {
  14987. var layeroffset = 0;
  14988. sidewalls( contour, layeroffset );
  14989. layeroffset += contour.length;
  14990. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14991. ahole = holes[ h ];
  14992. sidewalls( ahole, layeroffset );
  14993. //, true
  14994. layeroffset += ahole.length;
  14995. }
  14996. }
  14997. function sidewalls( contour, layeroffset ) {
  14998. var j, k;
  14999. i = contour.length;
  15000. while ( --i >= 0 ) {
  15001. j = i;
  15002. k = i - 1;
  15003. if ( k < 0 ) k = contour.length - 1;
  15004. //console.log('b', i,j, i-1, k,vertices.length);
  15005. var s = 0, sl = steps + bevelSegments * 2;
  15006. for ( s = 0; s < sl; s ++ ) {
  15007. var slen1 = vlen * s;
  15008. var slen2 = vlen * ( s + 1 );
  15009. var a = layeroffset + j + slen1,
  15010. b = layeroffset + k + slen1,
  15011. c = layeroffset + k + slen2,
  15012. d = layeroffset + j + slen2;
  15013. f4( a, b, c, d, contour, s, sl );
  15014. }
  15015. }
  15016. }
  15017. function v( x, y, z ) {
  15018. scope.vertices.push( new THREE.Vertex( x, y, z ) );
  15019. }
  15020. function f3( a, b, c, isBottom ) {
  15021. a += shapesOffset;
  15022. b += shapesOffset;
  15023. c += shapesOffset;
  15024. // normal, color, material
  15025. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  15026. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c)
  15027. : uvgen.generateTopUV( scope, shape, options, a, b, c);
  15028. scope.faceVertexUvs[ 0 ].push(uvs);
  15029. }
  15030. function f4( a, b, c, d, wallContour, stepIndex, stepsLength ) {
  15031. a += shapesOffset;
  15032. b += shapesOffset;
  15033. c += shapesOffset;
  15034. d += shapesOffset;
  15035. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  15036. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d, stepIndex, stepsLength);
  15037. scope.faceVertexUvs[ 0 ].push(uvs);
  15038. }
  15039. };
  15040. THREE.ExtrudeGeometry.WorldUVGenerator = {
  15041. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  15042. var ax = geometry.vertices[ indexA ].x,
  15043. ay = geometry.vertices[ indexA ].y,
  15044. bx = geometry.vertices[ indexB ].x,
  15045. by = geometry.vertices[ indexB ].y,
  15046. cx = geometry.vertices[ indexC ].x,
  15047. cy = geometry.vertices[ indexC ].y;
  15048. return [
  15049. new THREE.UV( ax, 1 - ay ),
  15050. new THREE.UV( bx, 1 - by ),
  15051. new THREE.UV( cx, 1 - cy )
  15052. ];
  15053. },
  15054. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  15055. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  15056. },
  15057. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  15058. indexA, indexB, indexC, indexD, stepIndex, stepsLength) {
  15059. var ax = geometry.vertices[ indexA ].x,
  15060. ay = geometry.vertices[ indexA ].y,
  15061. az = geometry.vertices[ indexA ].z,
  15062. bx = geometry.vertices[ indexB ].x,
  15063. by = geometry.vertices[ indexB ].y,
  15064. bz = geometry.vertices[ indexB ].z,
  15065. cx = geometry.vertices[ indexC ].x,
  15066. cy = geometry.vertices[ indexC ].y,
  15067. cz = geometry.vertices[ indexC ].z,
  15068. dx = geometry.vertices[ indexD ].x,
  15069. dy = geometry.vertices[ indexD ].y,
  15070. dz = geometry.vertices[ indexD ].z;
  15071. if ( Math.abs( ay - by ) < 0.01 ) {
  15072. return [
  15073. new THREE.UV( ax, az ),
  15074. new THREE.UV( bx, bz ),
  15075. new THREE.UV( cx, cz ),
  15076. new THREE.UV( dx, dz )
  15077. ];
  15078. } else {
  15079. return [
  15080. new THREE.UV( ay, az ),
  15081. new THREE.UV( by, bz ),
  15082. new THREE.UV( cy, cz ),
  15083. new THREE.UV( dy, dz )
  15084. ];
  15085. }
  15086. }
  15087. };
  15088. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  15089. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  15090. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  15091. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  15092. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  15093. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  15094. /**
  15095. * @author astrodud / http://astrodud.isgreat.org/
  15096. * @author zz85 / https://github.com/zz85
  15097. */
  15098. THREE.LatheGeometry = function ( points, steps, angle ) {
  15099. THREE.Geometry.call( this );
  15100. var _steps = steps || 12;
  15101. var _angle = angle || 2 * Math.PI;
  15102. var _newV = [];
  15103. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  15104. for ( var j = 0; j < points.length; j ++ ) {
  15105. _newV[ j ] = points[ j ].clone();
  15106. this.vertices.push( new THREE.Vertex().copy( _newV[ j ] ) );
  15107. }
  15108. var i;
  15109. var il = _steps + 1;
  15110. for ( i = 0; i < il; i ++ ) {
  15111. for ( var j = 0; j < _newV.length; j ++ ) {
  15112. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  15113. this.vertices.push( new THREE.Vertex().copy( _newV[ j ] ) );
  15114. }
  15115. }
  15116. for ( i = 0; i < _steps; i ++ ) {
  15117. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  15118. var a = i * kl + k;
  15119. var b = ( ( i + 1 ) % il ) * kl + k;
  15120. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  15121. var d = i * kl + ( k + 1 ) % kl;
  15122. this.faces.push( new THREE.Face4( a, b, c, d ) );
  15123. this.faceVertexUvs[ 0 ].push( [
  15124. new THREE.UV( 1 - i / _steps, k / kl ),
  15125. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  15126. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  15127. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  15128. ] );
  15129. }
  15130. }
  15131. this.computeCentroids();
  15132. this.computeFaceNormals();
  15133. this.computeVertexNormals();
  15134. };
  15135. THREE.LatheGeometry.prototype = new THREE.Geometry();
  15136. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  15137. /**
  15138. * @author mr.doob / http://mrdoob.com/
  15139. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  15140. */
  15141. THREE.PlaneGeometry = function ( width, depth, segmentsWidth, segmentsDepth ) {
  15142. THREE.Geometry.call( this );
  15143. var ix, iz,
  15144. width_half = width / 2,
  15145. depth_half = depth / 2,
  15146. gridX = segmentsWidth || 1,
  15147. gridZ = segmentsDepth || 1,
  15148. gridX1 = gridX + 1,
  15149. gridZ1 = gridZ + 1,
  15150. segment_width = width / gridX,
  15151. segment_depth = depth / gridZ,
  15152. normal = new THREE.Vector3( 0, 1, 0 );
  15153. for ( iz = 0; iz < gridZ1; iz ++ ) {
  15154. for ( ix = 0; ix < gridX1; ix ++ ) {
  15155. var x = ix * segment_width - width_half;
  15156. var z = iz * segment_depth - depth_half;
  15157. this.vertices.push( new THREE.Vertex( x, 0, z ) );
  15158. }
  15159. }
  15160. for ( iz = 0; iz < gridZ; iz ++ ) {
  15161. for ( ix = 0; ix < gridX; ix ++ ) {
  15162. var a = ix + gridX1 * iz;
  15163. var b = ix + gridX1 * ( iz + 1 );
  15164. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  15165. var d = ( ix + 1 ) + gridX1 * iz;
  15166. var face = new THREE.Face4( a, b, c, d );
  15167. face.normal.copy( normal );
  15168. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  15169. this.faces.push( face );
  15170. this.faceVertexUvs[ 0 ].push( [
  15171. new THREE.UV( ix / gridX, iz / gridZ ),
  15172. new THREE.UV( ix / gridX, ( iz + 1 ) / gridZ ),
  15173. new THREE.UV( ( ix + 1 ) / gridX, ( iz + 1 ) / gridZ ),
  15174. new THREE.UV( ( ix + 1 ) / gridX, iz / gridZ )
  15175. ] );
  15176. }
  15177. }
  15178. this.computeCentroids();
  15179. };
  15180. THREE.PlaneGeometry.prototype = new THREE.Geometry();
  15181. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  15182. /**
  15183. * @author mr.doob / http://mrdoob.com/
  15184. */
  15185. THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength ) {
  15186. THREE.Geometry.call( this );
  15187. radius = radius || 50;
  15188. phiStart = phiStart !== undefined ? phiStart : 0;
  15189. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  15190. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  15191. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  15192. var segmentsX = Math.max( 3, Math.floor( segmentsWidth ) || 8 );
  15193. var segmentsY = Math.max( 2, Math.floor( segmentsHeight ) || 6 );
  15194. var x, y, vertices = [], uvs = [];
  15195. for ( y = 0; y <= segmentsY; y ++ ) {
  15196. var verticesRow = [];
  15197. var uvsRow = [];
  15198. for ( x = 0; x <= segmentsX; x ++ ) {
  15199. var u = x / segmentsX;
  15200. var v = y / segmentsY;
  15201. var xpos = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15202. var ypos = radius * Math.cos( thetaStart + v * thetaLength );
  15203. var zpos = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15204. this.vertices.push( new THREE.Vertex( xpos, ypos, zpos ) );
  15205. verticesRow.push( this.vertices.length - 1 );
  15206. uvsRow.push( new THREE.UV( u, v ) );
  15207. }
  15208. vertices.push( verticesRow );
  15209. uvs.push( uvsRow );
  15210. }
  15211. for ( y = 0; y < segmentsY; y ++ ) {
  15212. for ( x = 0; x < segmentsX; x ++ ) {
  15213. var v1 = vertices[ y ][ x + 1 ];
  15214. var v2 = vertices[ y ][ x ];
  15215. var v3 = vertices[ y + 1 ][ x ];
  15216. var v4 = vertices[ y + 1 ][ x + 1 ];
  15217. var n1 = this.vertices[ v1 ].clone().normalize();
  15218. var n2 = this.vertices[ v2 ].clone().normalize();
  15219. var n3 = this.vertices[ v3 ].clone().normalize();
  15220. var n4 = this.vertices[ v4 ].clone().normalize();
  15221. var uv1 = uvs[ y ][ x + 1 ].clone();
  15222. var uv2 = uvs[ y ][ x ].clone();
  15223. var uv3 = uvs[ y + 1 ][ x ].clone();
  15224. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  15225. if ( Math.abs( this.vertices[ v1 ].y ) == radius ) {
  15226. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  15227. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  15228. } else if ( Math.abs( this.vertices[ v3 ].y ) == radius ) {
  15229. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  15230. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  15231. } else {
  15232. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  15233. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  15234. }
  15235. }
  15236. }
  15237. this.computeCentroids();
  15238. this.computeFaceNormals();
  15239. this.boundingSphere = { radius: radius };
  15240. };
  15241. THREE.SphereGeometry.prototype = new THREE.Geometry();
  15242. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  15243. /**
  15244. * @author zz85 / http://www.lab4games.net/zz85/blog
  15245. * @author alteredq / http://alteredqualia.com/
  15246. *
  15247. * For creating 3D text geometry in three.js
  15248. *
  15249. * Text = 3D Text
  15250. *
  15251. * parameters = {
  15252. * size: <float>, // size of the text
  15253. * height: <float>, // thickness to extrude text
  15254. * curveSegments: <int>, // number of points on the curves
  15255. *
  15256. * font: <string>, // font name
  15257. * weight: <string>, // font weight (normal, bold)
  15258. * style: <string>, // font style (normal, italics)
  15259. *
  15260. * bevelEnabled: <bool>, // turn on bevel
  15261. * bevelThickness: <float>, // how deep into text bevel goes
  15262. * bevelSize: <float>, // how far from text outline is bevel
  15263. *
  15264. * bend: <bool> // bend according to hardcoded curve (generates bendPath)
  15265. * bendPath: <curve> // wraps text according to bend Path
  15266. * }
  15267. *
  15268. * It uses techniques used in:
  15269. *
  15270. * typeface.js and canvastext
  15271. * For converting fonts and rendering with javascript
  15272. * http://typeface.neocracy.org
  15273. *
  15274. * Triangulation ported from AS3
  15275. * Simple Polygon Triangulation
  15276. * http://actionsnippet.com/?p=1462
  15277. *
  15278. * A Method to triangulate shapes with holes
  15279. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15280. *
  15281. */
  15282. /* Usage Examples
  15283. // TextGeometry wrapper
  15284. var text3d = new TextGeometry( text, options );
  15285. // Complete manner
  15286. var textPath = new THREE.TextPath( text, options );
  15287. var textShapes = textPath.toShapes();
  15288. var text3d = new ExtrudeGeometry( textShapes, options );
  15289. */
  15290. THREE.TextGeometry = function ( text, parameters ) {
  15291. var textPath = new THREE.TextPath( text, parameters );
  15292. var textShapes = textPath.toShapes();
  15293. // translate parameters to ExtrudeGeometry API
  15294. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  15295. // defaults
  15296. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  15297. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  15298. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  15299. if ( parameters.bend ) {
  15300. var b = textShapes[ textShapes.length - 1 ].getBoundingBox();
  15301. var max = b.maxX;
  15302. parameters.bendPath = new THREE.QuadraticBezierCurve( new THREE.Vector2( 0, 0 ),
  15303. new THREE.Vector2( max / 2, 120 ),
  15304. new THREE.Vector2( max, 0 ) );
  15305. }
  15306. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  15307. };
  15308. THREE.TextGeometry.prototype = new THREE.ExtrudeGeometry();
  15309. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  15310. THREE.FontUtils = {
  15311. faces : {},
  15312. // Just for now. face[weight][style]
  15313. face : "helvetiker",
  15314. weight: "normal",
  15315. style : "normal",
  15316. size : 150,
  15317. divisions : 10,
  15318. getFace : function() {
  15319. return this.faces[ this.face ][ this.weight ][ this.style ];
  15320. },
  15321. loadFace : function( data ) {
  15322. var family = data.familyName.toLowerCase();
  15323. var ThreeFont = this;
  15324. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15325. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15326. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15327. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15328. return data;
  15329. },
  15330. drawText : function( text ) {
  15331. var characterPts = [], allPts = [];
  15332. // RenderText
  15333. var i, p,
  15334. face = this.getFace(),
  15335. scale = this.size / face.resolution,
  15336. offset = 0,
  15337. chars = String( text ).split( '' ),
  15338. length = chars.length;
  15339. var fontPaths = [];
  15340. for ( i = 0; i < length; i ++ ) {
  15341. var path = new THREE.Path();
  15342. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15343. offset += ret.offset;
  15344. //characterPts.push( ret.points );
  15345. //allPts = allPts.concat( ret.points );
  15346. fontPaths.push( ret.path );
  15347. }
  15348. // get the width
  15349. var width = offset / 2;
  15350. //
  15351. // for ( p = 0; p < allPts.length; p++ ) {
  15352. //
  15353. // allPts[ p ].x -= width;
  15354. //
  15355. // }
  15356. //var extract = this.extractPoints( allPts, characterPts );
  15357. //extract.contour = allPts;
  15358. //extract.paths = fontPaths;
  15359. //extract.offset = width;
  15360. return { paths : fontPaths, offset : width };
  15361. },
  15362. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15363. var pts = [];
  15364. var i, i2, divisions,
  15365. outline, action, length,
  15366. scaleX, scaleY,
  15367. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15368. laste,
  15369. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15370. if ( !glyph ) return;
  15371. if ( glyph.o ) {
  15372. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15373. length = outline.length;
  15374. scaleX = scale;
  15375. scaleY = scale;
  15376. for ( i = 0; i < length; ) {
  15377. action = outline[ i ++ ];
  15378. //console.log( action );
  15379. switch( action ) {
  15380. case 'm':
  15381. // Move To
  15382. x = outline[ i++ ] * scaleX + offset;
  15383. y = outline[ i++ ] * scaleY;
  15384. pts.push( new THREE.Vector2( x, y ) );
  15385. path.moveTo( x, y );
  15386. break;
  15387. case 'l':
  15388. // Line To
  15389. x = outline[ i++ ] * scaleX + offset;
  15390. y = outline[ i++ ] * scaleY;
  15391. pts.push( new THREE.Vector2( x, y ) );
  15392. path.lineTo(x,y);
  15393. break;
  15394. case 'q':
  15395. // QuadraticCurveTo
  15396. cpx = outline[ i++ ] * scaleX + offset;
  15397. cpy = outline[ i++ ] * scaleY;
  15398. cpx1 = outline[ i++ ] * scaleX + offset;
  15399. cpy1 = outline[ i++ ] * scaleY;
  15400. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15401. laste = pts[ pts.length - 1 ];
  15402. if ( laste ) {
  15403. cpx0 = laste.x;
  15404. cpy0 = laste.y;
  15405. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15406. var t = i2 / divisions;
  15407. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15408. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15409. pts.push( new THREE.Vector2( tx, ty ) );
  15410. }
  15411. }
  15412. break;
  15413. case 'b':
  15414. // Cubic Bezier Curve
  15415. cpx = outline[ i++ ] * scaleX + offset;
  15416. cpy = outline[ i++ ] * scaleY;
  15417. cpx1 = outline[ i++ ] * scaleX + offset;
  15418. cpy1 = outline[ i++ ] * -scaleY;
  15419. cpx2 = outline[ i++ ] * scaleX + offset;
  15420. cpy2 = outline[ i++ ] * -scaleY;
  15421. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15422. laste = pts[ pts.length - 1 ];
  15423. if ( laste ) {
  15424. cpx0 = laste.x;
  15425. cpy0 = laste.y;
  15426. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15427. var t = i2 / divisions;
  15428. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15429. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15430. pts.push( new THREE.Vector2( tx, ty ) );
  15431. }
  15432. }
  15433. break;
  15434. }
  15435. }
  15436. }
  15437. return { offset: glyph.ha*scale, points:pts, path:path};
  15438. }
  15439. };
  15440. /**
  15441. * This code is a quick port of code written in C++ which was submitted to
  15442. * flipcode.com by John W. Ratcliff // July 22, 2000
  15443. * See original code and more information here:
  15444. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15445. *
  15446. * ported to actionscript by Zevan Rosser
  15447. * www.actionsnippet.com
  15448. *
  15449. * ported to javascript by Joshua Koo
  15450. * http://www.lab4games.net/zz85/blog
  15451. *
  15452. */
  15453. ( function( namespace ) {
  15454. var EPSILON = 0.0000000001;
  15455. // takes in an contour array and returns
  15456. var process = function( contour, indices ) {
  15457. var n = contour.length;
  15458. if ( n < 3 ) return null;
  15459. var result = [],
  15460. verts = [],
  15461. vertIndices = [];
  15462. /* we want a counter-clockwise polygon in verts */
  15463. var u, v, w;
  15464. if ( area( contour ) > 0.0 ) {
  15465. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15466. } else {
  15467. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15468. }
  15469. var nv = n;
  15470. /* remove nv - 2 vertices, creating 1 triangle every time */
  15471. var count = 2 * nv; /* error detection */
  15472. for( v = nv - 1; nv > 2; ) {
  15473. /* if we loop, it is probably a non-simple polygon */
  15474. if ( ( count-- ) <= 0 ) {
  15475. //** Triangulate: ERROR - probable bad polygon!
  15476. //throw ( "Warning, unable to triangulate polygon!" );
  15477. //return null;
  15478. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15479. console.log( "Warning, unable to triangulate polygon!" );
  15480. if ( indices ) return vertIndices;
  15481. return result;
  15482. }
  15483. /* three consecutive vertices in current polygon, <u,v,w> */
  15484. u = v; if ( nv <= u ) u = 0; /* previous */
  15485. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15486. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15487. if ( snip( contour, u, v, w, nv, verts ) ) {
  15488. var a, b, c, s, t;
  15489. /* true names of the vertices */
  15490. a = verts[ u ];
  15491. b = verts[ v ];
  15492. c = verts[ w ];
  15493. /* output Triangle */
  15494. /*
  15495. result.push( contour[ a ] );
  15496. result.push( contour[ b ] );
  15497. result.push( contour[ c ] );
  15498. */
  15499. result.push( [ contour[ a ],
  15500. contour[ b ],
  15501. contour[ c ] ] );
  15502. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15503. /* remove v from the remaining polygon */
  15504. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15505. verts[ s ] = verts[ t ];
  15506. }
  15507. nv--;
  15508. /* reset error detection counter */
  15509. count = 2 * nv;
  15510. }
  15511. }
  15512. if ( indices ) return vertIndices;
  15513. return result;
  15514. };
  15515. // calculate area of the contour polygon
  15516. var area = function ( contour ) {
  15517. var n = contour.length;
  15518. var a = 0.0;
  15519. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15520. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15521. }
  15522. return a * 0.5;
  15523. };
  15524. // see if p is inside triangle abc
  15525. var insideTriangle = function( ax, ay,
  15526. bx, by,
  15527. cx, cy,
  15528. px, py ) {
  15529. var aX, aY, bX, bY;
  15530. var cX, cY, apx, apy;
  15531. var bpx, bpy, cpx, cpy;
  15532. var cCROSSap, bCROSScp, aCROSSbp;
  15533. aX = cx - bx; aY = cy - by;
  15534. bX = ax - cx; bY = ay - cy;
  15535. cX = bx - ax; cY = by - ay;
  15536. apx= px -ax; apy= py - ay;
  15537. bpx= px - bx; bpy= py - by;
  15538. cpx= px - cx; cpy= py - cy;
  15539. aCROSSbp = aX*bpy - aY*bpx;
  15540. cCROSSap = cX*apy - cY*apx;
  15541. bCROSScp = bX*cpy - bY*cpx;
  15542. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  15543. };
  15544. var snip = function ( contour, u, v, w, n, verts ) {
  15545. var p;
  15546. var ax, ay, bx, by;
  15547. var cx, cy, px, py;
  15548. ax = contour[ verts[ u ] ].x;
  15549. ay = contour[ verts[ u ] ].y;
  15550. bx = contour[ verts[ v ] ].x;
  15551. by = contour[ verts[ v ] ].y;
  15552. cx = contour[ verts[ w ] ].x;
  15553. cy = contour[ verts[ w ] ].y;
  15554. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  15555. for ( p = 0; p < n; p++ ) {
  15556. if( (p == u) || (p == v) || (p == w) ) continue;
  15557. px = contour[ verts[ p ] ].x
  15558. py = contour[ verts[ p ] ].y
  15559. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  15560. }
  15561. return true;
  15562. };
  15563. namespace.Triangulate = process;
  15564. namespace.Triangulate.area = area;
  15565. return namespace;
  15566. })(THREE.FontUtils);
  15567. // To use the typeface.js face files, hook up the API
  15568. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  15569. /**
  15570. * @author oosmoxiecode
  15571. * @author mr.doob / http://mrdoob.com/
  15572. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  15573. */
  15574. THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {
  15575. THREE.Geometry.call( this );
  15576. var scope = this;
  15577. this.radius = radius || 100;
  15578. this.tube = tube || 40;
  15579. this.segmentsR = segmentsR || 8;
  15580. this.segmentsT = segmentsT || 6;
  15581. this.arc = arc || Math.PI * 2;
  15582. var center = new THREE.Vector3(), uvs = [], normals = [];
  15583. for ( var j = 0; j <= this.segmentsR; j ++ ) {
  15584. for ( var i = 0; i <= this.segmentsT; i ++ ) {
  15585. var u = i / this.segmentsT * this.arc;
  15586. var v = j / this.segmentsR * Math.PI * 2;
  15587. center.x = this.radius * Math.cos( u );
  15588. center.y = this.radius * Math.sin( u );
  15589. var vertex = new THREE.Vertex();
  15590. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  15591. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  15592. vertex.z = this.tube * Math.sin( v );
  15593. this.vertices.push( vertex );
  15594. uvs.push( new THREE.UV( i / this.segmentsT, 1 - j / this.segmentsR ) );
  15595. normals.push( vertex.clone().subSelf( center ).normalize() );
  15596. }
  15597. }
  15598. for ( var j = 1; j <= this.segmentsR; j ++ ) {
  15599. for ( var i = 1; i <= this.segmentsT; i ++ ) {
  15600. var a = ( this.segmentsT + 1 ) * j + i - 1;
  15601. var b = ( this.segmentsT + 1 ) * ( j - 1 ) + i - 1;
  15602. var c = ( this.segmentsT + 1 ) * ( j - 1 ) + i;
  15603. var d = ( this.segmentsT + 1 ) * j + i;
  15604. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  15605. face.normal.addSelf( normals[ a ] );
  15606. face.normal.addSelf( normals[ b ] );
  15607. face.normal.addSelf( normals[ c ] );
  15608. face.normal.addSelf( normals[ d ] );
  15609. face.normal.normalize();
  15610. this.faces.push( face );
  15611. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  15612. }
  15613. }
  15614. this.computeCentroids();
  15615. };
  15616. THREE.TorusGeometry.prototype = new THREE.Geometry();
  15617. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  15618. /**
  15619. * @author oosmoxiecode
  15620. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  15621. */
  15622. THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {
  15623. THREE.Geometry.call( this );
  15624. var scope = this;
  15625. this.radius = radius || 200;
  15626. this.tube = tube || 40;
  15627. this.segmentsR = segmentsR || 64;
  15628. this.segmentsT = segmentsT || 8;
  15629. this.p = p || 2;
  15630. this.q = q || 3;
  15631. this.heightScale = heightScale || 1;
  15632. this.grid = new Array(this.segmentsR);
  15633. var tang = new THREE.Vector3();
  15634. var n = new THREE.Vector3();
  15635. var bitan = new THREE.Vector3();
  15636. for ( var i = 0; i < this.segmentsR; ++ i ) {
  15637. this.grid[ i ] = new Array( this.segmentsT );
  15638. for ( var j = 0; j < this.segmentsT; ++ j ) {
  15639. var u = i / this.segmentsR * 2 * this.p * Math.PI;
  15640. var v = j / this.segmentsT * 2 * Math.PI;
  15641. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  15642. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  15643. var cx, cy;
  15644. tang.sub( p2, p1 );
  15645. n.add( p2, p1 );
  15646. bitan.cross( tang, n );
  15647. n.cross( bitan, tang );
  15648. bitan.normalize();
  15649. n.normalize();
  15650. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  15651. cy = this.tube * Math.sin( v );
  15652. p1.x += cx * n.x + cy * bitan.x;
  15653. p1.y += cx * n.y + cy * bitan.y;
  15654. p1.z += cx * n.z + cy * bitan.z;
  15655. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  15656. }
  15657. }
  15658. for ( var i = 0; i < this.segmentsR; ++ i ) {
  15659. for ( var j = 0; j < this.segmentsT; ++ j ) {
  15660. var ip = ( i + 1 ) % this.segmentsR;
  15661. var jp = ( j + 1 ) % this.segmentsT;
  15662. var a = this.grid[ i ][ j ];
  15663. var b = this.grid[ ip ][ j ];
  15664. var c = this.grid[ ip ][ jp ];
  15665. var d = this.grid[ i ][ jp ];
  15666. var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
  15667. var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
  15668. var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
  15669. var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );
  15670. this.faces.push( new THREE.Face4( a, b, c, d ) );
  15671. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  15672. }
  15673. }
  15674. this.computeCentroids();
  15675. this.computeFaceNormals();
  15676. this.computeVertexNormals();
  15677. function vert( x, y, z ) {
  15678. return scope.vertices.push( new THREE.Vertex( x, y, z ) ) - 1;
  15679. }
  15680. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  15681. var cu = Math.cos( u );
  15682. var cv = Math.cos( v );
  15683. var su = Math.sin( u );
  15684. var quOverP = in_q / in_p * u;
  15685. var cs = Math.cos( quOverP );
  15686. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  15687. var ty = radius * ( 2 + cs ) * su * 0.5;
  15688. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  15689. return new THREE.Vector3( tx, ty, tz );
  15690. }
  15691. };
  15692. THREE.TorusKnotGeometry.prototype = new THREE.Geometry();
  15693. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  15694. /**
  15695. * @author WestLangley / https://github.com/WestLangley
  15696. * @author zz85 / https://github.com/zz85
  15697. * @author miningold / https://github.com/miningold
  15698. *
  15699. * Modified from the TorusKnotGeometry by @oosmoxiecode
  15700. *
  15701. * Creates a tube which extrudes along a 3d spline
  15702. *
  15703. * Uses parallel transport frames as described in
  15704. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  15705. */
  15706. THREE.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {
  15707. THREE.Geometry.call( this );
  15708. this.path = path;
  15709. this.segments = segments || 64;
  15710. this.radius = radius || 1;
  15711. this.segmentsRadius = segmentsRadius || 8;
  15712. this.closed = closed || false;
  15713. if ( debug ) this.debug = new THREE.Object3D();
  15714. this.grid = [];
  15715. var scope = this,
  15716. tangent,
  15717. normal,
  15718. binormal,
  15719. numpoints = this.segments + 1,
  15720. x, y, z,
  15721. tx, ty, tz,
  15722. u, v,
  15723. cx, cy,
  15724. pos, pos2 = new THREE.Vector3(),
  15725. i, j,
  15726. ip, jp,
  15727. a, b, c, d,
  15728. uva, uvb, uvc, uvd;
  15729. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  15730. tangents = frames.tangents,
  15731. normals = frames.normals,
  15732. binormals = frames.binormals;
  15733. // proxy internals
  15734. this.tangents = tangents;
  15735. this.normals = normals;
  15736. this.binormals = binormals;
  15737. function vert( x, y, z ) {
  15738. return scope.vertices.push( new THREE.Vertex( x, y, z ) ) - 1;
  15739. }
  15740. // consruct the grid
  15741. for ( i = 0; i < numpoints; i++ ) {
  15742. this.grid[ i ] = [];
  15743. u = i / ( numpoints - 1 );
  15744. pos = path.getPointAt( u );
  15745. tangent = tangents[ i ];
  15746. normal = normals[ i ];
  15747. binormal = binormals[ i ];
  15748. if ( this.debug ) {
  15749. this.debug.add(new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff));
  15750. this.debug.add(new THREE.ArrowHelper(normal, pos, radius, 0xff0000));
  15751. this.debug.add(new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00));
  15752. }
  15753. for ( j = 0; j < this.segmentsRadius; j++ ) {
  15754. v = j / this.segmentsRadius * 2 * Math.PI;
  15755. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  15756. cy = this.radius * Math.sin( v );
  15757. pos2.copy( pos );
  15758. pos2.x += cx * normal.x + cy * binormal.x;
  15759. pos2.y += cx * normal.y + cy * binormal.y;
  15760. pos2.z += cx * normal.z + cy * binormal.z;
  15761. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  15762. }
  15763. }
  15764. // construct the mesh
  15765. for ( i = 0; i < this.segments; i++ ) {
  15766. for ( j = 0; j < this.segmentsRadius; j++ ) {
  15767. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  15768. jp = (j + 1) % this.segmentsRadius;
  15769. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  15770. b = this.grid[ ip ][ j ];
  15771. c = this.grid[ ip ][ jp ];
  15772. d = this.grid[ i ][ jp ];
  15773. uva = new THREE.UV( i / this.segments, j / this.segmentsRadius );
  15774. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.segmentsRadius );
  15775. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.segmentsRadius );
  15776. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.segmentsRadius );
  15777. this.faces.push( new THREE.Face4( a, b, c, d ) );
  15778. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  15779. }
  15780. }
  15781. this.computeCentroids();
  15782. this.computeFaceNormals();
  15783. this.computeVertexNormals();
  15784. };
  15785. THREE.TubeGeometry.prototype = new THREE.Geometry();
  15786. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  15787. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  15788. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  15789. var
  15790. tangent = new THREE.Vector3(),
  15791. normal = new THREE.Vector3(),
  15792. binormal = new THREE.Vector3(),
  15793. tangents = [],
  15794. normals = [],
  15795. binormals = [],
  15796. vec = new THREE.Vector3(),
  15797. mat = new THREE.Matrix4(),
  15798. numpoints = segments + 1,
  15799. theta,
  15800. epsilon = 0.0001,
  15801. smallest,
  15802. tx, ty, tz,
  15803. i, u, v;
  15804. // expose internals
  15805. this.tangents = tangents;
  15806. this.normals = normals;
  15807. this.binormals = binormals;
  15808. // compute the tangent vectors for each segment on the path
  15809. for ( i = 0; i < numpoints; i++ ) {
  15810. u = i / ( numpoints - 1 );
  15811. tangents[ i ] = path.getTangentAt( u );
  15812. tangents[ i ].normalize();
  15813. }
  15814. initialNormal3();
  15815. function initialNormal1(lastBinormal) {
  15816. // fixed start binormal. Has dangers of 0 vectors
  15817. normals[ 0 ] = new THREE.Vector3();
  15818. binormals[ 0 ] = new THREE.Vector3();
  15819. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  15820. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  15821. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  15822. }
  15823. function initialNormal2() {
  15824. // This uses the Frenet-Serret formula for deriving binormal
  15825. var t2 = path.getTangentAt( epsilon );
  15826. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  15827. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  15828. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  15829. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  15830. }
  15831. function initialNormal3() {
  15832. // select an initial normal vector perpenicular to the first tangent vector,
  15833. // and in the direction of the smallest tangent xyz component
  15834. normals[ 0 ] = new THREE.Vector3();
  15835. binormals[ 0 ] = new THREE.Vector3();
  15836. smallest = Number.MAX_VALUE;
  15837. tx = Math.abs( tangents[ 0 ].x );
  15838. ty = Math.abs( tangents[ 0 ].y );
  15839. tz = Math.abs( tangents[ 0 ].z );
  15840. if ( tx <= smallest ) {
  15841. smallest = tx;
  15842. normal.set( 1, 0, 0 );
  15843. }
  15844. if ( ty <= smallest ) {
  15845. smallest = ty;
  15846. normal.set( 0, 1, 0 );
  15847. }
  15848. if ( tz <= smallest ) {
  15849. normal.set( 0, 0, 1 );
  15850. }
  15851. vec.cross( tangents[ 0 ], normal ).normalize();
  15852. normals[ 0 ].cross( tangents[ 0 ], vec );
  15853. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  15854. }
  15855. // compute the slowly-varying normal and binormal vectors for each segment on the path
  15856. for ( i = 1; i < numpoints; i++ ) {
  15857. normals[ i ] = normals[ i-1 ].clone();
  15858. binormals[ i ] = binormals[ i-1 ].clone();
  15859. vec.cross( tangents[ i-1 ], tangents[ i ] );
  15860. if ( vec.length() > epsilon ) {
  15861. vec.normalize();
  15862. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  15863. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  15864. }
  15865. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  15866. }
  15867. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  15868. if ( closed ) {
  15869. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  15870. theta /= ( numpoints - 1 );
  15871. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  15872. theta = -theta;
  15873. }
  15874. for ( i = 1; i < numpoints; i++ ) {
  15875. // twist a little...
  15876. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  15877. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  15878. }
  15879. }
  15880. };
  15881. /**
  15882. * @author clockworkgeek / https://github.com/clockworkgeek
  15883. * @author timothypratley / https://github.com/timothypratley
  15884. */
  15885. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  15886. THREE.Geometry.call( this );
  15887. radius = radius || 1;
  15888. detail = detail || 0;
  15889. var that = this;
  15890. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  15891. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  15892. }
  15893. var midpoints = [], p = this.vertices;
  15894. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  15895. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  15896. }
  15897. this.mergeVertices();
  15898. // Apply radius
  15899. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  15900. this.vertices[ i ].multiplyScalar( radius );
  15901. }
  15902. /**
  15903. * Project vector onto sphere's surface
  15904. */
  15905. function prepare( vector ) {
  15906. var vertex = new THREE.Vertex().copy( vector.normalize() );
  15907. vertex.index = that.vertices.push( vertex ) - 1;
  15908. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  15909. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  15910. var v = inclination( vector ) / Math.PI + 0.5;
  15911. vertex.uv = new THREE.UV( u, v );
  15912. return vertex;
  15913. }
  15914. /**
  15915. * Approximate a curved face with recursively sub-divided triangles.
  15916. */
  15917. function make( v1, v2, v3, detail ) {
  15918. if ( detail < 1 ) {
  15919. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  15920. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  15921. face.normal = face.centroid.clone().normalize();
  15922. that.faces.push( face );
  15923. var azi = azimuth( face.centroid );
  15924. that.faceVertexUvs[ 0 ].push( [
  15925. correctUV( v1.uv, v1, azi ),
  15926. correctUV( v2.uv, v2, azi ),
  15927. correctUV( v3.uv, v3, azi )
  15928. ] );
  15929. }
  15930. else {
  15931. detail -= 1;
  15932. // split triangle into 4 smaller triangles
  15933. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  15934. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  15935. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  15936. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  15937. }
  15938. }
  15939. function midpoint( v1, v2 ) {
  15940. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  15941. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  15942. var mid = midpoints[ v1.index ][ v2.index ];
  15943. if ( mid === undefined ) {
  15944. // generate mean point and project to surface with prepare()
  15945. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  15946. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  15947. );
  15948. }
  15949. return mid;
  15950. }
  15951. /**
  15952. * Angle around the Y axis, counter-clockwise when looking from above.
  15953. */
  15954. function azimuth( vector ) {
  15955. return Math.atan2( vector.z, -vector.x );
  15956. }
  15957. /**
  15958. * Angle above the XZ plane.
  15959. */
  15960. function inclination( vector ) {
  15961. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  15962. }
  15963. /**
  15964. * Texture fixing helper. Spheres have some odd behaviours.
  15965. */
  15966. function correctUV( uv, vector, azimuth ) {
  15967. if ( (azimuth < 0) && (uv.u === 1) ) uv = new THREE.UV( uv.u - 1, uv.v );
  15968. if ( (vector.x === 0) && (vector.z === 0) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  15969. return uv;
  15970. }
  15971. this.computeCentroids();
  15972. this.boundingSphere = { radius: radius };
  15973. };
  15974. THREE.PolyhedronGeometry.prototype = new THREE.Geometry();
  15975. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  15976. /**
  15977. * @author timothypratley / https://github.com/timothypratley
  15978. */
  15979. THREE.IcosahedronGeometry = function ( radius, detail ) {
  15980. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15981. var vertices = [
  15982. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  15983. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  15984. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  15985. ];
  15986. var faces = [
  15987. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  15988. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  15989. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  15990. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  15991. ];
  15992. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  15993. };
  15994. THREE.IcosahedronGeometry.prototype = new THREE.Geometry();
  15995. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  15996. /**
  15997. * @author timothypratley / https://github.com/timothypratley
  15998. */
  15999. THREE.OctahedronGeometry = function ( radius, detail ) {
  16000. var vertices = [
  16001. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  16002. ];
  16003. var faces = [
  16004. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  16005. ];
  16006. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  16007. };
  16008. THREE.OctahedronGeometry.prototype = new THREE.Geometry();
  16009. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  16010. /**
  16011. * @author timothypratley / https://github.com/timothypratley
  16012. */
  16013. THREE.TetrahedronGeometry = function ( radius, detail ) {
  16014. var vertices = [
  16015. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  16016. ];
  16017. var faces = [
  16018. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  16019. ];
  16020. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  16021. };
  16022. THREE.TetrahedronGeometry.prototype = new THREE.Geometry();
  16023. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  16024. /**
  16025. * @author sroucheray / http://sroucheray.org/
  16026. * @author mr.doob / http://mrdoob.com/
  16027. */
  16028. THREE.AxisHelper = function () {
  16029. THREE.Object3D.call( this );
  16030. var lineGeometry = new THREE.Geometry();
  16031. lineGeometry.vertices.push( new THREE.Vertex() );
  16032. lineGeometry.vertices.push( new THREE.Vertex( 0, 100, 0 ) );
  16033. var coneGeometry = new THREE.CylinderGeometry( 0, 5, 25, 5, 1 );
  16034. var line, cone;
  16035. // x
  16036. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
  16037. line.rotation.z = - Math.PI / 2;
  16038. this.add( line );
  16039. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0xff0000 } ) );
  16040. cone.position.x = 100;
  16041. cone.rotation.z = - Math.PI / 2;
  16042. this.add( cone );
  16043. // y
  16044. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x00ff00 } ) );
  16045. this.add( line );
  16046. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x00ff00 } ) );
  16047. cone.position.y = 100;
  16048. this.add( cone );
  16049. // z
  16050. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
  16051. line.rotation.x = Math.PI / 2;
  16052. this.add( line );
  16053. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x0000ff } ) );
  16054. cone.position.z = 100;
  16055. cone.rotation.x = Math.PI / 2;
  16056. this.add( cone );
  16057. };
  16058. THREE.AxisHelper.prototype = new THREE.Object3D();
  16059. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  16060. /**
  16061. * @author WestLangley / https://github.com/WestLangley
  16062. * @author zz85 / https://github.com/zz85
  16063. *
  16064. * Creates an arrow for visualizing directions
  16065. *
  16066. * Parameters:
  16067. * dir - Vector3
  16068. * origin - Vector3
  16069. * length - Number
  16070. * hex - color in hex value
  16071. */
  16072. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  16073. THREE.Object3D.call( this );
  16074. if ( hex === undefined ) hex = 0xffff00;
  16075. if ( length === undefined ) length = 20;
  16076. var lineGeometry = new THREE.Geometry();
  16077. lineGeometry.vertices.push( new THREE.Vertex( 0, 0, 0 ) );
  16078. lineGeometry.vertices.push( new THREE.Vertex( 0, 1, 0 ) );
  16079. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : hex } ) );
  16080. this.add( this.line );
  16081. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  16082. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : hex } ) );
  16083. this.cone.position.set( 0, 1, 0 );
  16084. this.add( this.cone );
  16085. if ( origin instanceof THREE.Vector3 ) {
  16086. this.position = origin;
  16087. }
  16088. this.setDirection( dir );
  16089. this.setLength( length );
  16090. };
  16091. THREE.ArrowHelper.prototype = new THREE.Object3D();
  16092. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  16093. THREE.ArrowHelper.prototype.setDirection = function( dir ) {
  16094. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  16095. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  16096. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  16097. this.rotation.getRotationFromMatrix( this.matrix, this.scale );
  16098. };
  16099. THREE.ArrowHelper.prototype.setLength = function( length ) {
  16100. this.scale.set( length, length, length );
  16101. };
  16102. THREE.ArrowHelper.prototype.setColor = function( hex ) {
  16103. this.line.material.color.setHex( hex );
  16104. this.cone.material.color.setHex( hex );
  16105. };
  16106. /**
  16107. * @author alteredq / http://alteredqualia.com/
  16108. *
  16109. * - shows frustum, line of sight and up of the camera
  16110. * - suitable for fast updates
  16111. * - based on frustum visualization in lightgl.js shadowmap example
  16112. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  16113. */
  16114. THREE.CameraHelper = function ( camera ) {
  16115. THREE.Object3D.call( this );
  16116. var _this = this;
  16117. this.lineGeometry = new THREE.Geometry();
  16118. this.lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  16119. this.pointMap = {};
  16120. // colors
  16121. var hexFrustum = 0xffaa00,
  16122. hexCone = 0xff0000,
  16123. hexUp = 0x00aaff,
  16124. hexTarget = 0xffffff,
  16125. hexCross = 0x333333;
  16126. // near
  16127. addLine( "n1", "n2", hexFrustum );
  16128. addLine( "n2", "n4", hexFrustum );
  16129. addLine( "n4", "n3", hexFrustum );
  16130. addLine( "n3", "n1", hexFrustum );
  16131. // far
  16132. addLine( "f1", "f2", hexFrustum );
  16133. addLine( "f2", "f4", hexFrustum );
  16134. addLine( "f4", "f3", hexFrustum );
  16135. addLine( "f3", "f1", hexFrustum );
  16136. // sides
  16137. addLine( "n1", "f1", hexFrustum );
  16138. addLine( "n2", "f2", hexFrustum );
  16139. addLine( "n3", "f3", hexFrustum );
  16140. addLine( "n4", "f4", hexFrustum );
  16141. // cone
  16142. addLine( "p", "n1", hexCone );
  16143. addLine( "p", "n2", hexCone );
  16144. addLine( "p", "n3", hexCone );
  16145. addLine( "p", "n4", hexCone );
  16146. // up
  16147. addLine( "u1", "u2", hexUp );
  16148. addLine( "u2", "u3", hexUp );
  16149. addLine( "u3", "u1", hexUp );
  16150. // target
  16151. addLine( "c", "t", hexTarget );
  16152. addLine( "p", "c", hexCross );
  16153. // cross
  16154. addLine( "cn1", "cn2", hexCross );
  16155. addLine( "cn3", "cn4", hexCross );
  16156. addLine( "cf1", "cf2", hexCross );
  16157. addLine( "cf3", "cf4", hexCross );
  16158. this.camera = camera;
  16159. function addLine( a, b, hex ) {
  16160. addPoint( a, hex );
  16161. addPoint( b, hex );
  16162. }
  16163. function addPoint( id, hex ) {
  16164. _this.lineGeometry.vertices.push( new THREE.Vertex() );
  16165. _this.lineGeometry.colors.push( new THREE.Color( hex ) );
  16166. if ( _this.pointMap[ id ] === undefined ) _this.pointMap[ id ] = [];
  16167. _this.pointMap[ id ].push( _this.lineGeometry.vertices.length - 1 );
  16168. }
  16169. this.update( camera );
  16170. this.lines = new THREE.Line( this.lineGeometry, this.lineMaterial, THREE.LinePieces );
  16171. this.add( this.lines );
  16172. };
  16173. THREE.CameraHelper.prototype = new THREE.Object3D();
  16174. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  16175. THREE.CameraHelper.prototype.update = function () {
  16176. var camera = this.camera;
  16177. var w = 1;
  16178. var h = 1;
  16179. var _this = this;
  16180. // we need just camera projection matrix
  16181. // world matrix must be identity
  16182. THREE.CameraHelper.__c.projectionMatrix.copy( camera.projectionMatrix );
  16183. // center / target
  16184. setPoint( "c", 0, 0, -1 );
  16185. setPoint( "t", 0, 0, 1 );
  16186. // near
  16187. setPoint( "n1", -w, -h, -1 );
  16188. setPoint( "n2", w, -h, -1 );
  16189. setPoint( "n3", -w, h, -1 );
  16190. setPoint( "n4", w, h, -1 );
  16191. // far
  16192. setPoint( "f1", -w, -h, 1 );
  16193. setPoint( "f2", w, -h, 1 );
  16194. setPoint( "f3", -w, h, 1 );
  16195. setPoint( "f4", w, h, 1 );
  16196. // up
  16197. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  16198. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  16199. setPoint( "u3", 0, h * 2, -1 );
  16200. // cross
  16201. setPoint( "cf1", -w, 0, 1 );
  16202. setPoint( "cf2", w, 0, 1 );
  16203. setPoint( "cf3", 0, -h, 1 );
  16204. setPoint( "cf4", 0, h, 1 );
  16205. setPoint( "cn1", -w, 0, -1 );
  16206. setPoint( "cn2", w, 0, -1 );
  16207. setPoint( "cn3", 0, -h, -1 );
  16208. setPoint( "cn4", 0, h, -1 );
  16209. function setPoint( point, x, y, z ) {
  16210. THREE.CameraHelper.__v.set( x, y, z );
  16211. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  16212. var points = _this.pointMap[ point ];
  16213. if ( points !== undefined ) {
  16214. for ( var i = 0, il = points.length; i < il; i ++ ) {
  16215. var j = points[ i ];
  16216. _this.lineGeometry.vertices[ j ].copy( THREE.CameraHelper.__v );
  16217. }
  16218. }
  16219. }
  16220. this.lineGeometry.__dirtyVertices = true;
  16221. };
  16222. THREE.CameraHelper.__projector = new THREE.Projector();
  16223. THREE.CameraHelper.__v = new THREE.Vector3();
  16224. THREE.CameraHelper.__c = new THREE.Camera();
  16225. /*
  16226. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  16227. *
  16228. * Subdivision Geometry Modifier
  16229. * using Catmull-Clark Subdivision Surfaces
  16230. * for creating smooth geometry meshes
  16231. *
  16232. * Note: a modifier modifies vertices and faces of geometry,
  16233. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  16234. *
  16235. * Readings:
  16236. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  16237. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  16238. * http://xrt.wikidot.com/blog:31
  16239. * "Subdivision Surfaces in Character Animation"
  16240. *
  16241. * Supports:
  16242. * Closed and Open geometries.
  16243. *
  16244. * TODO:
  16245. * crease vertex and "semi-sharp" features
  16246. * selective subdivision
  16247. */
  16248. THREE.SubdivisionModifier = function( subdivisions ) {
  16249. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  16250. // Settings
  16251. this.useOldVertexColors = false;
  16252. this.supportUVs = true;
  16253. this.debug = false;
  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. //debug( '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( x, y, z ) );
  16271. }
  16272. var scope = this;
  16273. function debug() {
  16274. if (scope.debug) console.log.apply(console, arguments);
  16275. }
  16276. function warn() {
  16277. if (console)
  16278. console.log.apply(console, arguments);
  16279. }
  16280. function f4( a, b, c, d, oldFace, orders, facei ) {
  16281. // TODO move vertex selection over here!
  16282. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.material );
  16283. if (scope.useOldVertexColors) {
  16284. newFace.vertexColors = [];
  16285. var color, tmpColor, order;
  16286. for (var i=0;i<4;i++) {
  16287. order = orders[i];
  16288. color = new THREE.Color(),
  16289. color.setRGB(0,0,0);
  16290. for (var j=0, jl=0; j<order.length;j++) {
  16291. tmpColor = oldFace.vertexColors[order[j]-1];
  16292. color.r += tmpColor.r;
  16293. color.g += tmpColor.g;
  16294. color.b += tmpColor.b;
  16295. }
  16296. color.r /= order.length;
  16297. color.g /= order.length;
  16298. color.b /= order.length;
  16299. newFace.vertexColors[i] = color;
  16300. }
  16301. }
  16302. newFaces.push( newFace );
  16303. if (scope.supportUVs) {
  16304. var aUv = [
  16305. getUV(a, ''),
  16306. getUV(b, facei),
  16307. getUV(c, facei),
  16308. getUV(d, facei)
  16309. ];
  16310. if (!aUv[0]) debug('a :( ', a+':'+facei);
  16311. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  16312. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  16313. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  16314. else
  16315. newUVs.push( aUv );
  16316. }
  16317. }
  16318. function edge_hash( a, b ) {
  16319. return Math.min( a, b ) + "_" + Math.max( a, b );
  16320. }
  16321. function computeEdgeFaces( geometry ) {
  16322. var i, il, v1, v2, j, k,
  16323. face, faceIndices, faceIndex,
  16324. edge,
  16325. hash,
  16326. edgeFaceMap = {};
  16327. function mapEdgeHash( hash, i ) {
  16328. if ( edgeFaceMap[ hash ] === undefined ) {
  16329. edgeFaceMap[ hash ] = [];
  16330. }
  16331. edgeFaceMap[ hash ].push( i );
  16332. }
  16333. // construct vertex -> face map
  16334. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  16335. face = geometry.faces[ i ];
  16336. if ( face instanceof THREE.Face3 ) {
  16337. hash = edge_hash( face.a, face.b );
  16338. mapEdgeHash( hash, i );
  16339. hash = edge_hash( face.b, face.c );
  16340. mapEdgeHash( hash, i );
  16341. hash = edge_hash( face.c, face.a );
  16342. mapEdgeHash( hash, i );
  16343. } else if ( face instanceof THREE.Face4 ) {
  16344. hash = edge_hash( face.a, face.b );
  16345. mapEdgeHash( hash, i );
  16346. hash = edge_hash( face.b, face.c );
  16347. mapEdgeHash( hash, i );
  16348. hash = edge_hash( face.c, face.d );
  16349. mapEdgeHash( hash, i );
  16350. hash = edge_hash( face.d, face.a );
  16351. mapEdgeHash( hash, i );
  16352. }
  16353. }
  16354. // extract faces
  16355. // var edges = [];
  16356. //
  16357. // var numOfEdges = 0;
  16358. // for (i in edgeFaceMap) {
  16359. // numOfEdges++;
  16360. //
  16361. // edge = edgeFaceMap[i];
  16362. // edges.push(edge);
  16363. //
  16364. // }
  16365. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  16366. return edgeFaceMap;
  16367. }
  16368. var originalPoints = oldGeometry.vertices;
  16369. var originalFaces = oldGeometry.faces;
  16370. var newPoints = originalPoints.concat(); // Vertices
  16371. var facePoints = [], edgePoints = {};
  16372. var sharpEdges = {}, sharpVertices = [], sharpFaces = [];
  16373. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  16374. var originalVerticesLength = originalPoints.length;
  16375. function getUV(vertexNo, oldFaceNo) {
  16376. var j,jl;
  16377. var key = vertexNo+':'+oldFaceNo;
  16378. var theUV = uvForVertices[key];
  16379. if (!theUV) {
  16380. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  16381. debug('face pt');
  16382. } else {
  16383. debug('edge pt');
  16384. }
  16385. warn('warning, UV not found for', key);
  16386. return null;
  16387. }
  16388. return theUV;
  16389. // Original faces -> Vertex Nos.
  16390. // new Facepoint -> Vertex Nos.
  16391. // edge Points
  16392. }
  16393. function addUV(vertexNo, oldFaceNo, value) {
  16394. var key = vertexNo+':'+oldFaceNo;
  16395. if (!(key in uvForVertices)) {
  16396. uvForVertices[key] = value;
  16397. } else {
  16398. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  16399. }
  16400. }
  16401. // Step 1
  16402. // For each face, add a face point
  16403. // Set each face point to be the centroid of all original points for the respective face.
  16404. // debug(oldGeometry);
  16405. var i, il, j, jl, face;
  16406. // For Uvs
  16407. var uvs = oldGeometry.faceVertexUvs[0];
  16408. var abcd = 'abcd', vertice;
  16409. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  16410. if (scope.supportUVs)
  16411. for (i=0, il = uvs.length; i<il; i++ ) {
  16412. for (j=0,jl=uvs[i].length;j<jl;j++) {
  16413. vertice = originalFaces[i][abcd.charAt(j)];
  16414. addUV(vertice, i, uvs[i][j]);
  16415. }
  16416. }
  16417. if (uvs.length == 0) scope.supportUVs = false;
  16418. // Additional UVs check, if we index original
  16419. var uvCount = 0;
  16420. for (var u in uvForVertices) {
  16421. uvCount++;
  16422. }
  16423. if (!uvCount) {
  16424. scope.supportUVs = false;
  16425. debug('no uvs');
  16426. }
  16427. debug('-- Original Faces + Vertices UVs completed', uvForVertices, 'vs', uvs.length);
  16428. var avgUv ;
  16429. for (i=0, il = originalFaces.length; i<il ;i++) {
  16430. face = originalFaces[ i ];
  16431. facePoints.push( face.centroid );
  16432. newPoints.push( new THREE.Vertex().copy( face.centroid ) );
  16433. if (!scope.supportUVs) continue;
  16434. // Prepare subdivided uv
  16435. avgUv = new THREE.UV();
  16436. if ( face instanceof THREE.Face3 ) {
  16437. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  16438. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  16439. avgUv.u /= 3;
  16440. avgUv.v /= 3;
  16441. } else if ( face instanceof THREE.Face4 ) {
  16442. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  16443. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  16444. avgUv.u /= 4;
  16445. avgUv.v /= 4;
  16446. }
  16447. addUV(originalVerticesLength + i, '', avgUv);
  16448. }
  16449. debug('-- added UVs for new Faces', uvForVertices);
  16450. // Step 2
  16451. // For each edge, add an edge point.
  16452. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  16453. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index
  16454. var edge, faceIndexA, faceIndexB, avg;
  16455. // debug('edgeFaceMap', edgeFaceMap);
  16456. var edgeCount = 0;
  16457. var edgeVertex, edgeVertexA, edgeVertexB;
  16458. ////
  16459. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  16460. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  16461. function addVertexEdgeMap(vertex, edge) {
  16462. if (vertexEdgeMap[vertex]===undefined) {
  16463. vertexEdgeMap[vertex] = [];
  16464. }
  16465. vertexEdgeMap[vertex].push(edge);
  16466. }
  16467. function addVertexFaceMap(vertex, face, edge) {
  16468. if (vertexFaceMap[vertex]===undefined) {
  16469. vertexFaceMap[vertex] = {};
  16470. }
  16471. vertexFaceMap[vertex][face] = edge;
  16472. // vertexFaceMap[vertex][face] = null;
  16473. }
  16474. // Prepares vertexEdgeMap and vertexFaceMap
  16475. for (i in edgeFaceMap) { // This is for every edge
  16476. edge = edgeFaceMap[i];
  16477. edgeVertex = i.split('_');
  16478. edgeVertexA = edgeVertex[0];
  16479. edgeVertexB = edgeVertex[1];
  16480. // Maps an edgeVertex to connecting edges
  16481. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  16482. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  16483. for (j=0,jl=edge.length;j<jl;j++) {
  16484. face = edge[j];
  16485. addVertexFaceMap(edgeVertexA, face, i);
  16486. addVertexFaceMap(edgeVertexB, face, i);
  16487. }
  16488. if (edge.length < 2) {
  16489. // edge is "sharp";
  16490. sharpEdges[i] = true;
  16491. sharpVertices[edgeVertexA] = true;
  16492. sharpVertices[edgeVertexB] = true;
  16493. }
  16494. }
  16495. debug('vertexEdgeMap',vertexEdgeMap, 'vertexFaceMap', vertexFaceMap);
  16496. for (i in edgeFaceMap) {
  16497. edge = edgeFaceMap[i];
  16498. faceIndexA = edge[0]; // face index a
  16499. faceIndexB = edge[1]; // face index b
  16500. edgeVertex = i.split('_');
  16501. edgeVertexA = edgeVertex[0];
  16502. edgeVertexB = edgeVertex[1];
  16503. avg = new THREE.Vector3();
  16504. //debug(i, faceIndexB,facePoints[faceIndexB]);
  16505. if (sharpEdges[i]) {
  16506. //debug('warning, ', i, 'edge has only 1 connecting face', edge);
  16507. // For a sharp edge, average the edge end points.
  16508. avg.addSelf(originalPoints[edgeVertexA]);
  16509. avg.addSelf(originalPoints[edgeVertexB]);
  16510. avg.multiplyScalar(0.5);
  16511. sharpVertices[newPoints.length] = true;
  16512. } else {
  16513. avg.addSelf(facePoints[faceIndexA]);
  16514. avg.addSelf(facePoints[faceIndexB]);
  16515. avg.addSelf(originalPoints[edgeVertexA]);
  16516. avg.addSelf(originalPoints[edgeVertexB]);
  16517. avg.multiplyScalar(0.25);
  16518. }
  16519. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  16520. newPoints.push( new THREE.Vertex().copy( avg ) );
  16521. edgeCount ++;
  16522. if (!scope.supportUVs) {
  16523. continue;
  16524. }
  16525. // debug('faceIndexAB', faceIndexA, faceIndexB, sharpEdges[i]);
  16526. // Prepare subdivided uv
  16527. avgUv = new THREE.UV();
  16528. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  16529. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  16530. avgUv.u /= 2;
  16531. avgUv.v /= 2;
  16532. addUV(edgePoints[i], faceIndexA, avgUv);
  16533. if (!sharpEdges[i]) {
  16534. avgUv = new THREE.UV();
  16535. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  16536. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  16537. avgUv.u /= 2;
  16538. avgUv.v /= 2;
  16539. addUV(edgePoints[i], faceIndexB, avgUv);
  16540. }
  16541. }
  16542. debug('-- Step 2 done');
  16543. // Step 3
  16544. // For each face point, add an edge for every edge of the face,
  16545. // connecting the face point to each edge point for the face.
  16546. var facePt, currentVerticeIndex;
  16547. var hashAB, hashBC, hashCD, hashDA, hashCA;
  16548. var abc123 = ['123', '12', '2', '23'];
  16549. var bca123 = ['123', '23', '3', '31'];
  16550. var cab123 = ['123', '31', '1', '12'];
  16551. var abc1234 = ['1234', '12', '2', '23'];
  16552. var bcd1234 = ['1234', '23', '3', '34'];
  16553. var cda1234 = ['1234', '34', '4', '41'];
  16554. var dab1234 = ['1234', '41', '1', '12'];
  16555. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  16556. facePt = facePoints[i];
  16557. face = originalFaces[i];
  16558. currentVerticeIndex = originalVerticesLength+ i;
  16559. if ( face instanceof THREE.Face3 ) {
  16560. // create 3 face4s
  16561. hashAB = edge_hash( face.a, face.b );
  16562. hashBC = edge_hash( face.b, face.c );
  16563. hashCA = edge_hash( face.c, face.a );
  16564. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  16565. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  16566. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  16567. } else if ( face instanceof THREE.Face4 ) {
  16568. // create 4 face4s
  16569. hashAB = edge_hash( face.a, face.b );
  16570. hashBC = edge_hash( face.b, face.c );
  16571. hashCD = edge_hash( face.c, face.d );
  16572. hashDA = edge_hash( face.d, face.a );
  16573. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  16574. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  16575. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  16576. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  16577. } else {
  16578. debug('face should be a face!', face);
  16579. }
  16580. }
  16581. newVertices = newPoints;
  16582. // debug('original ', oldGeometry.vertices.length, oldGeometry.faces.length );
  16583. // debug('new points', newPoints.length, 'faces', newFaces.length );
  16584. // Step 4
  16585. // For each original point P,
  16586. // take the average F of all n face points for faces touching P,
  16587. // and take the average R of all n edge midpoints for edges touching P,
  16588. // where each edge midpoint is the average of its two endpoint vertices.
  16589. // Move each original point to the point
  16590. var F = new THREE.Vector3();
  16591. var R = new THREE.Vector3();
  16592. var n;
  16593. for (i=0, il = originalPoints.length; i<il; i++) {
  16594. // (F + 2R + (n-3)P) / n
  16595. if (vertexEdgeMap[i]===undefined) continue;
  16596. F.set(0,0,0);
  16597. R.set(0,0,0);
  16598. var newPos = new THREE.Vector3(0,0,0);
  16599. var f =0;
  16600. for (j in vertexFaceMap[i]) {
  16601. F.addSelf(facePoints[j]);
  16602. f++;
  16603. }
  16604. var sharpEdgeCount = 0;
  16605. n = vertexEdgeMap[i].length;
  16606. for (j=0;j<n;j++) {
  16607. if (
  16608. sharpEdges[
  16609. edge_hash(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  16610. ]) {
  16611. sharpEdgeCount++;
  16612. }
  16613. }
  16614. if ( sharpEdgeCount==2 ) {
  16615. continue;
  16616. // Do not move vertex if there's 2 connecting sharp edges.
  16617. }
  16618. /*
  16619. if (sharpEdgeCount>2) {
  16620. // TODO
  16621. }
  16622. */
  16623. F.divideScalar(f);
  16624. for (j=0; j<n;j++) {
  16625. edge = vertexEdgeMap[i][j];
  16626. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  16627. R.addSelf(midPt);
  16628. // R.addSelf(originalPoints[edge[0]]);
  16629. // R.addSelf(originalPoints[edge[1]]);
  16630. }
  16631. R.divideScalar(n);
  16632. newPos.addSelf(originalPoints[i]);
  16633. newPos.multiplyScalar(n - 3);
  16634. newPos.addSelf(F);
  16635. newPos.addSelf(R.multiplyScalar(2));
  16636. newPos.divideScalar(n);
  16637. newVertices[i] = newPos;
  16638. }
  16639. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  16640. newGeometry.vertices = newVertices;
  16641. newGeometry.faces = newFaces;
  16642. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  16643. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  16644. newGeometry.computeCentroids();
  16645. newGeometry.computeFaceNormals();
  16646. newGeometry.computeVertexNormals();
  16647. };
  16648. /**
  16649. * @author alteredq / http://alteredqualia.com/
  16650. */
  16651. THREE.Loader = function ( showStatus ) {
  16652. this.showStatus = showStatus;
  16653. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  16654. this.onLoadStart = function () {};
  16655. this.onLoadProgress = function() {};
  16656. this.onLoadComplete = function () {};
  16657. };
  16658. THREE.Loader.prototype = {
  16659. constructor: THREE.Loader,
  16660. crossOrigin: 'anonymous',
  16661. addStatusElement: function () {
  16662. var e = document.createElement( "div" );
  16663. e.style.position = "absolute";
  16664. e.style.right = "0px";
  16665. e.style.top = "0px";
  16666. e.style.fontSize = "0.8em";
  16667. e.style.textAlign = "left";
  16668. e.style.background = "rgba(0,0,0,0.25)";
  16669. e.style.color = "#fff";
  16670. e.style.width = "120px";
  16671. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  16672. e.style.zIndex = 1000;
  16673. e.innerHTML = "Loading ...";
  16674. return e;
  16675. },
  16676. updateProgress: function ( progress ) {
  16677. var message = "Loaded ";
  16678. if ( progress.total ) {
  16679. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  16680. } else {
  16681. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  16682. }
  16683. this.statusDomElement.innerHTML = message;
  16684. },
  16685. extractUrlBase: function ( url ) {
  16686. var parts = url.split( '/' );
  16687. parts.pop();
  16688. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  16689. },
  16690. initMaterials: function ( scope, materials, texturePath ) {
  16691. scope.materials = [];
  16692. for ( var i = 0; i < materials.length; ++ i ) {
  16693. scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  16694. }
  16695. },
  16696. hasNormals: function ( scope ) {
  16697. var m, i, il = scope.materials.length;
  16698. for( i = 0; i < il; i ++ ) {
  16699. m = scope.materials[ i ];
  16700. if ( m instanceof THREE.ShaderMaterial ) return true;
  16701. }
  16702. return false;
  16703. },
  16704. createMaterial: function ( m, texturePath ) {
  16705. var _this = this;
  16706. function is_pow2( n ) {
  16707. var l = Math.log( n ) / Math.LN2;
  16708. return Math.floor( l ) == l;
  16709. }
  16710. function nearest_pow2( n ) {
  16711. var l = Math.log( n ) / Math.LN2;
  16712. return Math.pow( 2, Math.round( l ) );
  16713. }
  16714. function load_image( where, url ) {
  16715. var image = new Image();
  16716. image.onload = function () {
  16717. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  16718. var width = nearest_pow2( this.width );
  16719. var height = nearest_pow2( this.height );
  16720. where.image.width = width;
  16721. where.image.height = height;
  16722. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  16723. } else {
  16724. where.image = this;
  16725. }
  16726. where.needsUpdate = true;
  16727. };
  16728. image.crossOrigin = _this.crossOrigin;
  16729. image.src = url;
  16730. }
  16731. function create_texture( where, name, sourceFile, repeat, offset, wrap ) {
  16732. var texture = document.createElement( 'canvas' );
  16733. where[ name ] = new THREE.Texture( texture );
  16734. where[ name ].sourceFile = sourceFile;
  16735. if( repeat ) {
  16736. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  16737. if ( repeat[ 0 ] != 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  16738. if ( repeat[ 1 ] != 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  16739. }
  16740. if ( offset ) {
  16741. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  16742. }
  16743. if ( wrap ) {
  16744. var wrapMap = {
  16745. "repeat" : THREE.RepeatWrapping,
  16746. "mirror" : THREE.MirroredRepeatWrapping
  16747. }
  16748. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  16749. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  16750. }
  16751. load_image( where[ name ], texturePath + "/" + sourceFile );
  16752. }
  16753. function rgb2hex( rgb ) {
  16754. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  16755. }
  16756. // defaults
  16757. var mtype = "MeshLambertMaterial";
  16758. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, wireframe: m.wireframe };
  16759. // parameters from model file
  16760. if ( m.shading ) {
  16761. var shading = m.shading.toLowerCase();
  16762. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  16763. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  16764. }
  16765. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  16766. mpars.blending = THREE[ m.blending ];
  16767. }
  16768. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  16769. mpars.transparent = m.transparent;
  16770. }
  16771. if ( m.depthTest !== undefined ) {
  16772. mpars.depthTest = m.depthTest;
  16773. }
  16774. if ( m.depthWrite !== undefined ) {
  16775. mpars.depthWrite = m.depthWrite;
  16776. }
  16777. if ( m.vertexColors !== undefined ) {
  16778. if ( m.vertexColors == "face" ) {
  16779. mpars.vertexColors = THREE.FaceColors;
  16780. } else if ( m.vertexColors ) {
  16781. mpars.vertexColors = THREE.VertexColors;
  16782. }
  16783. }
  16784. // colors
  16785. if ( m.colorDiffuse ) {
  16786. mpars.color = rgb2hex( m.colorDiffuse );
  16787. } else if ( m.DbgColor ) {
  16788. mpars.color = m.DbgColor;
  16789. }
  16790. if ( m.colorSpecular ) {
  16791. mpars.specular = rgb2hex( m.colorSpecular );
  16792. }
  16793. if ( m.colorAmbient ) {
  16794. mpars.ambient = rgb2hex( m.colorAmbient );
  16795. }
  16796. // modifiers
  16797. if ( m.transparency ) {
  16798. mpars.opacity = m.transparency;
  16799. }
  16800. if ( m.specularCoef ) {
  16801. mpars.shininess = m.specularCoef;
  16802. }
  16803. // textures
  16804. if ( m.mapDiffuse && texturePath ) {
  16805. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  16806. }
  16807. if ( m.mapLight && texturePath ) {
  16808. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  16809. }
  16810. if ( m.mapNormal && texturePath ) {
  16811. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  16812. }
  16813. if ( m.mapSpecular && texturePath ) {
  16814. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  16815. }
  16816. // special case for normal mapped material
  16817. if ( m.mapNormal ) {
  16818. var shader = THREE.ShaderUtils.lib[ "normal" ];
  16819. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  16820. uniforms[ "tNormal" ].texture = mpars.normalMap;
  16821. if ( m.mapNormalFactor ) {
  16822. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  16823. }
  16824. if ( mpars.map ) {
  16825. uniforms[ "tDiffuse" ].texture = mpars.map;
  16826. uniforms[ "enableDiffuse" ].value = true;
  16827. }
  16828. if ( mpars.specularMap ) {
  16829. uniforms[ "tSpecular" ].texture = mpars.specularMap;
  16830. uniforms[ "enableSpecular" ].value = true;
  16831. }
  16832. if ( mpars.lightMap ) {
  16833. uniforms[ "tAO" ].texture = mpars.lightMap;
  16834. uniforms[ "enableAO" ].value = true;
  16835. }
  16836. // for the moment don't handle displacement texture
  16837. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  16838. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  16839. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  16840. uniforms[ "uShininess" ].value = mpars.shininess;
  16841. if ( mpars.opacity !== undefined ) {
  16842. uniforms[ "uOpacity" ].value = mpars.opacity;
  16843. }
  16844. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  16845. var material = new THREE.ShaderMaterial( parameters );
  16846. } else {
  16847. var material = new THREE[ mtype ]( mpars );
  16848. }
  16849. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  16850. return material;
  16851. }
  16852. };
  16853. /**
  16854. * @author alteredq / http://alteredqualia.com/
  16855. */
  16856. THREE.BinaryLoader = function ( showStatus ) {
  16857. THREE.Loader.call( this, showStatus );
  16858. };
  16859. THREE.BinaryLoader.prototype = new THREE.Loader();
  16860. THREE.BinaryLoader.prototype.constructor = THREE.BinaryLoader;
  16861. THREE.BinaryLoader.prototype.supr = THREE.Loader.prototype;
  16862. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  16863. // - binary models consist of two files: JS and BIN
  16864. // - parameters
  16865. // - url (required)
  16866. // - callback (required)
  16867. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  16868. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  16869. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  16870. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  16871. binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
  16872. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  16873. this.onLoadStart();
  16874. // #1 load JS part via web worker
  16875. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  16876. };
  16877. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  16878. var xhr = new XMLHttpRequest();
  16879. xhr.onreadystatechange = function () {
  16880. if ( xhr.readyState == 4 ) {
  16881. if ( xhr.status == 200 || xhr.status == 0 ) {
  16882. var json = JSON.parse( xhr.responseText );
  16883. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  16884. } else {
  16885. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  16886. }
  16887. }
  16888. };
  16889. xhr.open( "GET", url, true );
  16890. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  16891. xhr.setRequestHeader( "Content-Type", "text/plain" );
  16892. xhr.send( null );
  16893. };
  16894. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  16895. var xhr = new XMLHttpRequest(),
  16896. url = binaryPath + "/" + json.buffers;
  16897. var length = 0;
  16898. xhr.onreadystatechange = function () {
  16899. if ( xhr.readyState == 4 ) {
  16900. if ( xhr.status == 200 || xhr.status == 0 ) {
  16901. THREE.BinaryLoader.prototype.createBinModel( xhr.response, callback, texturePath, json.materials );
  16902. } else {
  16903. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  16904. }
  16905. } else if ( xhr.readyState == 3 ) {
  16906. if ( callbackProgress ) {
  16907. if ( length == 0 ) {
  16908. length = xhr.getResponseHeader( "Content-Length" );
  16909. }
  16910. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  16911. }
  16912. } else if ( xhr.readyState == 2 ) {
  16913. length = xhr.getResponseHeader( "Content-Length" );
  16914. }
  16915. };
  16916. xhr.open( "GET", url, true );
  16917. xhr.responseType = "arraybuffer";
  16918. xhr.send( null );
  16919. };
  16920. // Binary AJAX parser
  16921. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
  16922. var Model = function ( texturePath ) {
  16923. var scope = this,
  16924. currentOffset = 0,
  16925. md,
  16926. normals = [],
  16927. uvs = [],
  16928. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  16929. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  16930. tri_size, quad_size,
  16931. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  16932. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  16933. THREE.Geometry.call( this );
  16934. THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
  16935. md = parseMetaData( data, currentOffset );
  16936. currentOffset += md.header_bytes;
  16937. /*
  16938. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  16939. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  16940. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  16941. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  16942. */
  16943. // buffers sizes
  16944. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  16945. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  16946. len_tri_flat = md.ntri_flat * ( tri_size );
  16947. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  16948. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  16949. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  16950. len_quad_flat = md.nquad_flat * ( quad_size );
  16951. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  16952. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  16953. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  16954. // read buffers
  16955. currentOffset += init_vertices( currentOffset );
  16956. currentOffset += init_normals( currentOffset );
  16957. currentOffset += handlePadding( md.nnormals * 3 );
  16958. currentOffset += init_uvs( currentOffset );
  16959. start_tri_flat = currentOffset;
  16960. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  16961. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  16962. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  16963. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  16964. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  16965. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  16966. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  16967. // have to first process faces with uvs
  16968. // so that face and uv indices match
  16969. init_triangles_flat_uv( start_tri_flat_uv );
  16970. init_triangles_smooth_uv( start_tri_smooth_uv );
  16971. init_quads_flat_uv( start_quad_flat_uv );
  16972. init_quads_smooth_uv( start_quad_smooth_uv );
  16973. // now we can process untextured faces
  16974. init_triangles_flat( start_tri_flat );
  16975. init_triangles_smooth( start_tri_smooth );
  16976. init_quads_flat( start_quad_flat );
  16977. init_quads_smooth( start_quad_smooth );
  16978. this.computeCentroids();
  16979. this.computeFaceNormals();
  16980. if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
  16981. function handlePadding( n ) {
  16982. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  16983. };
  16984. function parseMetaData( data, offset ) {
  16985. var metaData = {
  16986. 'signature' :parseString( data, offset, 12 ),
  16987. 'header_bytes' :parseUChar8( data, offset + 12 ),
  16988. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  16989. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  16990. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  16991. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  16992. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  16993. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  16994. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  16995. 'nvertices' :parseUInt32( data, offset + 20 ),
  16996. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  16997. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  16998. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  16999. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  17000. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  17001. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  17002. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  17003. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  17004. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  17005. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  17006. };
  17007. /*
  17008. console.log( "signature: " + metaData.signature );
  17009. console.log( "header_bytes: " + metaData.header_bytes );
  17010. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  17011. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  17012. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  17013. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  17014. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  17015. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  17016. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  17017. console.log( "nvertices: " + metaData.nvertices );
  17018. console.log( "nnormals: " + metaData.nnormals );
  17019. console.log( "nuvs: " + metaData.nuvs );
  17020. console.log( "ntri_flat: " + metaData.ntri_flat );
  17021. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  17022. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  17023. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  17024. console.log( "nquad_flat: " + metaData.nquad_flat );
  17025. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  17026. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  17027. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  17028. var total = metaData.header_bytes
  17029. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  17030. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  17031. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  17032. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  17033. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  17034. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  17035. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  17036. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  17037. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  17038. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  17039. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  17040. console.log( "total bytes: " + total );
  17041. */
  17042. return metaData;
  17043. };
  17044. function parseString( data, offset, length ) {
  17045. var charArray = new Uint8Array( data, offset, length );
  17046. var text = "";
  17047. for ( var i = 0; i < length; i ++ ) {
  17048. text += String.fromCharCode( charArray[ offset + i ] );
  17049. }
  17050. return text;
  17051. };
  17052. function parseUChar8( data, offset ) {
  17053. var charArray = new Uint8Array( data, offset, 1 );
  17054. return charArray[ 0 ];
  17055. };
  17056. function parseUInt32( data, offset ) {
  17057. var intArray = new Uint32Array( data, offset, 1 );
  17058. return intArray[ 0 ];
  17059. };
  17060. function init_vertices( start ) {
  17061. var nElements = md.nvertices;
  17062. var coordArray = new Float32Array( data, start, nElements * 3 );
  17063. var i, x, y, z;
  17064. for( i = 0; i < nElements; i ++ ) {
  17065. x = coordArray[ i * 3 ];
  17066. y = coordArray[ i * 3 + 1 ];
  17067. z = coordArray[ i * 3 + 2 ];
  17068. vertex( scope, x, y, z );
  17069. }
  17070. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  17071. };
  17072. function init_normals( start ) {
  17073. var nElements = md.nnormals;
  17074. if ( nElements ) {
  17075. var normalArray = new Int8Array( data, start, nElements * 3 );
  17076. var i, x, y, z;
  17077. for( i = 0; i < nElements; i ++ ) {
  17078. x = normalArray[ i * 3 ];
  17079. y = normalArray[ i * 3 + 1 ];
  17080. z = normalArray[ i * 3 + 2 ];
  17081. normals.push( x/127, y/127, z/127 );
  17082. }
  17083. }
  17084. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  17085. };
  17086. function init_uvs( start ) {
  17087. var nElements = md.nuvs;
  17088. if ( nElements ) {
  17089. var uvArray = new Float32Array( data, start, nElements * 2 );
  17090. var i, u, v;
  17091. for( i = 0; i < nElements; i ++ ) {
  17092. u = uvArray[ i * 2 ];
  17093. v = uvArray[ i * 2 + 1 ];
  17094. uvs.push( u, v );
  17095. }
  17096. }
  17097. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  17098. };
  17099. function init_uvs3( nElements, offset ) {
  17100. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  17101. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  17102. for( i = 0; i < nElements; i ++ ) {
  17103. uva = uvIndexBuffer[ i * 3 ];
  17104. uvb = uvIndexBuffer[ i * 3 + 1 ];
  17105. uvc = uvIndexBuffer[ i * 3 + 2 ];
  17106. u1 = uvs[ uva*2 ];
  17107. v1 = uvs[ uva*2 + 1 ];
  17108. u2 = uvs[ uvb*2 ];
  17109. v2 = uvs[ uvb*2 + 1 ];
  17110. u3 = uvs[ uvc*2 ];
  17111. v3 = uvs[ uvc*2 + 1 ];
  17112. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  17113. }
  17114. };
  17115. function init_uvs4( nElements, offset ) {
  17116. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  17117. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  17118. for( i = 0; i < nElements; i ++ ) {
  17119. uva = uvIndexBuffer[ i * 4 ];
  17120. uvb = uvIndexBuffer[ i * 4 + 1 ];
  17121. uvc = uvIndexBuffer[ i * 4 + 2 ];
  17122. uvd = uvIndexBuffer[ i * 4 + 3 ];
  17123. u1 = uvs[ uva*2 ];
  17124. v1 = uvs[ uva*2 + 1 ];
  17125. u2 = uvs[ uvb*2 ];
  17126. v2 = uvs[ uvb*2 + 1 ];
  17127. u3 = uvs[ uvc*2 ];
  17128. v3 = uvs[ uvc*2 + 1 ];
  17129. u4 = uvs[ uvd*2 ];
  17130. v4 = uvs[ uvd*2 + 1 ];
  17131. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  17132. }
  17133. };
  17134. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  17135. var i, a, b, c, m;
  17136. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  17137. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17138. for( i = 0; i < nElements; i ++ ) {
  17139. a = vertexIndexBuffer[ i * 3 ];
  17140. b = vertexIndexBuffer[ i * 3 + 1 ];
  17141. c = vertexIndexBuffer[ i * 3 + 2 ];
  17142. m = materialIndexBuffer[ i ];
  17143. f3( scope, a, b, c, m );
  17144. }
  17145. };
  17146. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  17147. var i, a, b, c, d, m;
  17148. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  17149. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17150. for( i = 0; i < nElements; i ++ ) {
  17151. a = vertexIndexBuffer[ i * 4 ];
  17152. b = vertexIndexBuffer[ i * 4 + 1 ];
  17153. c = vertexIndexBuffer[ i * 4 + 2 ];
  17154. d = vertexIndexBuffer[ i * 4 + 3 ];
  17155. m = materialIndexBuffer[ i ];
  17156. f4( scope, a, b, c, d, m );
  17157. }
  17158. };
  17159. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  17160. var i, a, b, c, m;
  17161. var na, nb, nc;
  17162. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  17163. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  17164. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17165. for( i = 0; i < nElements; i ++ ) {
  17166. a = vertexIndexBuffer[ i * 3 ];
  17167. b = vertexIndexBuffer[ i * 3 + 1 ];
  17168. c = vertexIndexBuffer[ i * 3 + 2 ];
  17169. na = normalIndexBuffer[ i * 3 ];
  17170. nb = normalIndexBuffer[ i * 3 + 1 ];
  17171. nc = normalIndexBuffer[ i * 3 + 2 ];
  17172. m = materialIndexBuffer[ i ];
  17173. f3n( scope, normals, a, b, c, m, na, nb, nc );
  17174. }
  17175. };
  17176. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  17177. var i, a, b, c, d, m;
  17178. var na, nb, nc, nd;
  17179. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  17180. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  17181. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17182. for( i = 0; i < nElements; i ++ ) {
  17183. a = vertexIndexBuffer[ i * 4 ];
  17184. b = vertexIndexBuffer[ i * 4 + 1 ];
  17185. c = vertexIndexBuffer[ i * 4 + 2 ];
  17186. d = vertexIndexBuffer[ i * 4 + 3 ];
  17187. na = normalIndexBuffer[ i * 4 ];
  17188. nb = normalIndexBuffer[ i * 4 + 1 ];
  17189. nc = normalIndexBuffer[ i * 4 + 2 ];
  17190. nd = normalIndexBuffer[ i * 4 + 3 ];
  17191. m = materialIndexBuffer[ i ];
  17192. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  17193. }
  17194. };
  17195. function init_triangles_flat( start ) {
  17196. var nElements = md.ntri_flat;
  17197. if ( nElements ) {
  17198. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17199. init_faces3_flat( nElements, start, offsetMaterials );
  17200. }
  17201. };
  17202. function init_triangles_flat_uv( start ) {
  17203. var nElements = md.ntri_flat_uv;
  17204. if ( nElements ) {
  17205. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17206. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17207. init_faces3_flat( nElements, start, offsetMaterials );
  17208. init_uvs3( nElements, offsetUvs );
  17209. }
  17210. };
  17211. function init_triangles_smooth( start ) {
  17212. var nElements = md.ntri_smooth;
  17213. if ( nElements ) {
  17214. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17215. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17216. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  17217. }
  17218. };
  17219. function init_triangles_smooth_uv( start ) {
  17220. var nElements = md.ntri_smooth_uv;
  17221. if ( nElements ) {
  17222. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17223. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17224. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17225. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  17226. init_uvs3( nElements, offsetUvs );
  17227. }
  17228. };
  17229. function init_quads_flat( start ) {
  17230. var nElements = md.nquad_flat;
  17231. if ( nElements ) {
  17232. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17233. init_faces4_flat( nElements, start, offsetMaterials );
  17234. }
  17235. };
  17236. function init_quads_flat_uv( start ) {
  17237. var nElements = md.nquad_flat_uv;
  17238. if ( nElements ) {
  17239. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17240. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17241. init_faces4_flat( nElements, start, offsetMaterials );
  17242. init_uvs4( nElements, offsetUvs );
  17243. }
  17244. };
  17245. function init_quads_smooth( start ) {
  17246. var nElements = md.nquad_smooth;
  17247. if ( nElements ) {
  17248. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17249. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17250. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  17251. }
  17252. };
  17253. function init_quads_smooth_uv( start ) {
  17254. var nElements = md.nquad_smooth_uv;
  17255. if ( nElements ) {
  17256. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17257. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17258. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17259. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  17260. init_uvs4( nElements, offsetUvs );
  17261. }
  17262. };
  17263. };
  17264. function vertex ( scope, x, y, z ) {
  17265. scope.vertices.push( new THREE.Vertex( x, y, z ) );
  17266. };
  17267. function f3 ( scope, a, b, c, mi ) {
  17268. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  17269. };
  17270. function f4 ( scope, a, b, c, d, mi ) {
  17271. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  17272. };
  17273. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  17274. var nax = normals[ na*3 ],
  17275. nay = normals[ na*3 + 1 ],
  17276. naz = normals[ na*3 + 2 ],
  17277. nbx = normals[ nb*3 ],
  17278. nby = normals[ nb*3 + 1 ],
  17279. nbz = normals[ nb*3 + 2 ],
  17280. ncx = normals[ nc*3 ],
  17281. ncy = normals[ nc*3 + 1 ],
  17282. ncz = normals[ nc*3 + 2 ];
  17283. scope.faces.push( new THREE.Face3( a, b, c,
  17284. [new THREE.Vector3( nax, nay, naz ),
  17285. new THREE.Vector3( nbx, nby, nbz ),
  17286. new THREE.Vector3( ncx, ncy, ncz )],
  17287. null,
  17288. mi ) );
  17289. };
  17290. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  17291. var nax = normals[ na*3 ],
  17292. nay = normals[ na*3 + 1 ],
  17293. naz = normals[ na*3 + 2 ],
  17294. nbx = normals[ nb*3 ],
  17295. nby = normals[ nb*3 + 1 ],
  17296. nbz = normals[ nb*3 + 2 ],
  17297. ncx = normals[ nc*3 ],
  17298. ncy = normals[ nc*3 + 1 ],
  17299. ncz = normals[ nc*3 + 2 ],
  17300. ndx = normals[ nd*3 ],
  17301. ndy = normals[ nd*3 + 1 ],
  17302. ndz = normals[ nd*3 + 2 ];
  17303. scope.faces.push( new THREE.Face4( a, b, c, d,
  17304. [new THREE.Vector3( nax, nay, naz ),
  17305. new THREE.Vector3( nbx, nby, nbz ),
  17306. new THREE.Vector3( ncx, ncy, ncz ),
  17307. new THREE.Vector3( ndx, ndy, ndz )],
  17308. null,
  17309. mi ) );
  17310. };
  17311. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  17312. var uv = [];
  17313. uv.push( new THREE.UV( u1, v1 ) );
  17314. uv.push( new THREE.UV( u2, v2 ) );
  17315. uv.push( new THREE.UV( u3, v3 ) );
  17316. where.push( uv );
  17317. };
  17318. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  17319. var uv = [];
  17320. uv.push( new THREE.UV( u1, v1 ) );
  17321. uv.push( new THREE.UV( u2, v2 ) );
  17322. uv.push( new THREE.UV( u3, v3 ) );
  17323. uv.push( new THREE.UV( u4, v4 ) );
  17324. where.push( uv );
  17325. };
  17326. Model.prototype = new THREE.Geometry();
  17327. Model.prototype.constructor = Model;
  17328. callback( new Model( texturePath ) );
  17329. };
  17330. /**
  17331. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  17332. */
  17333. THREE.ColladaLoader = function () {
  17334. var COLLADA = null;
  17335. var scene = null;
  17336. var daeScene;
  17337. var readyCallbackFunc = null;
  17338. var sources = {};
  17339. var images = {};
  17340. var animations = {};
  17341. var controllers = {};
  17342. var geometries = {};
  17343. var materials = {};
  17344. var effects = {};
  17345. var cameras = {};
  17346. var animData;
  17347. var visualScenes;
  17348. var baseUrl;
  17349. var morphs;
  17350. var skins;
  17351. var flip_uv = true;
  17352. var preferredShading = THREE.SmoothShading;
  17353. var options = {
  17354. // Force Geometry to always be centered at the local origin of the
  17355. // containing Mesh.
  17356. centerGeometry: false,
  17357. // Axis conversion is done for geometries, animations, and controllers.
  17358. // If we ever pull cameras or lights out of the COLLADA file, they'll
  17359. // need extra work.
  17360. convertUpAxis: false,
  17361. subdivideFaces: true,
  17362. upAxis: 'Y'
  17363. };
  17364. // TODO: support unit conversion as well
  17365. var colladaUnit = 1.0;
  17366. var colladaUp = 'Y';
  17367. var upConversion = null;
  17368. var TO_RADIANS = Math.PI / 180;
  17369. function load ( url, readyCallback, progressCallback ) {
  17370. var length = 0;
  17371. if ( document.implementation && document.implementation.createDocument ) {
  17372. var req = new XMLHttpRequest();
  17373. if ( req.overrideMimeType ) req.overrideMimeType( "text/xml" );
  17374. req.onreadystatechange = function() {
  17375. if( req.readyState == 4 ) {
  17376. if( req.status == 0 || req.status == 200 ) {
  17377. if ( req.responseXML ) {
  17378. readyCallbackFunc = readyCallback;
  17379. parse( req.responseXML, undefined, url );
  17380. } else {
  17381. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  17382. }
  17383. }
  17384. } else if ( req.readyState == 3 ) {
  17385. if ( progressCallback ) {
  17386. if ( length == 0 ) {
  17387. length = req.getResponseHeader( "Content-Length" );
  17388. }
  17389. progressCallback( { total: length, loaded: req.responseText.length } );
  17390. }
  17391. }
  17392. }
  17393. req.open( "GET", url, true );
  17394. req.send( null );
  17395. } else {
  17396. alert( "Don't know how to parse XML!" );
  17397. }
  17398. };
  17399. function parse( doc, callBack, url ) {
  17400. COLLADA = doc;
  17401. callBack = callBack || readyCallbackFunc;
  17402. if ( url !== undefined ) {
  17403. var parts = url.split( '/' );
  17404. parts.pop();
  17405. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  17406. }
  17407. parseAsset();
  17408. setUpConversion();
  17409. images = parseLib( "//dae:library_images/dae:image", _Image, "image" );
  17410. materials = parseLib( "//dae:library_materials/dae:material", Material, "material") ;
  17411. effects = parseLib( "//dae:library_effects/dae:effect", Effect, "effect" );
  17412. geometries = parseLib( "//dae:library_geometries/dae:geometry", Geometry, "geometry" );
  17413. cameras = parseLib( ".//dae:library_cameras/dae:camera", Camera, "camera" );
  17414. controllers = parseLib( "//dae:library_controllers/dae:controller", Controller, "controller" );
  17415. animations = parseLib( "//dae:library_animations/dae:animation", Animation, "animation" );
  17416. visualScenes = parseLib( ".//dae:library_visual_scenes/dae:visual_scene", VisualScene, "visual_scene" );
  17417. morphs = [];
  17418. skins = [];
  17419. daeScene = parseScene();
  17420. scene = new THREE.Object3D();
  17421. for ( var i = 0; i < daeScene.nodes.length; i ++ ) {
  17422. scene.add( createSceneGraph( daeScene.nodes[ i ] ) );
  17423. }
  17424. createAnimations();
  17425. var result = {
  17426. scene: scene,
  17427. morphs: morphs,
  17428. skins: skins,
  17429. animations: animData,
  17430. dae: {
  17431. images: images,
  17432. materials: materials,
  17433. cameras: cameras,
  17434. effects: effects,
  17435. geometries: geometries,
  17436. controllers: controllers,
  17437. animations: animations,
  17438. visualScenes: visualScenes,
  17439. scene: daeScene
  17440. }
  17441. };
  17442. if ( callBack ) {
  17443. callBack( result );
  17444. }
  17445. return result;
  17446. };
  17447. function setPreferredShading ( shading ) {
  17448. preferredShading = shading;
  17449. };
  17450. function parseAsset () {
  17451. var elements = COLLADA.evaluate( '//dae:asset', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  17452. var element = elements.iterateNext();
  17453. if ( element && element.childNodes ) {
  17454. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  17455. var child = element.childNodes[ i ];
  17456. switch ( child.nodeName ) {
  17457. case 'unit':
  17458. var meter = child.getAttribute( 'meter' );
  17459. if ( meter ) {
  17460. colladaUnit = parseFloat( meter );
  17461. }
  17462. break;
  17463. case 'up_axis':
  17464. colladaUp = child.textContent.charAt(0);
  17465. break;
  17466. }
  17467. }
  17468. }
  17469. };
  17470. function parseLib ( q, classSpec, prefix ) {
  17471. var elements = COLLADA.evaluate(q, COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
  17472. var lib = {};
  17473. var element = elements.iterateNext();
  17474. var i = 0;
  17475. while ( element ) {
  17476. var daeElement = ( new classSpec() ).parse( element );
  17477. if ( !daeElement.id || daeElement.id.length == 0 ) daeElement.id = prefix + ( i ++ );
  17478. lib[ daeElement.id ] = daeElement;
  17479. element = elements.iterateNext();
  17480. }
  17481. return lib;
  17482. };
  17483. function parseScene() {
  17484. var sceneElement = COLLADA.evaluate( './/dae:scene/dae:instance_visual_scene', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  17485. if ( sceneElement ) {
  17486. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  17487. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  17488. } else {
  17489. return null;
  17490. }
  17491. };
  17492. function createAnimations() {
  17493. animData = [];
  17494. // fill in the keys
  17495. recurseHierarchy( scene );
  17496. };
  17497. function recurseHierarchy( node ) {
  17498. var n = daeScene.getChildById( node.name, true ),
  17499. newData = null;
  17500. if ( n && n.keys ) {
  17501. newData = {
  17502. fps: 60,
  17503. hierarchy: [ {
  17504. node: n,
  17505. keys: n.keys,
  17506. sids: n.sids
  17507. } ],
  17508. node: node,
  17509. name: 'animation_' + node.name,
  17510. length: 0
  17511. };
  17512. animData.push(newData);
  17513. for ( var i = 0, il = n.keys.length; i < il; i++ ) {
  17514. newData.length = Math.max( newData.length, n.keys[i].time );
  17515. }
  17516. } else {
  17517. newData = {
  17518. hierarchy: [ {
  17519. keys: [],
  17520. sids: []
  17521. } ]
  17522. }
  17523. }
  17524. for ( var i = 0, il = node.children.length; i < il; i++ ) {
  17525. var d = recurseHierarchy( node.children[i] );
  17526. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  17527. newData.hierarchy.push( {
  17528. keys: [],
  17529. sids: []
  17530. } );
  17531. }
  17532. }
  17533. return newData;
  17534. };
  17535. function calcAnimationBounds () {
  17536. var start = 1000000;
  17537. var end = -start;
  17538. var frames = 0;
  17539. for ( var id in animations ) {
  17540. var animation = animations[ id ];
  17541. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  17542. var sampler = animation.sampler[ i ];
  17543. sampler.create();
  17544. start = Math.min( start, sampler.startTime );
  17545. end = Math.max( end, sampler.endTime );
  17546. frames = Math.max( frames, sampler.input.length );
  17547. }
  17548. }
  17549. return { start:start, end:end, frames:frames };
  17550. };
  17551. function createMorph ( geometry, ctrl ) {
  17552. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  17553. if ( !morphCtrl || !morphCtrl.morph ) {
  17554. console.log("could not find morph controller!");
  17555. return;
  17556. }
  17557. var morph = morphCtrl.morph;
  17558. for ( var i = 0; i < morph.targets.length; i ++ ) {
  17559. var target_id = morph.targets[ i ];
  17560. var daeGeometry = geometries[ target_id ];
  17561. if ( !daeGeometry.mesh ||
  17562. !daeGeometry.mesh.primitives ||
  17563. !daeGeometry.mesh.primitives.length ) {
  17564. continue;
  17565. }
  17566. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  17567. if ( target.vertices.length === geometry.vertices.length ) {
  17568. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  17569. }
  17570. }
  17571. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  17572. };
  17573. function createSkin ( geometry, ctrl, applyBindShape ) {
  17574. var skinCtrl = controllers[ ctrl.url ];
  17575. if ( !skinCtrl || !skinCtrl.skin ) {
  17576. console.log( "could not find skin controller!" );
  17577. return;
  17578. }
  17579. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  17580. console.log( "could not find the skeleton for the skin!" );
  17581. return;
  17582. }
  17583. var skin = skinCtrl.skin;
  17584. var skeleton = daeScene.getChildById( ctrl.skeleton[ 0 ] );
  17585. var hierarchy = [];
  17586. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  17587. var bones = [];
  17588. geometry.skinWeights = [];
  17589. geometry.skinIndices = [];
  17590. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  17591. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  17592. /*
  17593. geometry.animation = {
  17594. name: 'take_001',
  17595. fps: 30,
  17596. length: 2,
  17597. JIT: true,
  17598. hierarchy: hierarchy
  17599. };
  17600. */
  17601. if ( applyBindShape ) {
  17602. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  17603. skin.bindShapeMatrix.multiplyVector3( geometry.vertices[ i ] );
  17604. }
  17605. }
  17606. };
  17607. function setupSkeleton ( node, bones, frame, parent ) {
  17608. node.world = node.world || new THREE.Matrix4();
  17609. node.world.copy( node.matrix );
  17610. if ( node.channels && node.channels.length ) {
  17611. var channel = node.channels[ 0 ];
  17612. var m = channel.sampler.output[ frame ];
  17613. if ( m instanceof THREE.Matrix4 ) {
  17614. node.world.copy( m );
  17615. }
  17616. }
  17617. if ( parent ) {
  17618. node.world.multiply( parent, node.world );
  17619. }
  17620. bones.push( node );
  17621. for ( var i = 0; i < node.nodes.length; i ++ ) {
  17622. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  17623. }
  17624. };
  17625. function setupSkinningMatrices ( bones, skin ) {
  17626. // FIXME: this is dumb...
  17627. for ( var i = 0; i < bones.length; i ++ ) {
  17628. var bone = bones[ i ];
  17629. var found = -1;
  17630. if ( bone.type != 'JOINT' ) continue;
  17631. for ( var j = 0; j < skin.joints.length; j ++ ) {
  17632. if ( bone.sid == skin.joints[ j ] ) {
  17633. found = j;
  17634. break;
  17635. }
  17636. }
  17637. if ( found >= 0 ) {
  17638. var inv = skin.invBindMatrices[ found ];
  17639. bone.invBindMatrix = inv;
  17640. bone.skinningMatrix = new THREE.Matrix4();
  17641. bone.skinningMatrix.multiply(bone.world, inv); // (IBMi * JMi)
  17642. bone.weights = [];
  17643. for ( var j = 0; j < skin.weights.length; j ++ ) {
  17644. for (var k = 0; k < skin.weights[ j ].length; k ++) {
  17645. var w = skin.weights[ j ][ k ];
  17646. if ( w.joint == found ) {
  17647. bone.weights.push( w );
  17648. }
  17649. }
  17650. }
  17651. } else {
  17652. throw 'ColladaLoader: Could not find joint \'' + bone.sid + '\'.';
  17653. }
  17654. }
  17655. };
  17656. function applySkin ( geometry, instanceCtrl, frame ) {
  17657. var skinController = controllers[ instanceCtrl.url ];
  17658. frame = frame !== undefined ? frame : 40;
  17659. if ( !skinController || !skinController.skin ) {
  17660. console.log( 'ColladaLoader: Could not find skin controller.' );
  17661. return;
  17662. }
  17663. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  17664. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  17665. return;
  17666. }
  17667. var animationBounds = calcAnimationBounds();
  17668. var skeleton = daeScene.getChildById( instanceCtrl.skeleton[0], true ) ||
  17669. daeScene.getChildBySid( instanceCtrl.skeleton[0], true );
  17670. var i, j, w, vidx, weight;
  17671. var v = new THREE.Vector3(), o, s;
  17672. // move vertices to bind shape
  17673. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  17674. skinController.skin.bindShapeMatrix.multiplyVector3( geometry.vertices[i] );
  17675. }
  17676. // process animation, or simply pose the rig if no animation
  17677. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  17678. var bones = [];
  17679. var skinned = [];
  17680. // zero skinned vertices
  17681. for ( i = 0; i < geometry.vertices.length; i++ ) {
  17682. skinned.push( new THREE.Vertex() );
  17683. }
  17684. // process the frame and setup the rig with a fresh
  17685. // transform, possibly from the bone's animation channel(s)
  17686. setupSkeleton( skeleton, bones, frame );
  17687. setupSkinningMatrices( bones, skinController.skin );
  17688. // skin 'm
  17689. for ( i = 0; i < bones.length; i ++ ) {
  17690. if ( bones[ i ].type != 'JOINT' ) continue;
  17691. for ( j = 0; j < bones[ i ].weights.length; j ++ ) {
  17692. w = bones[ i ].weights[ j ];
  17693. vidx = w.index;
  17694. weight = w.weight;
  17695. o = geometry.vertices[vidx];
  17696. s = skinned[vidx];
  17697. v.x = o.x;
  17698. v.y = o.y;
  17699. v.z = o.z;
  17700. bones[i].skinningMatrix.multiplyVector3(v);
  17701. s.x += (v.x * weight);
  17702. s.y += (v.y * weight);
  17703. s.z += (v.z * weight);
  17704. }
  17705. }
  17706. geometry.morphTargets.push( { name: "target_" + frame, vertices: skinned } );
  17707. }
  17708. };
  17709. function createSceneGraph ( node, parent ) {
  17710. var obj = new THREE.Object3D();
  17711. var skinned = false;
  17712. var skinController;
  17713. var morphController;
  17714. var i, j;
  17715. // FIXME: controllers
  17716. for ( i = 0; i < node.controllers.length; i ++ ) {
  17717. var controller = controllers[ node.controllers[ i ].url ];
  17718. switch ( controller.type ) {
  17719. case 'skin':
  17720. if ( geometries[ controller.skin.source ] ) {
  17721. var inst_geom = new InstanceGeometry();
  17722. inst_geom.url = controller.skin.source;
  17723. inst_geom.instance_material = node.controllers[ i ].instance_material;
  17724. node.geometries.push( inst_geom );
  17725. skinned = true;
  17726. skinController = node.controllers[ i ];
  17727. } else if ( controllers[ controller.skin.source ] ) {
  17728. // urgh: controller can be chained
  17729. // handle the most basic case...
  17730. var second = controllers[ controller.skin.source ];
  17731. morphController = second;
  17732. // skinController = node.controllers[i];
  17733. if ( second.morph && geometries[ second.morph.source ] ) {
  17734. var inst_geom = new InstanceGeometry();
  17735. inst_geom.url = second.morph.source;
  17736. inst_geom.instance_material = node.controllers[ i ].instance_material;
  17737. node.geometries.push( inst_geom );
  17738. }
  17739. }
  17740. break;
  17741. case 'morph':
  17742. if ( geometries[ controller.morph.source ] ) {
  17743. var inst_geom = new InstanceGeometry();
  17744. inst_geom.url = controller.morph.source;
  17745. inst_geom.instance_material = node.controllers[ i ].instance_material;
  17746. node.geometries.push( inst_geom );
  17747. morphController = node.controllers[ i ];
  17748. }
  17749. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  17750. default:
  17751. break;
  17752. }
  17753. }
  17754. // FIXME: multi-material mesh?
  17755. // geometries
  17756. for ( i = 0; i < node.geometries.length; i ++ ) {
  17757. var instance_geometry = node.geometries[i];
  17758. var instance_materials = instance_geometry.instance_material;
  17759. var geometry = geometries[instance_geometry.url];
  17760. var used_materials = {};
  17761. var used_materials_array = [];
  17762. var num_materials = 0;
  17763. var first_material;
  17764. if ( geometry ) {
  17765. if ( !geometry.mesh || !geometry.mesh.primitives )
  17766. continue;
  17767. if ( obj.name.length == 0 ) {
  17768. obj.name = geometry.id;
  17769. }
  17770. // collect used fx for this geometry-instance
  17771. if ( instance_materials ) {
  17772. for ( j = 0; j < instance_materials.length; j ++ ) {
  17773. var instance_material = instance_materials[ j ];
  17774. var mat = materials[ instance_material.target ];
  17775. var effect_id = mat.instance_effect.url;
  17776. var shader = effects[ effect_id ].shader;
  17777. shader.material.opacity = !shader.material.opacity ? 1 : shader.material.opacity;
  17778. used_materials[ instance_material.symbol ] = num_materials;
  17779. used_materials_array.push( shader.material )
  17780. first_material = shader.material;
  17781. first_material.name = mat.name == null || mat.name === '' ? mat.id : mat.name;
  17782. num_materials ++;
  17783. }
  17784. }
  17785. var mesh;
  17786. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.FlatShading } );
  17787. var geom = geometry.mesh.geometry3js;
  17788. if ( num_materials > 1 ) {
  17789. material = new THREE.MeshFaceMaterial();
  17790. geom.materials = used_materials_array;
  17791. for ( j = 0; j < geom.faces.length; j ++ ) {
  17792. var face = geom.faces[ j ];
  17793. face.materialIndex = used_materials[ face.daeMaterial ]
  17794. }
  17795. }
  17796. if ( skinController !== undefined) {
  17797. applySkin( geom, skinController );
  17798. material.morphTargets = true;
  17799. mesh = new THREE.SkinnedMesh( geom, material );
  17800. mesh.skeleton = skinController.skeleton;
  17801. mesh.skinController = controllers[ skinController.url ];
  17802. mesh.skinInstanceController = skinController;
  17803. mesh.name = 'skin_' + skins.length;
  17804. skins.push( mesh );
  17805. } else if ( morphController !== undefined ) {
  17806. createMorph( geom, morphController );
  17807. material.morphTargets = true;
  17808. mesh = new THREE.Mesh( geom, material );
  17809. mesh.name = 'morph_' + morphs.length;
  17810. morphs.push( mesh );
  17811. } else {
  17812. mesh = new THREE.Mesh( geom, material );
  17813. // mesh.geom.name = geometry.id;
  17814. }
  17815. node.geometries.length > 1 ? obj.add( mesh ) : obj = mesh;
  17816. }
  17817. }
  17818. for ( i = 0; i < node.cameras.length; i ++ ) {
  17819. var instance_camera = node.cameras[i];
  17820. var cparams = cameras[instance_camera.url];
  17821. obj = new THREE.PerspectiveCamera(cparams.fov, cparams.aspect_ratio, cparams.znear, cparams.zfar);
  17822. }
  17823. obj.name = node.id || "";
  17824. obj.matrix = node.matrix;
  17825. var props = node.matrix.decompose();
  17826. obj.position = props[ 0 ];
  17827. obj.quaternion = props[ 1 ];
  17828. obj.useQuaternion = true;
  17829. obj.scale = props[ 2 ];
  17830. if ( options.centerGeometry && obj.geometry ) {
  17831. var delta = THREE.GeometryUtils.center( obj.geometry );
  17832. obj.quaternion.multiplyVector3( delta.multiplySelf( obj.scale ) );
  17833. obj.position.subSelf( delta );
  17834. }
  17835. for ( i = 0; i < node.nodes.length; i ++ ) {
  17836. obj.add( createSceneGraph( node.nodes[i], node ) );
  17837. }
  17838. return obj;
  17839. };
  17840. function getJointId( skin, id ) {
  17841. for ( var i = 0; i < skin.joints.length; i ++ ) {
  17842. if ( skin.joints[ i ] == id ) {
  17843. return i;
  17844. }
  17845. }
  17846. };
  17847. function getLibraryNode( id ) {
  17848. return COLLADA.evaluate( './/dae:library_nodes//dae:node[@id=\'' + id + '\']', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  17849. };
  17850. function getChannelsForNode (node ) {
  17851. var channels = [];
  17852. var startTime = 1000000;
  17853. var endTime = -1000000;
  17854. for ( var id in animations ) {
  17855. var animation = animations[id];
  17856. for ( var i = 0; i < animation.channel.length; i ++ ) {
  17857. var channel = animation.channel[i];
  17858. var sampler = animation.sampler[i];
  17859. var id = channel.target.split('/')[0];
  17860. if ( id == node.id ) {
  17861. sampler.create();
  17862. channel.sampler = sampler;
  17863. startTime = Math.min(startTime, sampler.startTime);
  17864. endTime = Math.max(endTime, sampler.endTime);
  17865. channels.push(channel);
  17866. }
  17867. }
  17868. }
  17869. if ( channels.length ) {
  17870. node.startTime = startTime;
  17871. node.endTime = endTime;
  17872. }
  17873. return channels;
  17874. };
  17875. function calcFrameDuration( node ) {
  17876. var minT = 10000000;
  17877. for ( var i = 0; i < node.channels.length; i ++ ) {
  17878. var sampler = node.channels[i].sampler;
  17879. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  17880. var t0 = sampler.input[ j ];
  17881. var t1 = sampler.input[ j + 1 ];
  17882. minT = Math.min( minT, t1 - t0 );
  17883. }
  17884. }
  17885. return minT;
  17886. };
  17887. function calcMatrixAt( node, t ) {
  17888. var animated = {};
  17889. var i, j;
  17890. for ( i = 0; i < node.channels.length; i ++ ) {
  17891. var channel = node.channels[ i ];
  17892. animated[ channel.sid ] = channel;
  17893. }
  17894. var matrix = new THREE.Matrix4();
  17895. for ( i = 0; i < node.transforms.length; i ++ ) {
  17896. var transform = node.transforms[ i ];
  17897. var channel = animated[ transform.sid ];
  17898. if ( channel !== undefined ) {
  17899. var sampler = channel.sampler;
  17900. var value;
  17901. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  17902. if ( sampler.input[ j + 1 ] > t ) {
  17903. value = sampler.output[ j ];
  17904. //console.log(value.flatten)
  17905. break;
  17906. }
  17907. }
  17908. if ( value !== undefined ) {
  17909. if ( value instanceof THREE.Matrix4 ) {
  17910. matrix = matrix.multiply( matrix, value );
  17911. } else {
  17912. // FIXME: handle other types
  17913. matrix = matrix.multiply( matrix, transform.matrix );
  17914. }
  17915. } else {
  17916. matrix = matrix.multiply( matrix, transform.matrix );
  17917. }
  17918. } else {
  17919. matrix = matrix.multiply( matrix, transform.matrix );
  17920. }
  17921. }
  17922. return matrix;
  17923. };
  17924. function bakeAnimations ( node ) {
  17925. if ( node.channels && node.channels.length ) {
  17926. var keys = [],
  17927. sids = [];
  17928. for ( var i = 0, il = node.channels.length; i < il; i++ ) {
  17929. var channel = node.channels[i],
  17930. fullSid = channel.fullSid,
  17931. sampler = channel.sampler,
  17932. input = sampler.input,
  17933. transform = node.getTransformBySid( channel.sid ),
  17934. member;
  17935. if ( channel.arrIndices ) {
  17936. member = [];
  17937. for ( var j = 0, jl = channel.arrIndices.length; j < jl; j++ ) {
  17938. member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
  17939. }
  17940. } else {
  17941. member = getConvertedMember( channel.member );
  17942. }
  17943. if ( transform ) {
  17944. if ( sids.indexOf( fullSid ) === -1 ) {
  17945. sids.push( fullSid );
  17946. }
  17947. for ( var j = 0, jl = input.length; j < jl; j++ ) {
  17948. var time = input[j],
  17949. data = sampler.getData( transform.type, j ),
  17950. key = findKey( keys, time );
  17951. if ( !key ) {
  17952. key = new Key( time );
  17953. var timeNdx = findTimeNdx( keys, time );
  17954. keys.splice( timeNdx == -1 ? keys.length : timeNdx, 0, key );
  17955. }
  17956. key.addTarget( fullSid, transform, member, data );
  17957. }
  17958. } else {
  17959. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  17960. }
  17961. }
  17962. // post process
  17963. for ( var i = 0; i < sids.length; i++ ) {
  17964. var sid = sids[ i ];
  17965. for ( var j = 0; j < keys.length; j++ ) {
  17966. var key = keys[ j ];
  17967. if ( !key.hasTarget( sid ) ) {
  17968. interpolateKeys( keys, key, j, sid );
  17969. }
  17970. }
  17971. }
  17972. node.keys = keys;
  17973. node.sids = sids;
  17974. }
  17975. };
  17976. function findKey ( keys, time) {
  17977. var retVal = null;
  17978. for ( var i = 0, il = keys.length; i < il && retVal == null; i++ ) {
  17979. var key = keys[i];
  17980. if ( key.time === time ) {
  17981. retVal = key;
  17982. } else if ( key.time > time ) {
  17983. break;
  17984. }
  17985. }
  17986. return retVal;
  17987. };
  17988. function findTimeNdx ( keys, time) {
  17989. var ndx = -1;
  17990. for ( var i = 0, il = keys.length; i < il && ndx == -1; i++ ) {
  17991. var key = keys[i];
  17992. if ( key.time >= time ) {
  17993. ndx = i;
  17994. }
  17995. }
  17996. return ndx;
  17997. };
  17998. function interpolateKeys ( keys, key, ndx, fullSid ) {
  17999. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx-1 : 0 ),
  18000. nextKey = getNextKeyWith( keys, fullSid, ndx+1 );
  18001. if ( prevKey && nextKey ) {
  18002. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  18003. prevTarget = prevKey.getTarget( fullSid ),
  18004. nextData = nextKey.getTarget( fullSid ).data,
  18005. prevData = prevTarget.data,
  18006. data;
  18007. if ( prevTarget.type === 'matrix' ) {
  18008. data = prevData;
  18009. } else if ( prevData.length ) {
  18010. data = [];
  18011. for ( var i = 0; i < prevData.length; ++i ) {
  18012. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  18013. }
  18014. } else {
  18015. data = prevData + ( nextData - prevData ) * scale;
  18016. }
  18017. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  18018. }
  18019. };
  18020. // Get next key with given sid
  18021. function getNextKeyWith( keys, fullSid, ndx ) {
  18022. for ( ; ndx < keys.length; ndx++ ) {
  18023. var key = keys[ ndx ];
  18024. if ( key.hasTarget( fullSid ) ) {
  18025. return key;
  18026. }
  18027. }
  18028. return null;
  18029. };
  18030. // Get previous key with given sid
  18031. function getPrevKeyWith( keys, fullSid, ndx ) {
  18032. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  18033. for ( ; ndx >= 0; ndx-- ) {
  18034. var key = keys[ ndx ];
  18035. if ( key.hasTarget( fullSid ) ) {
  18036. return key;
  18037. }
  18038. }
  18039. return null;
  18040. };
  18041. function _Image() {
  18042. this.id = "";
  18043. this.init_from = "";
  18044. };
  18045. _Image.prototype.parse = function(element) {
  18046. this.id = element.getAttribute('id');
  18047. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18048. var child = element.childNodes[ i ];
  18049. if ( child.nodeName == 'init_from' ) {
  18050. this.init_from = child.textContent;
  18051. }
  18052. }
  18053. return this;
  18054. };
  18055. function Controller() {
  18056. this.id = "";
  18057. this.name = "";
  18058. this.type = "";
  18059. this.skin = null;
  18060. this.morph = null;
  18061. };
  18062. Controller.prototype.parse = function( element ) {
  18063. this.id = element.getAttribute('id');
  18064. this.name = element.getAttribute('name');
  18065. this.type = "none";
  18066. for ( var i = 0; i < element.childNodes.length; i++ ) {
  18067. var child = element.childNodes[ i ];
  18068. switch ( child.nodeName ) {
  18069. case 'skin':
  18070. this.skin = (new Skin()).parse(child);
  18071. this.type = child.nodeName;
  18072. break;
  18073. case 'morph':
  18074. this.morph = (new Morph()).parse(child);
  18075. this.type = child.nodeName;
  18076. break;
  18077. default:
  18078. break;
  18079. }
  18080. }
  18081. return this;
  18082. };
  18083. function Morph() {
  18084. this.method = null;
  18085. this.source = null;
  18086. this.targets = null;
  18087. this.weights = null;
  18088. };
  18089. Morph.prototype.parse = function( element ) {
  18090. var sources = {};
  18091. var inputs = [];
  18092. var i;
  18093. this.method = element.getAttribute( 'method' );
  18094. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  18095. for ( i = 0; i < element.childNodes.length; i ++ ) {
  18096. var child = element.childNodes[ i ];
  18097. if ( child.nodeType != 1 ) continue;
  18098. switch ( child.nodeName ) {
  18099. case 'source':
  18100. var source = ( new Source() ).parse( child );
  18101. sources[ source.id ] = source;
  18102. break;
  18103. case 'targets':
  18104. inputs = this.parseInputs( child );
  18105. break;
  18106. default:
  18107. console.log( child.nodeName );
  18108. break;
  18109. }
  18110. }
  18111. for ( i = 0; i < inputs.length; i ++ ) {
  18112. var input = inputs[ i ];
  18113. var source = sources[ input.source ];
  18114. switch ( input.semantic ) {
  18115. case 'MORPH_TARGET':
  18116. this.targets = source.read();
  18117. break;
  18118. case 'MORPH_WEIGHT':
  18119. this.weights = source.read();
  18120. break;
  18121. default:
  18122. break;
  18123. }
  18124. }
  18125. return this;
  18126. };
  18127. Morph.prototype.parseInputs = function(element) {
  18128. var inputs = [];
  18129. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18130. var child = element.childNodes[i];
  18131. if ( child.nodeType != 1) continue;
  18132. switch ( child.nodeName ) {
  18133. case 'input':
  18134. inputs.push( (new Input()).parse(child) );
  18135. break;
  18136. default:
  18137. break;
  18138. }
  18139. }
  18140. return inputs;
  18141. };
  18142. function Skin() {
  18143. this.source = "";
  18144. this.bindShapeMatrix = null;
  18145. this.invBindMatrices = [];
  18146. this.joints = [];
  18147. this.weights = [];
  18148. };
  18149. Skin.prototype.parse = function( element ) {
  18150. var sources = {};
  18151. var joints, weights;
  18152. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  18153. this.invBindMatrices = [];
  18154. this.joints = [];
  18155. this.weights = [];
  18156. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18157. var child = element.childNodes[i];
  18158. if ( child.nodeType != 1 ) continue;
  18159. switch ( child.nodeName ) {
  18160. case 'bind_shape_matrix':
  18161. var f = _floats(child.textContent);
  18162. this.bindShapeMatrix = getConvertedMat4( f );
  18163. break;
  18164. case 'source':
  18165. var src = new Source().parse(child);
  18166. sources[ src.id ] = src;
  18167. break;
  18168. case 'joints':
  18169. joints = child;
  18170. break;
  18171. case 'vertex_weights':
  18172. weights = child;
  18173. break;
  18174. default:
  18175. console.log( child.nodeName );
  18176. break;
  18177. }
  18178. }
  18179. this.parseJoints( joints, sources );
  18180. this.parseWeights( weights, sources );
  18181. return this;
  18182. };
  18183. Skin.prototype.parseJoints = function ( element, sources ) {
  18184. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18185. var child = element.childNodes[ i ];
  18186. if ( child.nodeType != 1 ) continue;
  18187. switch ( child.nodeName ) {
  18188. case 'input':
  18189. var input = ( new Input() ).parse( child );
  18190. var source = sources[ input.source ];
  18191. if ( input.semantic == 'JOINT' ) {
  18192. this.joints = source.read();
  18193. } else if ( input.semantic == 'INV_BIND_MATRIX' ) {
  18194. this.invBindMatrices = source.read();
  18195. }
  18196. break;
  18197. default:
  18198. break;
  18199. }
  18200. }
  18201. };
  18202. Skin.prototype.parseWeights = function ( element, sources ) {
  18203. var v, vcount, inputs = [];
  18204. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18205. var child = element.childNodes[ i ];
  18206. if ( child.nodeType != 1 ) continue;
  18207. switch ( child.nodeName ) {
  18208. case 'input':
  18209. inputs.push( ( new Input() ).parse( child ) );
  18210. break;
  18211. case 'v':
  18212. v = _ints( child.textContent );
  18213. break;
  18214. case 'vcount':
  18215. vcount = _ints( child.textContent );
  18216. break;
  18217. default:
  18218. break;
  18219. }
  18220. }
  18221. var index = 0;
  18222. for ( var i = 0; i < vcount.length; i ++ ) {
  18223. var numBones = vcount[i];
  18224. var vertex_weights = [];
  18225. for ( var j = 0; j < numBones; j++ ) {
  18226. var influence = {};
  18227. for ( var k = 0; k < inputs.length; k ++ ) {
  18228. var input = inputs[ k ];
  18229. var value = v[ index + input.offset ];
  18230. switch ( input.semantic ) {
  18231. case 'JOINT':
  18232. influence.joint = value;//this.joints[value];
  18233. break;
  18234. case 'WEIGHT':
  18235. influence.weight = sources[ input.source ].data[ value ];
  18236. break;
  18237. default:
  18238. break;
  18239. }
  18240. }
  18241. vertex_weights.push( influence );
  18242. index += inputs.length;
  18243. }
  18244. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  18245. vertex_weights[ j ].index = i;
  18246. }
  18247. this.weights.push( vertex_weights );
  18248. }
  18249. };
  18250. function VisualScene () {
  18251. this.id = "";
  18252. this.name = "";
  18253. this.nodes = [];
  18254. this.scene = new THREE.Object3D();
  18255. };
  18256. VisualScene.prototype.getChildById = function( id, recursive ) {
  18257. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18258. var node = this.nodes[ i ].getChildById( id, recursive );
  18259. if ( node ) {
  18260. return node;
  18261. }
  18262. }
  18263. return null;
  18264. };
  18265. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  18266. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18267. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  18268. if ( node ) {
  18269. return node;
  18270. }
  18271. }
  18272. return null;
  18273. };
  18274. VisualScene.prototype.parse = function( element ) {
  18275. this.id = element.getAttribute( 'id' );
  18276. this.name = element.getAttribute( 'name' );
  18277. this.nodes = [];
  18278. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18279. var child = element.childNodes[ i ];
  18280. if ( child.nodeType != 1 ) continue;
  18281. switch ( child.nodeName ) {
  18282. case 'node':
  18283. this.nodes.push( ( new Node() ).parse( child ) );
  18284. break;
  18285. default:
  18286. break;
  18287. }
  18288. }
  18289. return this;
  18290. };
  18291. function Node() {
  18292. this.id = "";
  18293. this.name = "";
  18294. this.sid = "";
  18295. this.nodes = [];
  18296. this.controllers = [];
  18297. this.transforms = [];
  18298. this.geometries = [];
  18299. this.channels = [];
  18300. this.matrix = new THREE.Matrix4();
  18301. };
  18302. Node.prototype.getChannelForTransform = function( transformSid ) {
  18303. for ( var i = 0; i < this.channels.length; i ++ ) {
  18304. var channel = this.channels[i];
  18305. var parts = channel.target.split('/');
  18306. var id = parts.shift();
  18307. var sid = parts.shift();
  18308. var dotSyntax = (sid.indexOf(".") >= 0);
  18309. var arrSyntax = (sid.indexOf("(") >= 0);
  18310. var arrIndices;
  18311. var member;
  18312. if ( dotSyntax ) {
  18313. parts = sid.split(".");
  18314. sid = parts.shift();
  18315. member = parts.shift();
  18316. } else if ( arrSyntax ) {
  18317. arrIndices = sid.split("(");
  18318. sid = arrIndices.shift();
  18319. for ( var j = 0; j < arrIndices.length; j ++ ) {
  18320. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  18321. }
  18322. }
  18323. if ( sid == transformSid ) {
  18324. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  18325. return channel;
  18326. }
  18327. }
  18328. return null;
  18329. };
  18330. Node.prototype.getChildById = function ( id, recursive ) {
  18331. if ( this.id == id ) {
  18332. return this;
  18333. }
  18334. if ( recursive ) {
  18335. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18336. var n = this.nodes[ i ].getChildById( id, recursive );
  18337. if ( n ) {
  18338. return n;
  18339. }
  18340. }
  18341. }
  18342. return null;
  18343. };
  18344. Node.prototype.getChildBySid = function ( sid, recursive ) {
  18345. if ( this.sid == sid ) {
  18346. return this;
  18347. }
  18348. if ( recursive ) {
  18349. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18350. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  18351. if ( n ) {
  18352. return n;
  18353. }
  18354. }
  18355. }
  18356. return null;
  18357. };
  18358. Node.prototype.getTransformBySid = function ( sid ) {
  18359. for ( var i = 0; i < this.transforms.length; i ++ ) {
  18360. if ( this.transforms[ i ].sid == sid ) return this.transforms[ i ];
  18361. }
  18362. return null;
  18363. };
  18364. Node.prototype.parse = function( element ) {
  18365. var url;
  18366. this.id = element.getAttribute('id');
  18367. this.sid = element.getAttribute('sid');
  18368. this.name = element.getAttribute('name');
  18369. this.type = element.getAttribute('type');
  18370. this.type = this.type == 'JOINT' ? this.type : 'NODE';
  18371. this.nodes = [];
  18372. this.transforms = [];
  18373. this.geometries = [];
  18374. this.cameras = [];
  18375. this.controllers = [];
  18376. this.matrix = new THREE.Matrix4();
  18377. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18378. var child = element.childNodes[ i ];
  18379. if ( child.nodeType != 1 ) continue;
  18380. switch ( child.nodeName ) {
  18381. case 'node':
  18382. this.nodes.push( ( new Node() ).parse( child ) );
  18383. break;
  18384. case 'instance_camera':
  18385. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  18386. break;
  18387. case 'instance_controller':
  18388. this.controllers.push( ( new InstanceController() ).parse( child ) );
  18389. break;
  18390. case 'instance_geometry':
  18391. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  18392. break;
  18393. case 'instance_light':
  18394. break;
  18395. case 'instance_node':
  18396. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  18397. var iNode = getLibraryNode( url );
  18398. if ( iNode ) {
  18399. this.nodes.push( ( new Node() ).parse( iNode )) ;
  18400. }
  18401. break;
  18402. case 'rotate':
  18403. case 'translate':
  18404. case 'scale':
  18405. case 'matrix':
  18406. case 'lookat':
  18407. case 'skew':
  18408. this.transforms.push( ( new Transform() ).parse( child ) );
  18409. break;
  18410. case 'extra':
  18411. break;
  18412. default:
  18413. console.log( child.nodeName );
  18414. break;
  18415. }
  18416. }
  18417. this.channels = getChannelsForNode( this );
  18418. bakeAnimations( this );
  18419. this.updateMatrix();
  18420. return this;
  18421. };
  18422. Node.prototype.updateMatrix = function () {
  18423. this.matrix.identity();
  18424. for ( var i = 0; i < this.transforms.length; i ++ ) {
  18425. this.transforms[ i ].apply( this.matrix );
  18426. }
  18427. };
  18428. function Transform () {
  18429. this.sid = "";
  18430. this.type = "";
  18431. this.data = [];
  18432. this.obj = null;
  18433. };
  18434. Transform.prototype.parse = function ( element ) {
  18435. this.sid = element.getAttribute( 'sid' );
  18436. this.type = element.nodeName;
  18437. this.data = _floats( element.textContent );
  18438. this.convert();
  18439. return this;
  18440. };
  18441. Transform.prototype.convert = function () {
  18442. switch ( this.type ) {
  18443. case 'matrix':
  18444. this.obj = getConvertedMat4( this.data );
  18445. break;
  18446. case 'rotate':
  18447. this.angle = this.data[3] * TO_RADIANS;
  18448. case 'translate':
  18449. fixCoords( this.data, -1 );
  18450. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  18451. break;
  18452. case 'scale':
  18453. fixCoords( this.data, 1 );
  18454. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  18455. break;
  18456. default:
  18457. console.log( 'Can not convert Transform of type ' + this.type );
  18458. break;
  18459. }
  18460. };
  18461. Transform.prototype.apply = function ( matrix ) {
  18462. switch ( this.type ) {
  18463. case 'matrix':
  18464. matrix.multiplySelf( this.obj );
  18465. break;
  18466. case 'translate':
  18467. matrix.translate( this.obj );
  18468. break;
  18469. case 'rotate':
  18470. matrix.rotateByAxis( this.obj, this.angle );
  18471. break;
  18472. case 'scale':
  18473. matrix.scale( this.obj );
  18474. break;
  18475. }
  18476. };
  18477. Transform.prototype.update = function ( data, member ) {
  18478. var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
  18479. switch ( this.type ) {
  18480. case 'matrix':
  18481. if ( ! member ) {
  18482. this.obj.copy( data );
  18483. } else if ( member.length === 1 ) {
  18484. switch ( member[ 0 ] ) {
  18485. case 0:
  18486. this.obj.n11 = data[ 0 ];
  18487. this.obj.n21 = data[ 1 ];
  18488. this.obj.n31 = data[ 2 ];
  18489. this.obj.n41 = data[ 3 ];
  18490. break;
  18491. case 1:
  18492. this.obj.n12 = data[ 0 ];
  18493. this.obj.n22 = data[ 1 ];
  18494. this.obj.n32 = data[ 2 ];
  18495. this.obj.n42 = data[ 3 ];
  18496. break;
  18497. case 2:
  18498. this.obj.n13 = data[ 0 ];
  18499. this.obj.n23 = data[ 1 ];
  18500. this.obj.n33 = data[ 2 ];
  18501. this.obj.n43 = data[ 3 ];
  18502. break;
  18503. case 3:
  18504. this.obj.n14 = data[ 0 ];
  18505. this.obj.n24 = data[ 1 ];
  18506. this.obj.n34 = data[ 2 ];
  18507. this.obj.n44 = data[ 3 ];
  18508. break;
  18509. }
  18510. } else if ( member.length === 2 ) {
  18511. var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
  18512. this.obj[ propName ] = data;
  18513. } else {
  18514. console.log('Incorrect addressing of matrix in transform.');
  18515. }
  18516. break;
  18517. case 'translate':
  18518. case 'scale':
  18519. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  18520. member = members[ member[ 0 ] ];
  18521. }
  18522. switch ( member ) {
  18523. case 'X':
  18524. this.obj.x = data;
  18525. break;
  18526. case 'Y':
  18527. this.obj.y = data;
  18528. break;
  18529. case 'Z':
  18530. this.obj.z = data;
  18531. break;
  18532. default:
  18533. this.obj.x = data[ 0 ];
  18534. this.obj.y = data[ 1 ];
  18535. this.obj.z = data[ 2 ];
  18536. break;
  18537. }
  18538. break;
  18539. case 'rotate':
  18540. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  18541. member = members[ member[ 0 ] ];
  18542. }
  18543. switch ( member ) {
  18544. case 'X':
  18545. this.obj.x = data;
  18546. break;
  18547. case 'Y':
  18548. this.obj.y = data;
  18549. break;
  18550. case 'Z':
  18551. this.obj.z = data;
  18552. break;
  18553. case 'ANGLE':
  18554. this.angle = data * TO_RADIANS;
  18555. break;
  18556. default:
  18557. this.obj.x = data[ 0 ];
  18558. this.obj.y = data[ 1 ];
  18559. this.obj.z = data[ 2 ];
  18560. this.angle = data[ 3 ] * TO_RADIANS;
  18561. break;
  18562. }
  18563. break;
  18564. }
  18565. };
  18566. function InstanceController() {
  18567. this.url = "";
  18568. this.skeleton = [];
  18569. this.instance_material = [];
  18570. };
  18571. InstanceController.prototype.parse = function ( element ) {
  18572. this.url = element.getAttribute('url').replace(/^#/, '');
  18573. this.skeleton = [];
  18574. this.instance_material = [];
  18575. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18576. var child = element.childNodes[i];
  18577. if (child.nodeType != 1) continue;
  18578. switch ( child.nodeName ) {
  18579. case 'skeleton':
  18580. this.skeleton.push( child.textContent.replace(/^#/, '') );
  18581. break;
  18582. case 'bind_material':
  18583. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  18584. if ( instances ) {
  18585. var instance = instances.iterateNext();
  18586. while ( instance ) {
  18587. this.instance_material.push((new InstanceMaterial()).parse(instance));
  18588. instance = instances.iterateNext();
  18589. }
  18590. }
  18591. break;
  18592. case 'extra':
  18593. break;
  18594. default:
  18595. break;
  18596. }
  18597. }
  18598. return this;
  18599. };
  18600. function InstanceMaterial () {
  18601. this.symbol = "";
  18602. this.target = "";
  18603. };
  18604. InstanceMaterial.prototype.parse = function ( element ) {
  18605. this.symbol = element.getAttribute('symbol');
  18606. this.target = element.getAttribute('target').replace(/^#/, '');
  18607. return this;
  18608. };
  18609. function InstanceGeometry() {
  18610. this.url = "";
  18611. this.instance_material = [];
  18612. };
  18613. InstanceGeometry.prototype.parse = function ( element ) {
  18614. this.url = element.getAttribute('url').replace(/^#/, '');
  18615. this.instance_material = [];
  18616. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18617. var child = element.childNodes[i];
  18618. if ( child.nodeType != 1 ) continue;
  18619. if ( child.nodeName == 'bind_material' ) {
  18620. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  18621. if ( instances ) {
  18622. var instance = instances.iterateNext();
  18623. while ( instance ) {
  18624. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  18625. instance = instances.iterateNext();
  18626. }
  18627. }
  18628. break;
  18629. }
  18630. }
  18631. return this;
  18632. };
  18633. function Geometry() {
  18634. this.id = "";
  18635. this.mesh = null;
  18636. };
  18637. Geometry.prototype.parse = function ( element ) {
  18638. this.id = element.getAttribute('id');
  18639. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18640. var child = element.childNodes[i];
  18641. switch ( child.nodeName ) {
  18642. case 'mesh':
  18643. this.mesh = (new Mesh(this)).parse(child);
  18644. break;
  18645. case 'extra':
  18646. // console.log( child );
  18647. break;
  18648. default:
  18649. break;
  18650. }
  18651. }
  18652. return this;
  18653. };
  18654. function Mesh( geometry ) {
  18655. this.geometry = geometry.id;
  18656. this.primitives = [];
  18657. this.vertices = null;
  18658. this.geometry3js = null;
  18659. };
  18660. Mesh.prototype.parse = function( element ) {
  18661. this.primitives = [];
  18662. var i, j;
  18663. for ( i = 0; i < element.childNodes.length; i ++ ) {
  18664. var child = element.childNodes[ i ];
  18665. switch ( child.nodeName ) {
  18666. case 'source':
  18667. _source( child );
  18668. break;
  18669. case 'vertices':
  18670. this.vertices = ( new Vertices() ).parse( child );
  18671. break;
  18672. case 'triangles':
  18673. this.primitives.push( ( new Triangles().parse( child ) ) );
  18674. break;
  18675. case 'polygons':
  18676. this.primitives.push( ( new Polygons().parse( child ) ) );
  18677. break;
  18678. case 'polylist':
  18679. this.primitives.push( ( new Polylist().parse( child ) ) );
  18680. break;
  18681. default:
  18682. break;
  18683. }
  18684. }
  18685. this.geometry3js = new THREE.Geometry();
  18686. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  18687. for ( i = 0; i < vertexData.length; i += 3 ) {
  18688. var v = new THREE.Vertex().copy( getConvertedVec3( vertexData, i ) );
  18689. this.geometry3js.vertices.push( v );
  18690. }
  18691. for ( i = 0; i < this.primitives.length; i ++ ) {
  18692. var primitive = this.primitives[ i ];
  18693. primitive.setVertices( this.vertices );
  18694. this.handlePrimitive( primitive, this.geometry3js );
  18695. }
  18696. this.geometry3js.computeCentroids();
  18697. this.geometry3js.computeFaceNormals();
  18698. if ( this.geometry3js.calcNormals ) {
  18699. this.geometry3js.computeVertexNormals();
  18700. delete this.geometry3js.calcNormals;
  18701. }
  18702. this.geometry3js.computeBoundingBox();
  18703. return this;
  18704. };
  18705. Mesh.prototype.handlePrimitive = function( primitive, geom ) {
  18706. var j, k, pList = primitive.p, inputs = primitive.inputs;
  18707. var input, index, idx32;
  18708. var source, numParams;
  18709. var vcIndex = 0, vcount = 3, maxOffset = 0;
  18710. var texture_sets = [];
  18711. for ( j = 0; j < inputs.length; j ++ ) {
  18712. input = inputs[ j ];
  18713. var offset = input.offset + 1;
  18714. maxOffset = (maxOffset < offset)? offset : maxOffset;
  18715. switch ( input.semantic ) {
  18716. case 'TEXCOORD':
  18717. texture_sets.push( input.set );
  18718. break;
  18719. }
  18720. }
  18721. for ( var pCount = 0; pCount < pList.length; ++pCount ) {
  18722. var p = pList[pCount], i = 0;
  18723. while ( i < p.length ) {
  18724. var vs = [];
  18725. var ns = [];
  18726. var ts = {};
  18727. var cs = [];
  18728. if ( primitive.vcount ) {
  18729. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  18730. } else {
  18731. vcount = p.length / maxOffset;
  18732. }
  18733. for ( j = 0; j < vcount; j ++ ) {
  18734. for ( k = 0; k < inputs.length; k ++ ) {
  18735. input = inputs[ k ];
  18736. source = sources[ input.source ];
  18737. index = p[ i + ( j * maxOffset ) + input.offset ];
  18738. numParams = source.accessor.params.length;
  18739. idx32 = index * numParams;
  18740. switch ( input.semantic ) {
  18741. case 'VERTEX':
  18742. vs.push( index );
  18743. break;
  18744. case 'NORMAL':
  18745. ns.push( getConvertedVec3( source.data, idx32 ) );
  18746. break;
  18747. case 'TEXCOORD':
  18748. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  18749. // invert the V
  18750. ts[ input.set ].push( new THREE.UV( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  18751. break;
  18752. case 'COLOR':
  18753. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  18754. break;
  18755. default:
  18756. break;
  18757. }
  18758. }
  18759. }
  18760. var face = null, faces = [], uv, uvArr;
  18761. if ( ns.length == 0 ) {
  18762. // check the vertices source
  18763. input = this.vertices.input.NORMAL;
  18764. if ( input ) {
  18765. source = sources[ input.source ];
  18766. numParams = source.accessor.params.length;
  18767. for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
  18768. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  18769. }
  18770. }
  18771. else {
  18772. geom.calcNormals = true;
  18773. }
  18774. }
  18775. if ( vcount === 3 ) {
  18776. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  18777. } else if ( vcount === 4 ) {
  18778. faces.push( new THREE.Face4( vs[0], vs[1], vs[2], vs[3], ns, cs.length ? cs : new THREE.Color() ) );
  18779. } else if ( vcount > 4 && options.subdivideFaces ) {
  18780. var clr = cs.length ? cs : new THREE.Color(),
  18781. vec1, vec2, vec3, v1, v2, norm;
  18782. // subdivide into multiple Face3s
  18783. for ( k = 1; k < vcount-1; ) {
  18784. // FIXME: normals don't seem to be quite right
  18785. faces.push( new THREE.Face3( vs[0], vs[k], vs[k+1], [ ns[0], ns[k++], ns[k] ], clr ) );
  18786. }
  18787. }
  18788. if ( faces.length ) {
  18789. for (var ndx = 0, len = faces.length; ndx < len; ndx++) {
  18790. face = faces[ndx];
  18791. face.daeMaterial = primitive.material;
  18792. geom.faces.push( face );
  18793. for ( k = 0; k < texture_sets.length; k++ ) {
  18794. uv = ts[ texture_sets[k] ];
  18795. if ( vcount > 4 ) {
  18796. // Grab the right UVs for the vertices in this face
  18797. uvArr = [ uv[0], uv[ndx+1], uv[ndx+2] ];
  18798. } else if ( vcount === 4 ) {
  18799. uvArr = [ uv[0], uv[1], uv[2], uv[3] ];
  18800. } else {
  18801. uvArr = [ uv[0], uv[1], uv[2] ];
  18802. }
  18803. if ( !geom.faceVertexUvs[k] ) {
  18804. geom.faceVertexUvs[k] = [];
  18805. }
  18806. geom.faceVertexUvs[k].push( uvArr );
  18807. }
  18808. }
  18809. } else {
  18810. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  18811. }
  18812. i += maxOffset * vcount;
  18813. }
  18814. }
  18815. };
  18816. function Polygons () {
  18817. this.material = "";
  18818. this.count = 0;
  18819. this.inputs = [];
  18820. this.vcount = null;
  18821. this.p = [];
  18822. this.geometry = new THREE.Geometry();
  18823. };
  18824. Polygons.prototype.setVertices = function ( vertices ) {
  18825. for ( var i = 0; i < this.inputs.length; i ++ ) {
  18826. if ( this.inputs[ i ].source == vertices.id ) {
  18827. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  18828. }
  18829. }
  18830. };
  18831. Polygons.prototype.parse = function ( element ) {
  18832. this.material = element.getAttribute( 'material' );
  18833. this.count = _attr_as_int( element, 'count', 0 );
  18834. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18835. var child = element.childNodes[ i ];
  18836. switch ( child.nodeName ) {
  18837. case 'input':
  18838. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  18839. break;
  18840. case 'vcount':
  18841. this.vcount = _ints( child.textContent );
  18842. break;
  18843. case 'p':
  18844. this.p.push( _ints( child.textContent ) );
  18845. break;
  18846. case 'ph':
  18847. console.warn( 'polygon holes not yet supported!' );
  18848. break;
  18849. default:
  18850. break;
  18851. }
  18852. }
  18853. return this;
  18854. };
  18855. function Polylist () {
  18856. Polygons.call( this );
  18857. this.vcount = [];
  18858. };
  18859. Polylist.prototype = new Polygons();
  18860. Polylist.prototype.constructor = Polylist;
  18861. function Triangles () {
  18862. Polygons.call( this );
  18863. this.vcount = 3;
  18864. };
  18865. Triangles.prototype = new Polygons();
  18866. Triangles.prototype.constructor = Triangles;
  18867. function Accessor() {
  18868. this.source = "";
  18869. this.count = 0;
  18870. this.stride = 0;
  18871. this.params = [];
  18872. };
  18873. Accessor.prototype.parse = function ( element ) {
  18874. this.params = [];
  18875. this.source = element.getAttribute( 'source' );
  18876. this.count = _attr_as_int( element, 'count', 0 );
  18877. this.stride = _attr_as_int( element, 'stride', 0 );
  18878. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18879. var child = element.childNodes[ i ];
  18880. if ( child.nodeName == 'param' ) {
  18881. var param = {};
  18882. param[ 'name' ] = child.getAttribute( 'name' );
  18883. param[ 'type' ] = child.getAttribute( 'type' );
  18884. this.params.push( param );
  18885. }
  18886. }
  18887. return this;
  18888. };
  18889. function Vertices() {
  18890. this.input = {};
  18891. };
  18892. Vertices.prototype.parse = function ( element ) {
  18893. this.id = element.getAttribute('id');
  18894. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18895. if ( element.childNodes[i].nodeName == 'input' ) {
  18896. var input = ( new Input() ).parse( element.childNodes[ i ] );
  18897. this.input[ input.semantic ] = input;
  18898. }
  18899. }
  18900. return this;
  18901. };
  18902. function Input () {
  18903. this.semantic = "";
  18904. this.offset = 0;
  18905. this.source = "";
  18906. this.set = 0;
  18907. };
  18908. Input.prototype.parse = function ( element ) {
  18909. this.semantic = element.getAttribute('semantic');
  18910. this.source = element.getAttribute('source').replace(/^#/, '');
  18911. this.set = _attr_as_int(element, 'set', -1);
  18912. this.offset = _attr_as_int(element, 'offset', 0);
  18913. if ( this.semantic == 'TEXCOORD' && this.set < 0 ) {
  18914. this.set = 0;
  18915. }
  18916. return this;
  18917. };
  18918. function Source ( id ) {
  18919. this.id = id;
  18920. this.type = null;
  18921. };
  18922. Source.prototype.parse = function ( element ) {
  18923. this.id = element.getAttribute( 'id' );
  18924. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18925. var child = element.childNodes[i];
  18926. switch ( child.nodeName ) {
  18927. case 'bool_array':
  18928. this.data = _bools( child.textContent );
  18929. this.type = child.nodeName;
  18930. break;
  18931. case 'float_array':
  18932. this.data = _floats( child.textContent );
  18933. this.type = child.nodeName;
  18934. break;
  18935. case 'int_array':
  18936. this.data = _ints( child.textContent );
  18937. this.type = child.nodeName;
  18938. break;
  18939. case 'IDREF_array':
  18940. case 'Name_array':
  18941. this.data = _strings( child.textContent );
  18942. this.type = child.nodeName;
  18943. break;
  18944. case 'technique_common':
  18945. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  18946. if ( child.childNodes[ j ].nodeName == 'accessor' ) {
  18947. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  18948. break;
  18949. }
  18950. }
  18951. break;
  18952. default:
  18953. // console.log(child.nodeName);
  18954. break;
  18955. }
  18956. }
  18957. return this;
  18958. };
  18959. Source.prototype.read = function () {
  18960. var result = [];
  18961. //for (var i = 0; i < this.accessor.params.length; i++) {
  18962. var param = this.accessor.params[ 0 ];
  18963. //console.log(param.name + " " + param.type);
  18964. switch ( param.type ) {
  18965. case 'IDREF':
  18966. case 'Name': case 'name':
  18967. case 'float':
  18968. return this.data;
  18969. case 'float4x4':
  18970. for ( var j = 0; j < this.data.length; j += 16 ) {
  18971. var s = this.data.slice( j, j + 16 );
  18972. var m = getConvertedMat4( s );
  18973. result.push( m );
  18974. }
  18975. break;
  18976. default:
  18977. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  18978. break;
  18979. }
  18980. //}
  18981. return result;
  18982. };
  18983. function Material () {
  18984. this.id = "";
  18985. this.name = "";
  18986. this.instance_effect = null;
  18987. };
  18988. Material.prototype.parse = function ( element ) {
  18989. this.id = element.getAttribute( 'id' );
  18990. this.name = element.getAttribute( 'name' );
  18991. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18992. if ( element.childNodes[ i ].nodeName == 'instance_effect' ) {
  18993. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  18994. break;
  18995. }
  18996. }
  18997. return this;
  18998. };
  18999. function ColorOrTexture () {
  19000. this.color = new THREE.Color( 0 );
  19001. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  19002. this.color.a = 1.0;
  19003. this.texture = null;
  19004. this.texcoord = null;
  19005. this.texOpts = null;
  19006. };
  19007. ColorOrTexture.prototype.isColor = function () {
  19008. return ( this.texture == null );
  19009. };
  19010. ColorOrTexture.prototype.isTexture = function () {
  19011. return ( this.texture != null );
  19012. };
  19013. ColorOrTexture.prototype.parse = function ( element ) {
  19014. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19015. var child = element.childNodes[ i ];
  19016. if ( child.nodeType != 1 ) continue;
  19017. switch ( child.nodeName ) {
  19018. case 'color':
  19019. var rgba = _floats( child.textContent );
  19020. this.color = new THREE.Color(0);
  19021. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  19022. this.color.a = rgba[3];
  19023. break;
  19024. case 'texture':
  19025. this.texture = child.getAttribute('texture');
  19026. this.texcoord = child.getAttribute('texcoord');
  19027. // Defaults from:
  19028. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  19029. this.texOpts = {
  19030. offsetU: 0,
  19031. offsetV: 0,
  19032. repeatU: 1,
  19033. repeatV: 1,
  19034. wrapU: 1,
  19035. wrapV: 1,
  19036. };
  19037. this.parseTexture( child );
  19038. break;
  19039. default:
  19040. break;
  19041. }
  19042. }
  19043. return this;
  19044. };
  19045. ColorOrTexture.prototype.parseTexture = function ( element ) {
  19046. if ( ! element.childNodes ) return this;
  19047. // This should be supported by Maya, 3dsMax, and MotionBuilder
  19048. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  19049. element = element.childNodes[1];
  19050. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  19051. element = element.childNodes[1];
  19052. }
  19053. }
  19054. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19055. var child = element.childNodes[ i ];
  19056. switch ( child.nodeName ) {
  19057. case 'offsetU':
  19058. case 'offsetV':
  19059. case 'repeatU':
  19060. case 'repeatV':
  19061. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  19062. break;
  19063. case 'wrapU':
  19064. case 'wrapV':
  19065. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  19066. break;
  19067. default:
  19068. this.texOpts[ child.nodeName ] = child.textContent;
  19069. break;
  19070. }
  19071. }
  19072. return this;
  19073. };
  19074. function Shader ( type, effect ) {
  19075. this.type = type;
  19076. this.effect = effect;
  19077. this.material = null;
  19078. };
  19079. Shader.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 'ambient':
  19085. case 'emission':
  19086. case 'diffuse':
  19087. case 'specular':
  19088. case 'transparent':
  19089. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  19090. break;
  19091. case 'shininess':
  19092. case 'reflectivity':
  19093. case 'transparency':
  19094. var f = evaluateXPath( child, './/dae:float' );
  19095. if ( f.length > 0 )
  19096. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  19097. break;
  19098. default:
  19099. break;
  19100. }
  19101. }
  19102. this.create();
  19103. return this;
  19104. };
  19105. Shader.prototype.create = function() {
  19106. var props = {};
  19107. var transparent = ( this['transparency'] !== undefined && this['transparency'] < 1.0 );
  19108. for ( var prop in this ) {
  19109. switch ( prop ) {
  19110. case 'ambient':
  19111. case 'emission':
  19112. case 'diffuse':
  19113. case 'specular':
  19114. var cot = this[prop];
  19115. if ( cot instanceof ColorOrTexture ) {
  19116. if ( cot.isTexture() ) {
  19117. if ( this.effect.sampler && this.effect.surface ) {
  19118. if ( this.effect.sampler.source == this.effect.surface.sid ) {
  19119. var image = images[this.effect.surface.init_from];
  19120. if ( image ) {
  19121. var texture = THREE.ImageUtils.loadTexture(baseUrl + image.init_from);
  19122. texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  19123. texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  19124. texture.offset.x = cot.texOpts.offsetU;
  19125. texture.offset.y = cot.texOpts.offsetV;
  19126. texture.repeat.x = cot.texOpts.repeatU;
  19127. texture.repeat.y = cot.texOpts.repeatV;
  19128. props['map'] = texture;
  19129. // Texture with baked lighting?
  19130. if ( prop == 'emission' ) props[ 'emissive' ] = 0xffffff;
  19131. }
  19132. }
  19133. }
  19134. } else if ( prop == 'diffuse' || !transparent ) {
  19135. if ( prop == 'emission' ) {
  19136. props[ 'emissive' ] = cot.color.getHex();
  19137. } else {
  19138. props[ prop ] = cot.color.getHex();
  19139. }
  19140. }
  19141. }
  19142. break;
  19143. case 'shininess':
  19144. case 'reflectivity':
  19145. props[ prop ] = this[ prop ];
  19146. break;
  19147. case 'transparency':
  19148. if ( transparent ) {
  19149. props[ 'transparent' ] = true;
  19150. props[ 'opacity' ] = this[ prop ];
  19151. transparent = true;
  19152. }
  19153. break;
  19154. default:
  19155. break;
  19156. }
  19157. }
  19158. props[ 'shading' ] = preferredShading;
  19159. switch ( this.type ) {
  19160. case 'constant':
  19161. props.color = props.emission;
  19162. this.material = new THREE.MeshBasicMaterial( props );
  19163. break;
  19164. case 'phong':
  19165. case 'blinn':
  19166. props.color = props.diffuse;
  19167. this.material = new THREE.MeshPhongMaterial( props );
  19168. break;
  19169. case 'lambert':
  19170. default:
  19171. props.color = props.diffuse;
  19172. this.material = new THREE.MeshLambertMaterial( props );
  19173. break;
  19174. }
  19175. return this.material;
  19176. };
  19177. function Surface ( effect ) {
  19178. this.effect = effect;
  19179. this.init_from = null;
  19180. this.format = null;
  19181. };
  19182. Surface.prototype.parse = function ( element ) {
  19183. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19184. var child = element.childNodes[ i ];
  19185. if ( child.nodeType != 1 ) continue;
  19186. switch ( child.nodeName ) {
  19187. case 'init_from':
  19188. this.init_from = child.textContent;
  19189. break;
  19190. case 'format':
  19191. this.format = child.textContent;
  19192. break;
  19193. default:
  19194. console.log( "unhandled Surface prop: " + child.nodeName );
  19195. break;
  19196. }
  19197. }
  19198. return this;
  19199. };
  19200. function Sampler2D ( effect ) {
  19201. this.effect = effect;
  19202. this.source = null;
  19203. this.wrap_s = null;
  19204. this.wrap_t = null;
  19205. this.minfilter = null;
  19206. this.magfilter = null;
  19207. this.mipfilter = null;
  19208. };
  19209. Sampler2D.prototype.parse = function ( element ) {
  19210. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19211. var child = element.childNodes[ i ];
  19212. if ( child.nodeType != 1 ) continue;
  19213. switch ( child.nodeName ) {
  19214. case 'source':
  19215. this.source = child.textContent;
  19216. break;
  19217. case 'minfilter':
  19218. this.minfilter = child.textContent;
  19219. break;
  19220. case 'magfilter':
  19221. this.magfilter = child.textContent;
  19222. break;
  19223. case 'mipfilter':
  19224. this.mipfilter = child.textContent;
  19225. break;
  19226. case 'wrap_s':
  19227. this.wrap_s = child.textContent;
  19228. break;
  19229. case 'wrap_t':
  19230. this.wrap_t = child.textContent;
  19231. break;
  19232. default:
  19233. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  19234. break;
  19235. }
  19236. }
  19237. return this;
  19238. };
  19239. function Effect () {
  19240. this.id = "";
  19241. this.name = "";
  19242. this.shader = null;
  19243. this.surface = null;
  19244. this.sampler = null;
  19245. };
  19246. Effect.prototype.create = function () {
  19247. if ( this.shader == null ) {
  19248. return null;
  19249. }
  19250. };
  19251. Effect.prototype.parse = function ( element ) {
  19252. this.id = element.getAttribute( 'id' );
  19253. this.name = element.getAttribute( 'name' );
  19254. this.shader = null;
  19255. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19256. var child = element.childNodes[ i ];
  19257. if ( child.nodeType != 1 ) continue;
  19258. switch ( child.nodeName ) {
  19259. case 'profile_COMMON':
  19260. this.parseTechnique( this.parseProfileCOMMON( child ) );
  19261. break;
  19262. default:
  19263. break;
  19264. }
  19265. }
  19266. return this;
  19267. };
  19268. Effect.prototype.parseNewparam = function ( element ) {
  19269. var sid = element.getAttribute( 'sid' );
  19270. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19271. var child = element.childNodes[ i ];
  19272. if ( child.nodeType != 1 ) continue;
  19273. switch ( child.nodeName ) {
  19274. case 'surface':
  19275. this.surface = ( new Surface( this ) ).parse( child );
  19276. this.surface.sid = sid;
  19277. break;
  19278. case 'sampler2D':
  19279. this.sampler = ( new Sampler2D( this ) ).parse( child );
  19280. this.sampler.sid = sid;
  19281. break;
  19282. case 'extra':
  19283. break;
  19284. default:
  19285. console.log( child.nodeName );
  19286. break;
  19287. }
  19288. }
  19289. };
  19290. Effect.prototype.parseProfileCOMMON = function ( element ) {
  19291. var technique;
  19292. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19293. var child = element.childNodes[ i ];
  19294. if ( child.nodeType != 1 ) continue;
  19295. switch ( child.nodeName ) {
  19296. case 'profile_COMMON':
  19297. this.parseProfileCOMMON( child );
  19298. break;
  19299. case 'technique':
  19300. technique = child;
  19301. break;
  19302. case 'newparam':
  19303. this.parseNewparam( child );
  19304. break;
  19305. case 'image':
  19306. var _image = ( new _Image() ).parse( child );
  19307. images[ _image.id ] = _image;
  19308. break;
  19309. case 'extra':
  19310. break;
  19311. default:
  19312. console.log( child.nodeName );
  19313. break;
  19314. }
  19315. }
  19316. return technique;
  19317. };
  19318. Effect.prototype.parseTechnique= function ( element ) {
  19319. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19320. var child = element.childNodes[i];
  19321. if ( child.nodeType != 1 ) continue;
  19322. switch ( child.nodeName ) {
  19323. case 'constant':
  19324. case 'lambert':
  19325. case 'blinn':
  19326. case 'phong':
  19327. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  19328. break;
  19329. default:
  19330. break;
  19331. }
  19332. }
  19333. };
  19334. function InstanceEffect () {
  19335. this.url = "";
  19336. };
  19337. InstanceEffect.prototype.parse = function ( element ) {
  19338. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  19339. return this;
  19340. };
  19341. function Animation() {
  19342. this.id = "";
  19343. this.name = "";
  19344. this.source = {};
  19345. this.sampler = [];
  19346. this.channel = [];
  19347. };
  19348. Animation.prototype.parse = function ( element ) {
  19349. this.id = element.getAttribute( 'id' );
  19350. this.name = element.getAttribute( 'name' );
  19351. this.source = {};
  19352. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19353. var child = element.childNodes[ i ];
  19354. if ( child.nodeType != 1 ) continue;
  19355. switch ( child.nodeName ) {
  19356. case 'animation':
  19357. var anim = ( new Animation() ).parse( child );
  19358. for ( var src in anim.source ) {
  19359. this.source[ src ] = anim.source[ src ];
  19360. }
  19361. for ( var j = 0; j < anim.channel.length; j ++ ) {
  19362. this.channel.push( anim.channel[ j ] );
  19363. this.sampler.push( anim.sampler[ j ] );
  19364. }
  19365. break;
  19366. case 'source':
  19367. var src = ( new Source() ).parse( child );
  19368. this.source[ src.id ] = src;
  19369. break;
  19370. case 'sampler':
  19371. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  19372. break;
  19373. case 'channel':
  19374. this.channel.push( ( new Channel( this ) ).parse( child ) );
  19375. break;
  19376. default:
  19377. break;
  19378. }
  19379. }
  19380. return this;
  19381. };
  19382. function Channel( animation ) {
  19383. this.animation = animation;
  19384. this.source = "";
  19385. this.target = "";
  19386. this.fullSid = null;
  19387. this.sid = null;
  19388. this.dotSyntax = null;
  19389. this.arrSyntax = null;
  19390. this.arrIndices = null;
  19391. this.member = null;
  19392. };
  19393. Channel.prototype.parse = function ( element ) {
  19394. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  19395. this.target = element.getAttribute( 'target' );
  19396. var parts = this.target.split( '/' );
  19397. var id = parts.shift();
  19398. var sid = parts.shift();
  19399. var dotSyntax = ( sid.indexOf(".") >= 0 );
  19400. var arrSyntax = ( sid.indexOf("(") >= 0 );
  19401. if ( dotSyntax ) {
  19402. parts = sid.split(".");
  19403. this.sid = parts.shift();
  19404. this.member = parts.shift();
  19405. } else if ( arrSyntax ) {
  19406. var arrIndices = sid.split("(");
  19407. this.sid = arrIndices.shift();
  19408. for (var j = 0; j < arrIndices.length; j ++ ) {
  19409. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  19410. }
  19411. this.arrIndices = arrIndices;
  19412. } else {
  19413. this.sid = sid;
  19414. }
  19415. this.fullSid = sid;
  19416. this.dotSyntax = dotSyntax;
  19417. this.arrSyntax = arrSyntax;
  19418. return this;
  19419. };
  19420. function Sampler ( animation ) {
  19421. this.id = "";
  19422. this.animation = animation;
  19423. this.inputs = [];
  19424. this.input = null;
  19425. this.output = null;
  19426. this.strideOut = null;
  19427. this.interpolation = null;
  19428. this.startTime = null;
  19429. this.endTime = null;
  19430. this.duration = 0;
  19431. };
  19432. Sampler.prototype.parse = function ( element ) {
  19433. this.id = element.getAttribute( 'id' );
  19434. this.inputs = [];
  19435. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19436. var child = element.childNodes[ i ];
  19437. if ( child.nodeType != 1 ) continue;
  19438. switch ( child.nodeName ) {
  19439. case 'input':
  19440. this.inputs.push( (new Input()).parse( child ) );
  19441. break;
  19442. default:
  19443. break;
  19444. }
  19445. }
  19446. return this;
  19447. };
  19448. Sampler.prototype.create = function () {
  19449. for ( var i = 0; i < this.inputs.length; i ++ ) {
  19450. var input = this.inputs[ i ];
  19451. var source = this.animation.source[ input.source ];
  19452. switch ( input.semantic ) {
  19453. case 'INPUT':
  19454. this.input = source.read();
  19455. break;
  19456. case 'OUTPUT':
  19457. this.output = source.read();
  19458. this.strideOut = source.accessor.stride;
  19459. break;
  19460. case 'INTERPOLATION':
  19461. this.interpolation = source.read();
  19462. break;
  19463. case 'IN_TANGENT':
  19464. break;
  19465. case 'OUT_TANGENT':
  19466. break;
  19467. default:
  19468. console.log(input.semantic);
  19469. break;
  19470. }
  19471. }
  19472. this.startTime = 0;
  19473. this.endTime = 0;
  19474. this.duration = 0;
  19475. if ( this.input.length ) {
  19476. this.startTime = 100000000;
  19477. this.endTime = -100000000;
  19478. for ( var i = 0; i < this.input.length; i ++ ) {
  19479. this.startTime = Math.min( this.startTime, this.input[ i ] );
  19480. this.endTime = Math.max( this.endTime, this.input[ i ] );
  19481. }
  19482. this.duration = this.endTime - this.startTime;
  19483. }
  19484. };
  19485. Sampler.prototype.getData = function ( type, ndx ) {
  19486. var data;
  19487. if ( type === 'matrix' && this.strideOut === 16 ) {
  19488. data = this.output[ ndx ];
  19489. } else if ( this.strideOut > 1 ) {
  19490. data = [];
  19491. ndx *= this.strideOut;
  19492. for ( var i = 0; i < this.strideOut; ++i ) {
  19493. data[ i ] = this.output[ ndx + i ];
  19494. }
  19495. if ( this.strideOut === 3 ) {
  19496. switch ( type ) {
  19497. case 'rotate':
  19498. case 'translate':
  19499. fixCoords( data, -1 );
  19500. break;
  19501. case 'scale':
  19502. fixCoords( data, 1 );
  19503. break;
  19504. }
  19505. } else if ( this.strideOut === 4 && type === 'matrix' ) {
  19506. fixCoords( data, -1 );
  19507. }
  19508. } else {
  19509. data = this.output[ ndx ];
  19510. }
  19511. return data;
  19512. };
  19513. function Key ( time ) {
  19514. this.targets = [];
  19515. this.time = time;
  19516. };
  19517. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  19518. this.targets.push( {
  19519. sid: fullSid,
  19520. member: member,
  19521. transform: transform,
  19522. data: data
  19523. } );
  19524. };
  19525. Key.prototype.apply = function ( opt_sid ) {
  19526. for ( var i = 0; i < this.targets.length; ++i ) {
  19527. var target = this.targets[ i ];
  19528. if ( !opt_sid || target.sid === opt_sid ) {
  19529. target.transform.update( target.data, target.member );
  19530. }
  19531. }
  19532. };
  19533. Key.prototype.getTarget = function ( fullSid ) {
  19534. for ( var i = 0; i < this.targets.length; ++i ) {
  19535. if ( this.targets[ i ].sid === fullSid ) {
  19536. return this.targets[ i ];
  19537. }
  19538. }
  19539. return null;
  19540. };
  19541. Key.prototype.hasTarget = function ( fullSid ) {
  19542. for ( var i = 0; i < this.targets.length; ++i ) {
  19543. if ( this.targets[ i ].sid === fullSid ) {
  19544. return true;
  19545. }
  19546. }
  19547. return false;
  19548. };
  19549. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  19550. Key.prototype.interpolate = function ( nextKey, time ) {
  19551. for ( var i = 0; i < this.targets.length; ++i ) {
  19552. var target = this.targets[ i ],
  19553. nextTarget = nextKey.getTarget( target.sid ),
  19554. data;
  19555. if ( target.transform.type !== 'matrix' && nextTarget ) {
  19556. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  19557. nextData = nextTarget.data,
  19558. prevData = target.data;
  19559. // check scale error
  19560. if ( scale < 0 || scale > 1 ) {
  19561. console.log( "Key.interpolate: Warning! Scale out of bounds:" + scale );
  19562. scale = scale < 0 ? 0 : 1;
  19563. }
  19564. if ( prevData.length ) {
  19565. data = [];
  19566. for ( var j = 0; j < prevData.length; ++j ) {
  19567. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  19568. }
  19569. } else {
  19570. data = prevData + ( nextData - prevData ) * scale;
  19571. }
  19572. } else {
  19573. data = target.data;
  19574. }
  19575. target.transform.update( data, target.member );
  19576. }
  19577. };
  19578. function Camera() {
  19579. this.id = "";
  19580. this.name = "";
  19581. this.technique = "";
  19582. };
  19583. Camera.prototype.parse = function ( element ) {
  19584. this.id = element.getAttribute( 'id' );
  19585. this.name = element.getAttribute( 'name' );
  19586. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19587. var child = element.childNodes[ i ];
  19588. if ( child.nodeType != 1 ) continue;
  19589. switch ( child.nodeName ) {
  19590. case 'optics':
  19591. this.parseOptics( child );
  19592. break;
  19593. default:
  19594. break;
  19595. }
  19596. }
  19597. return this;
  19598. };
  19599. Camera.prototype.parseOptics = function ( element ) {
  19600. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19601. if ( element.childNodes[ i ].nodeName == 'technique_common' ) {
  19602. var technique = element.childNodes[ i ];
  19603. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  19604. this.technique = technique.childNodes[ j ].nodeName;
  19605. if ( this.technique == 'perspective' ) {
  19606. var perspective = technique.childNodes[ j ];
  19607. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  19608. var param = perspective.childNodes[ k ];
  19609. switch ( param.nodeName ) {
  19610. case 'yfov':
  19611. this.yfov = param.textContent;
  19612. break;
  19613. case 'xfov':
  19614. this.xfov = param.textContent;
  19615. break;
  19616. case 'znear':
  19617. this.znear = param.textContent;
  19618. break;
  19619. case 'zfar':
  19620. this.zfar = param.textContent;
  19621. break;
  19622. case 'aspect_ratio':
  19623. this.aspect_ratio = param.textContent;
  19624. break;
  19625. }
  19626. }
  19627. } else if ( this.technique == 'orthographic' ) {
  19628. var orthographic = technique.childNodes[ j ];
  19629. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  19630. var param = orthographic.childNodes[ k ];
  19631. switch ( param.nodeName ) {
  19632. case 'xmag':
  19633. this.xmag = param.textContent;
  19634. break;
  19635. case 'ymag':
  19636. this.ymag = param.textContent;
  19637. break;
  19638. case 'znear':
  19639. this.znear = param.textContent;
  19640. break;
  19641. case 'zfar':
  19642. this.zfar = param.textContent;
  19643. break;
  19644. case 'aspect_ratio':
  19645. this.aspect_ratio = param.textContent;
  19646. break;
  19647. }
  19648. }
  19649. }
  19650. }
  19651. }
  19652. }
  19653. return this;
  19654. };
  19655. function InstanceCamera() {
  19656. this.url = "";
  19657. };
  19658. InstanceCamera.prototype.parse = function ( element ) {
  19659. this.url = element.getAttribute('url').replace(/^#/, '');
  19660. return this;
  19661. };
  19662. function _source( element ) {
  19663. var id = element.getAttribute( 'id' );
  19664. if ( sources[ id ] != undefined ) {
  19665. return sources[ id ];
  19666. }
  19667. sources[ id ] = ( new Source(id )).parse( element );
  19668. return sources[ id ];
  19669. };
  19670. function _nsResolver( nsPrefix ) {
  19671. if ( nsPrefix == "dae" ) {
  19672. return "http://www.collada.org/2005/11/COLLADASchema";
  19673. }
  19674. return null;
  19675. };
  19676. function _bools( str ) {
  19677. var raw = _strings( str );
  19678. var data = [];
  19679. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  19680. data.push( (raw[i] == 'true' || raw[i] == '1') ? true : false );
  19681. }
  19682. return data;
  19683. };
  19684. function _floats( str ) {
  19685. var raw = _strings(str);
  19686. var data = [];
  19687. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  19688. data.push( parseFloat( raw[ i ] ) );
  19689. }
  19690. return data;
  19691. };
  19692. function _ints( str ) {
  19693. var raw = _strings( str );
  19694. var data = [];
  19695. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  19696. data.push( parseInt( raw[ i ], 10 ) );
  19697. }
  19698. return data;
  19699. };
  19700. function _strings( str ) {
  19701. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  19702. };
  19703. function _trimString( str ) {
  19704. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  19705. };
  19706. function _attr_as_float( element, name, defaultValue ) {
  19707. if ( element.hasAttribute( name ) ) {
  19708. return parseFloat( element.getAttribute( name ) );
  19709. } else {
  19710. return defaultValue;
  19711. }
  19712. };
  19713. function _attr_as_int( element, name, defaultValue ) {
  19714. if ( element.hasAttribute( name ) ) {
  19715. return parseInt( element.getAttribute( name ), 10) ;
  19716. } else {
  19717. return defaultValue;
  19718. }
  19719. };
  19720. function _attr_as_string( element, name, defaultValue ) {
  19721. if ( element.hasAttribute( name ) ) {
  19722. return element.getAttribute( name );
  19723. } else {
  19724. return defaultValue;
  19725. }
  19726. };
  19727. function _format_float( f, num ) {
  19728. if ( f === undefined ) {
  19729. var s = '0.';
  19730. while ( s.length < num + 2 ) {
  19731. s += '0';
  19732. }
  19733. return s;
  19734. }
  19735. num = num || 2;
  19736. var parts = f.toString().split( '.' );
  19737. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  19738. while( parts[ 1 ].length < num ) {
  19739. parts[ 1 ] += '0';
  19740. }
  19741. return parts.join( '.' );
  19742. };
  19743. function evaluateXPath( node, query ) {
  19744. var instances = COLLADA.evaluate( query, node, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  19745. var inst = instances.iterateNext();
  19746. var result = [];
  19747. while ( inst ) {
  19748. result.push( inst );
  19749. inst = instances.iterateNext();
  19750. }
  19751. return result;
  19752. };
  19753. // Up axis conversion
  19754. function setUpConversion() {
  19755. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  19756. upConversion = null;
  19757. } else {
  19758. switch ( colladaUp ) {
  19759. case 'X':
  19760. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  19761. break;
  19762. case 'Y':
  19763. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  19764. break;
  19765. case 'Z':
  19766. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  19767. break;
  19768. }
  19769. }
  19770. };
  19771. function fixCoords( data, sign ) {
  19772. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  19773. return;
  19774. }
  19775. switch ( upConversion ) {
  19776. case 'XtoY':
  19777. var tmp = data[ 0 ];
  19778. data[ 0 ] = sign * data[ 1 ];
  19779. data[ 1 ] = tmp;
  19780. break;
  19781. case 'XtoZ':
  19782. var tmp = data[ 2 ];
  19783. data[ 2 ] = data[ 1 ];
  19784. data[ 1 ] = data[ 0 ];
  19785. data[ 0 ] = tmp;
  19786. break;
  19787. case 'YtoX':
  19788. var tmp = data[ 0 ];
  19789. data[ 0 ] = data[ 1 ];
  19790. data[ 1 ] = sign * tmp;
  19791. break;
  19792. case 'YtoZ':
  19793. var tmp = data[ 1 ];
  19794. data[ 1 ] = sign * data[ 2 ];
  19795. data[ 2 ] = tmp;
  19796. break;
  19797. case 'ZtoX':
  19798. var tmp = data[ 0 ];
  19799. data[ 0 ] = data[ 1 ];
  19800. data[ 1 ] = data[ 2 ];
  19801. data[ 2 ] = tmp;
  19802. break;
  19803. case 'ZtoY':
  19804. var tmp = data[ 1 ];
  19805. data[ 1 ] = data[ 2 ];
  19806. data[ 2 ] = sign * tmp;
  19807. break;
  19808. }
  19809. };
  19810. function getConvertedVec3( data, offset ) {
  19811. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  19812. fixCoords( arr, -1 );
  19813. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  19814. };
  19815. function getConvertedMat4( data ) {
  19816. if ( options.convertUpAxis ) {
  19817. // First fix rotation and scale
  19818. // Columns first
  19819. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  19820. fixCoords( arr, -1 );
  19821. data[ 0 ] = arr[ 0 ];
  19822. data[ 4 ] = arr[ 1 ];
  19823. data[ 8 ] = arr[ 2 ];
  19824. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  19825. fixCoords( arr, -1 );
  19826. data[ 1 ] = arr[ 0 ];
  19827. data[ 5 ] = arr[ 1 ];
  19828. data[ 9 ] = arr[ 2 ];
  19829. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  19830. fixCoords( arr, -1 );
  19831. data[ 2 ] = arr[ 0 ];
  19832. data[ 6 ] = arr[ 1 ];
  19833. data[ 10 ] = arr[ 2 ];
  19834. // Rows second
  19835. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  19836. fixCoords( arr, -1 );
  19837. data[ 0 ] = arr[ 0 ];
  19838. data[ 1 ] = arr[ 1 ];
  19839. data[ 2 ] = arr[ 2 ];
  19840. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  19841. fixCoords( arr, -1 );
  19842. data[ 4 ] = arr[ 0 ];
  19843. data[ 5 ] = arr[ 1 ];
  19844. data[ 6 ] = arr[ 2 ];
  19845. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  19846. fixCoords( arr, -1 );
  19847. data[ 8 ] = arr[ 0 ];
  19848. data[ 9 ] = arr[ 1 ];
  19849. data[ 10 ] = arr[ 2 ];
  19850. // Now fix translation
  19851. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  19852. fixCoords( arr, -1 );
  19853. data[ 3 ] = arr[ 0 ];
  19854. data[ 7 ] = arr[ 1 ];
  19855. data[ 11 ] = arr[ 2 ];
  19856. }
  19857. return new THREE.Matrix4(
  19858. data[0], data[1], data[2], data[3],
  19859. data[4], data[5], data[6], data[7],
  19860. data[8], data[9], data[10], data[11],
  19861. data[12], data[13], data[14], data[15]
  19862. );
  19863. };
  19864. function getConvertedIndex( index ) {
  19865. if ( index > -1 && index < 3 ) {
  19866. var members = ['X', 'Y', 'Z'],
  19867. indices = { X: 0, Y: 1, Z: 2 };
  19868. index = getConvertedMember( members[ index ] );
  19869. index = indices[ index ];
  19870. }
  19871. return index;
  19872. };
  19873. function getConvertedMember( member ) {
  19874. if ( options.convertUpAxis ) {
  19875. switch ( member ) {
  19876. case 'X':
  19877. switch ( upConversion ) {
  19878. case 'XtoY':
  19879. case 'XtoZ':
  19880. case 'YtoX':
  19881. member = 'Y';
  19882. break;
  19883. case 'ZtoX':
  19884. member = 'Z';
  19885. break;
  19886. }
  19887. break;
  19888. case 'Y':
  19889. switch ( upConversion ) {
  19890. case 'XtoY':
  19891. case 'YtoX':
  19892. case 'ZtoX':
  19893. member = 'X';
  19894. break;
  19895. case 'XtoZ':
  19896. case 'YtoZ':
  19897. case 'ZtoY':
  19898. member = 'Z';
  19899. break;
  19900. }
  19901. break;
  19902. case 'Z':
  19903. switch ( upConversion ) {
  19904. case 'XtoZ':
  19905. member = 'X';
  19906. break;
  19907. case 'YtoZ':
  19908. case 'ZtoX':
  19909. case 'ZtoY':
  19910. member = 'Y';
  19911. break;
  19912. }
  19913. break;
  19914. }
  19915. }
  19916. return member;
  19917. };
  19918. return {
  19919. load: load,
  19920. parse: parse,
  19921. setPreferredShading: setPreferredShading,
  19922. applySkin: applySkin,
  19923. geometries : geometries,
  19924. options: options
  19925. };
  19926. };
  19927. /**
  19928. * @author mrdoob / http://mrdoob.com/
  19929. * @author alteredq / http://alteredqualia.com/
  19930. */
  19931. THREE.JSONLoader = function ( showStatus ) {
  19932. THREE.Loader.call( this, showStatus );
  19933. };
  19934. THREE.JSONLoader.prototype = new THREE.Loader();
  19935. THREE.JSONLoader.prototype.constructor = THREE.JSONLoader;
  19936. THREE.JSONLoader.prototype.supr = THREE.Loader.prototype;
  19937. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  19938. var worker, scope = this;
  19939. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  19940. this.onLoadStart();
  19941. this.loadAjaxJSON( this, url, callback, texturePath );
  19942. };
  19943. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  19944. var xhr = new XMLHttpRequest();
  19945. var length = 0;
  19946. xhr.onreadystatechange = function () {
  19947. if ( xhr.readyState === xhr.DONE ) {
  19948. if ( xhr.status === 200 || xhr.status === 0 ) {
  19949. if ( xhr.responseText ) {
  19950. var json = JSON.parse( xhr.responseText );
  19951. context.createModel( json, callback, texturePath );
  19952. } else {
  19953. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  19954. }
  19955. // in context of more complex asset initialization
  19956. // do not block on single failed file
  19957. // maybe should go even one more level up
  19958. context.onLoadComplete();
  19959. } else {
  19960. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  19961. }
  19962. } else if ( xhr.readyState === xhr.LOADING ) {
  19963. if ( callbackProgress ) {
  19964. if ( length === 0 ) {
  19965. length = xhr.getResponseHeader( "Content-Length" );
  19966. }
  19967. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  19968. }
  19969. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  19970. length = xhr.getResponseHeader( "Content-Length" );
  19971. }
  19972. };
  19973. xhr.open( "GET", url, true );
  19974. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  19975. xhr.setRequestHeader( "Content-Type", "text/plain" );
  19976. xhr.send( null );
  19977. };
  19978. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  19979. var scope = this,
  19980. geometry = new THREE.Geometry(),
  19981. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  19982. this.initMaterials( geometry, json.materials, texturePath );
  19983. parseModel( scale );
  19984. parseSkin();
  19985. parseMorphing( scale );
  19986. geometry.computeCentroids();
  19987. geometry.computeFaceNormals();
  19988. if ( this.hasNormals( geometry ) ) geometry.computeTangents();
  19989. function parseModel( scale ) {
  19990. function isBitSet( value, position ) {
  19991. return value & ( 1 << position );
  19992. }
  19993. var i, j, fi,
  19994. offset, zLength, nVertices,
  19995. colorIndex, normalIndex, uvIndex, materialIndex,
  19996. type,
  19997. isQuad,
  19998. hasMaterial,
  19999. hasFaceUv, hasFaceVertexUv,
  20000. hasFaceNormal, hasFaceVertexNormal,
  20001. hasFaceColor, hasFaceVertexColor,
  20002. vertex, face, color, normal,
  20003. uvLayer, uvs, u, v,
  20004. faces = json.faces,
  20005. vertices = json.vertices,
  20006. normals = json.normals,
  20007. colors = json.colors,
  20008. nUvLayers = 0;
  20009. // disregard empty arrays
  20010. for ( i = 0; i < json.uvs.length; i++ ) {
  20011. if ( json.uvs[ i ].length ) nUvLayers ++;
  20012. }
  20013. for ( i = 0; i < nUvLayers; i++ ) {
  20014. geometry.faceUvs[ i ] = [];
  20015. geometry.faceVertexUvs[ i ] = [];
  20016. }
  20017. offset = 0;
  20018. zLength = vertices.length;
  20019. while ( offset < zLength ) {
  20020. vertex = new THREE.Vertex();
  20021. vertex.x = vertices[ offset ++ ] * scale;
  20022. vertex.y = vertices[ offset ++ ] * scale;
  20023. vertex.z = vertices[ offset ++ ] * scale;
  20024. geometry.vertices.push( vertex );
  20025. }
  20026. offset = 0;
  20027. zLength = faces.length;
  20028. while ( offset < zLength ) {
  20029. type = faces[ offset ++ ];
  20030. isQuad = isBitSet( type, 0 );
  20031. hasMaterial = isBitSet( type, 1 );
  20032. hasFaceUv = isBitSet( type, 2 );
  20033. hasFaceVertexUv = isBitSet( type, 3 );
  20034. hasFaceNormal = isBitSet( type, 4 );
  20035. hasFaceVertexNormal = isBitSet( type, 5 );
  20036. hasFaceColor = isBitSet( type, 6 );
  20037. hasFaceVertexColor = isBitSet( type, 7 );
  20038. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  20039. if ( isQuad ) {
  20040. face = new THREE.Face4();
  20041. face.a = faces[ offset ++ ];
  20042. face.b = faces[ offset ++ ];
  20043. face.c = faces[ offset ++ ];
  20044. face.d = faces[ offset ++ ];
  20045. nVertices = 4;
  20046. } else {
  20047. face = new THREE.Face3();
  20048. face.a = faces[ offset ++ ];
  20049. face.b = faces[ offset ++ ];
  20050. face.c = faces[ offset ++ ];
  20051. nVertices = 3;
  20052. }
  20053. if ( hasMaterial ) {
  20054. materialIndex = faces[ offset ++ ];
  20055. face.materialIndex = materialIndex;
  20056. }
  20057. // to get face <=> uv index correspondence
  20058. fi = geometry.faces.length;
  20059. if ( hasFaceUv ) {
  20060. for ( i = 0; i < nUvLayers; i++ ) {
  20061. uvLayer = json.uvs[ i ];
  20062. uvIndex = faces[ offset ++ ];
  20063. u = uvLayer[ uvIndex * 2 ];
  20064. v = uvLayer[ uvIndex * 2 + 1 ];
  20065. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  20066. }
  20067. }
  20068. if ( hasFaceVertexUv ) {
  20069. for ( i = 0; i < nUvLayers; i++ ) {
  20070. uvLayer = json.uvs[ i ];
  20071. uvs = [];
  20072. for ( j = 0; j < nVertices; j ++ ) {
  20073. uvIndex = faces[ offset ++ ];
  20074. u = uvLayer[ uvIndex * 2 ];
  20075. v = uvLayer[ uvIndex * 2 + 1 ];
  20076. uvs[ j ] = new THREE.UV( u, v );
  20077. }
  20078. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  20079. }
  20080. }
  20081. if ( hasFaceNormal ) {
  20082. normalIndex = faces[ offset ++ ] * 3;
  20083. normal = new THREE.Vector3();
  20084. normal.x = normals[ normalIndex ++ ];
  20085. normal.y = normals[ normalIndex ++ ];
  20086. normal.z = normals[ normalIndex ];
  20087. face.normal = normal;
  20088. }
  20089. if ( hasFaceVertexNormal ) {
  20090. for ( i = 0; i < nVertices; i++ ) {
  20091. normalIndex = faces[ offset ++ ] * 3;
  20092. normal = new THREE.Vector3();
  20093. normal.x = normals[ normalIndex ++ ];
  20094. normal.y = normals[ normalIndex ++ ];
  20095. normal.z = normals[ normalIndex ];
  20096. face.vertexNormals.push( normal );
  20097. }
  20098. }
  20099. if ( hasFaceColor ) {
  20100. colorIndex = faces[ offset ++ ];
  20101. color = new THREE.Color( colors[ colorIndex ] );
  20102. face.color = color;
  20103. }
  20104. if ( hasFaceVertexColor ) {
  20105. for ( i = 0; i < nVertices; i++ ) {
  20106. colorIndex = faces[ offset ++ ];
  20107. color = new THREE.Color( colors[ colorIndex ] );
  20108. face.vertexColors.push( color );
  20109. }
  20110. }
  20111. geometry.faces.push( face );
  20112. }
  20113. };
  20114. function parseSkin() {
  20115. var i, l, x, y, z, w, a, b, c, d;
  20116. if ( json.skinWeights ) {
  20117. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  20118. x = json.skinWeights[ i ];
  20119. y = json.skinWeights[ i + 1 ];
  20120. z = 0;
  20121. w = 0;
  20122. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  20123. }
  20124. }
  20125. if ( json.skinIndices ) {
  20126. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  20127. a = json.skinIndices[ i ];
  20128. b = json.skinIndices[ i + 1 ];
  20129. c = 0;
  20130. d = 0;
  20131. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  20132. }
  20133. }
  20134. geometry.bones = json.bones;
  20135. geometry.animation = json.animation;
  20136. };
  20137. function parseMorphing( scale ) {
  20138. if ( json.morphTargets !== undefined ) {
  20139. var i, l, v, vl, x, y, z, dstVertices, srcVertices;
  20140. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  20141. geometry.morphTargets[ i ] = {};
  20142. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  20143. geometry.morphTargets[ i ].vertices = [];
  20144. dstVertices = geometry.morphTargets[ i ].vertices;
  20145. srcVertices = json.morphTargets [ i ].vertices;
  20146. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  20147. x = srcVertices[ v ] * scale;
  20148. y = srcVertices[ v + 1 ] * scale;
  20149. z = srcVertices[ v + 2 ] * scale;
  20150. dstVertices.push( new THREE.Vertex( x, y, z ) );
  20151. }
  20152. }
  20153. }
  20154. if ( json.morphColors !== undefined ) {
  20155. var i, l, c, cl, dstColors, srcColors, color;
  20156. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  20157. geometry.morphColors[ i ] = {};
  20158. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  20159. geometry.morphColors[ i ].colors = [];
  20160. dstColors = geometry.morphColors[ i ].colors;
  20161. srcColors = json.morphColors [ i ].colors;
  20162. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  20163. color = new THREE.Color( 0xffaa00 );
  20164. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  20165. dstColors.push( color );
  20166. }
  20167. }
  20168. }
  20169. };
  20170. callback( geometry );
  20171. };
  20172. /**
  20173. * @author alteredq / http://alteredqualia.com/
  20174. */
  20175. THREE.SceneLoader = function () {
  20176. this.onLoadStart = function () {};
  20177. this.onLoadProgress = function() {};
  20178. this.onLoadComplete = function () {};
  20179. this.callbackSync = function () {};
  20180. this.callbackProgress = function () {};
  20181. };
  20182. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  20183. THREE.SceneLoader.prototype.load = function( url, callbackFinished ) {
  20184. var context = this;
  20185. var xhr = new XMLHttpRequest();
  20186. xhr.onreadystatechange = function () {
  20187. if ( xhr.readyState == 4 ) {
  20188. if ( xhr.status == 200 || xhr.status == 0 ) {
  20189. var json = JSON.parse( xhr.responseText );
  20190. context.createScene( json, callbackFinished, url );
  20191. } else {
  20192. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  20193. }
  20194. }
  20195. };
  20196. xhr.open( "GET", url, true );
  20197. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  20198. xhr.setRequestHeader( "Content-Type", "text/plain" );
  20199. xhr.send( null );
  20200. };
  20201. THREE.SceneLoader.prototype.createScene = function ( json, callbackFinished, url ) {
  20202. var scope = this;
  20203. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  20204. var dg, dm, dd, dl, dc, df, dt,
  20205. g, o, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  20206. geometry, material, camera, fog,
  20207. texture, images,
  20208. light,
  20209. data, binLoader, jsonLoader,
  20210. counter_models, counter_textures,
  20211. total_models, total_textures,
  20212. result;
  20213. data = json;
  20214. binLoader = new THREE.BinaryLoader();
  20215. jsonLoader = new THREE.JSONLoader();
  20216. counter_models = 0;
  20217. counter_textures = 0;
  20218. result = {
  20219. scene: new THREE.Scene(),
  20220. geometries: {},
  20221. materials: {},
  20222. textures: {},
  20223. objects: {},
  20224. cameras: {},
  20225. lights: {},
  20226. fogs: {},
  20227. empties: {}
  20228. };
  20229. if ( data.transform ) {
  20230. var position = data.transform.position,
  20231. rotation = data.transform.rotation,
  20232. scale = data.transform.scale;
  20233. if ( position )
  20234. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  20235. if ( rotation )
  20236. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  20237. if ( scale )
  20238. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  20239. if ( position || rotation || scale ) {
  20240. result.scene.updateMatrix();
  20241. result.scene.updateMatrixWorld();
  20242. }
  20243. }
  20244. function get_url( source_url, url_type ) {
  20245. if ( url_type == "relativeToHTML" ) {
  20246. return source_url;
  20247. } else {
  20248. return urlBase + "/" + source_url;
  20249. }
  20250. };
  20251. function handle_objects() {
  20252. var object;
  20253. for( dd in data.objects ) {
  20254. if ( !result.objects[ dd ] ) {
  20255. o = data.objects[ dd ];
  20256. if ( o.geometry !== undefined ) {
  20257. geometry = result.geometries[ o.geometry ];
  20258. // geometry already loaded
  20259. if ( geometry ) {
  20260. var hasNormals = false;
  20261. // not anymore support for multiple materials
  20262. // shouldn't really be array
  20263. material = result.materials[ o.materials[ 0 ] ];
  20264. hasNormals = material instanceof THREE.ShaderMaterial;
  20265. if ( hasNormals ) {
  20266. geometry.computeTangents();
  20267. }
  20268. p = o.position;
  20269. r = o.rotation;
  20270. q = o.quaternion;
  20271. s = o.scale;
  20272. // turn off quaternions, for the moment
  20273. q = 0;
  20274. if ( o.materials.length == 0 ) {
  20275. material = new THREE.MeshFaceMaterial();
  20276. }
  20277. // dirty hack to handle meshes with multiple materials
  20278. // just use face materials defined in model
  20279. if ( o.materials.length > 1 ) {
  20280. material = new THREE.MeshFaceMaterial();
  20281. }
  20282. object = new THREE.Mesh( geometry, material );
  20283. object.name = dd;
  20284. object.position.set( p[0], p[1], p[2] );
  20285. if ( q ) {
  20286. object.quaternion.set( q[0], q[1], q[2], q[3] );
  20287. object.useQuaternion = true;
  20288. } else {
  20289. object.rotation.set( r[0], r[1], r[2] );
  20290. }
  20291. object.scale.set( s[0], s[1], s[2] );
  20292. object.visible = o.visible;
  20293. object.doubleSided = o.doubleSided;
  20294. object.castShadow = o.castShadow;
  20295. object.receiveShadow = o.receiveShadow;
  20296. result.scene.add( object );
  20297. result.objects[ dd ] = object;
  20298. }
  20299. // pure Object3D
  20300. } else {
  20301. p = o.position;
  20302. r = o.rotation;
  20303. q = o.quaternion;
  20304. s = o.scale;
  20305. // turn off quaternions, for the moment
  20306. q = 0;
  20307. object = new THREE.Object3D();
  20308. object.name = dd;
  20309. object.position.set( p[0], p[1], p[2] );
  20310. if ( q ) {
  20311. object.quaternion.set( q[0], q[1], q[2], q[3] );
  20312. object.useQuaternion = true;
  20313. } else {
  20314. object.rotation.set( r[0], r[1], r[2] );
  20315. }
  20316. object.scale.set( s[0], s[1], s[2] );
  20317. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  20318. result.scene.add( object );
  20319. result.objects[ dd ] = object;
  20320. result.empties[ dd ] = object;
  20321. }
  20322. }
  20323. }
  20324. };
  20325. function handle_mesh( geo, id ) {
  20326. result.geometries[ id ] = geo;
  20327. handle_objects();
  20328. };
  20329. function create_callback( id ) {
  20330. return function( geo ) {
  20331. handle_mesh( geo, id );
  20332. counter_models -= 1;
  20333. scope.onLoadComplete();
  20334. async_callback_gate();
  20335. }
  20336. };
  20337. function create_callback_embed( id ) {
  20338. return function( geo ) {
  20339. result.geometries[ id ] = geo;
  20340. }
  20341. };
  20342. function async_callback_gate() {
  20343. var progress = {
  20344. totalModels : total_models,
  20345. totalTextures : total_textures,
  20346. loadedModels : total_models - counter_models,
  20347. loadedTextures : total_textures - counter_textures
  20348. };
  20349. scope.callbackProgress( progress, result );
  20350. scope.onLoadProgress();
  20351. if( counter_models == 0 && counter_textures == 0 ) {
  20352. callbackFinished( result );
  20353. }
  20354. };
  20355. var callbackTexture = function( images ) {
  20356. counter_textures -= 1;
  20357. async_callback_gate();
  20358. scope.onLoadComplete();
  20359. };
  20360. // first go synchronous elements
  20361. // cameras
  20362. for( dc in data.cameras ) {
  20363. c = data.cameras[ dc ];
  20364. if ( c.type == "perspective" ) {
  20365. camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );
  20366. } else if ( c.type == "ortho" ) {
  20367. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  20368. }
  20369. p = c.position;
  20370. t = c.target;
  20371. u = c.up;
  20372. camera.position.set( p[0], p[1], p[2] );
  20373. camera.target = new THREE.Vector3( t[0], t[1], t[2] );
  20374. if ( u ) camera.up.set( u[0], u[1], u[2] );
  20375. result.cameras[ dc ] = camera;
  20376. }
  20377. // lights
  20378. var hex, intensity;
  20379. for ( dl in data.lights ) {
  20380. l = data.lights[ dl ];
  20381. hex = ( l.color !== undefined ) ? l.color : 0xffffff;
  20382. intensity = ( l.intensity !== undefined ) ? l.intensity : 1;
  20383. if ( l.type == "directional" ) {
  20384. p = l.direction;
  20385. light = new THREE.DirectionalLight( hex, intensity );
  20386. light.position.set( p[0], p[1], p[2] );
  20387. light.position.normalize();
  20388. } else if ( l.type == "point" ) {
  20389. p = l.position;
  20390. d = l.distance;
  20391. light = new THREE.PointLight( hex, intensity, d );
  20392. light.position.set( p[0], p[1], p[2] );
  20393. } else if ( l.type == "ambient" ) {
  20394. light = new THREE.AmbientLight( hex );
  20395. }
  20396. result.scene.add( light );
  20397. result.lights[ dl ] = light;
  20398. }
  20399. // fogs
  20400. for( df in data.fogs ) {
  20401. f = data.fogs[ df ];
  20402. if ( f.type == "linear" ) {
  20403. fog = new THREE.Fog( 0x000000, f.near, f.far );
  20404. } else if ( f.type == "exp2" ) {
  20405. fog = new THREE.FogExp2( 0x000000, f.density );
  20406. }
  20407. c = f.color;
  20408. fog.color.setRGB( c[0], c[1], c[2] );
  20409. result.fogs[ df ] = fog;
  20410. }
  20411. // defaults
  20412. if ( result.cameras && data.defaults.camera ) {
  20413. result.currentCamera = result.cameras[ data.defaults.camera ];
  20414. }
  20415. if ( result.fogs && data.defaults.fog ) {
  20416. result.scene.fog = result.fogs[ data.defaults.fog ];
  20417. }
  20418. c = data.defaults.bgcolor;
  20419. result.bgColor = new THREE.Color();
  20420. result.bgColor.setRGB( c[0], c[1], c[2] );
  20421. result.bgColorAlpha = data.defaults.bgalpha;
  20422. // now come potentially asynchronous elements
  20423. // geometries
  20424. // count how many models will be loaded asynchronously
  20425. for( dg in data.geometries ) {
  20426. g = data.geometries[ dg ];
  20427. if ( g.type == "bin_mesh" || g.type == "ascii_mesh" ) {
  20428. counter_models += 1;
  20429. scope.onLoadStart();
  20430. }
  20431. }
  20432. total_models = counter_models;
  20433. for ( dg in data.geometries ) {
  20434. g = data.geometries[ dg ];
  20435. if ( g.type == "cube" ) {
  20436. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.segmentsWidth, g.segmentsHeight, g.segmentsDepth, null, g.flipped, g.sides );
  20437. result.geometries[ dg ] = geometry;
  20438. } else if ( g.type == "plane" ) {
  20439. geometry = new THREE.PlaneGeometry( g.width, g.height, g.segmentsWidth, g.segmentsHeight );
  20440. result.geometries[ dg ] = geometry;
  20441. } else if ( g.type == "sphere" ) {
  20442. geometry = new THREE.SphereGeometry( g.radius, g.segmentsWidth, g.segmentsHeight );
  20443. result.geometries[ dg ] = geometry;
  20444. } else if ( g.type == "cylinder" ) {
  20445. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  20446. result.geometries[ dg ] = geometry;
  20447. } else if ( g.type == "torus" ) {
  20448. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  20449. result.geometries[ dg ] = geometry;
  20450. } else if ( g.type == "icosahedron" ) {
  20451. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  20452. result.geometries[ dg ] = geometry;
  20453. } else if ( g.type == "bin_mesh" ) {
  20454. binLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  20455. } else if ( g.type == "ascii_mesh" ) {
  20456. jsonLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  20457. } else if ( g.type == "embedded_mesh" ) {
  20458. var modelJson = data.embeds[ g.id ],
  20459. texture_path = "";
  20460. // Pass metadata along to jsonLoader so it knows the format version.
  20461. modelJson.metadata = data.metadata;
  20462. if ( modelJson ) {
  20463. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  20464. }
  20465. }
  20466. }
  20467. // textures
  20468. // count how many textures will be loaded asynchronously
  20469. for( dt in data.textures ) {
  20470. tt = data.textures[ dt ];
  20471. if( tt.url instanceof Array ) {
  20472. counter_textures += tt.url.length;
  20473. for( var n = 0; n < tt.url.length; n ++ ) {
  20474. scope.onLoadStart();
  20475. }
  20476. } else {
  20477. counter_textures += 1;
  20478. scope.onLoadStart();
  20479. }
  20480. }
  20481. total_textures = counter_textures;
  20482. for( dt in data.textures ) {
  20483. tt = data.textures[ dt ];
  20484. if ( tt.mapping != undefined && THREE[ tt.mapping ] != undefined ) {
  20485. tt.mapping = new THREE[ tt.mapping ]();
  20486. }
  20487. if( tt.url instanceof Array ) {
  20488. var url_array = [];
  20489. for( var i = 0; i < tt.url.length; i ++ ) {
  20490. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  20491. }
  20492. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, callbackTexture );
  20493. } else {
  20494. texture = THREE.ImageUtils.loadTexture( get_url( tt.url, data.urlBaseType ), tt.mapping, callbackTexture );
  20495. if ( THREE[ tt.minFilter ] != undefined )
  20496. texture.minFilter = THREE[ tt.minFilter ];
  20497. if ( THREE[ tt.magFilter ] != undefined )
  20498. texture.magFilter = THREE[ tt.magFilter ];
  20499. if ( tt.repeat ) {
  20500. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  20501. if ( tt.repeat[ 0 ] != 1 ) texture.wrapS = THREE.RepeatWrapping;
  20502. if ( tt.repeat[ 1 ] != 1 ) texture.wrapT = THREE.RepeatWrapping;
  20503. }
  20504. if ( tt.offset ) {
  20505. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  20506. }
  20507. // handle wrap after repeat so that default repeat can be overriden
  20508. if ( tt.wrap ) {
  20509. var wrapMap = {
  20510. "repeat" : THREE.RepeatWrapping,
  20511. "mirror" : THREE.MirroredRepeatWrapping
  20512. }
  20513. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  20514. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  20515. }
  20516. }
  20517. result.textures[ dt ] = texture;
  20518. }
  20519. // materials
  20520. for ( dm in data.materials ) {
  20521. m = data.materials[ dm ];
  20522. for ( pp in m.parameters ) {
  20523. if ( pp == "envMap" || pp == "map" || pp == "lightMap" ) {
  20524. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  20525. } else if ( pp == "shading" ) {
  20526. m.parameters[ pp ] = ( m.parameters[ pp ] == "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  20527. } else if ( pp == "blending" ) {
  20528. m.parameters[ pp ] = THREE[ m.parameters[ pp ] ] ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  20529. } else if ( pp == "combine" ) {
  20530. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  20531. } else if ( pp == "vertexColors" ) {
  20532. if ( m.parameters[ pp ] == "face" ) {
  20533. m.parameters[ pp ] = THREE.FaceColors;
  20534. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  20535. } else if ( m.parameters[ pp ] ) {
  20536. m.parameters[ pp ] = THREE.VertexColors;
  20537. }
  20538. }
  20539. }
  20540. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  20541. m.parameters.transparent = true;
  20542. }
  20543. if ( m.parameters.normalMap ) {
  20544. var shader = THREE.ShaderUtils.lib[ "normal" ];
  20545. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  20546. var diffuse = m.parameters.color;
  20547. var specular = m.parameters.specular;
  20548. var ambient = m.parameters.ambient;
  20549. var shininess = m.parameters.shininess;
  20550. uniforms[ "tNormal" ].texture = result.textures[ m.parameters.normalMap ];
  20551. if ( m.parameters.normalMapFactor ) {
  20552. uniforms[ "uNormalScale" ].value = m.parameters.normalMapFactor;
  20553. }
  20554. if ( m.parameters.map ) {
  20555. uniforms[ "tDiffuse" ].texture = m.parameters.map;
  20556. uniforms[ "enableDiffuse" ].value = true;
  20557. }
  20558. if ( m.parameters.lightMap ) {
  20559. uniforms[ "tAO" ].texture = m.parameters.lightMap;
  20560. uniforms[ "enableAO" ].value = true;
  20561. }
  20562. if ( m.parameters.specularMap ) {
  20563. uniforms[ "tSpecular" ].texture = result.textures[ m.parameters.specularMap ];
  20564. uniforms[ "enableSpecular" ].value = true;
  20565. }
  20566. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  20567. uniforms[ "uSpecularColor" ].value.setHex( specular );
  20568. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  20569. uniforms[ "uShininess" ].value = shininess;
  20570. if ( m.parameters.opacity ) {
  20571. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  20572. }
  20573. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  20574. material = new THREE.ShaderMaterial( parameters );
  20575. } else {
  20576. material = new THREE[ m.type ]( m.parameters );
  20577. }
  20578. result.materials[ dm ] = material;
  20579. }
  20580. // objects ( synchronous init of procedural primitives )
  20581. handle_objects();
  20582. // synchronous callback
  20583. scope.callbackSync( result );
  20584. // just in case there are no async elements:
  20585. async_callback_gate();
  20586. };
  20587. /**
  20588. * Loader for UTF8 encoded models generated by:
  20589. * http://code.google.com/p/webgl-loader/
  20590. *
  20591. * Limitations:
  20592. * - number of vertices < 65536 (this is after optimizations in compressor, input OBJ may have even less)
  20593. * - models must have normals and texture coordinates
  20594. * - texture coordinates must be only from <0,1>
  20595. * - no materials support yet
  20596. * - models are scaled and offset (copy numbers from compressor and use them as parameters in UTF8Loader.load() )
  20597. *
  20598. * @author alteredq / http://alteredqualia.com/
  20599. * @author won3d / http://twitter.com/won3d
  20600. */
  20601. THREE.UTF8Loader = function () {};
  20602. THREE.UTF8Loader.prototype.load = function ( url, callback, metadata ) {
  20603. var xhr = new XMLHttpRequest(),
  20604. callbackProgress = null,
  20605. scale = metadata.scale !== undefined ? metadata.scale : 1,
  20606. offsetX = metadata.offsetX !== undefined ? metadata.offsetX : 0,
  20607. offsetY = metadata.offsetY !== undefined ? metadata.offsetY : 0,
  20608. offsetZ = metadata.offsetZ !== undefined ? metadata.offsetZ : 0;
  20609. var length = 0;
  20610. xhr.onreadystatechange = function() {
  20611. if ( xhr.readyState == 4 ) {
  20612. if ( xhr.status == 200 || xhr.status == 0 ) {
  20613. THREE.UTF8Loader.prototype.createModel( xhr.responseText, callback, scale, offsetX, offsetY, offsetZ );
  20614. } else {
  20615. console.error( "THREE.UTF8Loader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  20616. }
  20617. } else if ( xhr.readyState == 3 ) {
  20618. if ( callbackProgress ) {
  20619. if ( length == 0 ) {
  20620. length = xhr.getResponseHeader( "Content-Length" );
  20621. }
  20622. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  20623. }
  20624. } else if ( xhr.readyState == 2 ) {
  20625. length = xhr.getResponseHeader( "Content-Length" );
  20626. }
  20627. }
  20628. xhr.open( "GET", url, true );
  20629. xhr.send( null );
  20630. };
  20631. // UTF-8 decoder from webgl-loader
  20632. // http://code.google.com/p/webgl-loader/
  20633. // Copyright 2011 Google Inc. All Rights Reserved.
  20634. //
  20635. // Licensed under the Apache License, Version 2.0 (the "License"); you
  20636. // may not use this file except in compliance with the License. You
  20637. // may obtain a copy of the License at
  20638. //
  20639. // http://www.apache.org/licenses/LICENSE-2.0
  20640. //
  20641. // Unless required by applicable law or agreed to in writing, software
  20642. // distributed under the License is distributed on an "AS IS" BASIS,
  20643. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  20644. // implied. See the License for the specific language governing
  20645. // permissions and limitations under the License.
  20646. THREE.UTF8Loader.prototype.decompressMesh = function ( str ) {
  20647. var num_verts = str.charCodeAt( 0 );
  20648. if ( num_verts >= 0xE000 ) {
  20649. num_verts -= 0x0800;
  20650. }
  20651. num_verts ++;
  20652. var attribs_out = new Float32Array( 8 * num_verts );
  20653. var offset = 1;
  20654. for ( var i = 0; i < 8; i ++ ) {
  20655. var prev_attrib = 0;
  20656. for ( var j = 0; j < num_verts; ++ j ) {
  20657. var code = str.charCodeAt( j + offset );
  20658. prev_attrib += ( code >> 1 ) ^ ( - ( code & 1 ) );
  20659. attribs_out[ 8 * j + i ] = prev_attrib;
  20660. }
  20661. offset += num_verts;
  20662. }
  20663. var num_indices = str.length - offset;
  20664. var indices_out = new Uint16Array( num_indices );
  20665. var index_high_water_mark = 0;
  20666. for ( var i = 0; i < num_indices; i ++ ) {
  20667. var code = str.charCodeAt( i + offset );
  20668. indices_out[ i ] = index_high_water_mark - code;
  20669. if ( code == 0 ) {
  20670. index_high_water_mark ++;
  20671. }
  20672. }
  20673. return [ attribs_out, indices_out ];
  20674. };
  20675. THREE.UTF8Loader.prototype.createModel = function ( data, callback, scale, offsetX, offsetY, offsetZ ) {
  20676. var Model = function ( texture_path ) {
  20677. //var s = (new Date).getTime();
  20678. var scope = this;
  20679. scope.materials = [];
  20680. THREE.Geometry.call( this );
  20681. var buffers = THREE.UTF8Loader.prototype.decompressMesh( data );
  20682. var normals = [],
  20683. uvs = [];
  20684. init_vertices( buffers[ 0 ], 8, 0 );
  20685. init_uvs( buffers[ 0 ], 8, 3 );
  20686. init_normals( buffers[ 0 ], 8, 5 );
  20687. init_faces( buffers[ 1 ] );
  20688. this.computeCentroids();
  20689. this.computeFaceNormals();
  20690. //this.computeTangents();
  20691. //var e = (new Date).getTime();
  20692. //console.log( "utf8 data parse time: " + (e-s) + " ms" );
  20693. function init_vertices( data, stride, offset ) {
  20694. var i, x, y, z,
  20695. end = data.length;
  20696. for( i = offset; i < end; i += stride ) {
  20697. x = data[ i ];
  20698. y = data[ i + 1 ];
  20699. z = data[ i + 2 ];
  20700. // fix scale and offsets
  20701. x = ( x / 16383 ) * scale;
  20702. y = ( y / 16383 ) * scale;
  20703. z = ( z / 16383 ) * scale;
  20704. x += offsetX;
  20705. y += offsetY;
  20706. z += offsetZ;
  20707. vertex( scope, x, y, z );
  20708. }
  20709. };
  20710. function init_normals( data, stride, offset ) {
  20711. var i, x, y, z,
  20712. end = data.length;
  20713. for( i = offset; i < end; i += stride ) {
  20714. x = data[ i ];
  20715. y = data[ i + 1 ];
  20716. z = data[ i + 2 ];
  20717. // normalize to <-1,1>
  20718. x = ( x - 512 ) / 511;
  20719. y = ( y - 512 ) / 511;
  20720. z = ( z - 512 ) / 511;
  20721. normals.push( x, y, z );
  20722. }
  20723. };
  20724. function init_uvs( data, stride, offset ) {
  20725. var i, u, v,
  20726. end = data.length;
  20727. for( i = offset; i < end; i += stride ) {
  20728. u = data[ i ];
  20729. v = data[ i + 1 ];
  20730. // normalize to <0,1>
  20731. u /= 1023;
  20732. v /= 1023;
  20733. uvs.push( u, 1 - v );
  20734. }
  20735. };
  20736. function init_faces( indices ) {
  20737. var i,
  20738. a, b, c,
  20739. u1, v1, u2, v2, u3, v3,
  20740. m,
  20741. end = indices.length;
  20742. m = 0; // all faces defaulting to material 0
  20743. for( i = 0; i < end; i += 3 ) {
  20744. a = indices[ i ];
  20745. b = indices[ i + 1 ];
  20746. c = indices[ i + 2 ];
  20747. f3n( scope, normals, a, b, c, m, a, b, c );
  20748. u1 = uvs[ a * 2 ];
  20749. v1 = uvs[ a * 2 + 1 ];
  20750. u2 = uvs[ b * 2 ];
  20751. v2 = uvs[ b * 2 + 1 ];
  20752. u3 = uvs[ c * 2 ];
  20753. v3 = uvs[ c * 2 + 1 ];
  20754. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  20755. }
  20756. }
  20757. };
  20758. function vertex ( scope, x, y, z ) {
  20759. scope.vertices.push( new THREE.Vertex( x, y, z ) );
  20760. };
  20761. function f3n ( scope, normals, a, b, c, mi, nai, nbi, nci ) {
  20762. var nax = normals[ nai * 3 ],
  20763. nay = normals[ nai * 3 + 1 ],
  20764. naz = normals[ nai * 3 + 2 ],
  20765. nbx = normals[ nbi * 3 ],
  20766. nby = normals[ nbi * 3 + 1 ],
  20767. nbz = normals[ nbi * 3 + 2 ],
  20768. ncx = normals[ nci * 3 ],
  20769. ncy = normals[ nci * 3 + 1 ],
  20770. ncz = normals[ nci * 3 + 2 ];
  20771. var na = new THREE.Vector3( nax, nay, naz ),
  20772. nb = new THREE.Vector3( nbx, nby, nbz ),
  20773. nc = new THREE.Vector3( ncx, ncy, ncz );
  20774. scope.faces.push( new THREE.Face3( a, b, c, [ na, nb, nc ], null, mi ) );
  20775. };
  20776. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  20777. var uv = [];
  20778. uv.push( new THREE.UV( u1, v1 ) );
  20779. uv.push( new THREE.UV( u2, v2 ) );
  20780. uv.push( new THREE.UV( u3, v3 ) );
  20781. where.push( uv );
  20782. };
  20783. Model.prototype = new THREE.Geometry();
  20784. Model.prototype.constructor = Model;
  20785. callback( new Model() );
  20786. };
  20787. /**
  20788. * @author alteredq / http://alteredqualia.com/
  20789. */
  20790. THREE.ImmediateRenderObject = function ( ) {
  20791. THREE.Object3D.call( this );
  20792. this.render = function( renderCallback ) {
  20793. };
  20794. };
  20795. THREE.ImmediateRenderObject.prototype = new THREE.Object3D();
  20796. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  20797. /**
  20798. * @author mikael emtinger / http://gomo.se/
  20799. * @author alteredq / http://alteredqualia.com/
  20800. */
  20801. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20802. THREE.Object3D.call( this );
  20803. this.lensFlares = [];
  20804. this.positionScreen = new THREE.Vector3();
  20805. this.customUpdateCallback = undefined;
  20806. if( texture !== undefined ) {
  20807. this.add( texture, size, distance, blending, color );
  20808. }
  20809. };
  20810. THREE.LensFlare.prototype = new THREE.Object3D();
  20811. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  20812. THREE.LensFlare.prototype.supr = THREE.Object3D.prototype;
  20813. /*
  20814. * Add: adds another flare
  20815. */
  20816. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20817. if( size === undefined ) size = -1;
  20818. if( distance === undefined ) distance = 0;
  20819. if( opacity === undefined ) opacity = 1;
  20820. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20821. if( blending === undefined ) blending = THREE.NormalBlending;
  20822. distance = Math.min( distance, Math.max( 0, distance ) );
  20823. this.lensFlares.push( { texture: texture, // THREE.Texture
  20824. size: size, // size in pixels (-1 = use texture.width)
  20825. distance: distance, // distance (0-1) from light source (0=at light source)
  20826. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20827. scale: 1, // scale
  20828. rotation: 1, // rotation
  20829. opacity: opacity, // opacity
  20830. color: color, // color
  20831. blending: blending } ); // blending
  20832. };
  20833. /*
  20834. * Update lens flares update positions on all flares based on the screen position
  20835. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20836. */
  20837. THREE.LensFlare.prototype.updateLensFlares = function () {
  20838. var f, fl = this.lensFlares.length;
  20839. var flare;
  20840. var vecX = -this.positionScreen.x * 2;
  20841. var vecY = -this.positionScreen.y * 2;
  20842. for( f = 0; f < fl; f ++ ) {
  20843. flare = this.lensFlares[ f ];
  20844. flare.x = this.positionScreen.x + vecX * flare.distance;
  20845. flare.y = this.positionScreen.y + vecY * flare.distance;
  20846. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20847. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20848. }
  20849. };
  20850. /**
  20851. * @author alteredq / http://alteredqualia.com/
  20852. */
  20853. THREE.MorphBlendMesh = function( geometry, material ) {
  20854. THREE.Mesh.call( this, geometry, material );
  20855. this.animationsMap = {};
  20856. this.animationsList = [];
  20857. // prepare default animation
  20858. // (all frames played together in 1 second)
  20859. var numFrames = this.geometry.morphTargets.length;
  20860. var name = "__default";
  20861. var startFrame = 0;
  20862. var endFrame = numFrames - 1;
  20863. var fps = numFrames / 1;
  20864. this.createAnimation( name, startFrame, endFrame, fps );
  20865. this.setAnimationWeight( name, 1 );
  20866. };
  20867. THREE.MorphBlendMesh.prototype = new THREE.Mesh();
  20868. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  20869. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20870. var animation = {
  20871. startFrame: start,
  20872. endFrame: end,
  20873. length: end - start + 1,
  20874. fps: fps,
  20875. duration: ( end - start ) / fps,
  20876. lastFrame: 0,
  20877. currentFrame: 0,
  20878. active: false,
  20879. time: 0,
  20880. direction: 1,
  20881. weight: 1,
  20882. directionBackwards: false,
  20883. mirroredLoop: false
  20884. };
  20885. this.animationsMap[ name ] = animation;
  20886. this.animationsList.push( animation );
  20887. };
  20888. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20889. var pattern = /([a-z]+)(\d+)/;
  20890. var firstAnimation, frameRanges = {};
  20891. var geometry = this.geometry;
  20892. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20893. var morph = geometry.morphTargets[ i ];
  20894. var chunks = morph.name.match( pattern );
  20895. if ( chunks && chunks.length > 1 ) {
  20896. var name = chunks[ 1 ];
  20897. var num = chunks[ 2 ];
  20898. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20899. var range = frameRanges[ name ];
  20900. if ( i < range.start ) range.start = i;
  20901. if ( i > range.end ) range.end = i;
  20902. if ( ! firstAnimation ) firstAnimation = name;
  20903. }
  20904. }
  20905. for ( var name in frameRanges ) {
  20906. var range = frameRanges[ name ];
  20907. this.createAnimation( name, range.start, range.end, fps );
  20908. }
  20909. this.firstAnimation = firstAnimation;
  20910. };
  20911. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20912. var animation = this.animationsMap[ name ];
  20913. if ( animation ) {
  20914. animation.direction = 1;
  20915. animation.directionBackwards = false;
  20916. }
  20917. };
  20918. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20919. var animation = this.animationsMap[ name ];
  20920. if ( animation ) {
  20921. animation.direction = -1;
  20922. animation.directionBackwards = true;
  20923. }
  20924. };
  20925. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20926. var animation = this.animationsMap[ name ];
  20927. if ( animation ) {
  20928. animation.fps = fps;
  20929. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20930. }
  20931. };
  20932. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20933. var animation = this.animationsMap[ name ];
  20934. if ( animation ) {
  20935. animation.duration = duration;
  20936. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20937. }
  20938. };
  20939. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20940. var animation = this.animationsMap[ name ];
  20941. if ( animation ) {
  20942. animation.weight = weight;
  20943. }
  20944. };
  20945. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20946. var animation = this.animationsMap[ name ];
  20947. if ( animation ) {
  20948. animation.time = time;
  20949. }
  20950. };
  20951. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20952. var time = 0;
  20953. var animation = this.animationsMap[ name ];
  20954. if ( animation ) {
  20955. time = animation.time;
  20956. }
  20957. return time;
  20958. };
  20959. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20960. var duration = -1;
  20961. var animation = this.animationsMap[ name ];
  20962. if ( animation ) {
  20963. duration = animation.duration;
  20964. }
  20965. return duration;
  20966. };
  20967. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20968. var animation = this.animationsMap[ name ];
  20969. if ( animation ) {
  20970. animation.time = 0;
  20971. animation.active = true;
  20972. } else {
  20973. console.warn( "animation[" + name + "] undefined" );
  20974. }
  20975. };
  20976. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20977. var animation = this.animationsMap[ name ];
  20978. if ( animation ) {
  20979. animation.active = false;
  20980. }
  20981. };
  20982. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20983. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20984. var animation = this.animationsList[ i ];
  20985. if ( ! animation.active ) continue;
  20986. var frameTime = animation.duration / animation.length;
  20987. animation.time += animation.direction * delta;
  20988. if ( animation.mirroredLoop ) {
  20989. if ( animation.time > animation.duration || animation.time < 0 ) {
  20990. animation.direction *= -1;
  20991. if ( animation.time > animation.duration ) {
  20992. animation.time = animation.duration;
  20993. animation.directionBackwards = true;
  20994. }
  20995. if ( animation.time < 0 ) {
  20996. animation.time = 0;
  20997. animation.directionBackwards = false;
  20998. }
  20999. }
  21000. } else {
  21001. animation.time = animation.time % animation.duration;
  21002. if ( animation.time < 0 ) animation.time += animation.duration;
  21003. }
  21004. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21005. var weight = animation.weight;
  21006. if ( keyframe !== animation.currentFrame ) {
  21007. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21008. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21009. this.morphTargetInfluences[ keyframe ] = 0;
  21010. animation.lastFrame = animation.currentFrame;
  21011. animation.currentFrame = keyframe;
  21012. }
  21013. var mix = ( animation.time % frameTime ) / frameTime;
  21014. if ( animation.directionBackwards ) mix = 1 - mix;
  21015. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21016. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21017. }
  21018. };
  21019. /**
  21020. * @author mikael emtinger / http://gomo.se/
  21021. * @author alteredq / http://alteredqualia.com/
  21022. */
  21023. THREE.LensFlarePlugin = function ( ) {
  21024. var _gl, _renderer, _lensFlare = {};
  21025. this.init = function ( renderer ) {
  21026. _gl = renderer.context;
  21027. _renderer = renderer;
  21028. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21029. _lensFlare.faces = new Uint16Array( 6 );
  21030. var i = 0;
  21031. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21032. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21033. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21034. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21035. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21036. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21037. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21038. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21039. i = 0;
  21040. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21041. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21042. // buffers
  21043. _lensFlare.vertexBuffer = _gl.createBuffer();
  21044. _lensFlare.elementBuffer = _gl.createBuffer();
  21045. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21046. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21047. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21048. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21049. // textures
  21050. _lensFlare.tempTexture = _gl.createTexture();
  21051. _lensFlare.occlusionTexture = _gl.createTexture();
  21052. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21053. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21054. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21055. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21056. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21057. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21058. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21059. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21060. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21061. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21062. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21063. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21064. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21065. _lensFlare.hasVertexTexture = false;
  21066. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  21067. } else {
  21068. _lensFlare.hasVertexTexture = true;
  21069. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  21070. }
  21071. _lensFlare.attributes = {};
  21072. _lensFlare.uniforms = {};
  21073. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21074. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21075. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21076. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21077. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21078. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21079. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21080. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21081. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21082. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21083. _lensFlare.attributesEnabled = false;
  21084. };
  21085. /*
  21086. * Render lens flares
  21087. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21088. * reads these back and calculates occlusion.
  21089. * Then _lensFlare.update_lensFlares() is called to re-position and
  21090. * update transparency of flares. Then they are rendered.
  21091. *
  21092. */
  21093. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21094. var flares = scene.__webglFlares,
  21095. nFlares = flares.length;
  21096. if ( ! nFlares ) return;
  21097. var tempPosition = new THREE.Vector3();
  21098. var invAspect = viewportHeight / viewportWidth,
  21099. halfViewportWidth = viewportWidth * 0.5,
  21100. halfViewportHeight = viewportHeight * 0.5;
  21101. var size = 16 / viewportHeight,
  21102. scale = new THREE.Vector2( size * invAspect, size );
  21103. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21104. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21105. var uniforms = _lensFlare.uniforms,
  21106. attributes = _lensFlare.attributes;
  21107. // set _lensFlare program and reset blending
  21108. _gl.useProgram( _lensFlare.program );
  21109. if ( ! _lensFlare.attributesEnabled ) {
  21110. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21111. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21112. _lensFlare.attributesEnabled = true;
  21113. }
  21114. // loop through all lens flares to update their occlusion and positions
  21115. // setup gl and common used attribs/unforms
  21116. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21117. _gl.uniform1i( uniforms.map, 1 );
  21118. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21119. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21120. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21121. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21122. _gl.disable( _gl.CULL_FACE );
  21123. _gl.depthMask( false );
  21124. var i, j, jl, flare, sprite;
  21125. for ( i = 0; i < nFlares; i ++ ) {
  21126. size = 16 / viewportHeight;
  21127. scale.set( size * invAspect, size );
  21128. // calc object screen position
  21129. flare = flares[ i ];
  21130. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21131. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  21132. camera.projectionMatrix.multiplyVector3( tempPosition );
  21133. // setup arrays for gl programs
  21134. screenPosition.copy( tempPosition )
  21135. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21136. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21137. // screen cull
  21138. if ( _lensFlare.hasVertexTexture || (
  21139. screenPositionPixels.x > 0 &&
  21140. screenPositionPixels.x < viewportWidth &&
  21141. screenPositionPixels.y > 0 &&
  21142. screenPositionPixels.y < viewportHeight ) ) {
  21143. // save current RGB to temp texture
  21144. _gl.activeTexture( _gl.TEXTURE1 );
  21145. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21146. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21147. // render pink quad
  21148. _gl.uniform1i( uniforms.renderType, 0 );
  21149. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21150. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21151. _gl.disable( _gl.BLEND );
  21152. _gl.enable( _gl.DEPTH_TEST );
  21153. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21154. // copy result to occlusionMap
  21155. _gl.activeTexture( _gl.TEXTURE0 );
  21156. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21157. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21158. // restore graphics
  21159. _gl.uniform1i( uniforms.renderType, 1 );
  21160. _gl.disable( _gl.DEPTH_TEST );
  21161. _gl.activeTexture( _gl.TEXTURE1 );
  21162. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21163. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21164. // update object positions
  21165. flare.positionScreen.copy( screenPosition )
  21166. if ( flare.customUpdateCallback ) {
  21167. flare.customUpdateCallback( flare );
  21168. } else {
  21169. flare.updateLensFlares();
  21170. }
  21171. // render flares
  21172. _gl.uniform1i( uniforms.renderType, 2 );
  21173. _gl.enable( _gl.BLEND );
  21174. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21175. sprite = flare.lensFlares[ j ];
  21176. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21177. screenPosition.x = sprite.x;
  21178. screenPosition.y = sprite.y;
  21179. screenPosition.z = sprite.z;
  21180. size = sprite.size * sprite.scale / viewportHeight;
  21181. scale.x = size * invAspect;
  21182. scale.y = size;
  21183. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21184. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21185. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21186. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21187. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21188. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21189. _renderer.setTexture( sprite.texture, 1 );
  21190. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21191. }
  21192. }
  21193. }
  21194. }
  21195. // restore gl
  21196. _gl.enable( _gl.CULL_FACE );
  21197. _gl.enable( _gl.DEPTH_TEST );
  21198. _gl.depthMask( true );
  21199. };
  21200. function createProgram ( shader ) {
  21201. var program = _gl.createProgram();
  21202. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21203. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21204. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21205. _gl.shaderSource( vertexShader, shader.vertexShader );
  21206. _gl.compileShader( fragmentShader );
  21207. _gl.compileShader( vertexShader );
  21208. _gl.attachShader( program, fragmentShader );
  21209. _gl.attachShader( program, vertexShader );
  21210. _gl.linkProgram( program );
  21211. return program;
  21212. };
  21213. };/**
  21214. * @author alteredq / http://alteredqualia.com/
  21215. */
  21216. THREE.ShadowMapPlugin = function ( ) {
  21217. var _gl,
  21218. _renderer,
  21219. _depthMaterial, _depthMaterialMorph,
  21220. _frustum = new THREE.Frustum(),
  21221. _projScreenMatrix = new THREE.Matrix4(),
  21222. _min = new THREE.Vector3(),
  21223. _max = new THREE.Vector3();
  21224. this.init = function ( renderer ) {
  21225. _gl = renderer.context;
  21226. _renderer = renderer;
  21227. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21228. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21229. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21230. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21231. _depthMaterial._shadowPass = true;
  21232. _depthMaterialMorph._shadowPass = true;
  21233. };
  21234. this.render = function ( scene, camera ) {
  21235. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21236. this.update( scene, camera );
  21237. };
  21238. this.update = function ( scene, camera ) {
  21239. var i, il, j, jl, n,
  21240. shadowMap, shadowMatrix, shadowCamera,
  21241. program, buffer, material,
  21242. webglObject, object, light,
  21243. renderList,
  21244. lights = [],
  21245. k = 0,
  21246. fog = null;
  21247. // set GL state for depth map
  21248. _gl.clearColor( 1, 1, 1, 1 );
  21249. _gl.disable( _gl.BLEND );
  21250. if ( _renderer.shadowMapCullFrontFaces ) _gl.cullFace( _gl.FRONT );
  21251. _renderer.setDepthTest( true );
  21252. // preprocess lights
  21253. // - skip lights that are not casting shadows
  21254. // - create virtual lights for cascaded shadow maps
  21255. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21256. light = scene.__lights[ i ];
  21257. if ( ! light.castShadow ) continue;
  21258. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21259. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21260. var virtualLight;
  21261. if ( ! light.shadowCascadeArray[ n ] ) {
  21262. virtualLight = createVirtualLight( light, n );
  21263. virtualLight.originalCamera = camera;
  21264. var gyro = new THREE.Gyroscope();
  21265. gyro.position = light.shadowCascadeOffset;
  21266. gyro.add( virtualLight );
  21267. gyro.add( virtualLight.target );
  21268. camera.add( gyro );
  21269. light.shadowCascadeArray[ n ] = virtualLight;
  21270. console.log( "Created virtualLight", virtualLight );
  21271. } else {
  21272. virtualLight = light.shadowCascadeArray[ n ];
  21273. }
  21274. updateVirtualLight( light, n );
  21275. lights[ k ] = virtualLight;
  21276. k ++;
  21277. }
  21278. } else {
  21279. lights[ k ] = light;
  21280. k ++;
  21281. }
  21282. }
  21283. // render depth map
  21284. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21285. light = lights[ i ];
  21286. if ( ! light.shadowMap ) {
  21287. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  21288. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21289. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21290. light.shadowMatrix = new THREE.Matrix4();
  21291. }
  21292. if ( ! light.shadowCamera ) {
  21293. if ( light instanceof THREE.SpotLight ) {
  21294. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21295. } else if ( light instanceof THREE.DirectionalLight ) {
  21296. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21297. } else {
  21298. console.error( "Unsupported light type for shadow" );
  21299. continue;
  21300. }
  21301. scene.add( light.shadowCamera );
  21302. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21303. }
  21304. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21305. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21306. light.shadowCamera.add( light.cameraHelper );
  21307. }
  21308. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21309. updateShadowCamera( camera, light );
  21310. }
  21311. shadowMap = light.shadowMap;
  21312. shadowMatrix = light.shadowMatrix;
  21313. shadowCamera = light.shadowCamera;
  21314. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  21315. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  21316. shadowCamera.updateMatrixWorld();
  21317. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21318. if ( light.cameraHelper ) light.cameraHelper.lines.visible = light.shadowCameraVisible;
  21319. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21320. // compute shadow matrix
  21321. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21322. 0.0, 0.5, 0.0, 0.5,
  21323. 0.0, 0.0, 0.5, 0.5,
  21324. 0.0, 0.0, 0.0, 1.0 );
  21325. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  21326. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  21327. // update camera matrices and frustum
  21328. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  21329. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  21330. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  21331. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  21332. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21333. _frustum.setFromMatrix( _projScreenMatrix );
  21334. // render shadow map
  21335. _renderer.setRenderTarget( shadowMap );
  21336. _renderer.clear();
  21337. // set object matrices & frustum culling
  21338. renderList = scene.__webglObjects;
  21339. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21340. webglObject = renderList[ j ];
  21341. object = webglObject.object;
  21342. webglObject.render = false;
  21343. if ( object.visible && object.castShadow ) {
  21344. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21345. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21346. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld);
  21347. webglObject.render = true;
  21348. }
  21349. }
  21350. }
  21351. // render regular objects
  21352. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21353. webglObject = renderList[ j ];
  21354. if ( webglObject.render ) {
  21355. object = webglObject.object;
  21356. buffer = webglObject.buffer;
  21357. _renderer.setObjectFaces( object );
  21358. if ( object.customDepthMaterial ) {
  21359. material = object.customDepthMaterial;
  21360. } else if ( object.geometry.morphTargets.length ) {
  21361. material = _depthMaterialMorph;
  21362. } else {
  21363. material = _depthMaterial;
  21364. }
  21365. if ( buffer instanceof THREE.BufferGeometry ) {
  21366. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21367. } else {
  21368. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21369. }
  21370. }
  21371. }
  21372. // set matrices and render immediate objects
  21373. renderList = scene.__webglObjectsImmediate;
  21374. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21375. webglObject = renderList[ j ];
  21376. object = webglObject.object;
  21377. if ( object.visible && object.castShadow ) {
  21378. if( object.matrixAutoUpdate ) {
  21379. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21380. }
  21381. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld);
  21382. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21383. }
  21384. }
  21385. }
  21386. // restore GL state
  21387. var clearColor = _renderer.getClearColor(),
  21388. clearAlpha = _renderer.getClearAlpha();
  21389. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21390. _gl.enable( _gl.BLEND );
  21391. if ( _renderer.shadowMapCullFrontFaces ) _gl.cullFace( _gl.BACK );
  21392. };
  21393. function createVirtualLight( light, cascade ) {
  21394. var virtualLight = new THREE.DirectionalLight();
  21395. virtualLight.isVirtual = true;
  21396. virtualLight.onlyShadow = true;
  21397. virtualLight.castShadow = true;
  21398. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21399. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21400. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21401. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21402. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21403. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21404. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21405. virtualLight.shadowDarkness = light.shadowDarkness;
  21406. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21407. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21408. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21409. virtualLight.pointsWorld = [];
  21410. virtualLight.pointsFrustum = [];
  21411. var pointsWorld = virtualLight.pointsWorld,
  21412. pointsFrustum = virtualLight.pointsFrustum;
  21413. for ( var i = 0; i < 8; i ++ ) {
  21414. pointsWorld[ i ] = new THREE.Vector3();
  21415. pointsFrustum[ i ] = new THREE.Vector3();
  21416. }
  21417. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21418. var farZ = light.shadowCascadeFarZ[ cascade ];
  21419. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21420. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21421. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21422. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21423. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21424. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21425. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21426. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21427. return virtualLight;
  21428. }
  21429. // Synchronize virtual light with the original light
  21430. function updateVirtualLight( light, cascade ) {
  21431. var virtualLight = light.shadowCascadeArray[ cascade ];
  21432. virtualLight.position.copy( light.position );
  21433. virtualLight.target.position.copy( light.target.position );
  21434. virtualLight.lookAt( virtualLight.target );
  21435. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21436. virtualLight.shadowDarkness = light.shadowDarkness;
  21437. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21438. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21439. var farZ = light.shadowCascadeFarZ[ cascade ];
  21440. var pointsFrustum = virtualLight.pointsFrustum;
  21441. pointsFrustum[ 0 ].z = nearZ;
  21442. pointsFrustum[ 1 ].z = nearZ;
  21443. pointsFrustum[ 2 ].z = nearZ;
  21444. pointsFrustum[ 3 ].z = nearZ;
  21445. pointsFrustum[ 4 ].z = farZ;
  21446. pointsFrustum[ 5 ].z = farZ;
  21447. pointsFrustum[ 6 ].z = farZ;
  21448. pointsFrustum[ 7 ].z = farZ;
  21449. }
  21450. // Fit shadow camera's ortho frustum to camera frustum
  21451. function updateShadowCamera( camera, light ) {
  21452. var shadowCamera = light.shadowCamera,
  21453. pointsFrustum = light.pointsFrustum,
  21454. pointsWorld = light.pointsWorld;
  21455. _min.set( Infinity, Infinity, Infinity );
  21456. _max.set( -Infinity, -Infinity, -Infinity );
  21457. for ( var i = 0; i < 8; i ++ ) {
  21458. var p = pointsWorld[ i ];
  21459. p.copy( pointsFrustum[ i ] );
  21460. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21461. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  21462. if ( p.x < _min.x ) _min.x = p.x;
  21463. if ( p.x > _max.x ) _max.x = p.x;
  21464. if ( p.y < _min.y ) _min.y = p.y;
  21465. if ( p.y > _max.y ) _max.y = p.y;
  21466. if ( p.z < _min.z ) _min.z = p.z;
  21467. if ( p.z > _max.z ) _max.z = p.z;
  21468. }
  21469. shadowCamera.left = _min.x;
  21470. shadowCamera.right = _max.x;
  21471. shadowCamera.top = _max.y;
  21472. shadowCamera.bottom = _min.y;
  21473. // can't really fit near/far
  21474. //shadowCamera.near = _min.z;
  21475. //shadowCamera.far = _max.z;
  21476. shadowCamera.updateProjectionMatrix();
  21477. }
  21478. };
  21479. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21480. /**
  21481. * @author mikael emtinger / http://gomo.se/
  21482. * @author alteredq / http://alteredqualia.com/
  21483. */
  21484. THREE.SpritePlugin = function ( ) {
  21485. var _gl, _renderer, _sprite = {};
  21486. this.init = function ( renderer ) {
  21487. _gl = renderer.context;
  21488. _renderer = renderer;
  21489. _sprite.vertices = new Float32Array( 8 + 8 );
  21490. _sprite.faces = new Uint16Array( 6 );
  21491. var i = 0;
  21492. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21493. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 0
  21494. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21495. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 1
  21496. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21497. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 2
  21498. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21499. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 3
  21500. i = 0;
  21501. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21502. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21503. _sprite.vertexBuffer = _gl.createBuffer();
  21504. _sprite.elementBuffer = _gl.createBuffer();
  21505. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21506. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21507. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21508. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21509. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  21510. _sprite.attributes = {};
  21511. _sprite.uniforms = {};
  21512. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21513. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21514. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21515. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21516. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21517. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21518. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21519. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21520. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21521. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21522. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21523. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  21524. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21525. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21526. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21527. _sprite.attributesEnabled = false;
  21528. };
  21529. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21530. var sprites = scene.__webglSprites,
  21531. nSprites = sprites.length;
  21532. if ( ! nSprites ) return;
  21533. var attributes = _sprite.attributes,
  21534. uniforms = _sprite.uniforms;
  21535. var invAspect = viewportHeight / viewportWidth;
  21536. var halfViewportWidth = viewportWidth * 0.5,
  21537. halfViewportHeight = viewportHeight * 0.5;
  21538. var mergeWith3D = true;
  21539. // setup gl
  21540. _gl.useProgram( _sprite.program );
  21541. if ( ! _sprite.attributesEnabled ) {
  21542. _gl.enableVertexAttribArray( attributes.position );
  21543. _gl.enableVertexAttribArray( attributes.uv );
  21544. _sprite.attributesEnabled = true;
  21545. }
  21546. _gl.disable( _gl.CULL_FACE );
  21547. _gl.enable( _gl.BLEND );
  21548. _gl.depthMask( true );
  21549. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21550. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21551. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21552. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21553. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  21554. _gl.activeTexture( _gl.TEXTURE0 );
  21555. _gl.uniform1i( uniforms.map, 0 );
  21556. // update positions and sort
  21557. var i, sprite, screenPosition, size, scale = [];
  21558. for( i = 0; i < nSprites; i ++ ) {
  21559. sprite = sprites[ i ];
  21560. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  21561. if( ! sprite.useScreenCoordinates ) {
  21562. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld);
  21563. sprite.z = - sprite._modelViewMatrix.elements[14];
  21564. } else {
  21565. sprite.z = - sprite.position.z;
  21566. }
  21567. }
  21568. sprites.sort( painterSort );
  21569. // render all sprites
  21570. for( i = 0; i < nSprites; i ++ ) {
  21571. sprite = sprites[ i ];
  21572. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  21573. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  21574. if ( sprite.useScreenCoordinates ) {
  21575. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21576. _gl.uniform3f( uniforms.screenPosition, ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21577. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21578. Math.max( 0, Math.min( 1, sprite.position.z ) ) );
  21579. } else {
  21580. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21581. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  21582. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements);
  21583. }
  21584. size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
  21585. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21586. scale[ 1 ] = size * sprite.scale.y;
  21587. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  21588. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  21589. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  21590. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21591. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21592. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21593. _gl.uniform2fv( uniforms.scale, scale );
  21594. if ( sprite.mergeWith3D && !mergeWith3D ) {
  21595. _gl.enable( _gl.DEPTH_TEST );
  21596. mergeWith3D = true;
  21597. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  21598. _gl.disable( _gl.DEPTH_TEST );
  21599. mergeWith3D = false;
  21600. }
  21601. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21602. _renderer.setTexture( sprite.map, 0 );
  21603. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21604. }
  21605. }
  21606. // restore gl
  21607. _gl.enable( _gl.CULL_FACE );
  21608. _gl.enable( _gl.DEPTH_TEST );
  21609. _gl.depthMask( true );
  21610. };
  21611. function createProgram ( shader ) {
  21612. var program = _gl.createProgram();
  21613. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21614. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21615. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21616. _gl.shaderSource( vertexShader, shader.vertexShader );
  21617. _gl.compileShader( fragmentShader );
  21618. _gl.compileShader( vertexShader );
  21619. _gl.attachShader( program, fragmentShader );
  21620. _gl.attachShader( program, vertexShader );
  21621. _gl.linkProgram( program );
  21622. return program;
  21623. };
  21624. function painterSort ( a, b ) {
  21625. return b.z - a.z;
  21626. };
  21627. };/**
  21628. * @author alteredq / http://alteredqualia.com/
  21629. */
  21630. THREE.DepthPassPlugin = function ( ) {
  21631. this.enabled = false;
  21632. this.renderTarget = null;
  21633. var _gl,
  21634. _renderer,
  21635. _depthMaterial, _depthMaterialMorph,
  21636. _frustum = new THREE.Frustum(),
  21637. _projScreenMatrix = new THREE.Matrix4();
  21638. this.init = function ( renderer ) {
  21639. _gl = renderer.context;
  21640. _renderer = renderer;
  21641. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21642. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21643. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21644. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21645. _depthMaterial._shadowPass = true;
  21646. _depthMaterialMorph._shadowPass = true;
  21647. };
  21648. this.render = function ( scene, camera ) {
  21649. if ( ! this.enabled ) return;
  21650. this.update( scene, camera );
  21651. };
  21652. this.update = function ( scene, camera ) {
  21653. var i, il, j, jl, n,
  21654. program, buffer, material,
  21655. webglObject, object, light,
  21656. renderList,
  21657. fog = null;
  21658. // set GL state for depth map
  21659. _gl.clearColor( 1, 1, 1, 1 );
  21660. _gl.disable( _gl.BLEND );
  21661. _renderer.setDepthTest( true );
  21662. // update scene
  21663. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21664. // update camera matrices and frustum
  21665. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  21666. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  21667. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21668. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  21669. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  21670. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21671. _frustum.setFromMatrix( _projScreenMatrix );
  21672. // render depth map
  21673. _renderer.setRenderTarget( this.renderTarget );
  21674. _renderer.clear();
  21675. // set object matrices & frustum culling
  21676. renderList = scene.__webglObjects;
  21677. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21678. webglObject = renderList[ j ];
  21679. object = webglObject.object;
  21680. webglObject.render = false;
  21681. if ( object.visible ) {
  21682. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21683. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21684. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  21685. webglObject.render = true;
  21686. }
  21687. }
  21688. }
  21689. // render regular objects
  21690. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21691. webglObject = renderList[ j ];
  21692. if ( webglObject.render ) {
  21693. object = webglObject.object;
  21694. buffer = webglObject.buffer;
  21695. _renderer.setObjectFaces( object );
  21696. if ( object.customDepthMaterial ) {
  21697. material = object.customDepthMaterial;
  21698. } else if ( object.geometry.morphTargets.length ) {
  21699. material = _depthMaterialMorph;
  21700. } else {
  21701. material = _depthMaterial;
  21702. }
  21703. if ( buffer instanceof THREE.BufferGeometry ) {
  21704. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21705. } else {
  21706. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21707. }
  21708. }
  21709. }
  21710. // set matrices and render immediate objects
  21711. renderList = scene.__webglObjectsImmediate;
  21712. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21713. webglObject = renderList[ j ];
  21714. object = webglObject.object;
  21715. if ( object.visible && object.castShadow ) {
  21716. if( object.matrixAutoUpdate ) {
  21717. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21718. }
  21719. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  21720. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21721. }
  21722. }
  21723. // restore GL state
  21724. var clearColor = _renderer.getClearColor(),
  21725. clearAlpha = _renderer.getClearAlpha();
  21726. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21727. _gl.enable( _gl.BLEND );
  21728. };
  21729. };
  21730. /**
  21731. * @author mrdoob / http://mrdoob.com/
  21732. * @author marklundin / http://mark-lundin.com/
  21733. * @author alteredq / http://alteredqualia.com/
  21734. */
  21735. if ( THREE.WebGLRenderer ) {
  21736. THREE.AnaglyphWebGLRenderer = function ( parameters ) {
  21737. THREE.WebGLRenderer.call( this, parameters );
  21738. this.autoUpdateScene = false;
  21739. var _this = this, _setSize = this.setSize, _render = this.render;
  21740. var _cameraL = new THREE.PerspectiveCamera(),
  21741. _cameraR = new THREE.PerspectiveCamera();
  21742. var eyeRight = new THREE.Matrix4(),
  21743. eyeLeft = new THREE.Matrix4(),
  21744. focalLength = 125,
  21745. _aspect, _near, _far, _fov;
  21746. _cameraL.matrixAutoUpdate = _cameraR.matrixAutoUpdate = false;
  21747. var _params = { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };
  21748. var _renderTargetL = new THREE.WebGLRenderTarget( 512, 512, _params ),
  21749. _renderTargetR = new THREE.WebGLRenderTarget( 512, 512, _params );
  21750. var _camera = new THREE.PerspectiveCamera( 53, 1, 1, 10000 );
  21751. _camera.position.z = 2;
  21752. var _material = new THREE.ShaderMaterial( {
  21753. uniforms: {
  21754. "mapLeft": { type: "t", value: 0, texture: _renderTargetL },
  21755. "mapRight": { type: "t", value: 1, texture: _renderTargetR }
  21756. },
  21757. vertexShader: [
  21758. "varying vec2 vUv;",
  21759. "void main() {",
  21760. "vUv = vec2( uv.x, 1.0 - uv.y );",
  21761. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  21762. "}"
  21763. ].join("\n"),
  21764. fragmentShader: [
  21765. "uniform sampler2D mapLeft;",
  21766. "uniform sampler2D mapRight;",
  21767. "varying vec2 vUv;",
  21768. "void main() {",
  21769. "vec4 colorL, colorR;",
  21770. "vec2 uv = vUv;",
  21771. "colorL = texture2D( mapLeft, uv );",
  21772. "colorR = texture2D( mapRight, uv );",
  21773. // http://3dtv.at/Knowhow/AnaglyphComparison_en.aspx
  21774. "gl_FragColor = vec4( colorL.g * 0.7 + colorL.b * 0.3, colorR.g, colorR.b, colorL.a + colorR.a ) * 1.1;",
  21775. "}"
  21776. ].join("\n")
  21777. } );
  21778. var _scene = new THREE.Scene();
  21779. var mesh = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), _material );
  21780. mesh.rotation.x = Math.PI / 2;
  21781. _scene.add( mesh );
  21782. _scene.add( _camera );
  21783. this.setSize = function ( width, height ) {
  21784. _setSize.call( _this, width, height );
  21785. _renderTargetL.width = width;
  21786. _renderTargetL.height = height;
  21787. _renderTargetR.width = width;
  21788. _renderTargetR.height = height;
  21789. };
  21790. /*
  21791. * Renderer now uses an asymmetric perspective projection (http://paulbourke.net/miscellaneous/stereographics/stereorender/).
  21792. * Each camera is offset by the eye seperation and its projection matrix is also skewed asymetrically back to converge on the same
  21793. * projection plane. Added a focal length parameter to, this is where the parallax is equal to 0.
  21794. */
  21795. this.render = function ( scene, camera, renderTarget, forceClear ) {
  21796. scene.updateMatrixWorld();
  21797. var hasCameraChanged = ( _aspect !== camera.aspect ) || ( _near !== camera.near ) || ( _far !== camera.far ) || ( _fov !== camera.fov );
  21798. if( hasCameraChanged ) {
  21799. _aspect = camera.aspect;
  21800. _near = camera.near;
  21801. _far = camera.far;
  21802. _fov = camera.fov;
  21803. var projectionMatrix = camera.projectionMatrix.clone(),
  21804. eyeSep = focalLength / 30 * 0.5,
  21805. eyeSepOnProjection = eyeSep * _near / focalLength,
  21806. ymax = _near * Math.tan( _fov * Math.PI / 360 ),
  21807. xmin, xmax;
  21808. // translate xOffset
  21809. eyeRight.elements[12] = eyeSep;
  21810. eyeLeft.elements[12] = -eyeSep;
  21811. // for left eye
  21812. xmin = -ymax * _aspect + eyeSepOnProjection;
  21813. xmax = ymax * _aspect + eyeSepOnProjection;
  21814. projectionMatrix.elements[0] = 2 * _near / ( xmax - xmin );
  21815. projectionMatrix.elements[8] = ( xmax + xmin ) / ( xmax - xmin );
  21816. _cameraL.projectionMatrix.copy( projectionMatrix );
  21817. // for right eye
  21818. xmin = -ymax * _aspect - eyeSepOnProjection;
  21819. xmax = ymax * _aspect - eyeSepOnProjection;
  21820. projectionMatrix.elements[0] = 2 * _near / ( xmax - xmin );
  21821. projectionMatrix.elements[8] = ( xmax + xmin ) / ( xmax - xmin );
  21822. _cameraR.projectionMatrix.copy( projectionMatrix );
  21823. }
  21824. _cameraL.matrixWorld.copy( camera.matrixWorld ).multiplySelf( eyeLeft );
  21825. _cameraL.position.copy( camera.position );
  21826. _cameraL.near = camera.near;
  21827. _cameraL.far = camera.far;
  21828. _render.call( _this, scene, _cameraL, _renderTargetL, true );
  21829. _cameraR.matrixWorld.copy( camera.matrixWorld ).multiplySelf( eyeRight );
  21830. _cameraR.position.copy( camera.position );
  21831. _cameraR.near = camera.near;
  21832. _cameraR.far = camera.far;
  21833. _render.call( _this, scene, _cameraR, _renderTargetR, true );
  21834. _scene.updateMatrixWorld();
  21835. _render.call( _this, _scene, _camera );
  21836. };
  21837. };
  21838. };
  21839. /**
  21840. * @author alteredq / http://alteredqualia.com/
  21841. */
  21842. if ( THREE.WebGLRenderer ) {
  21843. THREE.CrosseyedWebGLRenderer = function ( parameters ) {
  21844. THREE.WebGLRenderer.call( this, parameters );
  21845. this.autoClear = false;
  21846. var _this = this, _setSize = this.setSize, _render = this.render;
  21847. var _width, _height;
  21848. var _cameraL = new THREE.PerspectiveCamera();
  21849. _cameraL.target = new THREE.Vector3( 0, 0, 0 );
  21850. var _cameraR = new THREE.PerspectiveCamera();
  21851. _cameraR.target = new THREE.Vector3( 0, 0, 0 );
  21852. _this.separation = 10;
  21853. if ( parameters && parameters.separation !== undefined ) _this.separation = parameters.separation;
  21854. var SCREEN_WIDTH = window.innerWidth;
  21855. var SCREEN_HEIGHT = window.innerHeight;
  21856. var HALF_WIDTH = SCREEN_WIDTH / 2;
  21857. this.setSize = function ( width, height ) {
  21858. _setSize.call( _this, width, height );
  21859. _width = width/2;
  21860. _height = height;
  21861. };
  21862. this.render = function ( scene, camera, renderTarget, forceClear ) {
  21863. this.clear();
  21864. _cameraL.fov = camera.fov;
  21865. _cameraL.aspect = 0.5 * camera.aspect;
  21866. _cameraL.near = camera.near;
  21867. _cameraL.far = camera.far;
  21868. _cameraL.updateProjectionMatrix();
  21869. _cameraL.position.copy( camera.position );
  21870. _cameraL.target.copy( camera.target );
  21871. _cameraL.translateX( _this.separation );
  21872. _cameraL.lookAt( _cameraL.target );
  21873. _cameraR.projectionMatrix = _cameraL.projectionMatrix;
  21874. _cameraR.position.copy( camera.position );
  21875. _cameraR.target.copy( camera.target );
  21876. _cameraR.translateX( - _this.separation );
  21877. _cameraR.lookAt( _cameraR.target );
  21878. this.setViewport( 0, 0, _width, _height );
  21879. _render.call( _this, scene, _cameraL );
  21880. this.setViewport( _width, 0, _width, _height );
  21881. _render.call( _this, scene, _cameraR, false );
  21882. };
  21883. };
  21884. }
  21885. /**
  21886. * @author mikael emtinger / http://gomo.se/
  21887. *
  21888. */
  21889. THREE.ShaderFlares = {
  21890. 'lensFlareVertexTexture': {
  21891. vertexShader: [
  21892. "uniform vec3 screenPosition;",
  21893. "uniform vec2 scale;",
  21894. "uniform float rotation;",
  21895. "uniform int renderType;",
  21896. "uniform sampler2D occlusionMap;",
  21897. "attribute vec2 position;",
  21898. "attribute vec2 uv;",
  21899. "varying vec2 vUV;",
  21900. "varying float vVisibility;",
  21901. "void main() {",
  21902. "vUV = uv;",
  21903. "vec2 pos = position;",
  21904. "if( renderType == 2 ) {",
  21905. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21906. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21907. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21908. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21909. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21910. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21911. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21912. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21913. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21914. "vVisibility = ( visibility.r / 9.0 ) *",
  21915. "( 1.0 - visibility.g / 9.0 ) *",
  21916. "( visibility.b / 9.0 ) *",
  21917. "( 1.0 - visibility.a / 9.0 );",
  21918. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21919. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21920. "}",
  21921. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21922. "}"
  21923. ].join( "\n" ),
  21924. fragmentShader: [
  21925. "precision mediump float;",
  21926. "uniform sampler2D map;",
  21927. "uniform float opacity;",
  21928. "uniform int renderType;",
  21929. "uniform vec3 color;",
  21930. "varying vec2 vUV;",
  21931. "varying float vVisibility;",
  21932. "void main() {",
  21933. // pink square
  21934. "if( renderType == 0 ) {",
  21935. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21936. // restore
  21937. "} else if( renderType == 1 ) {",
  21938. "gl_FragColor = texture2D( map, vUV );",
  21939. // flare
  21940. "} else {",
  21941. "vec4 texture = texture2D( map, vUV );",
  21942. "texture.a *= opacity * vVisibility;",
  21943. "gl_FragColor = texture;",
  21944. "gl_FragColor.rgb *= color;",
  21945. "}",
  21946. "}"
  21947. ].join( "\n" )
  21948. },
  21949. 'lensFlare': {
  21950. vertexShader: [
  21951. "uniform vec3 screenPosition;",
  21952. "uniform vec2 scale;",
  21953. "uniform float rotation;",
  21954. "uniform int renderType;",
  21955. "attribute vec2 position;",
  21956. "attribute vec2 uv;",
  21957. "varying vec2 vUV;",
  21958. "void main() {",
  21959. "vUV = uv;",
  21960. "vec2 pos = position;",
  21961. "if( renderType == 2 ) {",
  21962. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21963. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21964. "}",
  21965. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21966. "}"
  21967. ].join( "\n" ),
  21968. fragmentShader: [
  21969. "precision mediump float;",
  21970. "uniform sampler2D map;",
  21971. "uniform sampler2D occlusionMap;",
  21972. "uniform float opacity;",
  21973. "uniform int renderType;",
  21974. "uniform vec3 color;",
  21975. "varying vec2 vUV;",
  21976. "void main() {",
  21977. // pink square
  21978. "if( renderType == 0 ) {",
  21979. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21980. // restore
  21981. "} else if( renderType == 1 ) {",
  21982. "gl_FragColor = texture2D( map, vUV );",
  21983. // flare
  21984. "} else {",
  21985. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21986. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21987. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21988. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21989. "visibility = ( 1.0 - visibility / 4.0 );",
  21990. "vec4 texture = texture2D( map, vUV );",
  21991. "texture.a *= opacity * visibility;",
  21992. "gl_FragColor = texture;",
  21993. "gl_FragColor.rgb *= color;",
  21994. "}",
  21995. "}"
  21996. ].join( "\n" )
  21997. }
  21998. };
  21999. /**
  22000. * @author mikael emtinger / http://gomo.se/
  22001. *
  22002. */
  22003. THREE.ShaderSprite = {
  22004. 'sprite': {
  22005. vertexShader: [
  22006. "uniform int useScreenCoordinates;",
  22007. "uniform int affectedByDistance;",
  22008. "uniform vec3 screenPosition;",
  22009. "uniform mat4 modelViewMatrix;",
  22010. "uniform mat4 projectionMatrix;",
  22011. "uniform float rotation;",
  22012. "uniform vec2 scale;",
  22013. "uniform vec2 alignment;",
  22014. "uniform vec2 uvOffset;",
  22015. "uniform vec2 uvScale;",
  22016. "attribute vec2 position;",
  22017. "attribute vec2 uv;",
  22018. "varying vec2 vUV;",
  22019. "void main() {",
  22020. "vUV = uvOffset + uv * uvScale;",
  22021. "vec2 alignedPosition = position + alignment;",
  22022. "vec2 rotatedPosition;",
  22023. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  22024. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  22025. "vec4 finalPosition;",
  22026. "if( useScreenCoordinates != 0 ) {",
  22027. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  22028. "} else {",
  22029. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  22030. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  22031. "}",
  22032. "gl_Position = finalPosition;",
  22033. "}"
  22034. ].join( "\n" ),
  22035. fragmentShader: [
  22036. "precision mediump float;",
  22037. "uniform vec3 color;",
  22038. "uniform sampler2D map;",
  22039. "uniform float opacity;",
  22040. "varying vec2 vUV;",
  22041. "void main() {",
  22042. "vec4 texture = texture2D( map, vUV );",
  22043. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  22044. "}"
  22045. ].join( "\n" )
  22046. }
  22047. };